diff --git "a/5119.jsonl" "b/5119.jsonl" new file mode 100644--- /dev/null +++ "b/5119.jsonl" @@ -0,0 +1,593 @@ +{"seq_id":"415358582","text":"# Logistic Regression\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass MLP(nn.Module):\n def __init__(self, input_size, num_classes, hidden_dim):\n super(MLP, self).__init__()\n self.linear_input = nn.Linear(input_size, hidden_dim)\n self.linear1 = nn.Linear(hidden_dim, hidden_dim)\n self.linear_output = nn.Linear(hidden_dim, num_classes)\n\n # xavier initialization\n torch.nn.init.xavier_normal(self.linear_input.weight)\n self.linear_input.bias.data.fill_(1e-5)\n torch.nn.init.xavier_normal(self.linear1.weight)\n self.linear1.bias.data.fill_(1e-5)\n torch.nn.init.xavier_normal(self.linear_output.weight)\n self.linear_output.bias.data.fill_(1e-5)\n\n def forward(self, x):\n out = F.tanh(self.linear_input(x))\n out = F.tanh(self.linear1(out))\n out = self.linear_output(out)\n return out\n","sub_path":"models/MLP.py","file_name":"MLP.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"182733541","text":"import numpy as np\nimport cv2\n\ndetector_path = '/mnt/sdb/mspark/data/brain_aneurysm_yonsei/npz/total/total_input_3dce_detector.npz'\nsegmentation_path = '/mnt/sdb/mspark/data/brain_aneurysm_yonsei/npz/total/total_input_3dce_segmentation.npz'\nlabel_path = '/mnt/sdb/mspark/data/brain_aneurysm_yonsei/npz/total/total_label_3dce_detector.npz'\n\ndef masking_rgb(img, color=None, multiply=255):\n if len(np.shape(img)) <= 2:\n _img = np.expand_dims(img, axis=3)\n else:\n _img = img\n rgb_list = [np.zeros(np.shape(_img)) for _ in range(3)]\n\n if color == 'yellow':\n rgb_list[1] = _img\n rgb_list[2] = _img\n B, G, R = rgb_list\n\n elif color != None:\n rgb_dic = {'blue': 0, 'green': 1, 'red': 2}\n rgb_list[rgb_dic[color]] = _img\n B, G, R = rgb_list\n else:\n B = G = R = _img\n\n concat_img = np.concatenate((B, G, R), axis=-1)\n out_img = concat_img * multiply\n\n return out_img\n\ndetector = np.load(detector_path)['all'][0]\nsegmentation = np.load(segmentation_path)['all'][0]\nlabel = np.load(label_path)['all'][0]\n\n# print(detector.shape, np.max(detector))\n# print(segmentation.shape, np.max(segmentation))\n# print(label.shape)\n\n\nfor idx, de, se in zip(range(9), detector, segmentation):\n print(np.max(de))\n print(np.max(se))\n # cv2.imwrite('/home/mspark/deepnoid/data/de{}.png'.format(idx), masking_rgb(de/np.max(de)))\n # cv2.imwrite('/home/mspark/deepnoid/data/se{}.png'.format(idx), masking_rgb(se/np.max(se)))\n#\n# segmentation = segmentation[4].astype(np.uint8)\n# label = np.round(label[0] * 256).astype(np.uint8)\n#\n# cv2.rectangle(segmentation, (label[2] - 5, label[1] - 5), (label[4] + 5, label[3] + 5), (1, 1, 1), 1)\n# cv2.imwrite('/home/mspark/deepnoid/data/label.png', masking_rgb(segmentation))\n\n\n\n","sub_path":"aneurysm_detection/seg_3dce/note.py","file_name":"note.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"407345293","text":"# -*- encoding:utf-8 -*-\n\nimport io\nimport os\nimport sys\nimport struct\nimport hashlib\nimport binascii\n\nfrom ecdsa import BadSignatureError\nfrom ecdsa.der import UnexpectedDER\nfrom ecdsa.keys import SigningKey, VerifyingKey\nfrom ecdsa.util import sigencode_der_canonize, sigdecode_der\nfrom ecdsa.curves import SECP256k1\n\nimport base58\n\nPY3 = True if sys.version_info[0] >= 3 else False\n\nif not PY3:\n\tfrom StringIO import StringIO\nelse:\n\tfrom io import BytesIO as StringIO\n\n# byte as int conversion\nbasint = (lambda e:e) if PY3 else \\\n (lambda e:ord(e))\n# read value as binary data from buffer\nunpack = lambda fmt, fileobj: struct.unpack(fmt, fileobj.read(struct.calcsize(fmt)))\n# write value as binary data into buffer\npack = lambda fmt, fileobj, value: fileobj.write(struct.pack(fmt, *value))\n# read bytes from buffer\nunpack_bytes = lambda f,n: unpack(\"<\"+\"%ss\"%n, f)[0]\n# write bytes into buffer\npack_bytes = (lambda f,v: pack(\"!\"+\"%ss\"%len(v), f, (v,))) if PY3 else \\\n (lambda f,v: pack(\"!\"+\"c\"*len(v), f, v))\n\n\ndef hexlify(data):\n\tresult = binascii.hexlify(data)\n\treturn str(result.decode() if isinstance(result, bytes) else result)\n\n\ndef unhexlify(data):\n\tif len(data)%2: data = \"0\"+data\n\tresult = binascii.unhexlify(data)\n\treturn result if isinstance(result, bytes) else result.encode()\n\n\ndef compressEcdsaPublicKey(pubkey):\n\tfirst, last = pubkey[:32], pubkey[32:]\n\t# check if last digit of second part is even (2%2 = 0, 3%2 = 1)\n\teven = not bool(basint(last[-1]) % 2)\n\treturn (b\"\\x02\" if even else b\"\\x03\") + first\n\n# Uncompressed public key is:\n# 0x04 + x-coordinate + y-coordinate\n#\n# Compressed public key is:\n# 0x02 + x-coordinate if y is even\n# 0x03 + x-coordinate if y is odd\n#\n# y^2 mod p = (x^3 + 7) mod p\n\ndef uncompressEcdsaPublicKey(pubkey):\n\t# read more : https://bitcointalk.org/index.php?topic=644919.msg7205689#msg7205689\n\tp = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f\n\ty_parity = int(pubkey[:2]) - 2\n\tx = int(pubkey[2:], 16)\n\ta = (pow(x, 3, p) + 7) % p\n\ty = pow(a, (p + 1) // 4, p)\n\tif y % 2 != y_parity:\n\t\ty = -y % p\n\t# return result as der signature (no 0x04 preffix)\n\treturn '{:x}{:x}'.format(x, y)\n\n\ndef getKeys(secret, seed=None):\n\t\"\"\"\n Generate keyring containing public key, signing and checking keys as\n attribute.\n\n Keyword arguments:\n secret (str or bytes) -- a human pass phrase\n seed (byte) -- a sha256 sequence bytes (private key actualy)\n\n Return dict\n \"\"\"\n\tseed = hashlib.sha256(secret.encode(\"utf8\") if not isinstance(secret, bytes) else secret).digest() if not seed else seed\n\tsigningKey = SigningKey.from_secret_exponent(int(hexlify(seed), 16), SECP256k1, hashlib.sha256)\n\tpublicKey = signingKey.get_verifying_key().to_string()\n\treturn {\n\t\t\"publicKey\": hexlify(compressEcdsaPublicKey(publicKey)),\n\t\t\"privateKey\": hexlify(signingKey.to_string()),\n\t}\n\n\ndef getSignature(tx, privateKey):\n\t\"\"\"\n\tGenerate transaction signature using private key.\n\n\tArguments:\n\ttx (dict) -- a transaction description\n\tprivateKey (str) -- a private key as hex string\n\n\tReturn str\n\t\"\"\"\n\tsigningKey = SigningKey.from_string(unhexlify(privateKey), SECP256k1, hashlib.sha256)\n\treturn hexlify(signingKey.sign_deterministic(getBytes(tx), hashlib.sha256, sigencode=sigencode_der_canonize))\n\n\ndef getSignatureFromBytes(data, privateKey):\n\t\"\"\"\n\tGenerate data signature using private key.\n\n\tArguments:\n\tdata (bytes) -- data in bytes\n\tprivateKey (str) -- a private key as hex string\n\n\tReturn str\n\t\"\"\"\n\tsigningKey = SigningKey.from_string(unhexlify(privateKey), SECP256k1, hashlib.sha256)\n\treturn hexlify(signingKey.sign_deterministic(data, hashlib.sha256, sigencode=sigencode_der_canonize))\n\n\ndef getId(tx):\n\t\"\"\"\n\tGenerate transaction id.\n\n\tArguments:\n\ttx (dict) -- a transaction description\n\n\tReturn str\n\t\"\"\"\n\treturn hexlify(hashlib.sha256(getBytes(tx)).digest())\n\n\ndef getIdFromBytes(data):\n\t\"\"\"\n\tGenerate data id.\n\n\tArguments:\n\tdata (bytes) -- data in bytes\n\n\tReturn str\n\t\"\"\"\n\treturn hexlify(hashlib.sha256(data).digest())\n\n\ndef verifySignatureFromBytes(data, publicKey, signature):\n\t\"\"\"\n\tVerify signature.\n\n\tArguments:\n\tdata (bytes) -- data in bytes\n\tpublicKey (str) -- a public key as hex string\n\tsignature (str) -- a signature as hex string\n\n\tReturn bool\n\t\"\"\"\n\tif len(publicKey) == 66:\n\t\tpublicKey = uncompressEcdsaPublicKey(publicKey)\n\tverifyingKey = VerifyingKey.from_string(unhexlify(publicKey), SECP256k1, hashlib.sha256)\n\ttry:\n\t\tverifyingKey.verify(unhexlify(signature), data, hashlib.sha256, sigdecode_der)\n\texcept (BadSignatureError, UnexpectedDER):\n\t\treturn False\n\treturn True\n\n\ndef getBytes(tx):\n\t\"\"\"\n\tHash transaction object into bytes data.\n\n\tArgument:\n\ttx (dict) -- transaction object\n\n\tReturn bytes sequence\n\t\"\"\"\n\tbuf = StringIO()\n\t# write type and timestamp\n\tpack(\"\"\n str_out += \"成功

\"\n return HttpResponse(str_out)\n# ------------------------------------------------------------------\n","sub_path":"src/file_upload/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"140519499","text":"import cv2\nfrom facenet_pytorch import MTCNN, InceptionResnetV1, fixed_image_standardization\nimport torch\nfrom torchvision import transforms\nimport numpy as np\nfrom PIL import Image\nimport datetime\nimport openpyxl\n\ndef recognize_faces():\n # testing image path\n frame_size = (640, 480)\n IMG_PATH = 'C:/Users/Gen Bodmas/PycharmProjects/CIFAR10/test_images'\n DATA_PATH = 'C:/Users/Gen Bodmas/PycharmProjects/CIFAR10'\n\n now = datetime.datetime.now()\n today = now.day\n month = now.month\n\n wb = openpyxl.load_workbook(\"attendance.xlsx\")\n ws = wb.active\n\n def trans(img):\n transform = transforms.Compose([\n transforms.ToTensor(),\n fixed_image_standardization\n ])\n return transform(img)\n\n\n # Loading facelist\n def load_faceslist():\n if device == 'cpu':\n embeds = torch.load(DATA_PATH + '/faceslistCPU.pth')\n else:\n embeds = torch.load(DATA_PATH + '/faceslist.pth')\n names = np.load(DATA_PATH + '/usernames.npy')\n return embeds, names\n\n\n def inference(model, face, local_embeds, threshold=3):\n embeds = []\n embeds.append(model(trans(face).to(device).unsqueeze(0)))\n detect_embeds = torch.cat(embeds) # [1,512]\n norm_diff = detect_embeds.unsqueeze(-1) - torch.transpose(local_embeds, 0, 1).unsqueeze(0)\n norm_score = torch.sum(torch.pow(norm_diff, 2), dim=1)\n min_dist, embed_idx = torch.min(norm_score, dim=1)\n print(min_dist * power, names[embed_idx])\n if min_dist * power > threshold:\n return -1, -1\n else:\n return embed_idx, min_dist.double()\n\n\n def extract_face(box, img, margin=20):\n face_size = 160\n img_size = frame_size\n margin = [\n margin * (box[2] - box[0]) / (face_size - margin),\n margin * (box[3] - box[1]) / (face_size - margin),\n ]\n box = [\n int(max(box[0] - margin[0] / 2, 0)),\n int(max(box[1] - margin[1] / 2, 0)),\n int(min(box[2] + margin[0] / 2, img_size[0])),\n int(min(box[3] + margin[1] / 2, img_size[1])),\n ]\n img = img[box[1]:box[3], box[0]:box[2]]\n face = cv2.resize(img, (face_size, face_size), interpolation=cv2.INTER_AREA)\n face = Image.fromarray(face)\n return face\n\n\n if __name__ == \"__main__\":\n power = pow(10, 6)\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n print(device)\n\n model = InceptionResnetV1(\n classify=False,\n pretrained=\"casia-webface\"\n ).to(device)\n model.eval()\n\n # BUG*****\n mtcnn = MTCNN(thresholds=[0.7, 0.7, 0.8], keep_all=False, device=device)\n\n cap = cv2.VideoCapture(0)\n cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)\n cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)\n embeddings, names = load_faceslist()\n while cap.isOpened():\n isSuccess, frame = cap.read()\n if isSuccess:\n boxes, _ = mtcnn.detect(frame)\n if boxes is not None:\n for box in boxes:\n bbox = list(map(int, box.tolist()))\n face = extract_face(bbox, frame)\n idx, score = inference(model, face, embeddings)\n if idx != -1:\n frame = cv2.rectangle(frame, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 0, 255), 6)\n score = torch.Tensor.cpu(score[0]).detach().numpy() * power\n frame = cv2.putText(frame, names[idx] + '_{:.2f}'.format(score), (bbox[0], bbox[1]),\n cv2.FONT_HERSHEY_DUPLEX, 2, (0, 255, 0), 2, cv2.LINE_8)\n\n else:\n frame = cv2.rectangle(frame, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 0, 255), 6)\n frame = cv2.putText(frame, 'Unknown', (bbox[0], bbox[1]), cv2.FONT_HERSHEY_DUPLEX, 2,\n (0, 255, 0), 2, cv2.LINE_8)\n\n cv2.imshow('Face Recognition', frame)\n if cv2.waitKey(1) & 0xFF == 27:\n break\n\n cap.release()\n cv2.destroyAllWindows()\n","sub_path":"face_recogntion.py","file_name":"face_recogntion.py","file_ext":"py","file_size_in_byte":4296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"539289659","text":"import unittest\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.webdriver.support.ui import WebDriverWait\nimport time\nfrom faker import Faker\n\nfake = Faker()\n\nname = \"Anna\"\nsurname = \"Nowak\"\ncountry = \"United States\"\nphone = \"123456789\"\nemail = fake.email()\npassword = \"12345\"\n\n\nclass WizzairRegistration(unittest.TestCase):\n\n def setUp(self) -> None:\n self.driver = webdriver.Chrome()\n self.driver.get(\"https://wizzair.com/pl-pl#/\")\n self.driver.maximize_window()\n self.driver.implicitly_wait(20)\n\n def testIncorrectEmail(self):\n\n # Kliknij \"Zaloguj się\"\n signin = self.driver.find_element_by_xpath(\"/html/body/div[2]/div/header/div[1]/div/nav/ul/li[11]/button\")\n signin.click()\n\n # Kliknij \"Rejestracja\"\n registration = self.driver.find_element_by_xpath(\"/html/body/div[2]/span/article/div/div/div/form/p/button\")\n registration.click()\n\n # Wpisz imię\n name_input = self.driver.find_element_by_xpath(\"/html/body/div[2]/span/article/div/div/div/form/div[2]/div[1]/label[1]/div[1]/input\")\n name_input.send_keys(name)\n\n # Wpisz nazwisko\n surname_input = self.driver.find_element_by_xpath(\"/html/body/div[2]/span/article/div/div/div/form/div[2]/div[1]/label[2]/div[1]/input\")\n surname_input.send_keys(surname)\n\n # Wybierz płeć\n gender_female = self.driver.find_element_by_xpath(\"/html/body/div[2]/span/article/div/div/div/form/div[3]/div[1]/label[1]/span\")\n gender_female.click()\n\n # Wybierz kod kraju\n\n\n\n # Wpisz numer\n phone_input = self.driver.find_element_by_xpath(\"/html/body/div[2]/span/article/div/div/div/form/div[4]/div[2]/div/div[1]/div/label/input\")\n phone_input.send_keys(phone)\n\n time.sleep(2)\n\n print(\"OK\")\n\n def tearDown(self) -> None:\n self.driver.close()\n\n\nif __name__ == \"__main__\":\n unittest.main(verbosity=2)","sub_path":"PycharmProjects/AutomationPractice/wizzairRegistration.py","file_name":"wizzairRegistration.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"11057259","text":"from pyquery import PyQuery as pq\nimport re\nimport urllib.request\nimport os\nimport shutil\nimport time\nimport multiprocessing\n\nbaseUrl = 'http://manhua.fzdm.com/91/'\ncomicName = \"美食的俘虏\"\n\ndef _writeLog(log, lock):\n with lock:\n with open(\"__log__.txt\", \"a\") as f:\n f.write(log)\n\ndef _parseChapterList(titleList, hrefList, lock):\n for index in range(len(titleList)):\n title = titleList[index]\n href = hrefList[index]\n _parseOneChapter(title, href, lock)\n\ndef _parseOneChapter(title, href, lock):\n rootDirPath = os.getcwd()\n title = comicName + \"\\\\\" + title\n if not os.path.exists(title):\n os.makedirs(title)\n else:\n print(\"%s already exist\" % (title))\n\n\n dirPath = rootDirPath + \"\\\\\" + title\n print(title + \" ----\" + href)\n\n docComic = pq(href)\n navigation = docComic('div.navigation')\n pageUrlList = []\n\n pageIndex = 0\n\n while True:\n pageIndex += 1\n pageHref = \"%sindex_%d.html\" % ( href, pageIndex - 1)\n if not pageHref in pageUrlList:\n pageUrlList.append(pageHref)\n print(pageHref)\n\n 'http://manhua.fzdm.com/17/011/index_0.html'\n\n jsStrContainsMhurl = \"\"\n\n f = None\n try:\n with urllib.request.urlopen(pageHref) as f:\n docxx = pq(f.read())\n for x in docxx(\"script\").items():\n if \"var mhurl\" in x.text():\n jsStrContainsMhurl = x.text()\n ''' print (jsStrContainsMhurl) '''\n break\n except Exception as e:\n if f:\n print(f.code)\n\n\n if not jsStrContainsMhurl:\n break\n\n m = re.search('var mhurl = \\\"(.*)\\\"', jsStrContainsMhurl)\n mhurl = m.group(1)\n\n mhss = \"p1.xiaoshidi.net\"\n\n if mhurl.startswith('2015') or mhurl.startswith('2016') or mhurl.startswith('2017'):\n mhss = \"p1.xiaoshidi.net\"\n else:\n mhss = \"s1.nb-pintai.com\"\n\n imgUrl = \"http://\" + mhss + \"/\" + mhurl;\n print(imgUrl)\n\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36\",\n \"Host\": mhss,\n \"Accept-Language\": \"zh-CN,zh;q=0.8\",\n \"Cache-Control\": \"no-cache\",\n \"Connection\": \"keep-alive\",\n \"Referer\": imgUrl,\n \"Upgrade-Insecure-Requests\": \"1\"\n }\n req = urllib.request.Request(imgUrl, None, headers)\n _downOnePic(dirPath, pageIndex, req, imgUrl, lock)\n '''\n with urllib.request.urlopen(req, None, 10) as f:\n with open(\"%s\\\\%d.jpg\" % (dirPath, pageIndex), \"ab\") as file:\n file.write(f.read())\n '''\n\ndef _downOnePic(dirPath, pageIndex, req, imgUrl, lock):\n destFilePath = \"%s\\\\%d.jpg\" % (dirPath, pageIndex)\n\n if os.path.exists(destFilePath):\n if os.path.getsize(destFilePath) == 0:\n os.remove(destFilePath)\n print('delete empty pic file')\n else:\n print ('picture already exist')\n return;\n\n retryTime = 0\n timeOutTime = 5\n while True:\n f = None\n try:\n print(\"%a----dowing...\" % (imgUrl))\n with urllib.request.urlopen(req, None, timeOutTime) as f:\n with open(destFilePath, \"ab\") as file:\n file.write(f.read())\n print(\"%a----saved\" % (imgUrl))\n '''\n _writeLog(\"%s\\\\%d.jpg ----- successfully saved\\n\" % (dirPath, pageIndex), lock);\n '''\n file.close()\n if os.path.exists(destFilePath):\n if os.path.getsize(destFilePath) == 0:\n _writeLog('download empty pic file---%s---%s' % (destFilePath, imgUrl))\n\n return\n except Exception as e:\n if f:\n print(f.code)\n\n if retryTime == 4:\n _writeLog(\"%s\\\\%d.jpg ----- %s ------ save failed!!!!!!!!!!!!!\\n\" % (dirPath, pageIndex, imgUrl), lock);\n return\n time.sleep(2)\n retryTime += 1\n timeOutTime += 30\n print(\"%a----retry---- %d times----\" % (imgUrl, retryTime))\n\ndef comicSpider():\n doc = pq(baseUrl)\n\n chapterTitleList = []\n chapterUrlList = []\n\n for item in doc('li.pure-u-1-2')('a').items():\n title = item.attr('title')\n href = baseUrl + item.attr('href')\n chapterTitleList.append(title)\n chapterUrlList.append(href)\n\n size = len(chapterTitleList)\n PROCESS_COUNT = 20\n blockSize = int(size / PROCESS_COUNT)\n\n processList = []\n lock = multiprocessing.Lock()\n end = 0\n for blockIndex in range(PROCESS_COUNT):\n subTileList = []\n subUrlList = []\n\n start = blockIndex * blockSize\n if blockIndex < PROCESS_COUNT - 1:\n end = start + blockSize - 1\n else:\n end = size - 1\n\n subTileList = chapterTitleList[start: end+1]\n subUrlList = chapterUrlList[start: end+1]\n '''\n _parseChapterList(subTileList, subUrlList)\n '''\n\n p = multiprocessing.Process(target=_parseChapterList, args=(subTileList, subUrlList, lock))\n p.start()\n processList.append(p)\n\n for pp in processList:\n pp.join()\n print(\"end\")\n\n'''\n _parseOnChapter(title, href)\n'''\n\nif __name__ == \"__main__\":\n comicSpider()\n\n\n\n'''\nprint (doc('div#mhimg0')('a').attr('href'))\n'''\n\n\n\n","sub_path":"myPythonDemos/fengzhidongman/manhua.fzdm.com_spider.py","file_name":"manhua.fzdm.com_spider.py","file_ext":"py","file_size_in_byte":5757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"108330483","text":"from selenium import webdriver\r\nimport time\r\nimport math\r\n\r\n\r\ndef script_1():\r\n try:\r\n browser = webdriver.Chrome()\r\n browser.execute_script(\"document.title='Script executing';alert('Robots at work');\")\r\n finally:\r\n time.sleep(3)\r\n browser.quit()\r\n\r\n\r\ndef script_2():\r\n browser = webdriver.Chrome()\r\n link = \"https://SunInJuly.github.io/execute_script.html\"\r\n browser.get(link)\r\n button = browser.find_element_by_tag_name(\"button\")\r\n browser.execute_script(\"return arguments[0].scrollIntoView(true);\", button)\r\n button.click()\r\n time.sleep(3)\r\n # Эта команда проскроллит страницу на 100 пикселей вниз:\r\n # browser.execute_script(\"window.scrollBy(0, 100);\")\r\n\r\n\r\ndef script_3():\r\n link = \"http://suninjuly.github.io/execute_script.html\"\r\n try:\r\n browser = webdriver.Chrome()\r\n browser.get(link)\r\n x = int(browser.find_element_by_id(\"input_value\").text)\r\n answer = math.log((abs(12*math.sin(x))))\r\n answer_edit = browser.find_element_by_id(\"answer\")\r\n answer_edit.send_keys(str(answer))\r\n checkbox = browser.find_element_by_id(\"robotCheckbox\")\r\n browser.execute_script(\"return arguments[0].scrollIntoView(true);\", checkbox)\r\n checkbox.click()\r\n radio = browser.find_element_by_id(\"robotsRule\")\r\n radio.click()\r\n button = browser.find_element_by_css_selector(\"button.btn\")\r\n button.click()\r\n finally:\r\n time.sleep(5)\r\n browser.quit()","sub_path":"script_execute.py","file_name":"script_execute.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"339703918","text":"'''\nWrite a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month.\nThe following variables contain values as described below:\n\nbalance - the outstanding balance on the credit card\n\nannualInterestRate - annual interest rate as a decimal\n\nmonthlyPaymentRate - minimum monthly payment rate as a decimal\n\nFor each month, calculate statements on the monthly payment and remaining balance. At the end of 12 months, print out the remaining balance.\n'''\ndef balancecalculator(balance,annualInterestRate,monthlyPaymentRate):\n \n \n counter = 0\n while(counter < 12 ):\n \n balance = balance + balance*(annualInterestRate/12)\n balance = balance - balance*monthlyPaymentRate\n balance = round(balance,2)\n \n counter = counter + 1\n print(balance) \n return balance\n\n \nbalancecalculator(42, 0.2, 0.04)\n","sub_path":"payingoffdebtyear.py","file_name":"payingoffdebtyear.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"20863270","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 time\nfrom openerp.report import report_sxw\nfrom openerp.osv import osv\nfrom openerp import pooler\n\nclass fleet_aditionals(report_sxw.rml_parse):\n _name = 'report.fleet.aditionals'\n\n def __init__(self, cr, uid, name, context):\n super(fleet_aditionals, self).__init__(cr, uid, name, context=context)\n self.localcontext.update({\n 'time': time,\n 'get_adds': self._get_adds,\n })\n self.context = context\n\n def _get_adds(self,vehicle,data):\n res = []\n for line in vehicle.aditional_ids:\n values = {\n 'name' : line.name,\n 'serial' : line.serial,\n 'type': line.type_id.name,\n 'brand': line.brand_id.name,\n 'use': line.use_id.name,\n 'size':line.size,\n 'date_in': line.date_in,\n }\n res.append(values)\n return res\n\nreport_sxw.report_sxw('report.fleet.aditionals','fleet.vehicle', parser=fleet_aditionals, header='header', rml='herrera_fleet/report/fleet_aditionals.rml')\n","sub_path":"herrera_fleet/report/fleet_aditionals.py","file_name":"fleet_aditionals.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"41325339","text":"import scipy.io\nimport scipy\nfrom control import matlab,tf\nimport control\nfrom control import StateSpace\nimport numpy as np\nfrom scipy import signal\nimport matplotlib.pyplot as plt\n\n# Read linearized model as ABCD matrix\n\ndef tf(ss,start,end):\n mat_dict = scipy.io.loadmat(\"./linmod_noctrl.mat\")\n st = mat_dict['linss']\n A,B,C,D,statename,outputname,inputname,operpoint,ts = st[0][0]\n ss = control.matlab.ss(A, B, C, D)\n inputname = np.asarray([i[0][0] for i in inputname])\n outputname = np.asarray([i[0][0] for i in outputname])\n \n idx_from = np.where(inputname==start)[0][0]\n idx_to = np.where(outputname==end)[0][0]\n print('From :',idx_from,inputname[idx_from])\n print('To :',idx_to,outputname[idx_to])\n out = ss.returnScipySignalLTI()\n ss = out[idx_to][idx_from]\n ss_siso = control.ss(ss.A,ss.B,ss.C,ss.D)\n return ss_siso\n\nif __name__ == '__main__':\n mat_dict = scipy.io.loadmat(\"./linmod/noctrl.mat\")\n st = mat_dict['linss']\n A,B,C,D,statename,outputname,inputname,operpoint,ts = st[0][0]\n ss = control.matlab.ss(A, B, C, D)\n inputname = np.asarray([i[0][0] for i in inputname])\n outputname = np.asarray([i[0][0] for i in outputname])\n #print(filter(lambda x: 'accGndL' in x, inputname))\n start = 'controlmodel/accGndL'\n end = 'controlmodel/dispTML'\n idx_from = np.where(inputname==start)[0][0]\n idx_to = np.where(outputname==end)[0][0]\n print('From :',idx_from,inputname[idx_from])\n print('To :',idx_to,outputname[idx_to])\n out = ss.returnScipySignalLTI()\n ss = out[idx_to][idx_from]\n ss_siso = control.ss(ss.A,ss.B,ss.C,ss.D)\n \n # Plot\n wrap = lambda phases : ( phases + np.pi) % (2 * np.pi ) - np.pi\n f = np.logspace(-3,1,1001)\n mag, phase,w = matlab.bode(ss_siso,f*2.0*np.pi,Plot=False)\n mag = mag*(w**2)\n phase = np.rad2deg(wrap(phase-np.pi))\n fig,(ax0,ax1) = plt.subplots(2,1)\n f = w/2.0/np.pi\n ax0.loglog(f,mag)\n ax1.semilogx(f,phase)\n ax0.set_xlim(1e-2,1e1)\n ax1.set_xlim(1e-2,1e1)\n ax0.set_ylim(1e-4,1e1)\n ax1.set_ylim(-181,181)\n ax1.set_yticks(range(-180,181,90))\n ax1.grid(which='major',color='black',linestyle='-')\n ax1.grid(which='minor',color='black',linestyle=':')\n ax0.grid(which='major',color='black',linestyle='-')\n ax0.grid(which='minor',color='black',linestyle=':')\n plt.savefig('TF.png')\n plt.close()\n","sub_path":"model/typeA/example_plottf.py","file_name":"example_plottf.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"535803575","text":"# -*- coding: utf8 -*-\n##################################################################\n## Create 2016.03.07 Holmes.\n##################################################################\nfrom PySide.QtGui import *\nfrom PySide.QtCore import *\n\nclass MysqlAddKeys(QDialog,QWidget):\n\tdef __init__(self):\n\t\tsuper(MysqlAddKeys,self).__init__()\n\t\tself.setWindowTitle(\"Identification Of Harmful Information System\")\n\t\tself.initgui()\n\t\tself.setIcon()\n\n\tdef center(self):\n\t\tself.qRect = self.frameGeometry()\n\t\tself.centerPoint = QDesktopWidget().availableGeometry().center()\n\t\tself.qRect.moveCenter(self.centerPoint)\n\t\tself.move(self.qRect.topLeft())\n\n\tdef setIcon(self):\n\t\t#设置icon\n\t\tappIcon = QIcon(\"res/icon/icon.png\")\n\t\tself.setWindowIcon(appIcon)\n\n\tdef keys(self):\n\t\tfrom core.KeyWordsHandle.AddNewKey import addNewKey\n\t\tword = self.wordEdit.text()\n\t\tspeech = self.speechEdit.text()\n\t\tlevel = self.levelEdit.text()\n\t\tif word == \"\":\n\t\t\tQMessageBox.about(self,\"Enter Error\",\"\\nPlease enter word.\\n[word] Is the key.\")\n\t\telif speech == \"\":\n\t\t\tQMessageBox.about(self,\"Enter Error\",\"\\nPlease enter speech.\\n[speech] Is the key speech.\")\n\t\telif level == \"\":\n\t\t\tQMessageBox.about(self,\"Enter Error\",\"\\nPlease enter level.\\n[level] Is the key word hazard level.\")\n\t\tif (word != \"\") & (speech != \"\") & (level != \"\"):\n\t\t\tresult = addNewKey(word,speech,level)\n\t\t\tif result == \"success\":\n\t\t\t\tself.info.hide()\n\t\t\t\tself.info = QLabel(\"[+] [%s %s %s] write success.\"%(word,speech,level))\n\t\t\t\tself.info.setFont(QFont(\"Times New Roman\",16,QFont.Bold))\n\t\t\t\tself.layout.addWidget(self.info,4,2,1,1)\n\t\t\telif result == \"exists\":\n\t\t\t\tself.info.hide()\n\t\t\t\tself.info = QLabel(\"[+] [%s %s %s] already exists.\"%(word,speech,level))\n\t\t\t\tself.info.setFont(QFont(\"Times New Roman\",16,QFont.Bold))\n\t\t\t\tself.layout.addWidget(self.info,4,2,1,1)\n\n\tdef initgui(self):\n\t\t(x, y, w, h) = (300, 300, 1010, 480)\n\t\tself.setGeometry(x, y, w, h)\n\t\tself.center()\n\n\t\tself.style = \"\"\"\n\t\tQPushButton{\n\t\tcolor:#FFFFFF;\n\t\tborder:1px solid #2e6da4;\n\t\tborder-radius:4px;\n\t\tfont:bold;\n\t\tfont-size:24px;\n\t\tfont-family:Time News Romen;\n\t\tbackground:qlineargradient(spread:pad,x1:0,y1:0,x2:0,y2:1,stop:0 #2e6da4,stop:1 #437ab7);\n\t\t}\n\n\t\tQPushButton:hover{\n\t\tbackground:qlineargradient(spread:pad,x1:0,y1:0,x2:0,y2:1,stop:0 #2e6da4,stop:1 #2e6da4);\n\t\t}\n\t\t\"\"\"\n\n\t\tself.setWindowTitle(\"KeyWords Add\")\n\t\tself.setWindowFlags(Qt.WindowSystemMenuHint | Qt.MSWindowsFixedSizeDialogHint | Qt.FramelessWindowHint)\n\n\t\tself.word = QLabel(\"KeyWord\")\n\t\tself.speech = QLabel(\"speech\")\n\t\tself.level = QLabel(\"Level\")\n\t\tself.info = QLabel()\n\n\t\tself.zkLabel = QLabel(\"\")\n\t\tself.zkLabel2 = QLabel()\n\t\tself.zkLabel.setFixedSize(128,128)\n\n\t\tself.word.setFont(QFont(\"Times New Roman\",16,QFont.Bold))\n\t\tself.speech.setFont(QFont(\"Times New Roman\",16,QFont.Bold))\n\t\tself.level.setFont(QFont(\"Times New Roman\",16,QFont.Bold))\n\t\tself.info.setFont(QFont(\"Times New Roman\",16,QFont.Bold))\n\n\t\tself.wordEdit = QLineEdit(unicode(\"冰毒\",\"utf8\"))\n\t\tself.speechEdit = QLineEdit(\"noun\")\n\t\tself.levelEdit = QLineEdit(\"5\")\n\n\t\tself.wordEdit.setFixedSize(360, 36)\n\t\tself.speechEdit.setFixedSize(360, 36)\n\t\tself.levelEdit.setFixedSize(360, 36)\n\n\t\tself.wordEdit.setFont(QFont(\"Times New Roman\",15))\n\t\tself.speechEdit.setFont(QFont(\"Times New Roman\",15))\n\t\tself.levelEdit.setFont(QFont(\"Times New Roman\",15))\n\n\t\tself.addkey = QPushButton(\"Add Key\")\n\t\tself.addkey.setStyleSheet(self.style)\n\t\tself.addkey.setFixedSize(QSize(240, 128))\n\n\t\tself.layout = QGridLayout()\n\n\t\tself.layout.addWidget(self.zkLabel,0,0,1,6)\n\t\tself.layout.addWidget(self.zkLabel2,0,0,1,6)\n\n\t\tself.layout.addWidget(self.word,1,1,1,1,4)\n\t\tself.layout.addWidget(self.wordEdit,1,2,1,1,4)\n\n\t\tself.layout.addWidget(self.speech,2,1,1,1,4)\n\t\tself.layout.addWidget(self.speechEdit,2,2,1,1,4)\n\n\t\tself.layout.addWidget(self.level,3,1,1,1,4)\n\t\tself.layout.addWidget(self.levelEdit,3,2,1,1,4)\n\n\t\tself.layout.addWidget(self.addkey,1,3,3,1,4)\n\n\t\tself.layout.addWidget(self.info,4,2,1,1)\n\n\n\n\t\tself.setLayout(self.layout)\n\n\t\tself.addkey.clicked.connect(self.keys)\n\n\t\tcloseb = \"\"\"\n\t\tQPushButton{\n\t\tcolor:#FFFFFF;\n\t\tborder:1px solid #d9534f;\n\t\tborder-radius:4px;\n\t\tfont:bold;\n\t\tfont-size:15px;\n\t\tfont-family:Time News Romen;\n\t\tbackground:qlineargradient(spread:pad,x1:0,y1:0,x2:0,y2:1,stop:0 #d9534f,stop:1 #d9534f);\n\t\t}\n\n\t\tQPushButton:hover{\n\t\tbackground:qlineargradient(spread:pad,x1:0,y1:0,x2:0,y2:1,stop:0 #C0392B,stop:1 #C0392B);\n\t\t}\n\t\t\"\"\"\n\n\t\taboutb = \"\"\"\n\t\tQPushButton{\n\t\tcolor:#FFFFFF;\n\t\tborder:1px solid #f0ad4e;\n\t\tborder-radius:4px;\n\t\tfont:bold;\n\t\tfont-size:15px;\n\t\tfont-family:Time News Romen;\n\t\tbackground:qlineargradient(spread:pad,x1:0,y1:0,x2:0,y2:1,stop:0 #f0ad4e,stop:1 #f0ad4e);\n\t\t}\n\n\t\tQPushButton:hover{\n\t\tbackground:qlineargradient(spread:pad,x1:0,y1:0,x2:0,y2:1,stop:0 #E67E22,stop:1 #E67E22);\n\t\t}\n\t\t\"\"\"\n\t\tcloseButton = QPushButton(unicode(\"Exit\",\"utf8\"),self)\n\t\tcloseButton.move(10, 10)\n\t\tcloseButton.setFixedSize(QSize(64, 32))\n\t\tcloseButton.setStyleSheet(closeb)\n\t\tcloseButton.clicked.connect(self.close)\n\n\t\taboutButton = QPushButton(unicode(\"About\",\"utf8\"),self)\n\t\taboutButton.move(84, 10)\n\t\taboutButton.setFixedSize(QSize(64, 32))\n\t\taboutButton.setStyleSheet(aboutb)\n\t\taboutButton.clicked.connect(self.showAbout)\n\t\t\n\tdef showAbout(self):\n\t\tQMessageBox.about(self, \"About Holmes\",\"Version : 1.0.\\nOwner : Holmes.\\nE-mail : vii26@outlook.com\\nIf you have any questions, please send me.\")\n\nif __name__ == '__main__':\n\timport sys\n\ttry:\n\t\tmyApp = QApplication(sys.argv)\n\t\tmyWindow = MysqlAddKeys()\n\t\tmyWindow.show()\n\t\tmyApp.exec_()\n\t\tsys.exit(0)\n\n\texcept NameError:\n\t\tprint(\"NameError:\", sys.exc_info()[1])\n\texcept SystemExit:\n\t\tprint(\"Closing Window...\")\n\texcept Exception:\n\t\tprint(sys.exc_info()[1])","sub_path":"core/gui/MysqlAddKeys.py","file_name":"MysqlAddKeys.py","file_ext":"py","file_size_in_byte":5673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"431641135","text":"from unittest import TestCase\nfrom modules.ms.one_note.one_note import OneNote\n\nclass TestOneNote(TestCase):\n def setUp(self) -> None:\n self.oneNote = OneNote()\n self.notebook = \"TestNotebook\"\n self.section = \"TestSection\"\n self.nameForRead = \"TestPage\"\n self.nameForModification = \"ModificationPage\"\n\n def test_can_get_page(self):\n page = self.oneNote.getPage(self.notebook, self.section, self.nameForRead)\n self.assertIsNotNone(page)\n\n def test_can_get_content_of_page(self):\n validation_text = \"Text for validation\"\n page = self.oneNote.getPage(self.notebook, self.section, self.nameForRead)\n text = page.getText()\n self.assertNotEqual(text.find(validation_text), -1)\n\n def test_can_modify_content_of_page(self):\n page = self.oneNote.getPage(self.notebook, self.section,\n self.nameForModification)\n modification_text = \"TextForModification\"\n text = page.getText()\n self.assertNotEqual(text.find(modification_text), -1)\n\n paragraphs = page.getParagraphs()\n updated_paragraph = paragraphs[0]\n updated_paragraph['text'] = \"New text\"\n page.updateContent(updated_paragraph)\n","sub_path":"tests/test_one_note.py","file_name":"test_one_note.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"559712900","text":"#%%\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom __future__ import print_function\n\nfrom tensorflow.keras.applications.vgg16 import VGG16\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import Sequential \n\nimport tensorflow as tf\nimport pandas as pd\nimport numpy as np\nimport os\nimport shutil\n\nprint('Tensorflow version: ', tf.VERSION)\n\nlearning_rate = 1e-3\nbatch_size = 20\nepochs = 80\nsteps_per_epoch = 1000\nimg_height = 256\nimg_width = 256\nimg_channels = 3\n\n# 为了测试代码,我们先不使用整个数据集,而是从原始数据集中划分出一小部分数据进行测试\nbase_dir = 'C:/Users/Admin/Downloads/dogvscat'\noriginal_dir = os.path.join(base_dir, 'train')\n\ntrain_dir = os.path.join(base_dir, 'small_train')\neval_dir = os.path.join(base_dir, 'small_eval')\ntest_dir = os.path.join(base_dir, 'test')\n\n#%%\n# if not os.path.exists(eval_dir):\n# os.mkdir(train_dir)\n# os.mkdir(eval_dir)\n\n# for i in range(2500, 12500):\n# name = 'cat.{}.jpg'.format(i)\n# src = os.path.join(original_dir, name)\n# if i < 2000:\n# dst = os.path.join(train_dir, name)\n# else:\n# dst = os.path.join(eval_dir, name)\n# shutil.copyfile(src, dst)\n\n# for i in range(2500, 12500):\n# name = 'dog.{}.jpg'.format(i)\n# src = os.path.join(original_dir, name)\n# if i < 2000:\n# dst = os.path.join(train_dir, name)\n# else:\n# dst = os.path.join(eval_dir, name)\n# shutil.copyfile(src, dst)\n\n#%%\ndef unison_shuffled_copies(a, b):\n a = np.array(a)\n b = np.array(b)\n assert len(a) == len(b)\n p = np.random.permutation(len(a))\n return a[p], b[p]\n\nfiles = os.listdir(train_dir)\ntrain_files = [os.path.join(train_dir, name) for name in files]\ntrain_labels = np.array(['dog' in name for name in files]).astype(np.float)\ntrain_files, train_labels = unison_shuffled_copies(train_files, train_labels)\n\nfiles = os.listdir(eval_dir)\neval_files = [os.path.join(eval_dir, name) for name in files]\neval_labels = np.array(['dog' in name for name in files]).astype(np.float)\neval_files, eval_labels = unison_shuffled_copies(eval_files, eval_labels)\n\nfiles = ['{}.jpg'.format(i) for i in range(1, 12501)]\ntest_files = [os.path.join(test_dir, name) for name in files]\ntest_labels = np.array([-1] * len(files)).astype(np.float)\n#%%\ndef image_input_fn(filenames, labels=None, shuffle=False, repeat_count=1, batch_size=1):\n def _read_img(filename, label=None):\n img_raw = tf.read_file(filename)\n img = tf.image.decode_image(img_raw, channels=3)\n img.set_shape([None, None, None])\n img = tf.image.resize_images(img, [img_height, img_width])\n img = tf.divide(img, 255.)\n img.set_shape([img_height, img_width, img_channels])\n if label is None:\n return img\n else:\n return img, label\n if labels is None:\n dataset = tf.data.Dataset.from_tensor_slices(filenames)\n else:\n dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))\n dataset = dataset.map(_read_img)\n if shuffle:\n dataset = dataset.shuffle(2000)\n dataset = dataset.batch(batch_size).repeat(repeat_count)\n return dataset\n\n# vgg16 = VGG16(\n# weights='imagenet',\n# include_top=False,\n# input_shape=(img_height, img_width, img_channels))\n# model = Sequential([\n# vgg16,\n# layers.Flatten(),\n# layers.Dropout(0.5),\n# layers.Dense(1, activation='sigmoid')\n# ])\n# vgg16.trainable = False\n\nmodel = Sequential([\n layers.Conv2D(32, 3, 1, padding='SAME', activation='relu', input_shape=(img_height, img_width, img_channels)),\n layers.MaxPool2D(strides=2, padding='SAME'),\n layers.Dropout(0.5),\n\n layers.Conv2D(64, 3, 1, padding='SAME', activation='relu'),\n layers.MaxPool2D(strides=2, padding='SAME'),\n layers.Dropout(0.5),\n \n layers.Conv2D(128, 3, 1, padding='SAME', activation='relu'),\n layers.MaxPool2D(strides=2, padding='SAME'),\n layers.Dropout(0.5),\n\n layers.Flatten(),\n layers.Dense(512, activation='relu'),\n layers.Dropout(0.5),\n layers.Dense(1, activation='sigmoid')\n])\n\nmodel.summary()\n\nmodel.compile(\n optimizer=tf.train.AdamOptimizer(learning_rate),\n loss='binary_crossentropy',\n metrics=['acc'])\n\nMODEL_DIR = './model/'\ncheckpoint_path = MODEL_DIR + \"cp-{epoch:04d}.ckpt\"\ncp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path, \n monitor='val_loss',\n save_best_only=True,\n verbose=1, \n save_weights_only=True, \n period=5)\n\n# model.load_weights('./model/cp-0040.ckpt')\n\nmodel.fit(\n image_input_fn(\n train_files, \n train_labels,\n shuffle=True, \n repeat_count=epochs,\n batch_size=batch_size), \n validation_data=image_input_fn(\n eval_files,\n eval_labels,\n shuffle=False,\n repeat_count=epochs,\n batch_size=50),\n epochs=epochs,\n steps_per_epoch=steps_per_epoch,\n validation_steps=100,\n callbacks=[cp_callback])\n#%%\nresult = model.predict(\n image_input_fn(\n test_files,\n test_labels,\n shuffle=False,\n batch_size=50), \n steps=250)\n\npath = './submission.csv'\ncounter = range(1, len(result) + 1)\nresult = np.array(result, np.float)\nresult = np.squeeze(result)\n\ndef limit(x):\n if x < 0.005:\n return 0.005\n elif x > 0.995:\n return 0.995\n else:\n return x\n\ndf = pd.DataFrame({'id': counter, 'label': result})\ndf['label'] = df['label'].map(limit)\n\nfile = df.to_csv(path_or_buf=None, index=None)\nwith tf.gfile.Open(path, 'w') as f:\n f.write(file)\n\nprint('Mission Accomplished!')","sub_path":"code/dogcat/dogcat.py","file_name":"dogcat.py","file_ext":"py","file_size_in_byte":5868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"172573079","text":"from euler import phi\nfrom time import time\nT = time()\n\n\n# length of the farey sequence F_n\ndef farey_length(n):\n res = 1\n for m in range(1, n+1):\n res += phi(m)\n\n return res-2 # discount the endpoints due to the exercise\n\n\nprint(farey_length(10**6))\nprint(\"time elapsed:\", time() - T)\n","sub_path":"072.py","file_name":"072.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"60962889","text":"\"\"\"\nMIT License\n\nCopyright (c) 2020 Hyeonki Hong \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\nfrom os import path\nimport time\nfrom typing import Union\n\nimport cv2\nimport numpy as np\n\ntry:\n import tensorflow.lite as tflite\nexcept ModuleNotFoundError:\n import tflite_runtime.interpreter as tflite\n\nfrom ..common import media, predict\nfrom ..common.base_class import BaseClass\n\n\nclass YOLOv4(BaseClass):\n def __init__(self, tiny: bool = False, tpu: bool = False):\n \"\"\"\n Default configuration\n \"\"\"\n super(YOLOv4, self).__init__(tiny=tiny, tpu=tpu)\n self.grid_coord = []\n self.input_index = None\n self.interpreter = None\n self.output_index = None\n self.output_size = None\n\n def load_tflite(self, tflite_path):\n if self.tpu:\n self.interpreter = tflite.Interpreter(\n model_path=tflite_path,\n experimental_delegates=[\n tflite.load_delegate(\"libedgetpu.so.1\")\n ],\n )\n else:\n self.interpreter = tflite.Interpreter(model_path=tflite_path)\n self.interpreter.allocate_tensors()\n input_details = self.interpreter.get_input_details()[0]\n self.input_size = input_details[\"shape\"][1]\n self.input_index = input_details[\"index\"]\n output_details = self.interpreter.get_output_details()\n self.output_index = [details[\"index\"] for details in output_details]\n if self.tpu:\n # sig, raw, sig, raw, ...\n self.output_size = [\n output_details[2 * i][\"shape\"][1]\n for i in range(len(output_details) // 2)\n ]\n self.grid_coord = []\n for _size in self.output_size:\n xy_grid = np.meshgrid(np.arange(_size), np.arange(_size))\n xy_grid = np.stack(xy_grid, axis=-1)\n xy_grid = xy_grid[np.newaxis, ...]\n self.grid_coord.append(xy_grid)\n\n #############\n # Inference #\n #############\n\n def tpu_hair(self, x):\n x = [np.split(_x, 3, axis=-1) for _x in x]\n\n for i in range(len(self.output_size)):\n for j in range(3):\n # pylint: disable=unbalanced-tuple-unpacking\n # sig\n txty, _, conf_prob = np.split(x[2 * i][j], (2, 4), axis=-1)\n # raw\n _, twth, _ = np.split(x[2 * i + 1][j], (2, 4), axis=-1)\n txty = (txty - 0.5) * self.xyscales[i] + 0.5\n bxby = (txty + self.grid_coord[i]) / self.output_size[i]\n bwbh = (self.anchors[i][j] / self.input_size) * np.exp(twth)\n x[2 * i][j] = np.concatenate([bxby, bwbh, conf_prob], axis=-1)\n\n pred = [\n np.concatenate(x[2 * i], axis=-1)\n for i in range(len(self.output_size))\n ]\n return pred\n\n def predict(self, frame: np.ndarray):\n \"\"\"\n Predict one frame\n\n @param frame: Dim(height, width, channels)\n\n @return pred_bboxes == Dim(-1, (x, y, w, h, class_id, probability))\n \"\"\"\n # image_data == Dim(1, input_szie, input_size, channels)\n image_data = self.resize_image(frame)\n image_data = image_data / 255\n image_data = image_data[np.newaxis, ...].astype(np.float32)\n\n # s_pred, m_pred, l_pred\n # x_pred == Dim(1, output_size, output_size, anchors, (bbox))\n self.interpreter.set_tensor(self.input_index, image_data)\n self.interpreter.invoke()\n candidates = [\n self.interpreter.get_tensor(index) for index in self.output_index\n ]\n if self.tpu:\n candidates = self.tpu_hair(candidates)\n _candidates = []\n for candidate in candidates:\n grid_size = candidate.shape[1]\n _candidates.append(\n np.reshape(candidate[0], (1, grid_size * grid_size * 3, -1))\n )\n candidates = np.concatenate(_candidates, axis=1)\n\n pred_bboxes = self.candidates_to_pred_bboxes(candidates[0])\n pred_bboxes = self.fit_pred_bboxes_to_original(pred_bboxes, frame.shape)\n return pred_bboxes\n\n def inference(self, media_path, is_image=True, cv_waitKey_delay=10):\n if not path.exists(media_path):\n raise FileNotFoundError(\"{} does not exist\".format(media_path))\n if is_image:\n frame = cv2.imread(media_path)\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n\n start_time = time.time()\n bboxes = self.predict(frame)\n exec_time = time.time() - start_time\n print(\"time: {:.2f} ms\".format(exec_time * 1000))\n\n frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n image = self.draw_bboxes(frame, bboxes)\n cv2.namedWindow(\"result\", cv2.WINDOW_AUTOSIZE)\n cv2.imshow(\"result\", image)\n else:\n vid = cv2.VideoCapture(media_path)\n while True:\n return_value, frame = vid.read()\n if return_value:\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n else:\n break\n\n start_time = time.time()\n bboxes = self.predict(frame)\n curr_time = time.time()\n exec_time = curr_time - start_time\n info = \"time: %.2f ms\" % (1000 * exec_time)\n print(info)\n\n frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n image = self.draw_bboxes(frame, bboxes)\n cv2.namedWindow(\"result\", cv2.WINDOW_AUTOSIZE)\n cv2.imshow(\"result\", image)\n if cv2.waitKey(cv_waitKey_delay) & 0xFF == ord(\"q\"):\n break\n\n print(\"YOLOv4: Inference is finished\")\n while cv2.waitKey(10) & 0xFF != ord(\"q\"):\n pass\n cv2.destroyWindow(\"result\")\n","sub_path":"py_src/yolov4/tflite/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"224675803","text":"def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:\r\n\ttrie = {}\r\n\t\r\n\tfor word in words:\r\n\t\tnode = trie\r\n\t\tfor char in word:\r\n\t\t\tnode = node.setdefault(char, {})\r\n\t\tnode['#'] = True\r\n\r\n\tdef search(i, j, node, pre, visited): \r\n\t\r\n\t\tif '#' in node: \r\n\t\t\tres.add(pre) \r\n\t\t\t\r\n\t\tfor (di, dj) in ((-1, 0), (1, 0), (0, -1), (0, 1)):\r\n\t\t\t_i, _j = i+di, j+dj\r\n\t\t\tif -1 < _i < h and -1 < _j < w and board[_i][_j] in node and (_i, _j) not in visited:\r\n\t\t\t\tsearch(_i, _j, node[board[_i][_j]], pre+board[_i][_j], visited | {(_i, _j)})\r\n\r\n\tres, h, w = set(), len(board), len(board[0])\r\n\tfor i in range(h):\r\n\t\tfor j in range(w):\r\n\t\t\tif board[i][j] in trie:\r\n\t\t\t\tsearch(i, j, trie[board[i][j]], board[i][j], {(i, j)})\r\n\treturn list(res)\t","sub_path":"Week 6/id_600/LeetCode_33_212.py","file_name":"LeetCode_33_212.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"627859356","text":"'''\n Author: Vidit Maheshwrai\n Date: 20170204 (YYYYMMDD)\n Copyright :\n\n Purpose: This service communicate between DB\n\n History:\n\n'''\n\n# dependencies\n\nimport json\n\n# Local app imports\nimport models as Models\nimport IM_Constants as constants\nimport IM_DAO as dao\n\ndef saveVehical(data):\n vehical = Models.Vehical\n jObject = json.loads(data)\n try:\n\n # TODO:\n # 1: Check if given documnet alsready exists\n # 2: Check if parameters are missing\n # 3: Othr validation\n\n _purchaseDate = jObject['purchanseDate']\n _vn = jObject['vn']\n _chasisNumber = jObject['chasisNumber']\n _tripHistory = {}\n _serviceHistory = {}\n\n #Check if vehical with given vn and chasisNumber already present\n if(dao.getVehicalByVinNumber(_vn) != None):\n return \"Error: Vehical with vn=\" + _vn + \" already exist.\"\n if (dao.getVehicalByChasisNumber(_chasisNumber) != None):\n return \"Error: Vehical with chasisNumber=\" + _chasisNumber + \" already exist.\"\n\n vehical = Models.Vehical();\n vehical.purchaseDate = _purchaseDate\n vehical.vn = _vn\n vehical.chasisNumber = _chasisNumber\n vehical.tripHistory = _tripHistory\n vehical.serviceHistory = _serviceHistory\n\n #Making connection to DB\n\n dao.saveVehicalDAO(vehical)\n\n return \"Success:\" + \"done\"\n except KeyError as e:\n\n return \"Error:\" + constants.MALFORMED_DATA;\n\n except Exception as e:\n print(e)\n return \"[Error] : \"\n\ndef getVehicalData(req):\n resp = \"\"\n try:\n print(req)\n if(req == \"\"):\n jObject = \"\";\n else:\n jObject = json.loads(req)\n vehicals = dao.getVehicalDataDAO(jObject)\n return vehicals[0].toJSON()\n except json.JSONDecoder as e:\n print(e)\n resp = \"Invalid JSON request\"\n\n return resp\n\ndef addTrip(req):\n try:\n print(req)\n jObject = json.loads(req)\n resp = {}\n # Get vehical information\n ## Check if valid vn is given\n vn = \"\";\n if('vn' not in jObject):\n resp['code'] = \"400\"\n resp['message']=\"Missing vn.\"\n return json.dumps(resp)\n else:\n vn = jObject['vn']\n\n ## Check for given vn we have vehical in the database\n _query = {}\n _query[\"vn\"] = vn\n vehical = dao.getVehicalDataDAO(_query)\n if(vehical is not None):\n ## Validate input request\n tripData = getTripDataFromRequest(jObject)\n if(tripData is not None):\n vehical.update(add_to_set__tripHistory=tripData )\n return \"Successfully Added Trip\"\n else:\n resp['code'] = \"203\"\n resp['message'] = \"Illegal Trip Data\"\n return json.dumps(resp)\n else:\n resp['code'] = \"203\"\n resp['message'] = \"Vehical Not In System.\"\n return json.dumps(resp)\n\n # Add new trip data\n ## check for valid trip data\n ## validate trip data from previous trip data\n\n\n except json.JSONDecoder as e:\n print(e)\n resp = \"Invalid JSON request\"\n return resp\n\n return \"Application Error\"\n\ndef addService(req):\n try:\n print(req)\n jObject = json.loads(req)\n resp = {}\n # Get vehical information\n ## Check if valid vn is given\n vn = \"\";\n if('vn' not in jObject):\n resp['code'] = \"400\"\n resp['message']=\"Missing vn.\"\n return json.dumps(resp)\n else:\n vn = jObject['vn']\n\n ## Check for given vn we have vehical in the database\n _query = {}\n _query[\"vn\"] = vn\n vehical = dao.getVehicalDataDAO(_query)\n if(vehical is not None):\n ## Validate input request\n serviceData = getServiceDataFromRequest(jObject)\n if(serviceData is not None):\n vehical.update(add_to_set__serviceHistory=serviceData )\n return \"Successfully Added Service\"\n else:\n resp['code'] = \"203\"\n resp['message'] = \"Illegal Trip Data\"\n return json.dumps(resp)\n else:\n resp['code'] = \"203\"\n resp['message'] = \"Vehical Not In System.\"\n return json.dumps(resp)\n\n # Add new trip data\n ## check for valid trip data\n ## validate trip data from previous trip data\n\n\n except json.JSONDecoder as e:\n print(e)\n resp = \"Invalid JSON request\"\n return resp\n\n return \"Application Error\"\n\ndef getTripDataFromRequest(jObject):\n if(\"trip\" not in jObject):\n return None\n else:\n tripData = jObject[\"trip\"]\n trip = Models.TripDetail();\n trip.setData(tripData[\"tripFrom\"], tripData[\"tripTo\"], tripData[\"revenueGenerated\"], tripData[\"runningCost\"],\n tripData[\"journeyDuration\"],tripData[\"journeyDate\"],tripData[\"odoMeasure\"])\n return trip;\n\ndef getServiceDataFromRequest(jObject):\n if(\"service\" not in jObject):\n return None\n else:\n serviceData = jObject[\"service\"]\n service = Models.ServiceData();\n service.setData(serviceData[\"created\"], serviceData[\"KMstand\"], serviceData[\"itemListReplaced\"], serviceData[\"comment\"],\n serviceData[\"cost\"])\n return service;\n\ndef getVehicalServiceData(req):\n resp = \"\"\n try:\n print(req)\n if(req == \"\"):\n jObject = \"\";\n else:\n jObject = json.loads(req)\n vehicals = dao.getVehicalDataDAO(jObject)\n resp = {}\n resp[\"ServiceHistory\"] = json.loads(vehicals[0].toJSON())[\"serviceHistory\"]\n return json.dumps(resp)\n except json.JSONDecoder as e:\n print(e)\n resp = \"Invalid JSON request\"\n\n return resp\n\ndef getVehicalTripData(req):\n resp = \"\"\n try:\n print(req)\n if(req == \"\"):\n jObject = \"\";\n else:\n jObject = json.loads(req)\n vehicals = dao.getVehicalDataDAO(jObject)\n resp = {}\n resp[\"TripHistory\"] = json.loads(vehicals[0].toJSON())[\"tripHistory\"]\n return json.dumps(resp)\n except json.JSONDecoder as e:\n print(e)\n resp = \"Invalid JSON request\"\n\n return resp\n","sub_path":"inventoryMangement/IM_Service.py","file_name":"IM_Service.py","file_ext":"py","file_size_in_byte":6414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"435454251","text":"import music21 as mc\nimport json\n\n\ndef read_midi_from_archive(archive, path):\n mf = mc.midi.MidiFile()\n mf.readstr(archive.read(path))\n return mc.midi.translate.midiFileToStream(mf)\n\n\ndef read_mode(archive, midi_path):\n symbol_nokey_path = midi_path.replace(\"/pianoroll/\", \"/event/\").replace(\n \"nokey.mid\", \"symbol_nokey.json\"\n )\n read_data = archive.read(symbol_nokey_path)\n json_data = json.loads(read_data)\n return json_data.get(\"metadata\", {}).get(\"mode\", \"?\")\n","sub_path":"src/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"628231032","text":"import datetime\n\nclass Person(object):\n def __init__(self, name):\n # create a person with name name\n self.name = name\n try:\n lastBlank = name.rindex(' ')\n self.lastName = name[lastBlank+1:]\n except:\n self.lastName = name\n self.birthday = None\n def getLastName(self):\n # return self's last name\n return self.lastName\n def setBirthday(self, birthDate):\n # assumes bd is of type datetime.date\n self.birthday = birthDate\n def getAge(self):\n #returns self's current age in days\n if self.birthday == None:\n raise ValueError\n return (datetime.date.today() - self.birthday).days\n def __lt__(self, other):\n # return true if name lexicographically less than other names, false if no\n if self.lastName == other.lastName:\n return self.name < other.name\n return self.lastName < other.lastName\n def __str__(self):\n # return self's name\n return self.name\n\n\nme = Person('Paul Washburn')\nhim = Person('Barack Hussein Obama')\nher = Person('Madonna')\nprint(him.getLastName())\nhim.setBirthday(datetime.date(1961, 8, 4))\nher.setBirthday(datetime.date(1958, 8, 16))\n\n\n# classes can be be used to inherit attributes to others (parent class)\n\nclass MITPerson(Person):\n nextIdNum = 0\n def __init__(self, name):\n Person.__init__(self, name)\n self.idNum = MITPerson.nextIdNum\n MITPerson.nextIdNum += 1\n def getIdNum(self):\n return self.idNum\n def __lt__(self, other):\n return self.idNum < other.idNum\n\nprint('''\nMITPerson is a subclass of Person, and inherits the attributes of its\nsuperclass. You can add new attributes here too. You can also override attributes\nof the superclass.\n\nThe method MITPerson.__init__ first invokes Person.__init__ to initialize inherited instance\nvariable self.name. Then it initializes self.idNum, an instance variable\nthat instances of MITPerson have but instances of Person do not.\n\nThe instances variable self.idNum is initializesd using a class variable,\nnextIdNum, and an instance of MITPerson is created, and a new instance of nextIDNum\nis not created. \n''')\n\np1 = MITPerson('Paul Washburn') #creates an MITPerson\nprint(str(p1) + '\\'s id number is ' + str(p1.getIdNum()))\n \n# Python checks if there is an __str__ method assoc with MITPerson; since\n# there is not, it checks for __str__ method associated with class Person.\n\n\nprint('''\nThere can be multiple levels of inheritance.\n\nReserved word pass will give all attributes from superclass to the inheritor.\n''')\n\nclass Student(MITPerson):\n pass\n\nclass UG(Student):\n def __init__(self, name, classYear):\n MITPerson.__init__(self, name)\n self.year = classYear\n def getClass(self):\n return self.year\n\nclass Grad(Student):\n pass\n\n\np5 = Grad('Vicky Crago')\np6 = UG('Jenny Consuela', 2032)\nprint(p5, 'is a graduate student is', type(p5) == Grad)\nprint(p5, 'is an undergraduate student is', type(p5) == UG)\n\n\n\n\n","sub_path":"Python-Basics/007_classes_object_oriented_programming.py","file_name":"007_classes_object_oriented_programming.py","file_ext":"py","file_size_in_byte":3043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"171069483","text":"#!/usr/bin/python3\n# coding=UTF-8\n\nfrom aiqdoctests.structures import AiqTest\n\n\n@AiqTest.SetStructure(\"health\")\nclass tests(AiqTest):\n def test_health(self):\n r = self.assertOK()\n self.assertEqual(\"Hello World! AiqdocTests-example\", r.json())\n","sub_path":"tests/test_health.py","file_name":"test_health.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"161724521","text":"import socket as s\r\nfrom threading import Thread as th\r\nimport tkinter as gui\r\n\r\nIP = s.gethostname(), 8081\r\n\r\ncs = s.socket(s.AF_INET, s.SOCK_STREAM)\r\ncs.connect(IP)\r\n\r\n\r\ndef receive():\r\n while True:\r\n try:\r\n msg = cs.recv(1024).decode(\"utf8\")\r\n if msg == b'quit':\r\n break\r\n msgList.insert(gui.END, msg)\r\n except OSError: # användare kan ha lämnat\r\n break\r\n\r\n\r\ndef handleMsg(event=None):\r\n msg = msgSend.get()\r\n msgSend.set(\"\") # rensar fältet\r\n cs.send(bytes(msg, \"utf8\"))\r\n if msg == 'quit':\r\n #cs.close()\r\n root.quit()\r\n\r\n\r\ndef close(event=None):\r\n msgSend.set('quit')\r\n handleMsg()\r\n\r\n\r\nroot = gui.Tk()\r\nroot.title(\"SlutUppgift\")\r\n\r\nmsgsFrame = gui.Frame(root)\r\nmsgSend = gui.StringVar()\r\nmsgSend.set(\"Type here\")\r\n# för att kunna gå tillbaka i meddelanden\r\nscroll = gui.Scrollbar(msgsFrame)\r\n\r\n# kommer att innehålla meddelandet\r\nmsgList = gui.Listbox(msgsFrame, height=25, width=60, yscrollcommand=scroll.set)\r\nscroll.pack(side=gui.RIGHT, fill=gui.Y)\r\nmsgList.pack(side=gui.LEFT, fill=gui.BOTH)\r\nmsgList.pack()\r\nmsgsFrame.pack()\r\n\r\nentryField = gui.Entry(root, textvariable=msgSend)\r\nentryField.bind(\"\", handleMsg)\r\nentryField.pack()\r\nsendBtn = gui.Button(root, text=\"Send\", command=handleMsg)\r\nsendBtn.pack()\r\n\r\nroot.protocol(\"WM_DELETE_WINDOW\", close)\r\n\r\n\r\n#######################################################\r\n\r\nif __name__ == \"__main__\":\r\n receiveThread = th(target=receive, daemon=True)\r\n receiveThread.start()\r\n gui.mainloop()\r\n receiveThread.join()\r\n cs.close()","sub_path":"KLNT.py","file_name":"KLNT.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"418368303","text":"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reservedimport unittest\n\nimport unittest\n\nimport torch\nfrom pytext.contrib.pytext_lib.transforms import TruncateTransform\n\n\nclass TestTruncateTranform(unittest.TestCase):\n\n DATA = [[0, 1, 2, 3, 4, 5, 6], [0, 1, 2], []]\n MAX_SEQ_LEN = 4\n\n def test_truncate_transform(self):\n transform = TruncateTransform(max_seq_len=TestTruncateTranform.MAX_SEQ_LEN)\n res = transform(TestTruncateTranform.DATA)\n\n for row in res:\n # Truncate lengths above max_seq_len, smaller lens aren't padded.\n self.assertEqual(len(row), min(TestTruncateTranform.MAX_SEQ_LEN, len(row)))\n\n def test_truncate_transform_torchscript(self):\n transform = TruncateTransform(max_seq_len=TestTruncateTranform.MAX_SEQ_LEN)\n ts_transform = torch.jit.script(transform)\n res = ts_transform(TestTruncateTranform.DATA)\n\n for row in res:\n # Truncate lengths above max_seq_len, smaller lens aren't padded.\n self.assertEqual(len(row), min(TestTruncateTranform.MAX_SEQ_LEN, len(row)))\n","sub_path":"pytext/contrib/pytext_lib/tests/transforms_test.py","file_name":"transforms_test.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"36997325","text":"T = int(input())\nfor test in range(T):\n n = input()\n flag = 0\n no = ['aa','aab','ana','aaaaa']\n for i in range(4):\n if n == no[i]:\n flag = 1\n break\n print(\"#{}\".format(test+1),end=' ')\n if flag == 0:\n count = 0\n n = list(map(str, n))\n j = len(n) - 1\n for i in range(int(len(n)/2)):\n if n[i] == n[j] or n[i] == '?' or n[j] == '?':\n count+=1\n j-=1\n if count == int(len(n)/2):\n print('Exist')\n else:\n print('Not exist')\n else:\n print('Not exist')","sub_path":"4522_world_of_palindrome.py","file_name":"4522_world_of_palindrome.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"327723392","text":"import pygame, sys # import pygame and sys\npygame.init() # initiate pygame\nfrom enemy import Enemy\nfrom player import Player\nfrom projectile import Projectile\nfrom map import Map\nfrom pygame.locals import * # import pygame modules\nfrom helpers import *\nfrom settings import *\n# from map_scripts.map1 import map1\n\nclock = pygame.time.Clock() # set up the clock\npygame.display.set_caption(WINDOW_NAME)# set the window name\nscreen = pygame.display.set_mode(WINDOW_SIZE,0,32) # initiate screen\ndisplay = pygame.Surface((300, 200))\n\nimport sprites;\nmap = Map(\"map1\")\nplayer = Player(pygame.Rect(50, 50, sprites.player.get_width(), sprites.player.get_height()))\nenemy = Enemy(pygame.Rect(50, 50, sprites.yeti_standing.get_width(), sprites.yeti_standing.get_height()))\n\nwhile True: # game loop\n #display stuff\n display.fill((146,244,255))\n map.draw(display, sprites)\n display.blit(sprites.player, (player.rect.x, player.rect.y))\n \n if(enemy.flipped):\n enemy.sprite = pygame.transform.flip(sprites.yeti_running[enemy.sprite_index], True, False)\n else:\n enemy.sprite = sprites.yeti_running[enemy.sprite_index]\n display.blit(enemy.sprite, (enemy.rect.x, enemy.rect.y))\n player.draw_health_bar(display)\n\n #movement\n player.move_projectiles(display)\n for event in pygame.event.get(): # event loop\n if event.type == KEYDOWN and event.key == K_SPACE: \n projectile = Projectile(10, player.rect.x, player.rect.y, 1 if player.moving_right == True else -1, BLACK)\n player.projectiles.append(projectile)\n\n if event.type == QUIT: # check for window quit\n pygame.quit() # stop pygame\n sys.exit() # stop script\n else:\n player.getMovementInput(event)#get WASD input\n player.move(map)\n enemy.moveRoutine(pygame, map, player)\n \n surf = pygame.transform.scale(display, WINDOW_SIZE)\n screen.blit(surf, (0, 0))\n pygame.display.update() # update display\n clock.tick(FPS) # maintain 60 f","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"435217802","text":"\"\"\"\nCopyright 2017 Nikolay Stanchev\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\n\n# Simple unittests for the ADT BinarySearchTree\nimport unittest\n\nfrom ADTs.AbstractDataStructures import BinarySearchTree\n\n\nclass BinarySearchTreeTest(unittest.TestCase):\n\n def test_size(self):\n binary = BinarySearchTree(12)\n self.assertEqual(binary.get_number_of_elements(), len(binary), \"Len method not working.\")\n self.assertEqual(binary.get_number_of_elements(), 1, \"The binary tree must be with 1 elements when initialised\"\n \"with a root.\")\n binary = BinarySearchTree()\n self.assertEqual(binary.get_number_of_elements(), 0, \"The binary tree must be with 0 elements when initialised\")\n binary.add(25)\n for i in range(1, 11):\n binary.add(i)\n binary.add(i + 25)\n self.assertEqual(binary.get_number_of_elements(), len(binary), \"Len method not working.\")\n self.assertEqual(binary.get_number_of_elements(), 21, \"BinaryTree gives wrong size.\")\n\n def test_contains(self):\n binary = BinarySearchTree(26)\n binary.add(12)\n with self.assertRaises(TypeError):\n binary.contains(12.50)\n binary.add(54)\n self.assertTrue(binary.contains(12), \"BinaryTree contain method doesn't work.\")\n binary.add(32)\n self.assertFalse(binary.contains(104), \"BinaryTree contain method doesn't work.\")\n binary.add(104)\n with self.assertRaises(TypeError):\n binary.contains(\"string\")\n binary.add(0)\n self.assertTrue(binary.contains(26), \"BinaryTree contain method doesn't work.\")\n binary.add(5)\n self.assertTrue(binary.contains(5), \"BinaryTree contain method doesn't work.\")\n self.assertTrue(binary.contains(0), \"BinaryTree contain method doesn't work.\")\n\n def test_add(self):\n binary = BinarySearchTree()\n binary.add(23)\n self.assertEqual(binary.get_root(), 23, \"Add method cannot add the item to the root\")\n self.assertEqual(binary.get_number_of_elements(), 1, \"Add method doesn't increment number of elements\")\n binary.add(12)\n binary.add(54)\n binary.add(1)\n self.assertEqual(binary.get_number_of_elements(), 4, \"Add method doesn't adjust the number of elements\")\n self.assertTrue(binary.contains(54), \"Add method doesn't add the elements properly\")\n self.assertFalse(binary.contains(0), \"Add method adds elements that are not supposed to be there.\")\n with self.assertRaises(TypeError):\n binary.add(\"string\")\n binary.add(23)\n self.assertEqual(binary.get_number_of_elements(), 4, \"Add method adds elements which already exist.\")\n\n def test_delete(self):\n binary = BinarySearchTree(50)\n binary.delete(50)\n self.assertEqual(binary.get_number_of_elements(), 0, \"Delete method cannot delete the root.\")\n self.assertFalse(binary.contains(50), \"Delete method cannot delete the root\")\n binary.add(1)\n binary.add(0)\n binary.add(2)\n binary.add(3)\n binary.delete(2)\n self.assertEqual(binary.get_number_of_elements(), 3, \"Delete method cannot delete properly.\")\n binary.add(12)\n binary.add(9)\n with self.assertRaises(TypeError):\n binary.delete(\"9\")\n binary.add(34)\n binary.delete(1)\n self.assertEqual(binary.get_number_of_elements(), 5, \"Delete method cannot delete the root.\")\n self.assertFalse(binary.contains(1), \"Delete method cannot delete the root\")\n binary.add(-4)\n binary.add(-6)\n binary.delete(-4)\n self.assertEqual(binary.get_number_of_elements(), 6, \"Delete method cannot delete a node with one child.\")\n self.assertFalse(binary.contains(-4), \"Delete method cannot a node with one child.\")\n with self.assertRaises(KeyError):\n binary.delete(11232)\n\n def test_iterator(self):\n numbers = [30, 22, 46, 11, 15, 26, 101, 67, 140, 38]\n binary = BinarySearchTree()\n for number in numbers:\n binary.add(number)\n index = 0\n numbers.sort()\n for number in binary:\n self.assertEqual(number, numbers[index], \"Iterator doesn't return correct values\")\n index += 1\n\n binary = BinarySearchTree()\n count = 0\n for i in binary:\n count += i\n self.assertEqual(count, 0, \"Iterator doesn't work with empty tree\")\n\n def test_type(self):\n with self.assertRaises(TypeError):\n BinarySearchTree(elements_type=None)\n\n with self.assertRaises(TypeError):\n BinarySearchTree(elements_type=2)\n\n binary = BinarySearchTree(elements_type=str)\n with self.assertRaises(TypeError):\n binary.add(4)\n with self.assertRaises(TypeError):\n BinarySearchTree(root=\"hey\", elements_type=int)\n\n binary = BinarySearchTree(root=\"hey\", elements_type=str)\n words = [\"hey\", \"abc\", \"zcd\", \"dfg\", \"cxz\", \"xsa\", \"gfd\", \"word\", \"anotherword\"]\n counter = 0\n for word in words:\n binary.add(word)\n with self.assertRaises(TypeError):\n binary.add(counter)\n counter += 1\n self.assertEqual(len(binary), counter, \"Len method of the binary tree doesn't work\")\n self.assertTrue(binary.contains(\"abc\"), \"Contains method doesn't work with strings\")\n self.assertFalse(binary.contains(\"hbh\"), \"Contains method doesn't work with strings\")\n self.assertEqual(binary.get_minimum(), \"abc\", \"Binary tree doesn't return minimum element.\")\n self.assertEqual(binary.get_maximum(), \"zcd\", \"Binary tree doesn't return maximum element.\")\n\n words.sort()\n index = 0\n for word in binary:\n self.assertEqual(word, words[index], \"Iterator doesn't work with strings\")\n index += 1\n\n with self.assertRaises(TypeError):\n binary.delete(index)\n with self.assertRaises(TypeError):\n binary.delete([])\n\n binary.delete(\"abc\")\n self.assertEqual(binary.get_minimum(), \"anotherword\", \"Binary tree delete method doesn't work properly\")\n\n with self.assertRaises(KeyError):\n binary.delete(\"gfgfg\")\n\n self.assertTrue(binary.get_root() == \"hey\", \"Binary tree get_root method doesn't work properly\")\n binary.delete(\"hey\")\n self.assertTrue(binary.get_root() != \"hey\", \"Binary tree delete method doesn't work properly\")\n\n binary = BinarySearchTree()\n self.assertTrue(binary.get_root() is None, \"Binary tree get_root method doesn't work properly\")\n binary.add(1)\n binary.delete(1)\n self.assertTrue(binary.get_root() is None, \"Binary tree get_root method doesn't work properly after deletion\")\n\n def test_get_min(self):\n binary = BinarySearchTree(elements_type=int)\n self.assertEqual(binary.get_minimum(), None, \"Incorrect implementation of get_min\")\n\n binary = BinarySearchTree(root=10)\n binary.add(11)\n binary.add(5)\n binary.add(223)\n self.assertEqual(binary.get_minimum(), 5, \"Incorrect implementation of get_min\")\n\n binary = BinarySearchTree(root=2.5, elements_type=float)\n l = [2.4, 5.7, 3.3, 7.8, 8.99]\n for i in l:\n binary.add(i)\n self.assertEqual(binary.get_minimum(), min(l))\n\n def test_get_max(self):\n binary = BinarySearchTree(elements_type=int)\n self.assertEqual(binary.get_maximum(), None, \"Incorrect implementation of get_max\")\n\n binary = BinarySearchTree(root=10)\n binary.add(11)\n binary.add(5)\n binary.add(223)\n self.assertEqual(binary.get_maximum(), 223, \"Incorrect implementation of get_max\")\n\n binary = BinarySearchTree(root=2.5, elements_type=float)\n l = [2.4, 5.7, 3.3, 7.8, 8.99]\n for i in l:\n binary.add(i)\n self.assertEqual(binary.get_maximum(), max(l))\n\n def test_str(self):\n binary = BinarySearchTree()\n self.assertEqual(str(binary), \"Binary search tree with root: None\")\n\n binary = BinarySearchTree(5)\n self.assertEqual(str(binary), \"Binary search tree with root: 5\")\n\n binary = BinarySearchTree(\"root\", elements_type=str)\n self.assertEqual(str(binary), \"Binary search tree with root: root\")\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"Tests/testBinarySearchTree.py","file_name":"testBinarySearchTree.py","file_ext":"py","file_size_in_byte":8960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"610519859","text":"\"\"\"This module provides view functions for experiments endpoints.\"\"\"\n\n# pylint: disable=wrong-import-order\n\nfrom fastapi import APIRouter, Form\nfrom http import HTTPStatus\nimport requests\nfrom starlette.responses import JSONResponse, RedirectResponse\nfrom starlette.requests import Request\nfrom typing import Text\n\nfrom common.utils import error_response, get_utc_timestamp\nfrom projects.src.project_management import ProjectManager\nfrom projects.src.utils import log_request\n\nrouter = APIRouter() # pylint: disable=invalid-name\n\n\n@router.get('/experiments', tags=['experiments'])\ndef list_experiments(request: Request, project_id: int) -> JSONResponse:\n \"\"\"Get experiments list.\n Args:\n project_id {int}: project id\n Returns:\n starlette.responses.JSONResponse\n \"\"\"\n log_request(request)\n\n project_manager = ProjectManager()\n url = project_manager.get_internal_tracking_uri(project_id)\n resp = requests.get(\n url=f'{url}/api/2.0/preview/mlflow/experiments/list'\n )\n experiments = []\n\n for exp in resp.json().get('experiments'):\n\n experiment_id = exp.get('experiment_id')\n runs_resp = requests.get(\n f'{url}/api/2.0/preview/mlflow/runs/search?experiment_ids=[{experiment_id}]'\n )\n runs = runs_resp.json().get('runs', [])\n creation_time = ''\n last_update_time = ''\n\n \"\"\"\n if corresponding tags are empty then fields:\n * creation_time = start_time of the first run;\n * last_update_time = end_time of the last run.\n \"\"\"\n if len(runs) > 0:\n creation_time = runs[len(runs) - 1].get('info', {}).get('start_time')\n last_update_time = runs[0].get('info', {}).get('end_time')\n\n tags = {tag['key']: tag['value'] for tag in exp.get('tags', [])}\n experiments.append({\n 'id': experiment_id,\n 'user_id': tags.get('user_id', ''),\n 'name': exp.get('name'),\n 'artifact_location': exp.get('artifact_location'),\n 'lifecycle_stage': exp.get('lifecycle_stage'),\n 'last_update_time': tags.get('last_update_time', last_update_time),\n 'creation_time': tags.get('creation_time', creation_time),\n 'description': tags.get('mlflow.note.content', ''),\n 'project_id': tags.get('project_id', project_id)\n })\n\n return JSONResponse(experiments)\n\n\n@router.post('/experiments', tags=['experiments'])\ndef create_experiment(\n request: Request,\n project_id: int,\n user_id: Text = Form(''),\n name: Text = Form(''),\n description: Text = Form('')\n) -> JSONResponse:\n \"\"\"Create experiment\n Args:\n project_id {int}: project id\n user_id {Text}: user id (name)\n name {Text}: experiment name\n description {Text}: experiment description\n Returns:\n starlette.responses.JSONResponse\n \"\"\"\n\n log_request(request, {\n 'project_id': project_id,\n 'user_id': user_id,\n 'name': name,\n 'description': description\n })\n\n project_manager = ProjectManager()\n url = project_manager.get_internal_tracking_uri(project_id)\n creation_resp = requests.post(\n url=f'{url}/api/2.0/preview/mlflow/experiments/create',\n json={'name': name}\n )\n creation_json = creation_resp.json()\n experiment_id = creation_json.get('experiment_id')\n\n if creation_resp.status_code != HTTPStatus.OK:\n return error_response(\n http_response_code=creation_resp.status_code,\n message=creation_json.get('message')\n )\n\n utc_timestamp = get_utc_timestamp()\n tags = {\n 'mlflow.note.content': description,\n 'user_id': user_id,\n 'project_id': str(project_id),\n 'creation_time': utc_timestamp,\n 'last_update_time': utc_timestamp\n }\n\n for key, value in tags.items():\n requests.post(\n url=f'{url}/api/2.0/preview/mlflow/experiments/set-experiment-tag',\n json={\n 'experiment_id': experiment_id,\n 'key': key,\n 'value': value\n }\n )\n\n experiment_request = requests.get(\n url=f'{url}/api/2.0/preview/mlflow/experiments/get?experiment_id={experiment_id}'\n )\n\n experiment = experiment_request.json().get('experiment')\n tags = {tag['key']: tag['value'] for tag in experiment.pop('tags', [])}\n experiment['description'] = tags.get('mlflow.note.content', '')\n experiment['user_id'] = tags.get('user_id', '')\n experiment['project_id'] = tags.get('project_id', '')\n experiment['creation_time'] = tags.get('creation_time', '')\n experiment['last_update_time'] = tags.get('last_update_time', '')\n\n return JSONResponse(experiment, HTTPStatus.CREATED)\n\n\n@router.get('/experiments/{experiment_id}', tags=['experiments'])\ndef get_experiment(request: Request, experiment_id: Text, project_id: int) -> JSONResponse:\n \"\"\"Get experiment.\n Args:\n experiment_id {Text}: experiment id\n project_id {int}: project id\n Returns:\n starlette.responses.JSONResponse\n \"\"\"\n\n log_request(request)\n\n project_manager = ProjectManager()\n url = project_manager.get_internal_tracking_uri(project_id)\n experiment_resp = requests.get(\n url=f'{url}/api/2.0/preview/mlflow/experiments/get?experiment_id={experiment_id}'\n )\n\n if experiment_resp.status_code != HTTPStatus.OK:\n return error_response(\n http_response_code=experiment_resp.status_code,\n message=experiment_resp.json().get('message')\n )\n\n experiment = experiment_resp.json().get('experiment')\n experiment_id = experiment.get('experiment_id')\n runs_resp = requests.get(\n f'{url}/api/2.0/preview/mlflow/runs/search?experiment_ids=[{experiment_id}]'\n )\n runs = runs_resp.json().get('runs', [])\n creation_time = ''\n last_update_time = ''\n\n \"\"\"\n if corresponding tags are empty then fields:\n * creation_time = start_time of the first run;\n * last_update_time = end_time of the last run.\n \"\"\"\n if len(runs) > 0:\n creation_time = runs[len(runs) - 1].get('info', {}).get('start_time')\n last_update_time = runs[0].get('info', {}).get('end_time')\n\n experiment['id'] = experiment.pop('experiment_id')\n tags = {tag['key']: tag['value'] for tag in experiment.pop('tags', [])}\n experiment['description'] = tags.get('mlflow.note.content', '')\n experiment['user_id'] = tags.get('user_id', '')\n experiment['project_id'] = tags.get('project_id', project_id)\n experiment['creation_time'] = tags.get('creation_time', creation_time)\n experiment['last_update_time'] = tags.get('last_update_time', last_update_time)\n\n return JSONResponse(experiment)\n\n\n@router.delete('/experiments/{experiment_id}', tags=['experiments'])\ndef delete_experiment(request: Request, experiment_id: Text, project_id: int) -> JSONResponse:\n \"\"\"Delete experiment.\n Args:\n experiment_id {Text}: experiment id\n project_id {int}: project id\n Returns:\n starlette.responses.JSONResponse\n \"\"\"\n\n log_request(request, {\n 'project_id': project_id,\n 'experiment_id': experiment_id\n })\n\n project_manager = ProjectManager()\n url = project_manager.get_internal_tracking_uri(project_id)\n experiment_resp = requests.post(\n url=f'{url}/api/2.0/preview/mlflow/experiments/delete',\n json={'experiment_id': experiment_id}\n )\n\n if experiment_resp.status_code != HTTPStatus.OK:\n return error_response(\n http_response_code=experiment_resp.status_code,\n message=experiment_resp.json().get('message')\n )\n\n return JSONResponse({'experiment_id': experiment_id})\n\n\n# TODO(Alex): remove endpoint\n@router.get('/projects/{id}/experiments')\ndef alt_list_experiments(id: int):\n\n return RedirectResponse(f'/experiments?project_id={id}')\n","sub_path":"services/projects/src/routers/experiments.py","file_name":"experiments.py","file_ext":"py","file_size_in_byte":7942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"394743829","text":"\"\"\"\n rfk.api.web\n ~~~~~~~~~~~\n\n A REST interface for PyRfK\n\n\"\"\"\n\nfrom functools import wraps, partial\nfrom datetime import datetime\n\nfrom sqlalchemy import between\n\nfrom flask import jsonify, request, g\n\nfrom rfk.api import api\nfrom rfk import exc as rexc\n\nimport rfk.database\nfrom rfk.database.base import User, ApiKey\nfrom rfk.database.show import Show, UserShow\nfrom rfk.database.track import Track\nfrom rfk.database.streaming import Listener, Relay\nfrom rfk.database.stats import Statistic, StatsistcsData\n\nfrom rfk.liquidsoap import LiquidInterface\nfrom rfk.exc.base import UserNotFoundException\n\n\ndef wrapper(data, ecode=0, emessage=None):\n return {'pyrfk': {'version': '0.1', 'codename': 'Weltklang'}, 'status': {'code': ecode, 'message': emessage}, 'data': data}\n\n\ndef check_auth(f=None, required_permissions=None):\n if f is None:\n return partial(check_auth, required_permissions=required_permissions)\n\n @wraps(f)\n def decorated_function(*args, **kwargs):\n\n def raise_error(text):\n response = jsonify(wrapper(None, 403, text))\n response.status_code = 403\n return response\n\n if not 'key' in request.args:\n return raise_error('api key missing')\n\n key = request.args.get('key')\n\n try:\n apikey = ApiKey.check_key(key)\n rfk.database.session.commit()\n except rexc.api.KeyInvalidException:\n return raise_error('api key invalid')\n except rexc.api.KeyDisabledException:\n return raise_error('api key disabled')\n except rexc.api.FastQueryException:\n return raise_error('throttling')\n except:\n return raise_error('unknown error')\n\n if required_permissions != None:\n for required_permission in required_permissions:\n if not apikey.flag & required_permission:\n return raise_error(\n 'Flag %s (%i) required' % (ApiKey.FLAGS.name(required_permission), required_permission))\n\n g.apikey = apikey\n\n return f(*args, **kwargs)\n\n return decorated_function\n\n\n@api.route('/web/')\ndef page_not_found(path):\n response = jsonify(wrapper(None, 404, \"'%s' not found\" % path))\n response.status_code = 404\n return response\n\n\n@api.route('/web/dj')\n@check_auth()\n## DONE\ndef dj():\n \"\"\"Returns complete dj information\n\n Keyword arguments:\n - dj_id -- database id of the requested dj\n - dj_name -- nickname of the requested dj\n\n Returns:\n {'dj': {'dj_id': x, 'dj_name': x }}\n\n At least one argument is required\n \"\"\"\n\n dj_id = request.args.get('dj_id', None)\n dj_name = request.args.get('dj_name', None)\n\n try:\n user = User.get_user(id=dj_id, username=dj_name)\n return jsonify(wrapper({'dj': {'dj_id': user.user, 'dj_name': user.username}}))\n except rexc.base.UserNotFoundException:\n return jsonify(wrapper({'dj': None}))\n except AssertionError:\n return jsonify(wrapper(None, 400, 'missing required query parameter'))\n\n\n@api.route('/web/current_dj')\n@check_auth()\n## DONE (for now) ##\ndef current_dj():\n \"\"\"Returns dj information for the currently streaming dj(s)\n\n Keyword arguments:\n - None\n\n Returns:\n {'current_dj': {'dj_id': x, 'dj_name': x, 'dj_status': x }}\n \"\"\"\n\n result = UserShow.query.filter(UserShow.status == UserShow.STATUS.STREAMING).first()\n if result:\n data = {'current_dj': {'dj_id': result.user.user, 'dj_name': result.user.username, 'dj_status': result.status}}\n else:\n data = {'current_dj': None}\n return jsonify(wrapper(data))\n\n\n@api.route('/web/kick_dj')\n@check_auth(required_permissions=[ApiKey.FLAGS.KICK])\n## DONE ##\ndef kick_dj():\n \"\"\"Kicks the dj, who's currently connected to the streaming server\n\n Keyword arguments:\n - None\n\n Returns:\n {'kick_dj': {'dj_id': x, 'dj_name': x, 'success': x}}\n \"\"\"\n\n def try_kick():\n try:\n li = LiquidInterface()\n li.connect()\n kicked = li.kick_harbor()\n li.close()\n return kicked\n except:\n return False\n\n result = UserShow.query.filter(UserShow.status == UserShow.STATUS.STREAMING).first()\n if result:\n if try_kick():\n data = {'kick_dj': {'dj_id': result.user.user, 'dj_name': result.user.username, 'success': True}}\n else:\n data = {'kick_dj': {'dj_id': result.user.user, 'dj_name': result.user.username, 'success': False}}\n else:\n data = {'kick_dj': None}\n return jsonify(wrapper(data))\n\n\n@api.route('/web/current_show')\n@check_auth()\n## DONE ##\ndef current_show():\n \"\"\"Return the currently running show\n\n Keyword arguments:\n - None\n \"\"\"\n\n clauses = [(between(datetime.utcnow(), Show.begin, Show.end)) | (Show.end == None)]\n result = Show.query.filter(*clauses).order_by(Show.begin.desc(), Show.end.asc()).all()\n\n data = {'current_show': {}}\n if result:\n for show in result:\n\n begin = show.begin.isoformat()\n if show.end:\n end = show.end.isoformat()\n else:\n end = None\n\n dj = []\n connected = False\n for usershow in show.users:\n dj.append({'dj_name': usershow.user.username, 'dj_id': usershow.user.user, 'status': usershow.status})\n if usershow.status == UserShow.STATUS.STREAMING:\n connected = True\n\n if (show.flags & Show.FLAGS.UNPLANNED and len(result) == 2) or len(result) == 1:\n target = 'running_show'\n if show.flags & Show.FLAGS.PLANNED and len(result) == 2:\n target = 'planned_show'\n\n data['current_show'][target] = {\n 'show_id': show.show,\n 'show_name': show.name,\n 'show_description': show.description,\n 'show_flags': show.flags,\n 'show_connected': connected,\n 'show_begin': begin,\n 'show_end': end,\n 'dj': dj\n }\n else:\n data = {'current_show': None}\n return jsonify(wrapper(data))\n\n\n@api.route('/web/next_shows')\n@check_auth\n## DONE ##\ndef next_shows():\n \"\"\"Return the next planned show(s)\n\n Keyword arguments:\n - dj_id -- filter by dj\n - dj_name -- filter by dj\n - limit -- limit the output (default=5)\n \"\"\"\n\n dj_id = request.args.get('dj_id', None)\n dj_name = request.args.get('dj_name', None)\n limit = request.args.get('limit', 5)\n\n clauses = [Show.begin > datetime.utcnow()]\n\n try:\n if dj_id:\n clauses.append(UserShow.user == User.get_user(id=dj_id))\n if dj_name:\n clauses.append(UserShow.user == User.get_user(username=dj_name))\n\n result = Show.query.join(UserShow).filter(*clauses).order_by(Show.begin.asc()).limit(limit).all()\n\n data = {'next_shows': {'shows': []}}\n if result:\n for show in result:\n\n begin = show.begin.isoformat()\n end = show.end.isoformat()\n\n dj = []\n for usershow in show.users:\n dj.append({'dj_name': usershow.user.username, 'dj_id': usershow.user.user, 'status': usershow.status})\n\n data['next_shows']['shows'].append({\n 'show_id': show.show,\n 'show_name': show.name,\n 'show_description': show.description,\n 'show_flags': show.flags,\n 'show_begin': begin,\n 'show_end': end,\n 'dj': dj\n })\n else:\n data = {'next_shows': None}\n return jsonify(wrapper(data))\n except UserNotFoundException:\n return jsonify(wrapper({'next_shows': None}))\n\n\n@api.route('/web/last_shows')\n@check_auth\n## DONE ##\ndef last_shows():\n \"\"\"Return show history\n\n Keyword arguments:\n - dj_id -- filter by dj\n - dj_name -- filter by dj\n - limit -- limit the output (default=5)\n \"\"\"\n\n dj_id = request.args.get('dj_id', None)\n dj_name = request.args.get('dj_name', None)\n limit = request.args.get('limit', 5)\n\n clauses = [Show.end < datetime.utcnow()]\n\n try:\n if dj_id:\n clauses.append(UserShow.user == User.get_user(id=dj_id))\n if dj_name:\n clauses.append(UserShow.user == User.get_user(username=dj_name))\n\n result = Show.query.join(UserShow).filter(*clauses).order_by(Show.begin.desc()).limit(limit).all()\n\n data = {'last_shows': {'shows': []}}\n if result:\n for show in result:\n\n begin = show.begin.isoformat()\n end = show.end.isoformat()\n\n dj = []\n for usershow in show.users:\n dj.append({'dj_name': usershow.user.username, 'dj_id': usershow.user.user, 'status': usershow.status})\n\n data['last_shows']['shows'].append({\n 'show_id': show.show,\n 'show_name': show.name,\n 'show_description': show.description,\n 'show_flags': show.flags,\n 'show_begin': begin,\n 'show_end': end,\n 'dj': dj\n })\n else:\n data = {'last_shows': None}\n return jsonify(wrapper(data))\n except UserNotFoundException:\n return jsonify(wrapper({'last_shows': None}))\n\n\n@api.route('/web/current_track')\n@check_auth\n## DONE ##\ndef current_track():\n \"\"\"Return the currently playing track\n\n Keyword arguments:\n - None\n \"\"\"\n\n result = Track.current_track()\n if result:\n data = {'current_track': {\n 'track_id': result.track,\n 'track_begin': result.begin.isoformat(),\n 'track_title': result.title.name,\n 'track_artist': result.title.artist.name\n }}\n else:\n data = {'current_track': None}\n return jsonify(wrapper(data))\n\n\n@api.route('/web/last_tracks')\n@check_auth\n## DONE ##\ndef last_tracks():\n \"\"\"Return the last played tracks\n\n Keyword arguments:\n - dj_id -- filter by dj\n - dj_name -- filter by dj\n - limit -- limit the output (default=5)\n \"\"\"\n\n dj_id = request.args.get('dj_id', None)\n dj_name = request.args.get('dj_name', None)\n limit = int(request.args.get('limit', 5))\n limit = limit if limit <= 50 else 50\n\n clauses = [Track.end < datetime.utcnow()]\n\n if dj_id is not None:\n clauses.append(UserShow.user == User.get_user(id=dj_id))\n if dj_name is not None:\n clauses.append(UserShow.user == User.get_user(username=dj_name))\n\n result = Track.query.join(Show).join(UserShow).filter(*clauses).order_by(Track.end.desc()).limit(limit).all()\n\n data = {'last_tracks': {'tracks': []}}\n if result:\n for track in result:\n begin = track.begin.isoformat()\n end = track.end.isoformat()\n\n data['last_tracks']['tracks'].append({\n 'track_id': track.track,\n 'track_begin': begin,\n 'track_end': end,\n 'track_title': track.title.name,\n 'track_artist': track.title.artist.name\n })\n else:\n data = {'last_tracks': None}\n return jsonify(wrapper(data))\n\n\n@api.route('/web/listener')\n@check_auth\n## DONE ##\ndef listener():\n \"\"\"Return current listener count\n\n Keyword arguments:\n - None\n \"\"\"\n\n clauses = [Listener.disconnect == None]\n result = Listener.query.filter(*clauses).all()\n\n data = {'listener': {'listener': []}}\n temp = {'per_stream': {}, 'per_country': {}, 'total_count': len(result)}\n\n if result:\n\n for listener in result:\n\n stream = listener.stream_relay.stream\n try:\n temp['per_stream'][stream.code]['count'] += 1\n except KeyError:\n temp['per_stream'][stream.code] = {'count': 1, 'name': stream.name}\n\n country = listener.country\n try:\n temp['per_country'][country]['count'] += 1\n except KeyError:\n temp['per_country'][country] = {'count': 1}\n\n data['listener'] = temp\n return jsonify(wrapper(data))\n\n\n@api.route('/web/active_relays')\n@check_auth\n## DONE ##\ndef active_relays():\n \"\"\"Return information about all active relays\n\n Keyword arguments:\n - None\n \"\"\"\n\n result = Relay.query.filter(Relay.status == Relay.STATUS.ONLINE).all()\n\n data = {'active_relays': {'relays': [], 'total_bandwidth': 0}}\n\n if result:\n for relay in result:\n data['active_relays']['relays'].append({\n 'relay_id': relay.relay,\n 'relay_type': relay.type,\n 'relay_address': relay.address,\n 'relay_max_bandwidth': relay.bandwidth,\n 'relay_current_bandwidth': relay.usage\n })\n data['active_relays']['total_bandwidth'] += relay.usage\n else:\n data = {'active_relays': None}\n return jsonify(wrapper(data))\n\n\n@api.route('/web/listener_peak')\n@check_auth\n## DONE ##\ndef listener_peak():\n \"\"\"Return the global listener peak\n\n Keyword arguments:\n - None\n \"\"\"\n\n peak = StatsistcsData.query.join(Statistic).filter(Statistic.identifier == 'lst-total').order_by(StatsistcsData.value.desc()).first()\n if peak:\n data = {'listener_peak': {'peak_value': peak.value, 'peak_time': peak.timestamp.isoformat()}}\n\n show = Show.query.join(UserShow).filter(between(peak.timestamp, Show.begin, Show.end)).first()\n if show:\n dj = []\n for usershow in show.users:\n dj.append({'dj_name': usershow.user.username, 'dj_id': usershow.user.user, 'status': usershow.status})\n\n data['listener_peak']['peak_show'] = {\n 'show_id': show.show,\n 'show_name': show.name,\n 'show_description': show.description,\n 'show_flags': show.flags,\n 'show_begin': show.begin.isoformat(),\n 'show_end': show.end.isoformat(),\n 'dj': dj\n }\n else:\n data['listener_peak']['peak_show'] = None\n else:\n data = {'listener_peak': None}\n return jsonify(wrapper(data))\n","sub_path":"lib/rfk/api/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":14405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"279548465","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator 2.3.33.0\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass OutputOptions(Model):\n \"\"\"Additional options that control how the data should be uploaded.\n\n :param path_on_compute: Which local path on compute the data should be\n uploaded from. This is only applicable to the\n mount and upload mechanisms.\n :type path_on_compute: str\n :param registration_options: If present, whether to register the output as\n a named dataset.\n :type registration_options: ~_restclient.models.RegistrationOptions\n :param upload_options: Options that is specific to upload. This should\n only be set if the mechanism is set to upload.\n :type upload_options: ~_restclient.models.UploadOptions\n \"\"\"\n\n _attribute_map = {\n 'path_on_compute': {'key': 'pathOnCompute', 'type': 'str'},\n 'registration_options': {'key': 'registrationOptions', 'type': 'RegistrationOptions'},\n 'upload_options': {'key': 'uploadOptions', 'type': 'UploadOptions'},\n }\n\n def __init__(self, path_on_compute=None, registration_options=None, upload_options=None):\n super(OutputOptions, self).__init__()\n self.path_on_compute = path_on_compute\n self.registration_options = registration_options\n self.upload_options = upload_options\n","sub_path":"venv/Lib/site-packages/azureml/_restclient/models/output_options.py","file_name":"output_options.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"469974187","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 11 14:26:58 2019\n\n@author: CCF\n\"\"\"\n\nfrom numpy import *\nimport pickle\ndef make_dataset(dataset):\n X = []\n Y = []\n\n for video in dataset:\n X.append(video[\"features\"])\n Y.append(video[\"category\"])\n\n return X, Y\n\n\n \nclass NeuralNet(object): \n def __init__(self): \n # Generate random numbers \n random.seed(1) \n \n # Assign random weights to a 3 x 1 matrix, \n self.synaptic_weights = 2 * random.random((3, 1)) - 1\n \n # The Sigmoid function \n def __sigmoid(self, x): \n return 1 / (1 + exp(-x)) \n \n # The derivative of the Sigmoid function. \n # This is the gradient of the Sigmoid curve. \n def __sigmoid_derivative(self, x): \n return x * (1 - x) \n \n # Train the neural network and adjust the weights each time. \n def train(self, inputs, outputs, training_iterations): \n for iteration in xrange(training_iterations): \n \n # Pass the training set through the network. \n output = self.learn(inputs) \n \n # Calculate the error \n error = outputs - output \n \n # Adjust the weights by a factor \n factor = dot(inputs.T, error * self.__sigmoid_derivative(output)) \n self.synaptic_weights += factor \n \n # The neural network thinks. \n def learn(self, inputs): \n return self.__sigmoid(dot(inputs, self.synaptic_weights)) \n \nif __name__ == \"__main__\": \n \n #Initialize \n neural_network = NeuralNet() \n \n # The training set. \n dataset = pickle.load(open(dataset_bow, \"rb\"))\n X, Y = make_dataset(dataset)\n \n # Train the neural network \n neural_network.train(X, Y, 10000) \n \n # Test the neural network with a test example. \n #print neural_network.learn() ","sub_path":"nn.py","file_name":"nn.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"439803386","text":"#! coding: utf-8\nfrom flask import request, url_for, jsonify\nfrom . import app\nfrom .task import parse_msg, format_task_list\nfrom .models import db, User, Task, MessageID\nfrom .message import FanfouClient\nfrom datetime import datetime\nfrom dateutil import parser\n\nclient = FanfouClient(\n {\n 'key': app.config.get('FANFOU_CONSUMER_KEY'),\n 'secret': app.config.get('FANFOU_CONSUMER_SECRET')\n },\n {\n 'key': app.config.get('FANFOU_AUTH_KEY'),\n 'secret': app.config.get('FANFOU_AUTH_SECRET')\n }\n)\n\ndef htmlec(s):\n el = {'<': '<', '>': '>', '"': '\"', '&': '&'}\n for k, v in el.items():\n s = s.replace(k, v)\n return s\n\ndef check_msg(msg_num):\n newest_msg = MessageID.query.filter_by(name='msg').first()\n if newest_msg:\n newest_msg_id = newest_msg.message_id\n newest_msg_ts = newest_msg.message_ts\n else:\n newest_msg_id = None\n newest_msg_ts = datetime.fromtimestamp(0)\n newest_msg = MessageID(name='msg', message_id='',\n message_ts=newest_msg_ts)\n db.session.add(newest_msg)\n count = min(60, msg_num)\n pages = msg_num / count + 2\n processed_msg = 0\n for page in range(1, pages):\n messages = client.get_msg_list(count, page, newest_msg_id)\n for item in messages:\n msg_timestamp = parser.parse(item['created_at']).replace(tzinfo=None)\n if newest_msg_ts < msg_timestamp:\n newest_msg_ts = msg_timestamp\n newest_msg_id = item['id']\n if not item['text'].startswith('@TodoBot'):\n continue\n text = item['text'].replace('@TodoBot ', '').strip()\n text = text.replace('@', '#')\n user_id = item['user']['id']\n user_name = item['user']['name']\n reply = parse_msg(user_id, text, user_name)\n user = User.query.filter_by(user_id=user_id).first()\n if not user:\n reply = u'没有任务'\n if not user or user.msg_type == 'public':\n client.send_msg(reply, user_id, user_name)\n else:\n client.send_dm(reply, user_id)\n processed_msg += 1\n newest_msg.message_id = newest_msg_id\n newest_msg.message_ts = newest_msg_ts\n db.session.commit()\n return processed_msg\n\ndef check_dm(dm_num):\n newest_msg = MessageID.query.filter_by(name='dm').first()\n if newest_msg:\n newest_msg_id = newest_msg.message_id\n newest_msg_ts = newest_msg.message_ts\n else:\n newest_msg_id = None\n newest_msg_ts = datetime.fromtimestamp(0)\n newest_msg = MessageID(name='dm', message_id='',\n message_ts=newest_msg_ts)\n db.session.add(newest_msg)\n count = min(60, dm_num)\n pages = dm_num / count + 2\n processed_dm = 0\n for page in range(1, pages):\n direct_messages = client.get_dm_list(count, page, newest_msg_id)\n for item in direct_messages:\n msg_timestamp = parser.parse(item['created_at']).replace(tzinfo=None)\n if newest_msg_ts < msg_timestamp:\n newest_msg_ts = msg_timestamp\n newest_msg_id = item['id']\n text = htmlec(item['text'].strip())\n text = text.replace('@', '#')\n user_id = item['sender']['id']\n user_name = item['sender']['name']\n client.delete_dm(item['id'])\n reply = parse_msg(user_id, text, user_name, 'private')\n user = User.query.filter_by(user_id=user_id).first()\n if not user:\n reply = u'没有任务'\n if not user or user.msg_type == 'private':\n client.send_dm(reply, user_id)\n else:\n client.send_msg(reply, user_id, user_name)\n processed_dm += 1\n newest_msg.message_id = newest_msg_id\n newest_msg.message_ts = newest_msg_ts\n db.session.commit()\n return processed_dm\n\n@app.route('/check')\ndef check():\n msg_num, dm_num = client.get_notification()\n processed_msg = processed_dm = 0\n if msg_num > 0:\n processed_msg = check_msg(msg_num)\n if dm_num > 0:\n processed_dm = check_dm(dm_num)\n return 'done checking, #msg %d #dm %d' % (processed_msg, processed_dm)\n\n@app.route('/notify')\ndef notify():\n users = User.query.all()\n for user in users:\n tasks = Task.query.filter_by(user=user).filter_by(status='todo').all()\n if not tasks:\n continue\n if user.msg_type == 'private':\n client.send_dm(format_task_list(tasks), user.user_id)\n elif user.msg_type == 'public':\n client.send_msg(format_task_list(tasks), user.user_id, user.user_name)\n return 'finished daily notification for %d users' % len(users)\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"610860026","text":"log_file = 'result-1/log-33000.txt'\n\nwith open(log_file) as f:\n bitrate = 0\n rebuf = 0\n cv = 0\n smooth = 0\n count = 0\n for line in f:\n parse = line.split()\n bitrate += float(parse[8])\n rebuf += float(parse[4])\n cv += float(parse[6])\n smooth += float(parse[10])\n count += 1\n if count == 10000:\n break\n ave_bitrate = bitrate / count\n ave_rebuf = rebuf / count\n ave_cv = cv / count\n ave_smooth = smooth / count\n reward = ave_bitrate - 33 * ave_rebuf / 1000 - 5.3 * ave_cv - ave_smooth\n print(ave_bitrate, ave_rebuf, ave_cv, ave_smooth, reward)\n\n","sub_path":"abr/a3c-final/analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"12551658","text":"#!/usr/bin/python3\n\n\n\nimport sys\nimport os\nimport shutil\nfrom datetime import datetime\n\ndef clean_downloads (dossier):\n \n liste_fichier = os.listdir (dossier)\n \n if len (liste_fichier) == 0:\n print ('No file in directory !')\n else:\n print (\"cleanup old files : (more than 10 days + 50MB)\\n\")\n for fichier in liste_fichier:\n jours_depuis_creation = (datetime.now() - datetime.fromtimestamp(os.stat(dossier+fichier).st_mtime)).days\n taille_fichier = os.stat (dossier+fichier).st_size\n if jours_depuis_creation > 10 and taille_fichier > 6250000:\n print (fichier)\n choix = input (\"[yes/No]?\\n\")\n if choix == \"y\":\n os.remove (dossier+fichier)\n print (fichier+\" delete\\n\")\n else:\n print(\"\")\n else:\n if jours_depuis_creation > 10:\n print (fichier)\n print (\"organizing your files :\")\n annee_mois_du_fichier = str(datetime.fromtimestamp(os.stat(dossier+fichier).st_atime).year)+\"-\"+str(datetime.fromtimestamp(os.stat(dossier+fichier).st_atime).month)\n try:\n os.mkdir (dossier+annee_mois_du_fichier)\n except:\n ligne_bidon = 0\n print (\"moving into \"+annee_mois_du_fichier+\" : \"+fichier+\"\\n\") \n shutil.move (dossier+fichier,dossier+annee_mois_du_fichier)\n \n\n\n \n \n\n return \"end\"\n \nif __name__ == \"__main__\":\n print(clean_downloads(sys.argv[1]))","sub_path":"exam3/clean_downloads.py","file_name":"clean_downloads.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"380956397","text":"from tkinter import *\r\nfrom tkinter import messagebox\r\nimport mysql.connector\r\n\r\n# WINDOW SETUP\r\nroot= Tk()\r\nroot.title(\"TONY TEXTILES\")\r\nroot.geometry('1920x1080')\r\nroot.config(background=\"#ffffff\")\r\n\r\nback_image=PhotoImage(file=\"canvas.png\")\r\nback=Label(root,image=back_image)\r\nback.place(relwidth=1,relheight=1)\r\n\r\nnew_frame= Frame(root,bg=\"#D1F2EB\",bd=5)\r\nnew_frame.place(relx=0.2,rely=0.11,relwidth=0.6,relheight=0.75)\r\n\r\nnew_frame_= Frame(new_frame,bg=\"white\",bd=5)\r\nnew_frame_.place(relx=0.26,rely=0.13,relwidth=0.46,relheight=0.5)\r\n\r\ncon = mysql.connector.connect(host = \"localhost\", user = \"root\", passwd = \"123456\")\r\ncrs = con.cursor()\r\ncrs.execute(\"USE tony_textiles;\")\r\n\r\ncon.commit()\r\n\r\n# CANVAS SETUP\r\n\r\nt= Label(\r\n new_frame,\r\n text= \"BUY DRESS:\",\r\n background= \"#D1F2EB\",\r\n foreground= \"#30110D\",\r\n font= (\"Goudy Old Style\",18),\r\n\r\n)\r\nt.place(relx=0.43,rely=0.05)\r\n\r\nt1= Label(\r\n text= \"ENTER THE DRESS CODE \\n BELOW..\",\r\n background= \"#D1F2EB\",\r\n foreground= \"#30110D\",\r\n font= (\"Goudy Old Style\",17),\r\n\r\n)\r\nt1.place(relx=0.42,rely=0.6)\r\n\r\nt2= Label(\r\n text= \"CODE :\",\r\n background= \"#D1F2EB\",\r\n foreground= \"#30110D\",\r\n font= (\"Goudy Old Style\",17),\r\n\r\n)\r\nt2.place(relx=0.4,rely=0.67)\r\n\r\ncode_entry= Entry(\r\n new_frame,\r\n font= (\"Goudy Old Style\",16),\r\n )\r\ncode_entry.place(relx=0.42,rely=0.75)\r\n\r\n\r\n# FUNCTIONS\r\n\r\ndef cancel_pressed():\r\n quit()\r\n\r\ndef ok_pressed():\r\n d_code=code_entry.get()\r\n \r\n crs.execute(\"SELECT d_code FROM men_wear;\")\r\n rows= crs.fetchall()\r\n ids= []\r\n for id in rows:\r\n ids.append(str(id[0]))\r\n\r\n if d_code in ids:\r\n crs.execute(f\"delete from men_wear where d_code = '{d_code}'\")\r\n con.commit()\r\n messagebox.showinfo(\"TONY TEXTILES\", \"PURCHASE SUCCESSFULL\")\r\n \r\n quit()\r\n else:\r\n messagebox.showinfo(\"TONY TEXTILES\", \"NO ITEM WITH THE ENTERED CODE,\\nPLEASE RE-CHECK THE CODE.\") \r\n\r\n# DECISION BUTTONS\r\n\r\ncancel_but= Button(\r\n new_frame,\r\n text=\"<< CANCEL\",\r\n font=(\"Comic Sans MS\",12),\r\n background= \"RED\",\r\n foreground=\"#D1F2EB\",\r\n command = cancel_pressed,\r\n )\r\ncancel_but.place(relx=0.38,rely=0.85,bordermode=OUTSIDE,relwidth=0.1)\r\n\r\nok_but= Button(\r\n new_frame,\r\n text=\"OK >>\",\r\n font=(\"Comic Sans MS\",12),\r\n background= \"green\",\r\n foreground=\"#D1F2EB\",\r\n command = ok_pressed,\r\n )\r\nok_but.place(relx=0.52,rely=0.85,bordermode=OUTSIDE,relwidth=0.1)\r\n\r\n# DISPLAYING TABLE\r\n\r\nattributes=[\"Dress code \",\" Dress Name \",' colour ',' size ',\" price \"]\r\ncrs.execute(\"SELECT * FROM men_wear ORDER BY d_code;\")\r\n\r\ninfo= crs.fetchall()\r\ndatabase=[]\r\n\r\nfor i in info:\r\n database.append(i)\r\n\r\nfor attr in attributes:\r\n heading= Label(\r\n new_frame_,\r\n text= attr,\r\n bg= \"white\",\r\n font=(\"Arial\",15),\r\n )\r\n heading.grid(\r\n row=2,\r\n column= attributes.index(attr)\r\n )\r\n\r\nfor item in database:\r\n for detail in item:\r\n item_detail= Label(\r\n new_frame_,\r\n text= detail,\r\n font= (\"Arial\",15),\r\n bg= \"white\"\r\n )\r\n item_detail.grid(\r\n row=database.index(item)+3,\r\n column= item.index(detail),\r\n )\r\n\r\nroot.mainloop()","sub_path":"tony tk/buy.py","file_name":"buy.py","file_ext":"py","file_size_in_byte":3338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"517317058","text":"from PIL import Image\n\n\ndef make_preview(size, n_colors):\n img = Image.open('27.1.jpg')\n img = img.resize(size)\n img = img.quantize(colors=n_colors)\n img.save('27.1.bmp', 'BMP')\n\n\nmake_preview((200, 150), 10)\n","sub_path":"Python3/27.1.py","file_name":"27.1.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"274095207","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport create_loss as crloss\n\nimport random\nimport numpy as np\nimport itertools as it\n# In[1]:\nimport torch\nimport torchvision.models as models\nfrom torch.utils.data import DataLoader\nimport torch.nn as nn\nfrom torchvision import datasets, transforms\n\nimport os\nimport time\nfrom data.my_dataset import MyDataset\n\nimport fire\n\n\n# In[3]:\n\n\nclass AverageMeter(object):\n \"\"\"\n Computes and stores the average and current value\n Copied from: https://github.com/pytorch/examples/blob/master/imagenet/main.py\n \"\"\"\n def __init__(self):\n self.reset()\n \n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n\n# In[ ]:\n\n\ndef train_epoch(model,loader,criterion,optimizer,epoch,n_epochs,print_freq=1):\n '''\n Args:\n model:\n loader:\n optimizer:\n criterion:\n \n \n '''\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n batch_time = AverageMeter()\n losses = AverageMeter()\n \n model.train()\n end = time.time()\n batch_idx = 0\n for inputs,labels in loader:\n \n #print(batch_idx)\n # Create vaiables\n \n inputs = inputs.to(device)\n labels = labels.to(device)\n \n # feed the network\n batch_size = labels.size(0)\n embeddings = model(inputs) # BS* m\n loss = criterion(embeddings, labels)\n #record loss\n losses.update(loss.item(), batch_size)\n \n \n # backpropagation\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n \n # print stats\n if batch_idx % print_freq == 0:\n res = '\\t'.join([\n 'Epoch: [%d/%d]' % (epoch + 1, n_epochs),\n 'Iter: [%d/%d]' % (batch_idx + 1, len(loader)),\n 'Time %.3f (%.3f)' % (batch_time.val, batch_time.avg),\n 'Loss %.4f (%.4f)' % (losses.val, losses.avg),\n ])\n print(res)\n batch_idx +=1\n \n return losses.avg\n \n \n\n\n# In[ ]:\n\n\ndef train(model,train_set, # model and data\n batch_size ,n_epochs,T, # others\n embed_size,loss,metric,sampler,num_cls,lambda_, # train\n save,result_f,model_f,\n wd=0,momentum=0.9,lr=0.001): # optim\n \n '''\n Args:\n model:\n result_f:\n data_sets:\n \n opti_para:\n scheduler_para:\n \n ''' \n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n freq = 7\n model = model.to(device)\n \n # Wrap model for multi-GPUs, if necessary\n model_wrapper = model\n \n # Optimizer : optim strategy to be completed...\n \n to_optim = [{'params':model_wrapper.parameters(),'lr':lr,'momentum': momentum ,'weight_decay':wd}]\n criterion,to_optim = crloss.select_loss(loss=loss,e_size = embed_size, metric=metric, sampling_method=sampler,num_cls=num_cls,lambda_=lambda_,lr=lr,momentum=momentum,wd=wd,to_optim=to_optim) # check if the new para are in the cuda or not??\n \n criterion = criterion.to(device)\n \n \n optimizer = torch.optim.SGD(to_optim)#model_wrapper.parameters(), lr=lr, momentum=0.9, dampening=0, weight_decay=0, nesterov=False)\n \n # scheduler\n #scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer,milestones=[5,9,12,14])\n # ...\n \n # Start log\n with open(os.path.join(save, result_f), 'w') as f:\n f.write('epoch,train_loss,l_r,dif\\n')\n l_rate = lr\n best_loss = 1000\n pre_loss = 10.\n for epoch in range(n_epochs):\n # scheduler.step()\n \n train_loss = train_epoch(\n model=model_wrapper,\n loader=train_set,\n optimizer=optimizer,\n criterion = criterion,\n epoch=epoch,\n n_epochs=n_epochs,\n )\n dif = abs(pre_loss-train_loss)\n if epoch % freq == 0:\n dif = pre_loss-train_loss\n pre_loss = train_loss\n \n if dif< T:\n \n l_rate *= 0.5\n # for p in optimizer.param_groups:\n # p['lr']*=0.5\n print('lr has been update \\n')\n \n \n # Determine if model is the best and save the best model\n if train_loss < best_loss:\n # save the model\n torch.save(model.state_dict(), os.path.join(save, model_f))\n if metric == 'maha' or metric == 'rM':\n cri_f = 'L.dat'\n torch.save(criterion.state_dict(),os.path.join(save,cri_f))\n # update the best_loss\n best_loss = train_loss\n \n # Log results\n with open(os.path.join(save, result_f), 'a') as f:\n f.write('%03d,%0.6f,%0.9f,%05f\\n' % ( #**\n (epoch + 1),\n train_loss,\n l_rate,\n dif\n ))\n \n \n \n \n\n\n# In[4]:\n\n\n\ndef demo_p(data,save,fine_tune,\n metric,loss,sampler='rand',embed_size=16,num_cls = 196, lambda_=0, lr=0.001,T = 0.005,\n model_saved=None,result='r_.csv',model_name='m_.dat',list_file = './cars_train.txt',\n batch_size=100,n_epochs = 10,seed=1):\n '''\n Arg:\n # data\n data: where the data are stored\n dataset: the name of the dataset: CIFAR196,etc.\n train_size:\n test_size:\n \n # log\n save: tr where the logs are stored\n model_saved: trained_model\n result: loss\n model_new : \n \n # trainning para\n embed_size: m : 16,32,64\n \n metric: 'E', 'rE','maha','snr','rM'\n \n sampler:'dist','npair'\n \n loss; 'tripl','contras','npair','lifted',\n \n #margin\n \n # others\n n_epochs :10 tr\n batch_size tr\n seed :1\n \n \n \n '''\n # seed\n torch.backends.cudnn.deterministic=True\n if seed is not None:\n \n torch.manual_seed(seed)\n if torch.cuda.is_available():\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n \n # dataLoader\n train_set = MyDataset(dataroot=data,phase='train',image_list_file =list_file )\n #test_set = MyDataset(dataroot=data,phase='test',image_lise_file = list_file)\n \n #test_loader = DataLoader(dataset=test_set, batch_size=batch_size,shuffle=False, num_workers=4,pin_memory=torch.cuda.is_available())\n train_loader = DataLoader(dataset=train_set, batch_size=batch_size,shuffle=True, num_workers=4,pin_memory=torch.cuda.is_available()) \n # model_setup\n if model_saved:\n model = models.resnet18(pretrained=False)\n for p in model.parameters():\n p.requires_grad=False\n \n inp_fts = model.fc.in_features\n #classifier[6].in_features\n #inp_fts = model.fc.in_features#model.classifier[6] = nn.Linear(inp_fts, embed_size)\n \n model.fc = nn.Linear(inp_fts,embed_size)\n model.load_state_dict(torch.load(os.path.join(save, model_saved),map_location = 'cpu'))\n \n if fine_tune:\n for p in model.parameters():\n p.requires_grad = not p.requires_grad\n else:\n model = models.resnet18(pretrained=True)\n for p in model.parameters():\n p.requires_grad=False\n \n inp_fts = model.fc.in_features#\n #inp_fts=model.classifier[6].in_features\n model.fc = nn.Linear(inp_fts,embed_size)\n #model.classifier[6] = nn.Linear(inp_fts, embed_size)\n if fine_tune:\n for p in model.parameters():\n p.requires_grad = not p.requires_grad\n \n \n print(model)\n # create folder for logging file\n # Make save directory\n if not os.path.exists(save):\n os.makedirs(save)\n if not os.path.isdir(save):\n raise Exception('%s is not a dir' % save)\n \n train(model=model,train_set=train_loader, # model and data\n batch_size = batch_size,n_epochs=n_epochs, lambda_=lambda_,lr=lr,T=T, # others\n embed_size=embed_size,loss = loss,metric = metric,sampler =sampler,num_cls = num_cls, # train\n save=save,result_f=result,model_f=model_name # log\n )\n print('Done')\n \n \nif __name__ == '__main__':\n fire.Fire(demo_p)\n \n\n\n# In[ ]:\n\n\n\n\n","sub_path":"demo_p.py","file_name":"demo_p.py","file_ext":"py","file_size_in_byte":8710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"608317452","text":"#!/usr/bin/python\n\nimport sys\nimport pandas as pd\nimport Select as st\nfrom decimal import *\nimport time\n\n\ndef initial_selection(df_origin, rul='2_3_4'):\n \"\"\"\n Initial selection of STR loci: apply repeat unit length filter\n :param df_origin:\n :param rul:\n :return:\n \"\"\"\n print('========================================================================================')\n print('Processing begins')\n print('Total loci:', len(df_origin))\n df_origin = df_origin[~df_origin.CHROM.isin(['chrX', 'chrY'])] # drop chrX and chrY\n print('========================================================================================')\n print('After drop chrX and chrY, remaining:', len(df_origin))\n df_origin = df_origin[df_origin.RUL.isin([int(i) for i in rul.split('_')])] # select repeat length\n df_origin = df_origin.sort_values(by=['PD', 'GT_FREQ'], ascending=[False, False]).reset_index(drop=True)\n return df_origin\n\n\ndef para_selection(df_origin, called_threshold, n_sample):\n \"\"\"\n Select loci with required HE, PM, PE\n :param called_threshold:\n :param df_origin:\n :param n_sample:\n :return:\n \"\"\"\n # called_threshold = float(called_threshold)\n # isFound = False\n # filter_info = []\n # final_selected_df = None\n\n step_filter_info = Decimal(called_threshold).quantize(Decimal('0.01'), rounding=ROUND_UP), # turple\n # step_filter_info = round(called_threshold, 2)\n print('=======================================================================================')\n print('After selecting repeat length, remaining:', len(df_origin))\n step_filter_info += len(df_origin), # append filter info\n\n if called_threshold < 0:\n print('No eligible loci')\n\n else:\n df = st.filter_called(df_origin, int(n_sample), called_threshold) # filter with called number\n print('=======================================================================================')\n print('After filtering nonentity, remaining:', len(df))\n step_filter_info += len(df),\n\n # select filter type #\n # loose filter\n\n # Default\n\n # df = df[df.EXP_HE >= 0.777]\n df = df[df.EXP_HE >= 0.1]\n print('=======================================================================================')\n print('After filtering with HE, remaining:', len(df))\n step_filter_info += len(df),\n\n # df = df[df.PM <= 0.087]\n df = df[df.PM <= 0.9]\n print('=======================================================================================')\n print('After filtering with PM, remaining:', len(df))\n step_filter_info += len(df),\n\n # df = df[df.PE >= 0.579]\n df = df[df.PE >= 0.1]\n print('=======================================================================================')\n print('After filtering with PE, remaining:', len(df), '\\n')\n step_filter_info += len(df),\n\n return df\n\n\n# HE 0.864\t0.777\n# PD 0.967\t0.913\n# PE 0.729\t0.579\n# PM 0.198\t0.087\n\ndef main():\n\n ################### Phrase Parameters ######################\n import argparse\n Argparser = argparse.ArgumentParser()\n Argparser.add_argument('-f', '--file', action='store', dest='data_in', type=str, help='Input file [.txt]')\n Argparser.add_argument('-v', '--vcf-in', action='store', dest='vcf_in', type=str, default=None)\n Argparser.add_argument('-n', '--n-sample', action='store', dest='n_sample', type=int, default=30)\n Argparser.add_argument('-t', '--thres', action='store', dest='called_threshold', type=float)\n Argparser.add_argument('-p', '--prob-thres', action='store', dest='prob_threshold', type=str, default='0.000001')\n Argparser.add_argument('--tag', action='store', dest='species_name', type=str, default='Unknown')\n Argparser.add_argument('--filter', action='store', dest='filter_type', type=str, default='default')\n Argparser.add_argument('-r', '--rul', action='store', dest='rul', type=str, default='2_3_4')\n Argparser.add_argument('-o', '--out-dir', action='store', dest='output_path', type=str)\n\n para, unknown = Argparser.parse_known_args()\n\n ################### Main Body ######################\n print('Selection info.:')\n print('\\tNumber of sample:', para.n_sample)\n print('\\tCalled threshold:', para.called_threshold)\n print('\\tProb threshold:', para.prob_threshold)\n print('\\tFilter:', para.filter_type)\n print('\\tRUL:', para.rul, '\\n\\n')\n df_origin = pd.read_table(para.data_in, dtype={'ID': str})\n #vcf_canis = vcf.Reader(filename=para.vcf_in)\n\n print('========================================================================================')\n print('Processing begins')\n\n called_threshold = float(para.called_threshold)\n\n df_selected = initial_selection(df_origin, rul='2_3_4')\n print('Current called threshold:', called_threshold)\n df = para_selection(df_selected, para.called_threshold, para.n_sample)\n df.to_csv(para.output_path + para.filter_type + '_' + para.prob_threshold + '_info', sep='\\t', index=False)\n\n return 0\n\n\nif __name__ == '__main__':\n start_time = time.time()\n return_code = main()\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n sys.exit(return_code)\n","sub_path":"filter_loci.py","file_name":"filter_loci.py","file_ext":"py","file_size_in_byte":5182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"81926565","text":"#! /usr/bin/python\n\nfrom __init__ import *\nimport tensorflow as tf\nimport numpy as np\n\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)\n\nclass vgg16:\n def __init__(self, param):\n self._param = param;\n\n def inference(self, input):\n \"\"\"Build vgg model\n \"\"\"\n\n def conv_relu(self, input, kernel_shape):\n weights = tf.get_variable(\"weights\",\n kernel_shape,\n initializer = tf.truncated_normal_initializer(0, 0.01),\n dtype = tf.float32)\n biases = tf.get_variable(\"biases\",\n [kernel_shape[-1]],\n initializer = tf.constant_initializer(0.0),\n dtype = tf.float32)\n conv = tf.nn.conv2d(input,\n weights,\n [1,1,1,1],\n padding='SAME',\n use_cudnn_on_gpu=True,\n data_format = 'NCHW')\n out = tf.nn.bias_add(conv, biases, data_format = 'NCHW')\n return tf.nn.relu(out, name = 'relu')\n\n def vgg_conv(self, name, input, n_conv, in_filters, out_filters):\n with tf.variable_scope(name):\n for idx in range(n_conv):\n kernel_shape = [3, 3, 0, 0]\n if idx == 0:\n kernel_shape[2] = in_filters\n if idx == n_conv - 1:\n kernel_shape[3] = out_filters\n with tf.variable_scope(str(idx)):\n conv_relu_layer = conv_relu(input, kernel_shape)\n pool = tf.nn.max_pool(conv_relu_layer,\n ksize = [1, 2, 2, 1],\n strides = [1, 2, 2, 1],\n padding = 'SAME',\n name = 'pool',\n data_format = 'NCHW')\n return pool\n\n def conv_net(self, x):\n pool1 = vgg_conv('conv1', x, 2, 64, 128)\n pool2 = vgg_conv('conv2', pool1, 2, 128, 256)\n pool3 = vgg_conv('conv3', pool2, 3, 256, 512)\n pool4 = vgg_conv('conv4', pool3, 3, 512, 512)\n pool5 = vgg_conv('conv5', pool4, 3, 512, 512)\n return pool5\n\n def inference(self, x):\n x = tf.placeholder(tf.float32)\n y = tf.placeholder(tf.float32)\n pred = conv_net(x)\n cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y) )\n optimizer = tf.train.AdamOptimizer(learning_rate=self._param.lr).minimize(cost)\n init = tf.global_variables_initializer()\n with tf.Session() as sess:\n sess.run(init)\n step = 1\n with step * self._param.batch_size < self._param.training_iters:\n batch_x, batch_y = mnist.traning.net_batch(self._param.batch_size)\n sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})\n step += 1\n print(\"Optimization Finished!\")\n","sub_path":"wal/model/vgg.py","file_name":"vgg.py","file_ext":"py","file_size_in_byte":2883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"512888136","text":"# https://www.acmicpc.net/problem/10814\n\nfrom sys import stdin\ninput = stdin.readline\n\nmembers = {}\nfor _ in range(int(input())):\n\tage, name = input().rstrip().split()\n\tif members.get(int(age)):\n\t\tmembers[int(age)].append(name)\n\telse :\n\t\tmembers[int(age)] = [name]\n[print(age, name) for age, name_list in sorted(members.items()) for name in name_list]","sub_path":"dojinyou/code_2week/06_10814.py","file_name":"06_10814.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"399152394","text":"import grpc\n\nfrom dataservice_pb2_grpc import BostonHousingStub\nfrom dataservice_pb2 import ParamsRequest\n\nfrom io import BytesIO\nimport numpy as np\n\nchannel = grpc.insecure_channel(\"localhost:50051\")\nclient = BostonHousingStub(channel)\n\nrequest = ParamsRequest(test_size=0.2)\n\nresponse = client.PrepareData(request)\nnorm_train_X_bytes = BytesIO(response.norm_train_x)\nnorm_train_X = np.load(norm_train_X_bytes, allow_pickle=False)\nnorm_test_X_bytes = BytesIO(response.norm_test_x)\nnorm_test_X = np.load(norm_test_X_bytes, allow_pickle=False)\nnorm_val_X_bytes = BytesIO(response.norm_val_x)\nnorm_val_X = np.load(norm_val_X_bytes, allow_pickle=False)\ntrain_Y_bytes = BytesIO(response.train_y)\ntrain_Y = np.load(train_Y_bytes, allow_pickle=False)\ntest_Y_bytes = BytesIO(response.test_y)\ntest_Y = np.load(test_Y_bytes, allow_pickle=False)\nval_Y_bytes = BytesIO(response.val_y)\nval_Y = np.load(val_Y_bytes, allow_pickle=False)\n\nprint('Normalized training X:', norm_train_X.shape)\nprint('Normalized testing X:', norm_test_X.shape)\nprint('Normalized validation X:', norm_val_X.shape)\nprint('Training Y:', train_Y[0].shape)\nprint('Testing Y:', test_Y[0].shape)\nprint('Validation Y:', val_Y[0].shape)\n\n","sub_path":"services/dataservice/app/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"228660255","text":"from datetime import time\nfrom vnpy.app.cta_strategy import (\n CtaTemplate,\n StopOrder,\n TickData,\n BarData,\n TradeData,\n OrderData,\n BarGenerator,\n ArrayManager\n)\nfrom vnpy.app.cta_strategy.base import (\n EngineType,\n STOPORDER_PREFIX,\n StopOrder,\n StopOrderStatus,\n)\nfrom vnpy.app.cta_strategy.TSMtools import TSMArrayManager\n\nclass TSMyoTemplateStrategy(CtaTemplate):\n \"\"\"\"\"\"\n\n author = \"TheSuperMyo\"\n\n # 日内交易\n exit_time = time(hour=14, minute=55)\n\n # 针对不同交易时间的市场\n open_time_night = time(hour=21,minute=0)# 商品夜盘\n open_time_day_1 = time(hour=9,minute=0)# 商品\n open_time_day_2 = time(hour=9,minute=30)# 股指\n\n close_time_day = time(hour=15,minute=0)# 商品/股指(除了利率期货)\n close_time_night_1 = time(hour=23,minute=0)# 其他夜盘商品\n close_time_night_2 = time(hour=1,minute=0)# 工业金属\n close_time_night_3 = time(hour=2,minute=30)# 黄金/白银/原油\n \n break_time_start_1 = time(hour=10,minute=15)# 商品茶歇\n break_time_start_2 = time(hour=11,minute=30)# 全体午休\n break_time_end_1 = time(hour=10,minute=30)# 商品茶歇\n break_time_end_2 = time(hour=13,minute=0)# 股指下午\n break_time_end_3 = time(hour=13,minute=30)# 商品下午\n\n parameters = []\n variables = []\n\n def __init__(self, cta_engine, strategy_name, vt_symbol, setting):\n \"\"\"\"\"\"\n super(TSMyoTemplateStrategy, self).__init__(\n cta_engine, strategy_name, vt_symbol, setting\n )\n self.bg = BarGenerator(self.on_bar)\n self.am = TSMArrayManager()\n # 策略自身订单管理\n self.active_orderids = []\n\n def on_init(self):\n \"\"\"\n Callback when strategy is inited.\n \"\"\"\n self.write_log(\"策略初始化\")\n # 根据需要的历史数据长度设定\n self.load_bar(5)\n \n def on_start(self):\n \"\"\"\n Callback when strategy is started.\n \"\"\"\n self.write_log(\"策略启动\")\n\n def on_stop(self):\n \"\"\"\n Callback when strategy is stopped.\n \"\"\"\n self.write_log(\"策略停止\")\n\n def tick_filter(self, tick: TickData):\n \"\"\"\n 过滤异常时间的tick\n \"\"\"\n pass\n\n def on_tick(self, tick: TickData):\n \"\"\"\n Callback of new tick data update.\n \"\"\"\n self.bg.update_tick(tick)\n\n def on_bar(self, bar: BarData):\n \"\"\"\n Callback of new bar data update.\n \"\"\"\n\n def on_order(self, order: OrderData):\n \"\"\"\n Callback of new order data update.\n \"\"\"\n # 移除已成交或已撤销的订单\n if not order.is_active() and order.vt_orderid in self.active_orderids:\n self.active_orderids.remove(order.vt_orderid)\n\n def on_trade(self, trade: TradeData):\n \"\"\"\n Callback of new trade data update.\n \"\"\"\n # 邮寄提醒\n self.send_email(f\"{trade.vt_symbol}在{trade.time}成交,价格{trade.price},方向{trade.direction}{trade.offset},数量{trade.volume}\")\n self.put_event()\n\n def on_stop_order(self, stop_order: StopOrder):\n \"\"\"\n Callback of stop order update.\n \"\"\"\n # 刚刚生成的本地停止单\n if stop_order.status == StopOrderStatus.WAITING:\n return\n # 撤销的本地停止单,从活跃列表移除\n if stop_order.status == StopOrderStatus.CANCELLED:\n if stop_order.stop_orderid in self.active_orderids:\n self.active_orderids.remove(stop_order.stop_orderid)\n # 触发的本地停止单,停止单移除,限价单加入\n if stop_order.status == StopOrderStatus.TRIGGERED:\n if stop_order.stop_orderid in self.active_orderids:\n self.active_orderids.remove(stop_order.stop_orderid)\n self.active_orderids.extend(stop_order.vt_orderids)\n # 撤掉其他停止单\n for other_orderids in self.active_orderids:\n if other_orderids.startswith(STOPORDER_PREFIX):\n self.cancel_order(other_orderids)","sub_path":"vnpy/app/cta_strategy/strategies/tsmyo_template.py","file_name":"tsmyo_template.py","file_ext":"py","file_size_in_byte":4166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"67654317","text":"# coding=utf-8\n\n\"\"\"\nCollect basic metrics from cassandra using nodetool (yuk!)\n\"\"\"\n\nimport subprocess\nimport re\n\nimport diamond.collector\n\n\nclass CassandraCollector(diamond.collector.Collector):\n def get_default_config(self):\n config = super(CassandraCollector, self).get_default_config()\n config.update({\n 'path': 'cassandra',\n })\n return config\n\n def publish_dict(self, prefix, metrics):\n for name, value in metrics.iteritems():\n self.publish('.'.join((prefix, name)), value)\n\n def _nodetool(self, *args):\n command = ['/usr/bin/nodetool']\n command.extend(args)\n self.log.debug('Running %r' % command)\n return subprocess.check_output(command).split('\\n')\n\n def nodetool_gcstats(self):\n output = self._nodetool('gcstats')\n names = ['interval', 'elapsed_max', 'elapsed_total', 'elapsed_stdev',\n 'reclaimed_mb', 'collections']\n values = re.split(r'\\s+', output[1].strip())\n return dict(zip(names, values))\n\n def nodetool_compactionstats(self):\n output = self._nodetool('compactionstats')\n metrics = {}\n for line in output:\n m = re.search('pending tasks: (\\d+)', line)\n if m:\n metrics['pending'] = m.group(1)\n return metrics\n\n def nodetool_status(self):\n output = self._nodetool('status')\n status_map = {\n 'U': 'up', 'D': 'down',\n 'N': 'normal', 'L': 'leaving',\n 'J': 'joining', 'M': 'moving',\n }\n metrics = {}\n in_status = False\n for line in output:\n if line.startswith('-- '):\n in_status = True\n if not in_status:\n continue\n if re.match('^[UD][NLJM] ', line):\n node_updown = status_map[line[0]]\n node_status = status_map[line[1]]\n metrics[node_updown] = metrics.setdefault(node_updown, 0) + 1\n metrics[node_status] = metrics.setdefault(node_status, 0) + 1\n return metrics\n\n def nodetool_tpstats(self):\n output = self._nodetool('tpstats')\n names = ['name', 'active', 'pending', 'completed',\n 'blocked', 'all_time_blocked']\n metrics = {}\n for line in output[1:]:\n parts = re.split('\\s+', line.strip())\n if len(parts) != len(names):\n continue\n tp_stat = dict(zip(names, parts))\n for key, value in tp_stat.iteritems():\n if key == 'name':\n continue\n metric_name = '.'.join((tp_stat['name'], key))\n metrics[metric_name] = value\n return metrics\n\n def collect(self):\n self.publish_dict('status', self.nodetool_status())\n self.publish_dict('compaction', self.nodetool_compactionstats())\n self.publish_dict('gc', self.nodetool_gcstats())\n self.publish_dict('tpstats', self.nodetool_tpstats())\n","sub_path":"modules/diamond/files/collector/cassandra.py","file_name":"cassandra.py","file_ext":"py","file_size_in_byte":3017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"392952337","text":"import torch\nfrom torch import nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport data_helper_2018\nimport numpy as np\nimport time\nfrom sklearn.metrics import classification_report\nimport os\n\nclass TextBiLSTM(nn.Module):\n def __init__(self, config):\n super(TextBiLSTM, self).__init__()\n self.word2id = config['word2id']\n self.pretrain_emb = config['pretrain_emb']\n self.vocabulary_size = len(self.word2id) + 1\n self.embedding_size = config['embedding_size']\n self.hidden_size = config['hidden_size']\n self.layer_num = config['layer_num']\n self.do_BN = config['do_BN']\n\n self.dropout = nn.Dropout(config['dropout'])\n self.embedding = nn.Embedding(num_embeddings=self.vocabulary_size, embedding_dim=self.embedding_size)\n # self.init_embeddings()\n self.embedding.weight.data[0] = 0\n\n if self.pretrain_emb:\n self.load_pretrained_embeddings()\n\n if self.do_BN:\n self.quote_input_BN = nn.BatchNorm1d(num_features=self.embedding_size)\n self.response_input_BN = nn.BatchNorm1d(num_features=self.embedding_size)\n\n self.quote_bilstm = nn.LSTM(\n input_size=self.embedding_size,\n hidden_size=self.hidden_size,\n num_layers=self.layer_num,\n dropout=config['lstm_dropout'],\n bidirectional=True,\n batch_first=True\n )\n\n self.response_bilstm = nn.LSTM(\n input_size=self.embedding_size,\n hidden_size=self.hidden_size,\n num_layers=self.layer_num,\n dropout=config['lstm_dropout'],\n bidirectional=True,\n batch_first=True\n )\n\n def forward(self, X_q_inputs, X_r_inputs, q_init_state, r_init_state):\n\n # quote_inputs = self.dropout(self.embedding(X_q_inputs))\n # response_inputs = self.dropout(self.embedding(X_r_inputs))\n quote_inputs = self.embedding(X_q_inputs)\n response_inputs = self.embedding(X_r_inputs)\n\n if self.do_BN:\n quote_inputs = quote_inputs.transpose(1, 2).contiguous()\n quote_inputs = self.quote_input_BN(quote_inputs)\n quote_inputs = quote_inputs.transpose(1, 2)\n response_inputs = response_inputs.transpose(1, 2).contiguous()\n response_inputs = self.response_input_BN(response_inputs)\n response_inputs = response_inputs.transpose(1, 2)\n\n quote_outputs, _ = self.quote_bilstm(quote_inputs, q_init_state)\n response_outputs, _ = self.response_bilstm(response_inputs, r_init_state)\n\n return quote_outputs, response_outputs\n\n def init_embeddings(self, init_range=0.1):\n self.embedding.weight.data.uniform_(-init_range, init_range)\n\n def init_hidden(self, batch_size):\n weight = next(self.parameters()).data\n return (Variable(weight.new(self.layer_num * 2, batch_size, self.hidden_size).zero_()),\n Variable(weight.new(self.layer_num * 2, batch_size, self.hidden_size).zero_()))\n\n def load_pretrained_embeddings(self, embeddingFileName='../qrPair/data/glove.840B.300d.txt'):\n hit = 0\n with open(embeddingFileName, 'r') as fr:\n lines = fr.readlines()\n for line in lines:\n line = line.strip().split(' ')\n word = line[0]\n embedding = line[1:]\n if word in self.word2id.index:\n wordIndex = self.word2id[word]\n embeddingArray = np.fromstring('\\n'.join(embedding), dtype=np.float32, sep='\\n')\n self.embedding.weight.data[wordIndex].copy_(torch.from_numpy(embeddingArray))\n hit += 1\n hitRate = float(hit) / self.vocabulary_size\n print('PreTrain Embedding hitRate={}'.format(hitRate))\n\nclass AttentionModel(nn.Module):\n def __init__(self, config):\n super(AttentionModel, self).__init__()\n self.bilstm = TextBiLSTM(config)\n self.dropout = nn.Dropout(config['dropout'])\n self.attention_mechanism = config['attention_mechanism']\n self.hidden_size = config['hidden_size']\n self.do_BN = config['do_BN']\n\n if self.do_BN:\n if self.attention_mechanism['Type'] != 'both_concat':\n self.quote_output_BN = nn.BatchNorm1d(num_features=self.hidden_size * 2)\n self.response_output_BN = nn.BatchNorm1d(num_features=self.hidden_size * 2)\n else:\n self.quote_output_BN = nn.BatchNorm1d(num_features=self.hidden_size * 2 * 2)\n self.response_output_BN = nn.BatchNorm1d(num_features=self.hidden_size * 2 * 2)\n\n if self.attention_mechanism['Type'] != 'None':\n\n if self.attention_mechanism['Type'][:4] == 'both':\n self.quote2quote_attention_layer = nn.Linear(in_features=self.hidden_size * 2, out_features=1)\n self.response2quote_attention_layer = nn.Linear(in_features=self.hidden_size * 2, out_features=1)\n self.response2response_attention_layer = nn.Linear(in_features=self.hidden_size * 2, out_features=1)\n self.quote2response_attention_layer = nn.Linear(in_features=self.hidden_size * 2, out_features=1)\n elif self.attention_mechanism['Type'] == 'share':\n self.share_attention_layer = nn.Linear(in_features=self.hidden_size * 2, out_features=1)\n else:\n self.quote_attention_layer = nn.Linear(in_features=self.hidden_size * 2, out_features=1)\n self.response_attention_layer = nn.Linear(in_features=self.hidden_size * 2, out_features=1)\n # init_range = 0.1\n # self.quote_attention_layer.weight.data.uniform_(-init_range, init_range)\n # self.quote_attention_layer.bias.data.fill_(init_range)\n # self.response_attention_layer.weight.data.uniform_(-init_range, init_range)\n # self.response_attention_layer.bias.data.fill_(init_range)\n\n def forward(self, X_q_inputs, X_r_inputs, q_init_state, r_init_state):\n quote_outputs, response_outputs = self.bilstm.forward(X_q_inputs, X_r_inputs, q_init_state, r_init_state)\n\n if self.attention_mechanism['Type'] != 'None':\n ActFunc = self.attention_mechanism['ActFunc']\n if self.attention_mechanism['Type'] == 'self_attention':\n quote_outputs = self.attention_layer(self.quote_attention_layer, bilstm_outputs=quote_outputs, attention_source=quote_outputs, ActFunc=ActFunc)\n response_outputs = self.attention_layer(self.response_attention_layer, bilstm_outputs=response_outputs, attention_source=response_outputs, ActFunc=ActFunc)\n if self.attention_mechanism['Type'] == 'cross_attention':\n _quote_outputs = self.attention_layer(self.quote_attention_layer, bilstm_outputs=quote_outputs, attention_source=response_outputs, ActFunc=ActFunc)\n _response_outputs = self.attention_layer(self.response_attention_layer, bilstm_outputs=response_outputs, attention_source=quote_outputs, ActFunc=ActFunc)\n quote_outputs = _quote_outputs\n response_outputs = _response_outputs\n if self.attention_mechanism['Type'] == 'both_sum':\n _quote_outputs = self.attention_layer(self.quote2quote_attention_layer, bilstm_outputs=quote_outputs, attention_source=quote_outputs, ActFunc=ActFunc) + \\\n self.attention_layer(self.response2quote_attention_layer, bilstm_outputs=quote_outputs, attention_source=response_outputs, ActFunc=ActFunc)\n _response_outputs = self.attention_layer(self.response2response_attention_layer, bilstm_outputs=response_outputs, attention_source=response_outputs, ActFunc=ActFunc) + \\\n self.attention_layer(self.quote2response_attention_layer, bilstm_outputs=response_outputs, attention_source=quote_outputs, ActFunc=ActFunc)\n quote_outputs = _quote_outputs\n response_outputs = _response_outputs\n if self.attention_mechanism['Type'] == 'both_concat':\n _quote_outputs = torch.cat((self.attention_layer(self.quote2quote_attention_layer, bilstm_outputs=quote_outputs, attention_source=quote_outputs, ActFunc=ActFunc),\n self.attention_layer(self.response2quote_attention_layer, bilstm_outputs=quote_outputs, attention_source=response_outputs, ActFunc=ActFunc)), dim=1)\n _response_outputs = torch.cat((self.attention_layer(self.response2response_attention_layer, bilstm_outputs=response_outputs, attention_source=response_outputs, ActFunc=ActFunc), \n self.attention_layer(self.quote2response_attention_layer, bilstm_outputs=response_outputs, attention_source=quote_outputs, ActFunc=ActFunc)), dim=1)\n quote_outputs = _quote_outputs\n response_outputs = _response_outputs\n if self.attention_mechanism['Type'] == 'share':\n _quote_outputs = self.attention_layer(self.share_attention_layer, bilstm_outputs=quote_outputs, attention_source=response_outputs, ActFunc=ActFunc)\n _response_outputs = self.attention_layer(self.share_attention_layer, bilstm_outputs=response_outputs, attention_source=quote_outputs, ActFunc=ActFunc)\n quote_outputs = _quote_outputs\n response_outputs = _response_outputs\n else:\n quote_outputs = torch.sum(quote_outputs, dim=1)\n response_outputs = torch.sum(response_outputs, dim=1)\n # quote_outputs = torch.mean(quote_outputs, dim=1)\n # response_outputs = torch.mean(response_outputs, dim=1)\n if self.do_BN:\n quote_outputs = self.quote_output_BN(quote_outputs)\n response_outputs = self.response_output_BN(response_outputs)\n return quote_outputs, response_outputs\n\n def attention_layer(self, layer, bilstm_outputs, attention_source, ActFunc):\n\n attention_inputs = attention_source.contiguous().view(-1, self.hidden_size * 2) # [32, 150, 256] -> [32*150, 256]\n # attention_logits = ActFunc(layer(self.dropout(attention_inputs))) # [32*150, 256] -> [32*150, 1]\n attention_logits = ActFunc(layer(attention_inputs)) # [32*150, 256] -> [32*150, 1]\n attention_logits = attention_logits.view(-1, attention_source.size()[1], 1) # [32*150, 1] -> [32, 150, 1]\n attention_logits = attention_logits.transpose(1, 2).contiguous() # [32, 150, 1] -> [32, 1, 150]\n attention_logits = attention_logits.view(-1, attention_source.size()[1]) # [32, 1, 150] -> [32*1, 150]\n attention_signals = F.softmax(attention_logits, dim=1).view(-1, 1, attention_source.size()[1]) # [32*1, 150] -> [32, 1, 150]\n\n return torch.bmm(attention_signals, bilstm_outputs).view(-1, bilstm_outputs.size()[2])\n \n # attention_inputs = attention_source.contiguous().view(-1, self.hidden_size * 2)\n # # attention_logits = layer(self.dropout(attention_inputs)).view(-1, attention_source.size()[1])\n # attention_logits = layer(attention_inputs).view(-1, attention_source.size()[1])\n # attention_signals = F.softmax(ActFunc(attention_logits), dim=1).view(-1, attention_source.size()[1], 1)\n # outputs = attention_signals * bilstm_outputs\n # outputs = torch.sum(outputs, dim=1)\n # # outputs = torch.mean(outputs, dim=1)\n # return outputs\n\n def init_hidden(self, batch_size):\n return self.bilstm.init_hidden(batch_size)\n\nclass Classifier(nn.Module):\n def __init__(self, config):\n super(Classifier, self).__init__()\n self.model = AttentionModel(config)\n self.dropout = nn.Dropout(config['dropout'])\n self.hidden_size = config['hidden_size']\n self.attention_mechanism = config['attention_mechanism']\n self.do_BN = config['do_BN']\n self.class_num = config['class_num']\n \n if self.attention_mechanism['Type'] != 'both_concat':\n self.out = nn.Linear(in_features=self.hidden_size * 2 * 2, out_features=self.class_num)\n else:\n self.out = nn.Linear(in_features=self.hidden_size * 2 * 2 * 2, out_features=self.class_num)\n\n # self.init_weights()\n\n if self.do_BN:\n # self.concat_output_BN = nn.BatchNorm1d(num_features=self.hidden_size * 2 * 2)\n if self.attention_mechanism['Type'] != 'both_concat':\n self.concat_output_BN = nn.BatchNorm1d(num_features=self.hidden_size * 2 * 2)\n else:\n self.concat_output_BN = nn.BatchNorm1d(num_features=self.hidden_size * 2 * 2 * 2)\n\n def init_weights(self, init_range=0.1):\n self.out.weight.data.uniform_(-init_range, init_range)\n self.out.bias.data.fill_(init_range)\n\n def forward(self, X_q_inputs, X_r_inputs, q_init_state, r_init_state):\n quote_outputs, response_outputs = self.model.forward(X_q_inputs, X_r_inputs, q_init_state, r_init_state)\n concat_outputs = torch.cat((quote_outputs, response_outputs), dim=1)\n\n # Siamese\n # response_outputs_siamese, quote_outputs_siamese = self.model.forward(X_r_inputs, X_q_inputs, r_init_state, q_init_state)\n # concat_outputs_siamese = torch.cat((quote_outputs_siamese, response_outputs_siamese), dim=1)\n # Siamese\n\n if self.do_BN:\n concat_outputs = self.concat_output_BN(concat_outputs)\n # concat_outputs_siamese = self.concat_output_BN(concat_outputs_siamese)\n output = self.out(self.dropout(concat_outputs))\n # return output, concat_outputs, concat_outputs_siamese\n return output, quote_outputs, response_outputs\n\n def init_hidden(self, batch_size):\n return self.model.init_hidden(batch_size)\n\nclass ContrastiveLoss(nn.Module):\n\n def __init__(self, margin=2.0):\n super(ContrastiveLoss, self).__init__()\n self.margin = margin\n\n def forward(self, output1, output2, label):\n label = label.float().view(-1, 1)\n euclidean_distance = F.pairwise_distance(output1, output2)\n loss_contrastive = torch.mean(label * torch.pow(euclidean_distance, 2) + (1-label) * torch.pow(torch.clamp(self.margin - euclidean_distance, min=0.0), 2))\n return loss_contrastive\n\ndef train_epoch(model, data_train):\n model.train()\n \n tr_batch_num = int(data_train.y.shape[0] / tr_batch_size)\n display_batch = int(tr_batch_num / display_num)\n\n start_time = time.time()\n _accs = 0.0\n _costs = 0.0\n show_accs = 0.0\n show_costs = 0.0\n\n for batch in range(tr_batch_num):\n model.train()\n\n X_q_batch, X_r_batch, y_batch = data_train.next_batch(tr_batch_size)\n\n X_q_batch = Variable(torch.LongTensor(X_q_batch)).cuda() if USE_GPU else Variable(torch.LongTensor(X_q_batch))\n X_r_batch = Variable(torch.LongTensor(X_r_batch)).cuda() if USE_GPU else Variable(torch.LongTensor(X_r_batch))\n\n y_batch = Variable(torch.LongTensor(y_batch)).cuda() if USE_GPU else Variable(torch.LongTensor(y_batch))\n\n q_init_state = model.init_hidden(y_batch.size()[0])\n r_init_state = model.init_hidden(y_batch.size()[0])\n\n output, quote_outputs, response_outputs = model(X_q_batch, X_r_batch, q_init_state, r_init_state)\n _cost = loss_func(output, y_batch) + 0.1 * siamese_loss(quote_outputs, response_outputs, y_batch)\n # _cost = loss_func(output, y_batch) + siamese_loss(quote_outputs, response_outputs, y_batch)\n y_pred = torch.max(output, 1)[1]\n\n _acc = sum(y_pred.data.cpu() == y_batch.data.cpu()) / float(y_batch.size(0)) if USE_GPU else sum(y_pred.data == y_batch.data) / float(y_batch.size(0))\n\n _accs += _acc\n _costs += _cost.data[0]\n show_accs += _acc\n show_costs += _cost.data[0]\n\n optimizer.zero_grad()\n _cost.backward()\n nn.utils.clip_grad_norm(model.parameters(), max_norm=max_grad_norm)\n optimizer.step()\n\n if (batch + 1) % display_batch == 0:\n valid_acc, valid_cost, _ = test_epoch(model, data_test)\n print('\\ttraining acc={:.6f}, cost={:.6f}; valid acc={:.6f}, cost={:.6f}'.format(show_accs / display_batch, show_costs / display_batch, valid_acc, valid_cost))\n show_accs = 0.0\n show_costs = 0.0\n\n mean_acc = _accs / tr_batch_num\n mean_cost = _costs / tr_batch_num\n\n print('Epoch training {}, acc={:.6f}, cost={:.6f}, speed={:.6f} s/epoch'.format(data_train.y.shape[0], mean_acc, mean_cost, time.time() - start_time))\n test_acc, test_cost, test_cr = test_epoch(model, data_test)\n print('**Test {}, acc={:.6f}, cost={:.6f}\\n'.format(data_test.y.shape[0], test_acc, test_cost))\n print(test_cr)\n\ndef test_epoch(model, dataset):\n model.eval()\n data_size = len(dataset.y)\n _batch_size = data_size\n # _batch_size = int(data_size / 2)\n batch_num = int(data_size / _batch_size)\n _accs = 0.0\n _costs = 0.0\n _pred = []\n _true = []\n for i in range(batch_num):\n\n X_q_batch, X_r_batch, y_batch = dataset.next_batch(_batch_size)\n\n X_q_batch = Variable(torch.LongTensor(X_q_batch), volatile=True).cuda() if USE_GPU else Variable(torch.LongTensor(X_q_batch), volatile=True)\n X_r_batch = Variable(torch.LongTensor(X_r_batch), volatile=True).cuda() if USE_GPU else Variable(torch.LongTensor(X_r_batch), volatile=True)\n\n y_batch = Variable(torch.LongTensor(y_batch), volatile=True).cuda() if USE_GPU else Variable(torch.LongTensor(y_batch), volatile=True)\n\n q_init_state = model.init_hidden(y_batch.size()[0])\n r_init_state = model.init_hidden(y_batch.size()[0])\n\n test_output, quote_outputs, response_outputs = model(X_q_batch, X_r_batch, q_init_state, r_init_state)\n _cost = loss_func(test_output, y_batch) + 0.1 * siamese_loss(quote_outputs, response_outputs, y_batch)\n # _cost = loss_func(test_output, y_batch) + siamese_loss(quote_outputs, response_outputs, y_batch)\n\n y_pred = torch.max(test_output, 1)[1]\n _acc = sum(y_pred.data.cpu() == y_batch.data.cpu()) / float(y_batch.size(0)) if USE_GPU else sum(y_pred.data == y_batch.data) / float(y_batch.size(0))\n\n if i == 0:\n _pred = y_pred.data.cpu().numpy() if USE_GPU else y_pred.data.numpy()\n _true = y_batch.data.cpu().numpy() if USE_GPU else y_batch.data.numpy()\n else:\n _pred = np.concatenate((_pred, y_pred.data.cpu().numpy())) if USE_GPU else np.concatenate((_pred, y_pred.data.numpy()))\n _true = np.concatenate((_true, y_batch.data.cpu().numpy())) if USE_GPU else np.concatenate((_true, y_batch.data.numpy()))\n _accs += _acc\n _costs += _cost.data[0]\n mean_acc = _accs / batch_num\n mean_cost = _costs / batch_num\n cr = classification_report(y_true=_true, y_pred=_pred, target_names=['disagree', 'agree'], digits=4)\n return mean_acc, mean_cost, cr\n\nif __name__ == '__main__':\n\n USE_GPU = True\n if USE_GPU:\n os.environ['CUDA_VISIBLE_DEVICES'] = '0'\n print('Using GPU: {}...'.format(os.environ['CUDA_VISIBLE_DEVICES']))\n \n # attention_mechanism_config = {'Type': 'None', 'ActFunc': F.tanh} # gpu: 0\n # attention_mechanism_config = {'Type': 'self_attention', 'ActFunc': F.tanh} # gpu: 1\n attention_mechanism_config = {'Type': 'cross_attention', 'ActFunc': F.tanh} # gpu: 2\n # attention_mechanism_config = {'Type': 'both_sum', 'ActFunc': F.tanh} # gpu: 2\n # attention_mechanism_config = {'Type': 'both_concat', 'ActFunc': F.tanh} # gpu: 2\n # attention_mechanism_config = {'Type': 'share', 'ActFunc': F.tanh} # gpu: 2\n\n # data_train, data_test, word2id = data_helper_2018.getDataSet(task='disagree_agree', topic='evolution', max_len=64, resampleFlag=False)\n data_train, data_test, word2id = data_helper_2018.getDataSet(task='disagree_agree', topic=None, max_len=64, resampleFlag=False)\n # data_train, data_test, word2id = data_helper_2018.getDataSet(task='debatepedia', topic=None, max_len=64, resampleFlag=False)\n\n # import data_helper_2018_cd\n # data_train, data_test, word2id = data_helper_2018_cd.getDataSet(task='create_debate', max_len=64)\n # data_train, data_test, word2id = data_helper_2018_cd.getDataSet(task='create_debate_noise', max_len=64)\n # data_train, data_test, word2id = data_helper_2018_cd.getDataSet(task='create_debate', max_len=80)\n\n config = {\n 'word2id': word2id, 'pretrain_emb': True, 'class_num': 2,\n 'embedding_size': 300, 'hidden_size': 128, 'layer_num': 2, 'dropout': 0.3, 'lstm_dropout': 0.5,\n 'do_BN': True, 'attention_mechanism': attention_mechanism_config}\n \n model = Classifier(config)\n\n max_grad_norm = 0.1\n\n for name, para in model.named_parameters():\n if para.requires_grad == True:\n print(name)\n if USE_GPU:\n model.cuda()\n\n lr = 1e-3\n optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n loss_func = nn.CrossEntropyLoss()\n siamese_loss = ContrastiveLoss()\n\n tr_batch_size = 32\n max_epoch = 30\n max_max_epoch = 100\n display_num = 5\n\n for epoch in range(1, max_max_epoch+1):\n if epoch > max_epoch:\n for param_group in optimizer.param_groups:\n param_group['lr'] *= 0.97\n lr = optimizer.param_groups[0]['lr']\n print('EPOCH {}, lr={}'.format(epoch, lr))\n train_epoch(model, data_train)\n\n\n\n\n\n\n\n","sub_path":"qrPair_2018/pytorch_bilstm_2018_siamese.py","file_name":"pytorch_bilstm_2018_siamese.py","file_ext":"py","file_size_in_byte":21470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"392995848","text":"from enum import Enum\n\nfrom common.sc_keynodes import ScKeynodes\nfrom common.sc_set import ScSet\nfrom common.sc_event import ScEventParams\n\nfrom sc import *\nfrom scb import *\n\n\nclass ScAgent:\n\n # keynodes\n kCmdInitiated = 'command_initiated'\n kCmdFinished = 'command_finished'\n kNrelResult = 'nrel_result'\n\n kResultNo = 'sc_result_no'\n kResultUnknown = 'sc_result_unknown'\n kResultError = 'sc_result_error'\n kResultErrorInvalidParams = 'sc_result_error_invalid_params'\n kResultErrorInvalidType = 'sc_result_error_invalid_type'\n kResultErrorIO = 'sc_result_error_io'\n kResultInvalidState = 'sc_result_invalid_state'\n kResultErrorNotFound = 'sc_result_error_not_found'\n kResultErrorNoWriteRights = 'sc_result_error_no_write_rights'\n kResultErrorNoReadRights = 'sc_result_error_no_read_rights'\n\n def __init__(self, module):\n self.module = module\n self.evt = None\n self.keynodes = ScKeynodes(module.ctx)\n\n def Register(self, addr, evt_type):\n \"\"\"Register this agent to a specified event\n addr - ScAddr of sc-element to subscribe event\n evt_type - on of ScPythonEventType values (type of event)\n \"\"\"\n assert self.evt == None\n self.evt = self.module.events.CreateEventInternal(\n addr, evt_type, self._run)\n \n self.module.log.info(self.__class__.__name__ + ' registered')\n\n def Unregister(self):\n self.module.events.DestroyEvent(self.evt)\n self.evt = None\n\n self.module.log.info(self.__class__.__name__ + ' unregistered')\n\n def RunImpl(self, evt: ScEventParams) -> ScResult:\n \"\"\"Should be override and do agent logic.\n It should return one of ScAgent.Status values\n\n evt - ScEventParams instance\n \"\"\"\n return ScResult.Error\n\n def CheckImpl(self, evt: ScEventParams):\n \"\"\"This function can be overrided to check any conditions before run.\n If this function returns True, then RunImpl should be called; \n otherwise it woudn't be run\n \"\"\"\n return True\n\n # --- Internal usage methods ---\n def _run(self, evt: ScEventParams):\n \"\"\"Just for internal usage\n \"\"\"\n if self.CheckImpl(evt):\n self.module.log.info(self.__class__.__name__ + ' emited')\n result = self.RunImpl(evt)\n if result != ScResult.Ok:\n self.module.log.warning(self.__class__.__name__ + ' finished with error')\n else:\n self.module.log.info(self.__class__.__name__ + ' finished')\n\n\nclass ScAgentCommand(ScAgent):\n \"\"\"This type of agents initiated with command_initiated set.\n It check if initiated command class is equal to specified one,\n then run it. You doesn't need to call register function for this\n type of agents\n \"\"\"\n\n def __init__(self, module, cmd_class_addr):\n ScAgent.__init__(self, module)\n self.cmd_class = cmd_class_addr\n self.cmd_addr = ScAddr()\n self.result_set = None\n\n self.Register(\n self.keynodes[ScAgent.kCmdInitiated],\n ScPythonEventType.AddOutputEdge)\n\n def CheckImpl(self, evt):\n \"\"\"Check if type of initiated command is equal to specified one\n \"\"\"\n return self.module.ctx.HelperCheckEdge(\n self.cmd_class,\n evt.other_addr,\n ScType.EdgeAccessConstPosPerm)\n\n def RunImpl(self, evt):\n self.cmd_addr = evt.other_addr\n assert self.cmd_addr.IsValid()\n\n # change state to a progress\n progress_edge = evt.edge_addr\n\n def change_progress(state: ScAddr):\n self.module.ctx.DeleteElement(progress_edge)\n self.module.ctx.CreateEdge(ScType.EdgeAccessConstPosPerm, state, self.cmd_addr)\n\n change_progress(ScKeynodes.kCommandProgressdAddr())\n\n # create result structure\n templ = ScTemplate()\n templ.TripleWithRelation(\n self.cmd_addr,\n ScType.EdgeDCommonVar,\n ScType.NodeVarStruct >> '_result',\n ScType.EdgeAccessVarPosPerm,\n self.keynodes[ScAgent.kNrelResult])\n\n gen_res = self.module.ctx.HelperGenTemplate(templ, ScTemplateGenParams())\n assert gen_res.Size() > 0\n\n res_addr = gen_res['_result']\n self.result_set = ScSet(self.module.ctx, res_addr)\n\n # run implementation of command\n result = self.DoCommand()\n\n # generate result type\n self.module.ctx.CreateEdge(ScType.EdgeAccessConstPosPerm, ScKeynodes.GetResultCodeAddr(result), res_addr)\n change_progress(ScKeynodes.kCommandFinishedAddr())\n\n return result\n\n def DoCommand(self) -> ScResult:\n \"\"\"Should be overrided.\n This method calls to run command implementation\n Should return value like RunImpl\n \"\"\"\n return ScResult.No\n\n def GetParam(self, index):\n \"\"\"Return parameter of command by specified index.\n Index value starts from 1. This function trying to find\n sc-element in command structure with attribute `rrel_`\n \"\"\"\n templ = ScTemplate()\n templ.TripleWithRelation(\n self.cmd_addr,\n ScType.EdgeAccessVarPosPerm,\n ScType.Unknown >> '_el',\n ScType.EdgeAccessVarPosPerm,\n self.keynodes['rrel_{}'.format(index)])\n\n search_res = self.module.ctx.HelperSearchTemplate(templ)\n if search_res.Size() == 0:\n return ScAddr()\n\n return search_res[0]['_el']\n\n @staticmethod\n def CreateCommand(ctx: ScMemoryContext, cmd_class_addr: ScAddr, params: [ScAddr]) -> ScAddr:\n return ScAgentCommandImpl.CreateCommand(ctx, cmd_class_addr, params)\n\n @staticmethod\n def RunCommand(ctx: ScMemoryContext, cmd_addr: ScAddr) -> bool:\n return ScAgentCommandImpl.RunCommand(ctx, cmd_addr)\n\n @staticmethod\n def RunCommandWait(ctx: ScMemoryContext, cmd_addr: ScAddr, wait_timeout_ms: int) -> bool:\n return ScAgentCommandImpl.RunCommandWait(ctx, cmd_addr, wait_timeout_ms)\n\n @staticmethod\n def GetCommandResultAddr(ctx: ScMemoryContext, cmd_addr: ScAddr) -> ScAddr:\n return ScAgentCommandImpl.GetCommandResultAddr(ctx, cmd_addr)\n\n # --- internal functions ---\n def _kb_resolve_status_addr(self, status):\n if status == ScAgent.Status.SC_RESULT_ERROR:\n sc_result_ok\n\n return ScAddr()\n\n def _kb_generate_status(self, status):\n \"\"\"Append result structure to a special set depending on a status\n \"\"\"\n pass\n","sub_path":"sc-kpm/sc-python/services/common/sc_agent.py","file_name":"sc_agent.py","file_ext":"py","file_size_in_byte":6032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"120736415","text":"import _plotly_utils.basevalidators\n\n\nclass InsidetextorientationValidator(_plotly_utils.basevalidators.EnumeratedValidator):\n def __init__(\n self, plotly_name=\"insidetextorientation\", parent_name=\"sunburst\", **kwargs\n ):\n super(InsidetextorientationValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"plot\"),\n values=kwargs.pop(\"values\", [\"horizontal\", \"radial\", \"tangential\", \"auto\"]),\n **kwargs,\n )\n","sub_path":"packages/python/plotly/plotly/validators/sunburst/_insidetextorientation.py","file_name":"_insidetextorientation.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"649661224","text":"from permission import registry\nfrom permission import PermissionHandler\n\nfrom models import YourModel\n\nclass FilizverPermissionHandler(PermissionHandler):\n \"\"\"Permission handler class for ``YourModel``. Similar with AdminSite\"\"\"\n def has_perm(self, user_obj, perm, obj=None):\n \"\"\"this is called for checking permission of the model.\"\"\"\n if user_obj.is_authenticated():\n if perm == 'yourapp.add_yourmodel':\n # Authenticated user has add permissions of this model\n return True\n elif obj and obj.author == user_obj:\n # Otherwise (change/delete) user must be an author\n return True\n # User doesn't have permission of ``perm``\n return False\n\n# register this ``YourModelPermissionHandler`` with ``YourModel``\n#registry.register(YourModel, YourModelPermissionHandler)","sub_path":"filizver/_apps/core/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"639593478","text":"#!/usr/local/bin/python3\n# coding: utf-8\nfrom copy import deepcopy\n\nfrom .lib.util import LOG_FILE_PATH\n\nTEMPLATE = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"formatters\": {\n \"default\": {\n \"format\": \"[%(asctime)s] %(levelname)s %(message)s\",\n \"datefmt\": \"%Y-%m-%d %H:%M:%S\",\n },\n \"long\": {\n \"format\": \"[%(asctime)s] %(levelname)s - \" +\n \"%(filename)s#%(funcName)s:%(lineno)d: %(message)s\",\n \"datefmt\": \"%Y-%m-%d %H:%M:%S\",\n },\n },\n \"handlers\": {\n \"console\": {\n \"level\": \"INFO\",\n \"class\": \"logging.StreamHandler\",\n \"formatter\": \"default\",\n \"stream\": \"ext://sys.stderr\"\n },\n \"file\": {\n \"level\": \"INFO\",\n \"class\": \"logging.FileHandler\",\n \"formatter\": \"default\",\n \"filename\": str(LOG_FILE_PATH),\n },\n },\n \"root\": {\n \"handlers\": [\"console\", \"file\"],\n \"level\": \"INFO\",\n },\n}\n\nwsgi_info = deepcopy(TEMPLATE)\nwsgi_info[\"root\"][\"handlers\"] = [\"file\"]\nwsgi_debug = deepcopy(TEMPLATE)\nwsgi_debug[\"handlers\"][\"file\"][\"level\"] = \"DEBUG\"\nwsgi_debug[\"handlers\"][\"file\"][\"formatter\"] = \"long\"\nwsgi_debug[\"root\"][\"handlers\"] = [\"file\"]\nwsgi_debug[\"root\"][\"level\"] = \"DEBUG\"\n\nlocal_info = deepcopy(TEMPLATE)\nlocal_debug = deepcopy(TEMPLATE)\nlocal_debug[\"handlers\"][\"console\"][\"level\"] = \"DEBUG\"\nlocal_debug[\"handlers\"][\"console\"][\"formatter\"] = \"long\"\nlocal_debug[\"handlers\"][\"file\"][\"level\"] = \"DEBUG\"\nlocal_debug[\"handlers\"][\"file\"][\"formatter\"] = \"long\"\nlocal_debug[\"root\"][\"level\"] = \"DEBUG\"\n","sub_path":"src/app/logging_config.py","file_name":"logging_config.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"285531510","text":"import re\n\nurl_param_re = re.compile(\"/{([0-9a-zA-Z_]+)}/?\")\n\n\nclass UrlParamParser:\n def __init__(self, route):\n self.route = route\n self.fields = []\n\n self._build()\n\n def _build(self):\n url_matcher = self.route\n\n match = url_param_re.search(self.route)\n if match:\n for grp in match.groups():\n self.fields.append(grp)\n\n url_matcher = url_matcher.replace(\"{\" + grp + \"}\", \"(.+)\")\n\n self.matcher = re.compile(\"^\" + url_matcher + \"/?$\")\n\n def match(self, route):\n return self.matcher.match(route) is not None\n\n def resolve_params(self, route):\n params = {}\n\n match = self.matcher.search(route)\n if not match:\n return {}\n\n groups = list(match.groups())\n\n if len(groups) != len(self.fields):\n raise Exception(\n f\"Field and group counts do not match while resolving params. \"\n \"Groups: {len(groups)} Fields: {len(self.fields)}\"\n )\n\n for grp, field in zip(groups, self.fields):\n params[field] = grp\n\n return params\n","sub_path":"sydney/server/url_param_parser.py","file_name":"url_param_parser.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"651909051","text":"import sys\nimport random\nimport time\nimport cv2\nimport operator\nimport numpy as np\nfrom sim import *\nimport tflearn\nfrom tflearn.layers.core import input_data, dropout, fully_connected\nfrom tflearn.layers.estimator import regression\nfrom statistics import mean, median\nfrom collections import Counter\n\ns = Simulator(512, 512)\n\ndef neural_network_model(input_size):\n\n network = input_data(shape=[None, input_size, 1], name=\"input\")\n\n network = fully_connected(network, 128, activation=\"relu\")\n network = dropout(network, 0.8)\n\n network = fully_connected(network, 256, activation=\"relu\")\n network = dropout(network, 0.8)\n\n network = fully_connected(network, 512, activation=\"relu\")\n network = dropout(network, 0.8)\n\n network = fully_connected(network, 256, activation=\"relu\")\n network = dropout(network, 0.8)\n\n network = fully_connected(network, 128, activation=\"relu\")\n network = dropout(network, 0.8)\n\n network = fully_connected(network, 2, activation=\"softmax\")\n network = regression(network, optimizer=\"adam\", learning_rate = 1e-3, loss=\"categorical_crossentropy\", name=\"targets\")\n model = tflearn.DNN(network, tensorboard_dir=\"j_log\")\n\n model.load('jm.model')\n\n return model\n\n# try:\n# for i in range(256):\n# model = neural_network_model(i)\n# print(i)\n# except:\n# pass\n\nfor i in range(256):\n try:\n model = neural_network_model(i)\n except:\n continue\n\n\nscores = []\nchoices = []\n\nfor each_game in range(5):\n score = 0\n game_memory = []\n prev_obs = []\n steps = 0\n s.reset(view=True)\n for i in range(1000):\n \n if len(prev_obs) == 0: # prev_obs\n action = s.randomActionSampler()\n else:\n action = np.argmax(model.predict(prev_obs.reshape(-1,len(prev_obs),1))[0])\n \n choices.append(action)\n steps += 1\n\n if action == 0:\n s.emulateKeyPress(\"w\", view=True)\n print(\"w\")\n elif action == 1:\n s.emulateKeyPress(\"a\", view=True)\n print(\"a\")\n elif action == 2:\n s.emulateKeyPress(\"s\", view=True)\n print(\"s\")\n elif action == 3:\n s.emulateKeyPress(\"d\", view=True)\n print(\"d\")\n\n new_observation = s.getObservation()\n prev_obs = new_observation\n game_memory.append([new_observation, action])\n score += s.getScore()\n # cv2.waitKey(0)\n # time.sleep(.1)\n if steps > 150:\n s.reset()\n break\n \n if s.getDoneStatus():\n break\n \n scores.append(score)\n\nprint('Average Score:',sum(scores)/len(scores))\n# print('choice 1:{} choice 0:{}'.format(choices.count(1)/len(choices),choices.count(0)/len(choices)))\nprint(\"choices: {}\".format(choices))\nprint(\"choice 0 (W): {}\".format(choices.count(0)))\nprint(\"choice 1 (A): {}\".format(choices.count(1)))\nprint(\"choice 2 (S): {}\".format(choices.count(2)))\nprint(\"choice 3 (D): {}\".format(choices.count(3)))\nprint(score_requirement)\n","sub_path":"testModel.py","file_name":"testModel.py","file_ext":"py","file_size_in_byte":3038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"472596601","text":"#!/usr/bin/env python\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\n\nimport sys\nfrom datetime import datetime\nfrom humanize import naturalsize\nfrom collections import OrderedDict, deque\nfrom pprint import pformat\nfrom semantic_version import Version as semver\n\ntry:\n import ConfigParser as configparser\nexcept ImportError:\n import configparser\n\nif sys.version_info[0] == 2:\n reload(sys)\n sys.setdefaultencoding('utf-8')\n\ndef info(*objs):\n print(\"INFO:\", *objs, file=sys.stderr)\n\ndef warning(*objs):\n print(\"WARNING:\", *objs, file=sys.stderr)\n\n\ndef debug(*objs):\n print(\"DEBUG:\\n\", *objs, file=sys.stderr)\n\n\ndef get_date(date_string, uts=False):\n if not uts:\n return datetime.strptime(date_string, \"%a %b %d %H:%M:%S %Y\")\n else:\n return datetime.fromtimestamp(float(date_string))\n\n\ndef get_str(s):\n if sys.version_info[0] == 2 and s is not None:\n return s.decode('ISO-8859-1')\n else:\n return s\n\n\n\nclass ConfigLoader(object):\n\n def __init__(self, config_file):\n self.settings = {}\n self.vpns = OrderedDict()\n config = configparser.RawConfigParser()\n contents = config.read(config_file)\n\n if not contents and config_file == './openvpn-monitor.conf':\n warning('Config file does not exist or is unreadable: {0!s}'.format(config_file))\n if sys.prefix == '/usr':\n conf_path = '/etc/'\n else:\n conf_path = sys.prefix + '/etc/'\n config_file = conf_path + 'openvpn-monitor.conf'\n contents = config.read(config_file)\n\n if contents:\n info('Using config file: {0!s}'.format(config_file))\n fp = open(\"port_info.txt\",\"w\")\n fp.close()\n else:\n warning('Config file does not exist or is unreadable: {0!s}'.format(config_file))\n self.load_default_settings()\n\n for section in config.sections():\n if section == 'OpenVPN-Monitor':\n self.parse_global_section(config)\n else:\n self.parse_vpn_section(config, section)\n\n def load_default_settings(self):\n info('Using default settings => localhost:5555')\n self.settings = {'site': 'Default Site',\n 'geoip_data': '/usr/share/GeoIP/GeoIPCity.dat',\n 'datetime_format': '%d/%m/%Y %H:%M:%S'}\n self.vpns['Default VPN'] = {'name': 'default',\n 'host': 'localhost',\n 'port': '5555',\n 'show_disconnect': False}\n\n def parse_global_section(self, config):\n global_vars = ['site', 'logo', 'latitude', 'longitude', 'maps', 'geoip_data', 'datetime_format']\n for var in global_vars:\n try:\n self.settings[var] = config.get('OpenVPN-Monitor', var)\n except configparser.NoOptionError:\n pass\n\n def parse_vpn_section(self, config, section):\n self.vpns[section] = {}\n vpn = self.vpns[section]\n options = config.options(section)\n for option in options:\n try:\n vpn[option] = config.get(section, option)\n if vpn[option] == -1:\n warning('CONFIG: skipping {0!s}'.format(option))\n except configparser.Error as e:\n warning('CONFIG: {0!s} on option {1!s}: '.format(e, option))\n vpn[option] = None\n if 'show_disconnect' in vpn and vpn['show_disconnect'] == 'True':\n vpn['show_disconnect'] = True\n else:\n vpn['show_disconnect'] = False\n\n\n\n","sub_path":"config_loader.py","file_name":"config_loader.py","file_ext":"py","file_size_in_byte":3757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"629962462","text":"#!/usr/bin/env/python\n\n'''\nModule :mod: 'hmtk.plotting.seismicity.completeness.plot_stepp_1971' \ncreates plot to illustrate outcome of Stepp (1972) method for completeness \nanalysis\n'''\nimport os.path\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nvalid_markers = ['*', '+', '1', '2', '3', '4', '8', '<', '>', 'D', 'H', '^',\n '_', 'd', 'h', 'o', 'p', 's', 'v', 'x', '|']\n\n\ndef create_stepp_plot(model, filename, filetype='png', \n filedpi=300):\n '''\n Creates the classic Stepp (1972) plots for a completed Stepp analysis, \n and exports the figure to a file.\n :param model:\n Completed Stepp (1972) analysis as instance of :class:\n 'hmtk.seismicity.completeness.comp_stepp_1971.Stepp1971'\n :param string filename: \n Name of output file\n :param string filetype: \n Type of file (from list supported by matplotlib)\n :param int filedpi:\n Resolution (dots per inch) of output file\n '''\n if os.path.exists(filename):\n raise IOError('File already exists!')\n \n legend_list = [(str(model.magnitude_bin[iloc] + 0.01) + ' - ' + \n str(model.magnitude_bin[iloc + 1])) for iloc in range(0, \n len(model.magnitude_bin) - 1)]\n \n rgb_list = []\n marker_vals = []\n # Get marker from valid list\n while len(valid_markers) < len(model.magnitude_bin):\n valid_markers.append(valid_markers)\n \n marker_sampler = np.arange(0, len(valid_markers),1)\n np.random.shuffle(marker_sampler)\n # Get colour for each bin\n for value in range(0, len(model.magnitude_bin) - 1):\n rgb_samp = np.random.uniform(0., 1., 3)\n rgb_list.append((rgb_samp[0], rgb_samp[1], rgb_samp[2]))\n marker_vals.append(valid_markers[marker_sampler[value]])\n # Plot observed Sigma lambda\n for iloc in range(0, len(model.magnitude_bin) - 1):\n plt.loglog(model.time_values, \n model.sigma[:, iloc],\n linestyle='None',\n marker=marker_vals[iloc], \n color=rgb_list[iloc])\n \n plt.legend(legend_list)\n # Plot expected Poisson rate\n for iloc in range(0, len(model.magnitude_bin) - 1):\n plt.loglog(model.time_values, \n model.model_line[:,iloc], \n linestyle='-',\n marker='None',\n color=rgb_list[iloc])\n xmarker = model.end_year - model.completeness_table[iloc, 0]\n id0 = model.model_line[:, iloc] > 0.\n ymarker = 10.0 ** np.interp(np.log10(xmarker),\n np.log10(model.time_values[id0]),\n np.log10(model.model_line[id0, iloc]))\n plt.loglog(xmarker, ymarker, 'ks')\n plt.xlabel('Time (years)', fontsize=15)\n plt.ylabel('$\\sigma_{\\lambda} = \\sqrt{\\lambda} / \\sqrt{T}$', \n fontsize=15)\n # Save figure to file\n plt.savefig(filename, dpi=filedpi, format=filetype)\n","sub_path":"hmtk/plotting/seismicity/completeness/plot_stepp_1972.py","file_name":"plot_stepp_1972.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"257019482","text":"import logging\n\nfrom src.api_rest.model.entity.EntityRoute import EntityRoute\nfrom src.api_rest.model.planning_strategies.StochasticVRPMultiDepotStrategy import StochasticVRPMultiDepotStrategy\nfrom src.api_rest.service.ProductService import modifyProductsStock\nfrom src.api_rest.utils import toRoutes, toProducts, ProdutOperation\nfrom src.commons import MongoCollection, MongoRouteFields, RouteState\nfrom src.mongo_adapter.MongoClientSingleton import MongoClientSingleton\n\n\n### function: getRoutes ###\n\ndef getRoutes (filters = None) :\n try :\n query = {}\n if filters is not None : query = filters\n\n logging.info (\"RouteService: getRoutes: filters: [\" + str (filters) + \"]\")\n\n res = MongoClientSingleton ().getCollection (MongoCollection.ROUTE).find (query)\n\n return toRoutes (res)\n\n except Exception as exc :\n logging.error (\"RouteService: getRoutes: Error getting routes, filters: \" + str (filters))\n logging.error (\"[Exception: \" + str (exc) + \"]\")\n\n\n### function: addRoute ###\n\ndef addRoute (origin, destiny, departure, arrival, productsJson, strategy) :\n try :\n if strategy == StochasticVRPMultiDepotStrategy.STRATEGY_NAME :\n strategy = StochasticVRPMultiDepotStrategy ()\n else :\n raise Exception (\"Unknow strategy '\" + strategy + \"'\")\n\n route = EntityRoute (origin, destiny, departure, arrival, toProducts (productsJson), strategy)\n\n MongoClientSingleton ().getCollection (MongoCollection.ROUTE).insertOne (route.toJson ())\n\n modifyProductsStock (route.products, ProdutOperation.DECREMENT)\n\n return route\n\n except Exception as exc :\n logging.error (\"RouteService: addRoute: Error addind route. Params: \" + origin + \", \" + destiny + \", \" + \\\n departure + \", \" + arrival + \", \" + productsJson)\n logging.error (\"[Exception: \" + str (exc) + \"]\")\n\n\n### function: checkEditRoute ###\n\ndef checkEditRoute (route) :\n if (route.state == RouteState.PENDING): return True\n else : return False\n\n\n### function: updateRoute ###\n\ndef updateRoute (originalRoute, fieldsToUpdate) :\n MongoClientSingleton ().getCollection (MongoCollection.ROUTE).updateOneById (originalRoute.id, fieldsToUpdate)\n\n return getRoutes ({MongoRouteFields.ID : originalRoute.id}) [0]\n\n\n### function: cancelRoute ###\n\ndef cancelRoute (route) :\n try :\n route.state = RouteState.CANCELED\n\n MongoClientSingleton ().getCollection (MongoCollection.ROUTE)\\\n .updateOneFieldById (route.id, MongoRouteFields.STATE, route.state)\n\n modifyProductsStock (route.products, ProdutOperation.INCREMENT)\n\n return route\n\n except Exception as exc :\n logging.error (\"RouteService: cancelRoute: Error canceling route: \" + str (route))\n logging.error (\"[Exception: \" + str (exc) + \"]\")","sub_path":"src/api_rest/service/RouteService.py","file_name":"RouteService.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"377118952","text":"# !/usr/bin/env python\nimport os\n\ndef main():\n path = os.getcwd()\n # print(path)\n for root, dirs, files in os.walk(path):\n # print(root, dirs, files)\n for f in files:\n fname = os.path.splitext(f)\n if fname[1] == \".wav\":\n # print(f)\n os.remove(os.path.join(root,f))\n print(\"remove file \"+os.path.join(root,f)+\" success!\")\n os.system(\"pause\")\n\nif __name__ == '__main__':\n main()","sub_path":"delWAV.py","file_name":"delWAV.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"533433115","text":"#! usr/bin/python3\nimport os\n\nos.chdir(os.getenv(\"HOME\"))\n\nprint(\" Open Shell !!!\\n\")\n\n# Running the terminal\nwhile True:\n command = input(\">>>\")\n if command.split()[0] == \"cd\":\n try:\n os.chdir(command[3:])\n except FileNotFoundError:\n print(\"bash: cd: No such file or directory\")\n elif command == 'exit':\n break\n else:\n os.system(command)","sub_path":"7.shell.py","file_name":"7.shell.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"206421456","text":"from rest_framework import generics, serializers\nfrom rest_framework.response import Response\n\nfrom sundaycodelab.models import CodeLabExternal\n\n\nclass CodelabListSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = CodeLabExternal\n fields = '__all__'\n\n\nclass CodeLabExternalListView(generics.ListAPIView):\n queryset = CodeLabExternal.objects.all()\n serializer_class = CodelabListSerializer\n\n def list(self, request):\n queryset = self.get_queryset()\n serializer_class = self.get_serializer_class()\n serializer = serializer_class(queryset, many=True)\n\n page = self.paginate_queryset(queryset)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n\n return Response(serializer.data)\n\n\nclass CodelabExternalDetailSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = CodeLabExternal\n exclude = ()\n depth = 1\n fields = '__all__'\n\n\nclass CodeLabExternalDetailView(generics.RetrieveAPIView):\n queryset = CodeLabExternal.objects.all()\n serializer_class = CodelabExternalDetailSerializer\n lookup_field = 'pk'\n","sub_path":"api/views/codelab.py","file_name":"codelab.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"175842728","text":"\"\"\"Test nsjail.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport subprocess\nimport unittest\nimport nsjail\n\n\nclass NsjailTest(unittest.TestCase):\n\n def setUp(self):\n nsjail.__file__ = '/'\n\n def testMinimalParameters(self):\n commands = nsjail.run(\n nsjail_bin='/bin/true',\n chroot='/chroot',\n source_dir='/source_dir',\n command=['/bin/bash'],\n android_target='target_name')\n self.assertEqual(\n commands,\n [\n [\n '/bin/true',\n '--bindmount', '/source_dir:/src',\n '--chroot', '/chroot',\n '--env', 'USER=android-build',\n '--config', '/nsjail.cfg',\n '--', '/bin/bash'\n ]\n ]\n )\n\n def testFailingJailedCommand(self):\n with self.assertRaises(subprocess.CalledProcessError):\n nsjail.run(\n nsjail_bin='/bin/false',\n chroot='/chroot',\n source_dir='/source_dir',\n command=['/bin/bash'],\n android_target='target_name')\n\n def testDist(self):\n commands = nsjail.run(\n nsjail_bin='/bin/true',\n chroot='/chroot',\n source_dir='/source_dir',\n command=['/bin/bash'],\n android_target='target_name',\n dist_dir='/dist_dir')\n self.assertEqual(\n commands,\n [\n [\n '/bin/true',\n '--bindmount', '/source_dir:/src',\n '--chroot', '/chroot',\n '--env', 'USER=android-build',\n '--config', '/nsjail.cfg',\n '--bindmount', '/dist_dir:/dist',\n '--env', 'DIST_DIR=/dist',\n '--', '/bin/bash'\n ]\n ]\n )\n\n def testBuildID(self):\n commands = nsjail.run(\n nsjail_bin='/bin/true',\n chroot='/chroot',\n source_dir='/source_dir',\n command=['/bin/bash'],\n android_target='target_name',\n build_id='0')\n self.assertEqual(\n commands,\n [\n [\n '/bin/true',\n '--bindmount', '/source_dir:/src',\n '--chroot', '/chroot',\n '--env', 'USER=android-build',\n '--config', '/nsjail.cfg',\n '--env', 'BUILD_NUMBER=0',\n '--', '/bin/bash'\n ]\n ]\n )\n\n def testMaxCPU(self):\n commands = nsjail.run(\n nsjail_bin='/bin/true',\n chroot='/chroot',\n source_dir='/source_dir',\n command=['/bin/bash'],\n android_target='target_name',\n max_cpus=1)\n self.assertEqual(\n commands,\n [\n [\n '/bin/true',\n '--bindmount', '/source_dir:/src',\n '--chroot', '/chroot',\n '--env', 'USER=android-build',\n '--config', '/nsjail.cfg',\n '--max_cpus=1',\n '--', '/bin/bash'\n ]\n ]\n )\n\n def testUserGroupID(self):\n nsjail.GROUPADD_COMMAND = '/bin/true'\n nsjail.USERADD_COMMAND = '/bin/true'\n commands = nsjail.run(\n nsjail_bin='/bin/true',\n chroot='/chroot',\n source_dir='/source_dir',\n command=['/bin/bash'],\n android_target='target_name',\n user_id=os.getuid(),\n group_id=os.getgid())\n self.assertEqual(\n commands,\n [\n [\n '/bin/true',\n 'android-build',\n '--gid', str(os.getgid()),\n ],\n [\n '/bin/true',\n '--gid', 'android-build',\n '--groups', 'sudo',\n '--uid', str(os.getuid()),\n '--create-home',\n 'android-build'\n ],\n [\n '/bin/true',\n '--bindmount', '/source_dir:/src',\n '--chroot', '/chroot',\n '--env', 'USER=android-build',\n '--config', '/nsjail.cfg',\n '--', '/bin/bash'\n ]\n ]\n )\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"keystone/nsjail_test.py","file_name":"nsjail_test.py","file_ext":"py","file_size_in_byte":4133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"266327220","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport sys\nimport re\nimport os\n\ndef __read_file_lines(file_name):\n try:\n with open(file_name, 'r') as file:\n lines = (file.read())\n lines = lines.split('\\n') \n except:\n print('file not exist or corupted')\n sys.exit()\n return lines \n \ndef __get_input_file_name(dir_name,sub_dir):\n file_list = []\n try:\n file_dir = os.getcwd() + '\\\\' + dir_name + '\\\\' + sub_dir\n for root, dirs, files in os.walk(file_dir):\n for file in files:\n if os.path.splitext(file)[1] == '.h': \n file_list.append(os.path.join(root,file))\n return file_list\n except:\n print('file not exist or corupted')\n sys.exit()\n \ndef __mkdir_out_filefolder():\n try:\n myfile = os.getcwd()+'\\\\out_dir'\n if not os.path.exists(myfile):\n os.mkdir(myfile)\n except:\n print('file not exist or corupted')\n sys.exit()\n \ndef __demo_file_line_process_module(line,demo_lines,oldstr):\n demo_lines_out = [] \n try:\n modulestr = line.split('\\\"')[1]\n modulestr = modulestr.split('[')[0]\n modulestr = modulestr.upper()\n for demo_line in demo_lines: \n demo_line = demo_line.replace(oldstr,modulestr) \n demo_lines_out.append(demo_line) \n except:\n print('len of line is 1 ')\n sys.exit() \n return demo_lines_out \n\ndef __demo_file_line_process_bit(line,demo_lines,oldstr):\n demo_lines_out = [] \n modulestr = line.split(' ')\n modulestr = modulestr[0]\n modulestr = modulestr.upper()\n try:\n for demo_line in demo_lines: \n demo_line = demo_line.replace(oldstr,modulestr)\n demo_lines_out.append(demo_line) \n except:\n print('len of line is 1 ')\n sys.exit() \n return demo_lines_out \n\ndef __get_output_file_name(out_file_name):\n try: \n out_file_name = out_file_name.lower()\n out_file_name = 'out_dir\\\\' + out_file_name + '_'+ 'struct_interface_bit.h' \n return out_file_name \n except:\n print('len of line is 1 ')\n sys.exit() \n \ndef __file_line_process(lines,demo_lines): \n demo_lines_out = demo_lines\n try: \n demo_lines_out = __demo_file_line_process_module(lines[0],demo_lines_out,'AAAAA')\n demo_lines_out = __demo_file_line_process_module(lines[1],demo_lines_out,'BBBBB')\n oldstr = 'NULL'\n counter = 0\n for line in lines[2:]: \n line_check = line[0:1] \n if line_check !='' and line_check !='\\n' and line_check !=' ' : \n oldstr1 = oldstr + str(counter)\n demo_lines_out = __demo_file_line_process_bit(line,demo_lines_out,oldstr1) \n counter = counter+1 \n return demo_lines_out \n except:\n print('len of line is 22 ')\n sys.exit() \n \ndef __wirte_list_to_file(list_out,file_name):\n try:\n with open(file_name, 'w+') as file:\n file_name = file_name.split('\\\\')\n file_name = file_name[-1]\n file_name = file_name.replace('.','_')\n file_name1 = '#ifndef ' + file_name.upper()+'\\n'\n file_name2 = '#define ' + file_name.upper()+'\\n'\n file.write(file_name1)\n file.write(file_name2)\n file.write('\\n'.join(list_out)) \n file.write('\\n#endif\\n')\n except:\n print('file not exist or corupted')\n sys.exit()\n \ndef __file_read_process(file_all,demo_lines,sub_dir):\n demo_lines_out_all = []\n for file_name in file_all: \n lines = __read_file_lines(file_name)\n demo_lines_out = __file_line_process(lines,demo_lines)\n demo_lines_out_all = demo_lines_out_all + demo_lines_out\n out_file_name = __get_output_file_name(sub_dir)\n __wirte_list_to_file(demo_lines_out_all,out_file_name)\n \n \ndef get_struct_bit(dir_name,sub_dir):\n file_list = __get_input_file_name(dir_name,sub_dir)\n demo_lines = __read_file_lines('demo.h')\n __mkdir_out_filefolder() \n __file_read_process(file_list,demo_lines,sub_dir)\n \ndef main(argv=None):\n if argv is None:\n argv = sys.argv\n if len(argv) < 2:\n print('please set argv as log file')\n else: \n get_struct_bit(argv[1]) \n print('generate file end'); \n\nif __name__ == \"__main__\":\n sys.exit(main())\n ","sub_path":"struct_bit.py","file_name":"struct_bit.py","file_ext":"py","file_size_in_byte":4681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"500436656","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Project: QuestionFromProfWang\n# File name: query_church\n# Author: Mark Wang\n# Date: 24/7/2016\n\nimport os\n\nfrom ..google_maps.query_us_place_information import query_information_from_google_maps\n\npath = '/'.join(__file__.split('/')[:-1])\n# print path\n\n# raise Exception('hahah')\n\nboundary = {'west': -88.73352838270105,\n 'east': -88.38255513960547,\n 'north': 47.26982759633027,\n 'south': 43.16892014678899}\n\nquery_information_from_google_maps(query_type='church', country_code='usa', radius=5000.0, save_path=path,\n boundary=boundary, require_detail=False,\n # previous_file=os.path.join(path, 'usa_church_information.csv')\n )\n","sub_path":"GeoInfoQuery/church/query_church.py","file_name":"query_church.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"526902888","text":"t=int(input())\n\nwhile(t!=0):\n\tn=int(input())\n\tls=[]\n\tfor i in range(n):\n\t\tls.append(list(input()))\n\t\t\n\tarr=[]\n\tfor i in range(n):\n\t\tarr.append(int (ls[i][-1]))\n\t# ~ print(arr)\n\tones=arr.count(1)\n\tzeroes=arr.count(0)\n\tans=max(ones,zeroes)\n\tif(ans==ones):\n\t\tprint(ans)\n\telse:\n\t\t\n\t\tif(ans%2==0):\n\t\t\tprint(ans)\n\t\telse:\n\t\t\tprint(ans+1)\n\tt-=1\n","sub_path":"TRAINSET.py","file_name":"TRAINSET.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"641631534","text":"import json\nimport os\nimport secrets\n\nfrom functools import wraps\n\nfrom flask import Flask, request, Response, abort, redirect, make_response, session\n\nfrom jupyterhub.services.auth import HubOAuth\nfrom models import JobsResponse\nfrom services import SlurmAPI\n\nprefix = os.environ.get('JUPYTERHUB_SERVICE_PREFIX', '/')\n\nauth = HubOAuth(api_token=os.environ['JUPYTERHUB_API_TOKEN'], cache_max_age=60)\n\napp = Flask('slurm_proxy')\napp.secret_key = secrets.token_bytes(32)\n\ndef authenticated(f):\n \"\"\"Decorator for authenticating with the Hub\"\"\"\n @wraps(f)\n def decorated(*args, **kwargs):\n token = session.get(\"token\")\n if token:\n user = auth.user_for_token(token)\n else:\n user = None\n if user:\n return f(user, *args, **kwargs)\n else:\n state = auth.generate_state(next_url=request.host_url)\n response = make_response(redirect(auth.login_url + '&state=%s' % state))\n response.set_cookie(auth.state_cookie_name, state)\n return response\n return decorated\n\n\n@app.route(prefix)\n@authenticated\ndef home(user):\n return Response(\n json.dumps(user, indent=1, sort_keys=True), mimetype='application/json')\n\n@app.route(prefix + 'oauth_callback')\ndef oauth_callback():\n code = request.args.get('code', None)\n if code is None:\n return 403\n # validate state field\n arg_state = request.args.get('state', None)\n cookie_state = request.cookies.get(auth.state_cookie_name)\n if arg_state is None or arg_state != cookie_state:\n # state doesn't match\n return 403\n\n token = auth.token_for_code(code)\n # store token in session cookie\n session[\"token\"] = token\n next_url = auth.get_next_url(cookie_state) or prefix\n response = make_response(redirect(next_url))\n return response\n\n@app.route(prefix + '/api/jobs/')\n@authenticated\ndef get_jobs(user):\n slurm_api = SlurmAPI(user)\n jobs = slurm_api.get_slurm_jobs_list()\n response = JobsResponse(jobs=jobs)\n return response.dict()\n\n\n@app.route(prefix + '/api/jobs//log/')\n@authenticated\ndef get_job_logs(user, job_id):\n slurm_api = SlurmAPI(user)\n job = slurm_api.get_job_stdout_log(job_id)\n return job\n\n\n@app.route(prefix + '/api/jobs//', methods=['GET', 'DELETE'])\n@authenticated\ndef get_job(user, job_id):\n slurm_api = SlurmAPI(user)\n if request.method == 'DELETE':\n return slurm_api.delete_job(job_id)\n job = slurm_api.get_job_or_404(job_id)\n return job.dict()\n\n\nif __name__ == '__main__':\n print('Starting SlurmProxy service..........')\n from waitress import serve\n serve(app, host=\"0.0.0.0\", port=5000)\n","sub_path":"jupyterhub/files/etc/jupyterhub/services/slurm_proxy/slurm_proxy.py","file_name":"slurm_proxy.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"605070914","text":"from src import randomvideo\nimport re\n\n\ndef response_random_video(update):\n \"\"\"\n response_random_video(request, bot) - sends random video to telegram chat\n\n :param update: web request from telegram bot\n :return: link to YouTube Video\n \"\"\"\n regex = 'bm[\\.\\?\\!]?'\n\n if update.message is None:\n message = update.inline_query.query\n else:\n message = update.message.text\n user = update.message.chat.username\n print('Received message %s from %s' % (message, user))\n\n if re.match(regex, message, re.IGNORECASE):\n\n video_link = randomvideo.random_video()\n\n return video_link\n return None\n","sub_path":"src/random_video_request_handler.py","file_name":"random_video_request_handler.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"145629660","text":"import os\nimport sys\nfrom .rules.rules import Artefact\nimport json\nimport logging\n\nlogging.basicConfig(stream=sys.stdout, level=logging.DEBUG)\n\n\ndef classify(identifier_result_file):\n result_file = os.path.join(\n os.path.dirname(identifier_result_file), \"classifier_results.json\"\n )\n with open(identifier_result_file) as f:\n links = json.load(f)\n\n for fname, artefacts in links.items():\n for artefact in artefacts:\n a = Artefact(artefact)\n a.set_categories()\n artefact[\"possible_categories\"] = a.categories\n artefact[\"categorie\"] = a.categorie\n\n # save to result file\n with open(result_file, \"w\") as f:\n json.dump(links, f, indent=4, sort_keys=False)\n print(\"Finished classification.\", f\"results saved in {result_file}\")\n return result_file\n\n\ndef main(links):\n pass\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"classifier/classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"280994304","text":"import os\n\ndef rm_subtitles(path):\n \"\"\" delete all subtitles in path recursively\n \"\"\"\n sub_exts = ['ass', 'srt', 'sub']\n for root, dirs, files in os.walk(path):\n for f in files:\n _, ext = os.path.splitext(f)\n ext = ext[1:]\n if ext in sub_exts:\n os.remove(os.path.join(root, f))\n\n\n","sub_path":"subfinder/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"644966598","text":"from typing import Dict\n\nimport httpx\nimport pytest\nfrom starlette import status\n\n\n@pytest.mark.asyncio\nasync def test_get(test_client_all_sensitive: httpx.AsyncClient):\n response = await test_client_all_sensitive.get(\"/get\")\n\n assert response.status_code == status.HTTP_200_OK\n\n assert \"csrftoken\" in response.cookies\n\n set_cookie_header = response.headers[\"set-cookie\"]\n assert \"Path=/;\" in set_cookie_header\n assert \"HttpOnly\" not in set_cookie_header\n assert \"Secure\" not in set_cookie_header\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\n \"cookies,headers\",\n [\n ({}, {}),\n ({}, {\"x-csrftoken\": \"aaa\"}),\n ({\"csrftoken\": \"aaa\"}, {}),\n ({\"csrftoken\": \"aaa\"}, {\"x-csrftoken\": \"aaa\"}),\n ],\n)\nasync def test_post_invalid_csrf(\n test_client_all_sensitive: httpx.AsyncClient,\n cookies: Dict[str, str],\n headers: Dict[str, str],\n):\n response = await test_client_all_sensitive.post(\n \"/post\", cookies=cookies, headers=headers\n )\n\n assert response.status_code == status.HTTP_403_FORBIDDEN\n\n\n@pytest.mark.asyncio\nasync def test_valid_csrf(test_client_all_sensitive: httpx.AsyncClient):\n response_get = await test_client_all_sensitive.get(\"/get\")\n csrf_cookie = response_get.cookies[\"csrftoken\"]\n\n response_post = await test_client_all_sensitive.post(\n \"/post\",\n headers={\"x-csrftoken\": csrf_cookie},\n json={\"hello\": \"world\"},\n )\n\n assert response_post.status_code == status.HTTP_200_OK\n\n\n@pytest.mark.asyncio\nasync def test_some_sensitive_csrf(test_client_some_sensitive: httpx.AsyncClient):\n response_get = await test_client_some_sensitive.get(\"/get\")\n csrf_cookie = response_get.cookies[\"csrftoken\"]\n\n response_post_not_sensitive = await test_client_some_sensitive.post(\n \"/post\",\n cookies={\"foo\": \"bar\"},\n json={\"hello\": \"world\"},\n )\n\n assert response_post_not_sensitive.status_code == status.HTTP_200_OK\n\n response_post_sensitive_no_csrf_token = await test_client_some_sensitive.post(\n \"/post\",\n cookies={\"sensitive\": \"bar\"},\n json={\"hello\": \"world\"},\n )\n\n assert (\n response_post_sensitive_no_csrf_token.status_code == status.HTTP_403_FORBIDDEN\n )\n\n response_post_sensitive_csrf_token = await test_client_some_sensitive.post(\n \"/post\",\n cookies={\"sensitive\": \"bar\"},\n headers={\"x-csrftoken\": csrf_cookie},\n json={\"hello\": \"world\"},\n )\n\n assert response_post_sensitive_csrf_token.status_code == status.HTTP_200_OK\n","sub_path":"tests/test_middleware.py","file_name":"test_middleware.py","file_ext":"py","file_size_in_byte":2546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"544757511","text":"# centroids_helper_test.py - Tests for crf_helper.py\n# Written by: Ben Lengerich\n# Created at: Sat May 30 18:19:59 EDT 2015\n# Last Modified at: Sat May 30 18:19:59 EDT 2015\n\n\nfrom __future__ import print_function\n\nimport centroids_helper\nfrom nose.tools import eq_\nfrom nose.tools import with_setup\nimport os\n\ntest_file_name = \"centroids_helper_test_file.txt\"\ntest_centroids = [\"AGCTTAGCT\", \"TGACTGATC\", \"GTACGTAC\"]\n\n# Setup functions\ndef write_file():\n with open(test_file_name, 'w') as test_file:\n for centroid in test_centroids:\n print(centroid, file=test_file)\n\n# Cleanup functions\ndef cleanup_file():\n os.remove(test_file_name)\n\n# Test functions\n@with_setup(write_file, cleanup_file)\ndef read_all_test():\n with open(test_file_name, 'r') as test_file:\n eq_(centroids_helper.read_all(test_file), test_centroids)\n","sub_path":"src/common/data_gen/centroids_helper_test.py","file_name":"centroids_helper_test.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"286832706","text":"'''\nCopyright (C) 2017-2021 Bryant Moscon - bmoscon@gmail.com\n\nPlease see the LICENSE file for the terms and conditions\nassociated with this software.\n'''\nimport asyncio\nfrom decimal import Decimal\nimport hashlib\nimport hmac\nimport logging\nimport time\n\nfrom yapic import json\n\nfrom cryptofeed.defines import BUY, SELL, TRADES\nfrom cryptofeed.exchange import RestExchange\n\n\nLOG = logging.getLogger('cryptofeed.rest')\n\n\nclass BinanceRestMixin(RestExchange):\n api = \"https://api.binance.com/api/v3/\"\n rest_channels = (\n TRADES\n )\n\n def _nonce(self):\n return str(int(round(time.time() * 1000)))\n\n def _generate_signature(self, url: str, body=json.dumps({})):\n nonce = self._nonce()\n signature = \"/api/\" + url + nonce + body\n h = hmac.new(self.config.key_secret.encode('utf8'), signature.encode('utf8'), hashlib.sha384)\n signature = h.hexdigest()\n\n return {\n \"X-MBX-APIKEY\": self.config.key_id,\n \"signature\": signature,\n \"content-type\": \"application/json\"\n }\n\n async def trades(self, symbol: str, start=None, end=None, retry_count=1, retry_delay=60):\n symbol = self.std_symbol_to_exchange_symbol(symbol)\n start, end = self._interval_normalize(start, end)\n if start and end:\n start = int(start * 1000)\n end = int(end * 1000)\n\n while True:\n if start and end:\n endpoint = f\"{self.api}aggTrades?symbol={symbol}&limit=1000&startTime={start}&endTime={end}\"\n else:\n endpoint = f\"{self.api}aggTrades?symbol={symbol}&limit=1000\"\n\n r = await self.http_conn.read(endpoint, retry_count=retry_count, retry_delay=retry_delay)\n data = json.loads(r, parse_float=Decimal)\n\n if data:\n if data[-1]['T'] == start:\n LOG.warning(\"%s: number of trades exceeds exchange time window, some data will not be retrieved for time %d\", self.id, start)\n start += 1\n else:\n start = data[-1]['T']\n\n yield [self._trade_normalization(symbol, d) for d in data]\n\n if len(data) < 1000 or end is None:\n break\n await asyncio.sleep(1 / self.request_limit)\n\n def _trade_normalization(self, symbol: str, trade: list) -> dict:\n ret = {\n 'timestamp': self.timestamp_normalize(trade['T']),\n 'symbol': self.exchange_symbol_to_std_symbol(symbol),\n 'id': trade['a'],\n 'feed': self.id,\n 'side': BUY if trade['m'] else SELL,\n 'amount': abs(Decimal(trade['q'])),\n 'price': Decimal(trade['p']),\n }\n return ret\n\n\nclass BinanceFuturesRestMixin(BinanceRestMixin):\n api = \"https://fapi.binance.com/fapi/v1/\"\n rest_channels = (\n TRADES\n )\n\n\nclass BinanceDeliveryRestMixin(BinanceRestMixin):\n api = \"https://dapi.binance.com/dapi/v1/\"\n rest_channels = (\n TRADES\n )\n","sub_path":"cryptofeed/exchanges/mixins/binance_rest.py","file_name":"binance_rest.py","file_ext":"py","file_size_in_byte":3011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"278974560","text":"import unittest\nimport tempfile\nimport os\nimport shutil\nimport numpy as np\n\nfrom coremltools.libmilstoragepython import _BlobStorageWriter as BlobWriter\nfrom coremltools.libmilstoragepython import _BlobStorageReader as BlobReader\n\nclass WeightTest(unittest.TestCase):\n def setUp(self):\n self.working_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n if os.path.exists(self.working_dir):\n shutil.rmtree(self.working_dir)\n\n def test_weight_blob_uint8(self):\n writer = BlobWriter(self.working_dir + \"/net.wt\")\n input_arr = np.array([1.0, 2, 3, 4, 5], dtype=np.uint8)\n offset = writer.write_uint8_data(input_arr)\n writer = None\n\n reader = BlobReader(self.working_dir + \"/net.wt\")\n output_arr = np.array(reader.read_uint8_data(offset))\n np.testing.assert_almost_equal(input_arr, output_arr)\n\n def test_weight_blob_fp16(self):\n writer = BlobWriter(self.working_dir + \"/net.wt\")\n input_arr = np.array([1.0, 2, 3, 4, 5], dtype=np.float16)\n offset = writer.write_fp16_data(input_arr)\n writer = None\n\n reader = BlobReader(self.working_dir + \"/net.wt\")\n output_arr = np.array(reader.read_fp16_data(offset))\n np.testing.assert_almost_equal(input_arr, output_arr)\n\n def test_weight_blob_fp32(self):\n writer = BlobWriter(self.working_dir + \"/net.wt\")\n input_arr = np.array([1.0, 2, 3, 4, 5], dtype=np.float32)\n offset = writer.write_float_data(input_arr)\n writer = None\n\n reader = BlobReader(self.working_dir + \"/net.wt\")\n output_arr = np.array(reader.read_float_data(offset))\n np.testing.assert_almost_equal(input_arr, output_arr)\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"coremltools/test/blob/test_weights.py","file_name":"test_weights.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"517063015","text":"'''\npretrain_fb_kbeam\n'''\nimport sys, time, os, itertools\nsys.path.insert(0, '..')\n \nimport input_data \nfrom modules.degradlNet import residualNet\nfrom modules.budgetNet import budgetNet_kbeam\nfrom loss import *\nfrom utils import *\nfrom validation import run_validation\n\nfrom common_flags import COMMON_FLAGS\nfrom pretrain_flags import FLAGS\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=FLAGS.GPU_id\nprint('Using GPU:', FLAGS.GPU_id)\nprint('GPU_NUM:', FLAGS.GPU_NUM)\n\n_K = 8\n\nMAX_STEPS = 150\nSAVE_STEP = 50\nVAL_STEP = 10\nPRINT_STEP = 10\nTRAIN_BATCH_SIZE = 2\n\ndef create_architecture_adversarial(scope, videos, budget_labels, istraining_placeholder):\n\t'''\n\tCreate the architecture of the adversarial model in the graph\n\tis_training: whether it is in the adversarial training part. (include testing, not two-fold)\n\t'''\n\t# fd part:\n\tdegrad_videos = residualNet(videos, is_video=True)\n\tdegrad_videos = avg_replicate(degrad_videos) if FLAGS.use_avg_replicate else degrad_videos\n\t# fd part ends\n\n\t# fb part:\n\tloss_budget, logits_budget = [0.0]*_K, [tf.zeros([TRAIN_BATCH_SIZE, COMMON_FLAGS.NUM_CLASSES_BUDGET])]*_K\n\tfor i in range(_K): # each element in loss_budget and logits_budget have the same graph structure.\n\t\twith tf.name_scope('%d' % _K) as scope:\n\t\t\tlogits = budgetNet_kbeam(degrad_videos, K_id=FLAGS.base_idx+i, is_training=istraining_placeholder, depth_multiplier=0.6)\n\t\t\tloss = tower_loss_xentropy_sparse(logits, budget_labels, use_weight_decay=False)\n\t\t\tlogits_budget[i] += logits\n\t\t\tloss_budget[i] += loss\n\t# fd part ends.\n\t\n\treturn loss_budget, logits_budget\n\n# Training set for traning, validation set for validation.\n# lambda: weight for L1 loss (degrade model L1 loss)\ndef pretrain_fb_kbeam(start_from_trained_model):\n\t'''\n\tpretrain_fb_kbeam\n\tArgs:\n start_from_trained_model: boolean. If False, use random initialized fb. If true, use pretrained fb.\n\t'''\n\t# mkdir:\n\tdegradation_ckpt_dir = os.path.join(COMMON_FLAGS.pretrain_dir, 'degradation_models')\n\tbudget_ckpt_dir = ['']*_K\n\tfor i in range(_K):\n\t\tbudget_ckpt_dir[i] = os.path.join(COMMON_FLAGS.pretrain_dir, 'budget_k%d_new' % (FLAGS.base_idx+i))\n\t\tif not os.path.isdir(budget_ckpt_dir[i]):\n\t\t\tos.mkdir(budget_ckpt_dir[i])\n\n\t# define graph\n\tgraph = tf.Graph()\n\twith graph.as_default():\n\t\t# global step:\n\t\tglobal_step = tf.get_variable('global_step', [], initializer=tf.constant_initializer(0), trainable=False)\n\t\t# placeholder inputs:\n\t\tvideos_placeholder, utility_labels_placeholder, budget_labels_placeholder, dropout_placeholder, istraining_placeholder = \\\n\t\t\tplaceholder_inputs(TRAIN_BATCH_SIZE * FLAGS.GPU_NUM)\n\n\t\t# initialize some lists, each element coresponds to one gpu:\n\t\ttower_grads_budget, logits_budget_lst, loss_budget_lst = [[] for i in range(_K)], [[] for i in range(_K)], [[] for i in range(_K)] # budget\n\n\t\t# Optimizer for the 3 components respectively\n\t\topt_budget = tf.train.AdamOptimizer(FLAGS.budget_lr)\n\n\t\twith tf.variable_scope(tf.get_variable_scope()):\n\t\t\tfor gpu_index in range(0, FLAGS.GPU_NUM):\n\t\t\t\twith tf.device('/gpu:%d' % gpu_index):\n\t\t\t\t\tprint('/gpu:%d' % gpu_index)\n\t\t\t\t\twith tf.name_scope('%s_%d' % ('gpu', gpu_index)) as scope:\n\t\t\t\t\t\t# placeholder inputs:\n\t\t\t\t\t\tvideos = videos_placeholder[gpu_index * TRAIN_BATCH_SIZE:(gpu_index + 1) * TRAIN_BATCH_SIZE]\n\t\t\t\t\t\tbudget_labels = budget_labels_placeholder[gpu_index * TRAIN_BATCH_SIZE:(gpu_index + 1) * TRAIN_BATCH_SIZE]\n\t\t\t\t\t\t# output of the graph:\n\t\t\t\t\t\tloss_budget, logits_budget = \\\n\t\t\t\t\t\t\t\t\tcreate_architecture_adversarial(scope, videos, budget_labels, istraining_placeholder)\n\t\t\t\t\t\t# Reuse variables for the next tower.\n\t\t\t\t\t\ttf.get_variable_scope().reuse_variables()\n\t\t\t\t\n\t\t\t\t# degrade:\n\t\t\t\tvarlist_degrad = [v for v in tf.trainable_variables() if \"DegradationModule\" in v.name]\n\t\t\t\t# bn varlist\n\t\t\t\tvarlist_bn = [g for g in tf.global_variables() if 'moving_mean' in g.name]\n\t\t\t\tvarlist_bn += [g for g in tf.global_variables() if 'moving_variance' in g.name]\n\t\t\t\t# budget:\n\t\t\t\tvarlist_budget = [[] for i in range(_K)]\n\t\t\t\tvarlist_budget_bn = [[] for i in range(_K)]\n\t\t\t\t### Append elements on each GPU to lists:\n\t\t\t\tfor i in range(_K):\n\t\t\t\t\t# loss and logits:\n\t\t\t\t\tloss_budget_lst[i].append(loss_budget[i])\n\t\t\t\t\tlogits_budget_lst[i].append(logits_budget[i])\n\t\t\t\t\t# gradients:\n\t\t\t\t\tvarlist_budget[i] = [v for v in tf.trainable_variables() if \"BudgetModule_%d\" % (FLAGS.base_idx+i) in v.name]\n\t\t\t\t\tvarlist_budget_bn[i] = [v for v in varlist_bn if \"BudgetModule_%d\" % (FLAGS.base_idx+i) in v.name]\n\t\t\t\t\tgrads_budget = opt_budget.compute_gradients(loss_budget[i], varlist_budget[i])\n\t\t\t\t\ttower_grads_budget[i].append(grads_budget)\n\t\t\t\t### End appending elements on each GPU to lists.\n\t\t\n\t\t### Average or concat Operations/Tnesors in a list to a single Operation/Tensor:\n\t\t## L_b\n\t\t# budget:\n\t\tloss_budget_op, accuracy_budget_op, right_count_budget_op = [None,]*_K, [None,]*_K, [None,]*_K\n\t\tzero_ops_budget, accum_ops_budget, apply_gradient_op_budget = [None,]*_K, [None,]*_K, [None,]*_K\n\t\tfor i in range(_K):\n\t\t\tloss_budget_op[i] = tf.reduce_mean(loss_budget_lst[i], name='softmax') # Lb\n\t\t\t_logits_budget = tf.concat(logits_budget_lst[i], 0)\n\t\t\taccuracy_budget_op[i] = accuracy(_logits_budget, budget_labels_placeholder)\n\t\t\tright_count_budget_op[i] = correct_num(_logits_budget, budget_labels_placeholder)\n\t\t\tzero_ops_budget[i], accum_ops_budget[i], apply_gradient_op_budget[i] = create_grad_accum_for_late_update(\n\t\t\t\topt_budget, tower_grads_budget[i], varlist_budget[i], FLAGS.n_minibatches, global_step, decay_with_global_step=False)\n\t\t### End averaging or concatenating Operations/Tnesors in a list to a single Operation/Tensor.\n\t\t\n\t\t# operations for placeholder inputs:\n\t\ttr_videos_op, _, tr_actor_labels_op = create_videos_reading_ops(is_train=True, is_val=False, GPU_NUM=FLAGS.GPU_NUM, BATCH_SIZE=TRAIN_BATCH_SIZE)\n\t\t# saver and summary files:\n\t\tsaver_kb = [None]*_K\n\t\tfor i in range(_K): # saver used for saving pretrained fb.\n\t\t\tsaver_kb[i] = tf.train.Saver(var_list=varlist_budget[i]+varlist_budget_bn[i], max_to_keep=1)\n\t\t\n\t\tinit_op = tf.group(tf.local_variables_initializer(), tf.global_variables_initializer())\n\n\t# session config:\n\tconfig = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False)\n\t# run session:\n\twith tf.Session(graph=graph, config=config) as sess:\n\t\t# initialize:\n\t\tsess.run(init_op)\n\t\t# multi-threads:\n\t\tcoord = tf.train.Coordinator()\n\t\tthreads = tf.train.start_queue_runners(sess=sess, coord=coord)\n\t\t# restore d net:\n\t\trestore_model_ckpt(sess=sess, ckpt_dir=degradation_ckpt_dir, varlist=varlist_degrad)\n\t\t# restore b net:\n\t\tif start_from_trained_model:\n\t\t\tfor i in range(_K):\n\t\t\t\trestore_model_ckpt(sess, budget_ckpt_dir[i], varlist_budget[i]+varlist_budget_bn[i])\n\t\t\t\t\n\t\t# train\n\t\tfor step in range(0, MAX_STEPS):\n\t\t\tstart_time = time.time()\n\t\t\tsess.run(zero_ops_budget)\n\t\t\tacc_budget_lst, loss_budget_lst = [[] for i in range(_K)], [[] for i in range(_K)]\n\t\t\tacc_budget_lst_mean, loss_budget_lst_mean = [None]*_K, [None]*_K\n\t\t\t# accumulating gradient for late update:\n\t\t\tfor _ in itertools.repeat(None, FLAGS.n_minibatches):\n\t\t\t\t# placeholder inputs:\n\t\t\t\ttr_videos, tr_actor_labels = sess.run([tr_videos_op, tr_actor_labels_op])\n\t\t\t\t# run operations:\n\t\t\t\ttemp_sess_run_return_list = sess.run(accum_ops_budget + accuracy_budget_op + loss_budget_op,\n\t\t\t\t\t\t\tfeed_dict={videos_placeholder: tr_videos,\n\t\t\t\t\t\t\t\t\t\tbudget_labels_placeholder: tr_actor_labels,\n\t\t\t\t\t\t\t\t\t\tistraining_placeholder: True})\n\t\t\t\tacc_budget_value = temp_sess_run_return_list[_K : 2*_K]\n\t\t\t\tloss_budget_value = temp_sess_run_return_list[2*_K : 3*_K]\n\t\t\t\t# append loss and acc for budget model:\n\t\t\t\tfor i in range(_K):\n\t\t\t\t\tacc_budget_lst[i].append(acc_budget_value[i])\n\t\t\t\t\tloss_budget_lst[i].append(loss_budget_value[i])\n\t\t\t# finish accumulating gradient for late update\n\t\t\t# find acc and loss mean across all gpus:\n\t\t\tfor i in range(_K):\n\t\t\t\tacc_budget_lst_mean[i] = np.mean(acc_budget_lst[i])\n\t\t\t\tloss_budget_lst_mean[i] = np.mean(loss_budget_lst[i])\n\t\t\t\n\t\t\tsess.run([apply_gradient_op_budget]) # update all k wb's\n\t\t\t# finish update on fb\n\n\t\t\t# loss summary:\n\t\t\tif step % PRINT_STEP == 0:\n\t\t\t\tloss_summary = 'step: %4d, time: %.4f, ' \\\n\t\t\t\t\t\t\t'training budget accuracy: %s, budget loss: %s' % (\n\t\t\t\t\t\t\tstep, time.time() - start_time, \n\t\t\t\t\t\t\tacc_budget_lst_mean, loss_budget_lst_mean)\n\t\t\t\tprint(loss_summary)\n\t\t\t# end loss summary\t\n\n\t\t\tif step % VAL_STEP == 0:\n\t\t\t\ttest_correct_num_lst, test_acc_lst, total_v = run_validation(sess=sess, \n\t\t\t\t\tright_count_op_list=right_count_budget_op,\n\t\t\t\t\tplaceholder_list=[videos_placeholder, utility_labels_placeholder, budget_labels_placeholder, dropout_placeholder, istraining_placeholder],\n\t\t\t\t\tbatch_size=TRAIN_BATCH_SIZE*FLAGS.GPU_NUM, dataset='val', istraining=True)\n\t\t\t\ttest_summary = \"Step: %d, validation budget correct num: %s, accuracy: %s\" % (\n step, test_correct_num_lst, test_acc_lst)\n\t\t\t\tprint(test_summary)\n\t\t\t\t# bn_temp_value = sess.run(varlist_bn[-1])\n\t\t\t\t# print('bn_temp_value:', bn_temp_value.shape, bn_temp_value[0:5])\n\n\t\t\t# save model:\n\t\t\tif step % SAVE_STEP == 0 or (step + 1) == MAX_STEPS:\n\t\t\t\tfor i in range(_K):\n\t\t\t\t\tsaver_kb[i].save(sess, os.path.join(budget_ckpt_dir[i], 'pretrained_fb_k%d.ckpt' % i), global_step=step) \n\t\t# End min step\n\t\t# End part 3\n\n\t\tcoord.request_stop()\n\t\tcoord.join(threads)\n\tprint(\"done\")\n\n\nif __name__ == '__main__':\n\tstart_from_trained_model = False\n\tpretrain_fb_kbeam(start_from_trained_model)","sub_path":"SBU-exp/adversarial_training/pretraining/pretrain_fb_kbeam.py","file_name":"pretrain_fb_kbeam.py","file_ext":"py","file_size_in_byte":9383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"263304934","text":"\"\"\"\ndef samnefnari(n, m):\n if n%m == 0:\n return m\n elif n%m == 1:\n return 1\n return samnefnari(m, n%m)\n\nprint(samnefnari(25,85))\n\ndef thversumma(n):\n if not n:\n return 0\n else:\n return int(str(n)[0]) + thversumma(str(n)[1:])\n\nprint(thversumma(10))\n\ndef runa(m):\n if m == 1:\n print(1, end=\" \")\n else:\n runa(m-1)\n print(str((m**2 + m)//2), end=\" \")\n\n\"\"\"\ndef summa(m):\n if m == 0:\n return 0\n return m**2 + summa(m-1)\nprint(summa(5))\n\"\"\"\ndef decimalToBinary(num):\n if num > 1:\n decimalToBinary(num // 2)\n print(num % 2, end='')\n\n\nnumber = int(input(\"Enter any decimal number: \"))\n\ndecimalToBinary(number)\n\"\"\"\n","sub_path":"Skilaverkefni_2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"136643003","text":"# Overrides\nfrom .settings import * # noqa: F401\n\nSECRET_KEY = 'za#q^j+$6frru&3*)b0yl=#9wmue%rf38akqux(fjvl-&zy@_l'\n\nDEBUG = True\n\nALLOWED_HOSTS = ['0.0.0.0', '118.201.195.130']\n\nRUNSERVERPLUS_SERVER_ADDRESS_PORT = '0.0.0.0:8080'\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': 'local.sqlite3',\n }\n}\n\nEMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\nEMAIL_FILE_PATH = os.path.join(BASE_DIR, 'sent_emails')\nprint('EMAIL_FILE_PATH', EMAIL_FILE_PATH)\n\n# TICKET-specific settings\nTICKET_STAFF_ONLY = True\nTICKET_DEFAULT_ASSIGNEE = None\nTICKET_PUBLIC_SUBMIT_REDIRECT = 'ticket:mine'\n# TICKET_ALLOW_FILE_ATTACHMENTS = True\n# TICKET_LIMIT_FILE_ATTACHMENTS = [\".jpg\", \".gif\", \".png\", \".csv\", \".pdf\"]\n# TICKET_MAXIMUM_ATTACHMENT_SIZE = 5000000 # In bytes\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': True,\n 'formatters': {\n 'verbose': {\n 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s',\n 'datefmt' : '%Y/%b/%d %H:%M:%S'\n },\n 'simple': {\n 'format': '%(levelname)s %(message)s'\n },\n },\n 'handlers': {\n 'null': {\n 'level': 'DEBUG',\n 'class': 'logging.NullHandler',\n },\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n },\n 'file': {\n 'level': 'DEBUG',\n 'class': 'logging.handlers.TimedRotatingFileHandler',\n 'filename': '/home/it/cs-ticketing/debug.log',\n 'backupCount': 30,\n 'when': 'midnight',\n 'formatter': 'verbose'\n },\n },\n 'loggers': {\n 'django': {\n 'handlers': ['console', 'file'],\n 'propagate': True,\n 'level': 'INFO',\n },\n 'werkzeug': {\n 'handlers': ['console', 'file'],\n 'level': 'DEBUG',\n 'propagate': True,\n },\n },\n}","sub_path":"project/deployment.py","file_name":"deployment.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"62174714","text":"import cv2\r\nimport numpy as np\r\nimg1 =cv2.imread(\"ex.png\")#reads your image\r\nrows,cols,z=img1.shape\r\nx=rows/2#sets coordinate about which image is to be rotated\r\ny=cols/2\r\nimg3=cv2.getRotationMatrix2D((x,y),90,1)#rotation angle is 90 degree\r\nimg2=cv2.warpAffine(img1,img3,(cols,rows))\r\nprint(img2.shape)#print the resolution of rotated image\r\ncv2.imshow(\"abc\",img2)\r\ncv2.waitKey()\r\ncv2.destroyAllWindows()\r\n","sub_path":"rotateimg.py","file_name":"rotateimg.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"123769476","text":"# SPDX-License-Identifier: Apache-2.0\n#\n# The OpenSearch Contributors require contributions made to\n# this file be licensed under the Apache-2.0 license or a\n# compatible open source license.\n\nimport os\nimport stat\nimport unittest\n\nfrom system.temporary_directory import TemporaryDirectory\n\n\nclass TestTemporaryDirectory(unittest.TestCase):\n def test_keep_true(self):\n with TemporaryDirectory(keep=True) as work_dir:\n self.assertTrue(os.path.exists(work_dir.name))\n self.assertTrue(os.path.exists(work_dir.name))\n\n def test_keep_false(self):\n with TemporaryDirectory() as work_dir:\n self.assertTrue(os.path.exists(work_dir.name))\n self.assertFalse(os.path.exists(work_dir.name))\n\n def test_remove_readonly(self):\n with TemporaryDirectory() as work_dir:\n filename = os.path.join(work_dir.name, \"test.txt\")\n with open(filename, \"w+\") as f:\n f.write(\"This is intentionally left blank.\")\n mode = os.stat(filename)[stat.ST_MODE]\n os.chmod(filename, mode & ~stat.S_IWUSR & ~stat.S_IWGRP & ~stat.S_IWOTH)\n self.assertTrue(os.path.exists(filename))\n self.assertFalse(os.path.exists(work_dir.name))\n self.assertFalse(os.path.exists(filename))\n\n def test_chdir_true(self):\n before_dir = os.getcwd()\n with TemporaryDirectory(chdir=True):\n self.assertNotEqual(before_dir, os.getcwd())\n self.assertEqual(before_dir, os.getcwd())\n\n def test_chdir_false(self):\n before_dir = os.getcwd()\n with TemporaryDirectory():\n self.assertEqual(before_dir, os.getcwd())\n self.assertEqual(before_dir, os.getcwd())\n","sub_path":"tests/tests_system/test_temporary_directory.py","file_name":"test_temporary_directory.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"14443768","text":"import contextlib\nimport glfw # type: ignore\nimport skia # type: ignore\nimport traceback\nimport random\nimport math\nimport ast\nimport importlib\nfrom dataclasses import dataclass\nfrom OpenGL import GL # type: ignore\nfrom typing import List\nfrom functools import lru_cache, wraps\nimport numpy as np # type: ignore\nimport matplotlib # type: ignore\nfrom buffer import Buffer\n\nfont = skia.Font(skia.Typeface('Liberation Mono'), 14)\nline_height = font.getSpacing()\ncol_width = font.getWidths([ord('x')])[0]\n\n\n@dataclass\nclass Cell:\n input: Buffer\n output: object\n\n\ntarget_scroll = [0, 0]\n\n\ndef clamp(l, u, v):\n return max(min(v, u), l)\n\n\ndef scroll(x, y):\n lines = 100 # FIXME\n target_scroll[0] = x\n target_scroll[1] = y\n\n # clamp along y axis\n if target_scroll[1] > 0:\n target_scroll[1] = 0\n if target_scroll[1] - HEIGHT < -(line_height * lines):\n target_scroll[1] = -line_height * lines + HEIGHT\n\n\ndef scroll_to_line(i):\n scroll(target_scroll[0], -line_height * i)\n\n\ninput_paint = skia.Paint(AntiAlias=True, Color=skia.ColorBLACK)\noutput_paint = skia.Paint(AntiAlias=True, Color=skia.ColorGRAY)\n\nWIDTH, HEIGHT = 800, 600\n\n\n@contextlib.contextmanager\ndef glfw_window():\n if not glfw.init():\n raise RuntimeError('glfw.init() failed')\n glfw.window_hint(glfw.STENCIL_BITS, 8)\n window = glfw.create_window(WIDTH, HEIGHT, '', None, None)\n glfw.make_context_current(window)\n yield window\n glfw.terminate()\n\n\n@contextlib.contextmanager\ndef skia_surface(window):\n context = skia.GrDirectContext.MakeGL()\n backend_render_target = skia.GrBackendRenderTarget(\n WIDTH,\n HEIGHT,\n 0, # sampleCnt\n 0, # stencilBits\n skia.GrGLFramebufferInfo(0, GL.GL_RGBA8))\n surface = skia.Surface.MakeFromBackendRenderTarget(\n context, backend_render_target, skia.kBottomLeft_GrSurfaceOrigin,\n skia.kRGBA_8888_ColorType, skia.ColorSpace.MakeSRGB())\n assert surface is not None\n yield surface\n context.abandonContext()\n\n\n@dataclass\nclass Cursor:\n _buf: Buffer\n _pos: int = 0\n\n @property\n def column(self):\n return self._buf.col(self._pos)\n\n @column.setter\n def column(self, v):\n line_start = self._buf.pos_for_line(self.line)\n line_len = self._buf.line_length(self.line) - 1\n self._pos = clamp(line_start, line_start + line_len, line_start + v)\n\n @property\n def line(self):\n return self._buf.line(self._pos)\n\n @line.setter\n def line(self, n):\n if 0 <= n < self._buf.nlines():\n c = self.column\n self._pos = self._buf.pos_for_line(n)\n self.column = c\n\n\ndef exec_block(block, context_globals=None):\n if context_globals is None:\n context_globals = {}\n\n if isinstance(block.body[-1], ast.Expr):\n last = ast.Expression(block.body.pop().value)\n\n exec(compile(block, '', mode='exec'),\n context_globals)\n return eval(compile(last, '', mode='eval'),\n context_globals)\n else:\n exec(compile(block, '', mode='exec'),\n context_globals)\n return None\n\n\ncells: List[Cell] = []\ncells.append(Cell(Buffer(''), 'some output'))\ncells.append(Cell(Buffer('some\\nmore\\ninput\\nhere'), 'some output'))\n\ncur_cell = 0\ncursor = Cursor(cells[cur_cell].input)\n\nevent_pipe = []\n\nwith glfw_window() as window:\n GL.glClear(GL.GL_COLOR_BUFFER_BIT)\n\n def char_callback(_win, c):\n event_pipe.append(('key_press', chr(c)))\n\n def key_callback(_win, k, scancode, action, mods):\n key_map = {glfw.KEY_BACKSPACE: 'backspace',\n glfw.KEY_ENTER: 'enter',\n glfw.KEY_UP: 'up',\n glfw.KEY_DOWN: 'down',\n glfw.KEY_LEFT: 'left',\n glfw.KEY_RIGHT: 'right'}\n\n if k in key_map and action in (glfw.PRESS, glfw.REPEAT):\n key = key_map[k]\n else: # not a key we handle in the key callback\n return\n\n if mods & glfw.MOD_CONTROL:\n event_pipe.append(('key_combo', 'ctrl', key))\n else:\n event_pipe.append(('key_press', key))\n\n def scroll_callback(_win, dx, dy):\n target_scroll[0] += dx * line_height * 2\n target_scroll[1] += dy * line_height * 2\n scroll(target_scroll[0] + dx * 20, target_scroll[1] + dy * 20)\n\n glfw.set_scroll_callback(window, scroll_callback)\n glfw.set_char_callback(window, char_callback)\n glfw.set_key_callback(window, key_callback)\n\n globs = {}\n globs['plt'] = importlib.import_module(\n 'matplotlib.pyplot')\n\n # wrap plt.plot\n _orig_plot = globs['plt'].plot\n @wraps(_orig_plot)\n def wrapped_plot(*args, **kwargs):\n wrapped_plot.was_called = True\n return _orig_plot(*args, **kwargs)\n\n\n last_frame = 0\n with skia_surface(window) as surface:\n while (glfw.get_key(window, glfw.KEY_ESCAPE) != glfw.PRESS\n and not glfw.window_should_close(window)):\n\n current_frame = glfw.get_time()\n dt = current_frame - last_frame\n last_frame = current_frame\n\n glfw.poll_events()\n\n while event_pipe:\n event_type, *args = event_pipe.pop(0)\n if event_type == 'key_press':\n if args[0] == 'enter':\n cells[cur_cell].input.insert('\\n', cursor._pos)\n cursor._pos += 1\n elif args[0] == 'down':\n cursor.line += 1\n elif args[0] == 'up':\n cursor.line -= 1\n elif args[0] == 'right':\n cursor.column += 1\n elif args[0] == 'left':\n cursor.column -= 1\n elif args[0] == 'backspace':\n if cursor._pos - 1 >= 0:\n cells[cur_cell].input.delete(cursor._pos-1, 1)\n cursor._pos -= 1\n else:\n cells[cur_cell].input.insert(args[0], cursor._pos)\n cursor._pos += 1\n elif event_type == 'key_combo':\n mod, key = args\n if mod == 'ctrl' and key == 'up':\n if cur_cell > 0:\n cur_cell -= 1\n cursor = Cursor(cells[cur_cell].input)\n if mod == 'ctrl' and key == 'down':\n if cur_cell + 1 < len(cells):\n cur_cell += 1\n cursor = Cursor(cells[cur_cell].input)\n if mod == 'ctrl' and key == 'enter':\n tree = ast.parse(cells[cur_cell].input.as_str(),\n mode='exec')\n try:\n globs['plt'].clf() # clear out plot\n globs['plt'].plot = wrapped_plot\n wrapped_plot.was_called = False\n globs['np'] = importlib.import_module('numpy')\n output = exec_block(tree, globs)\n\n if wrapped_plot.was_called:\n output = globs['plt'].gcf()\n output.canvas.draw()\n data = np.fromstring(\n output.canvas.tostring_rgb(), dtype=np.uint8, sep='')\n data = data.reshape(\n output.canvas.get_width_height()[::-1] + (3,))\n data = np.dstack(\n (data, np.ones((data.shape[0], data.shape[1]), dtype=np.uint8) * 255))\n cells[cur_cell].output = skia.Image.fromarray(data)\n else:\n cells[cur_cell].output = str(output)\n except:\n cells[cur_cell].output = traceback.format_exc()\n\n with surface as canvas:\n # ensure cursor is visible\n target_scroll[1] = clamp(\n cursor.line * -line_height, (cursor.line + 2) * -line_height + HEIGHT, target_scroll[1])\n\n M = canvas.getTotalMatrix()\n if abs(target_scroll[1] - M.getTranslateY()) > 2:\n canvas.translate(\n 0, (target_scroll[1] - M.getTranslateY()) * 0.2)\n elif abs(target_scroll[1] - M.getTranslateY()) > 1: # snap\n canvas.translate(0, target_scroll[1] - M.getTranslateY())\n\n canvas.clear(skia.Color(255, 255, 255))\n line = 1\n for c in cells:\n if cursor._buf == c.input:\n # draw cursor\n canvas.drawRect(skia.Rect.MakeXYWH(\n cursor.column * col_width, line_height * (line - 1) + cursor.line * line_height + 4, 2, line_height), input_paint)\n\n # display input\n for l in c.input.as_str().split('\\n'):\n canvas.drawString(\n l, 0, line_height * line, font, input_paint)\n line += 1\n\n # display output\n if isinstance(c.output, str):\n for l in c.output.split('\\n'):\n canvas.drawString(\n l, 0, line_height * line, font, output_paint)\n line += 1\n elif isinstance(c.output, skia.Image):\n canvas.drawImage(c.output, 0, line_height * line, None)\n line += np.ceil(c.output.height() / line_height)\n surface.flushAndSubmit()\n glfw.swap_buffers(window)\n\n\n'''\nMain TODO items\n\n== UI\n* wordwise movement, cell movement\n* text selection (with keyboard *and* mouse)\n* copy/paste\n* tab layout for different outputs of the same object\n\n== Serialization and deserialization\n\n== Track inputs and allow more input types\n* Resource -- watched for changes to file/socket/etc (mark dirty, reload and\n recompute)\n* VariableValue -- an input value that the user can change (e.g. slider,\n mouse pos)\n* RecordedVariableValue -- record a value (potentially into a circular\n buffer) and replay it\n\n== Add additional widgets\n* OpenGL output\n* Buttons/sliders/dropdowns\n'''\n","sub_path":"workbench.py","file_name":"workbench.py","file_ext":"py","file_size_in_byte":10560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"653855656","text":"#1. Получить common words со страниц, на которые есть ссылки\n#Получить ссылки на соседние страницы.\n#Спарсить отдельно соседние страницы.\n#Сложить все в один список.\n\nimport wiki_requests as wiki\nimport re\n\ndef get_topic_words (link):\n html_content = wiki.get_topic_page (link)\n words = re.findall(r\"[а-яА-Я\\-\\']{3,}\", html_content)\n return words\n\ndef get_common_words (words_list): \n rate = {}\n for word in words_list:\n if word in rate:\n rate[word] +=1\n else:\n rate[word] = 1\n rate_list = list (rate.items())\n rate_list.sort(key = lambda x:-x[1])\n return rate_list\n\ndef visualize_common_words(topic):\n link = wiki.get_link (topic)\n words = get_topic_words (link)\n list_links = wiki.get_list_of_links (topic)\n\n for link in list_links:\n words += get_topic_words (link)\n\n rate_list = get_common_words (words)\n print (\"TOP 10:\")\n for i in rate_list[0:9]:\n print (i[0])\n\ndef main():\n topic = input(\"topic?: \")\n visualize_common_words (topic)\n\nmain()","sub_path":"GeekBrains OOP/lesson05/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"383747490","text":"# 王泽昊\n# 1700010718\n# 4 min\n# Computing 8.3\n\ndef squeeze(list1,list2):\n for x in list1:\n assert isinstance(x,int)\n for x in list2:\n assert isinstance(x,int) \n l = []\n for x in list1:\n d = 0\n for y in list2:\n if x - y == 1:\n d = 1\n if d == 0:\n l.append(x)\n return l\n\nprint([1,2,3],[1],':',squeeze([1,2,3],[1]))\nprint([1,2,3],[1,2],':',squeeze([1,2,3],[1,2]))\nprint([1,10],[1,2,3],':',squeeze([1,10],[1,2,3]))\n","sub_path":"计算概论/作业/0510/8.3.py","file_name":"8.3.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"306089610","text":"\"\"\"\nTratamiento de archivos CSV\n\"\"\"\n\"\"\"\nHay que modificar el programa para que admita csv de columnas desconocidas \nque hay que comprobar con el header\n\"\"\"\n# import sys\nimport csv\n\nfilename = \"estadistica_audio_PC.csv\"\nseparador = ';'\n\ndata = []\nmi_dic = {}\ntry:\n with open(filename) as f:\n reader = csv.reader(f, delimiter = separador)\n c = 0\n for row in reader:\n k = row[0]\n v = row[1]\n w = row[2]\n mi_dic[k] = v, w\n if c == 0:\n header = row\n n_cols = len(header)\n else:\n data.append(row)\n c += 1\nexcept csv.Error as e:\n print(\"csv.error at line %s : %s\" , (reader.line_enum, e))\n\n\nif header:\n print('header tamaño', len(header), header)\n print(\"===================================\")\nfor datarow in data:\n print(datarow)\n\nprint(mi_dic)\nprint(type(header))\nprint(type(row))\nprint(type(reader))\n","sub_path":"utilidades/csv/ejemplos_csv.py","file_name":"ejemplos_csv.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"487035516","text":"#!/usr/bin/python3\n# -*- coding: utf8\n#\n#####################################################\n#\nimport os\nimport sys\nimport argparse\nimport re\nimport requests # sudo dnf install python3-requests\nfrom urllib.request import urlopen, ProxyHandler # sudo dnf install python3-urllib\nimport socket\nfrom bs4 import BeautifulSoup # sudo dnf install python3-beautifulsoup4\nimport chardet # detection encodage fichier (installé d'origine ???)\nfrom time import sleep\n# classes locales\n# fichier des regexp\nfrom lib import ApplyRegex\nfrom lib import rulesKikourou as kikourou\nfrom lib import rulesBaseFFA as ffa\nfrom lib import Tools\n#\n#####################################################\n# globales\n\n####################### a modifier en fonction de son environement ####################\n#FICDIR = '{}{}'.format(os.environ['HOME'], '/nextcloud/kikourou/fichiers/source/')\nREPWORK = '{}{}'.format(os.environ['HOME'], '/nextcloud/kikourou/fichiers/source/')\nREPDEST = '{}{}'.format(os.environ['HOME'], '/nextcloud/kikourou/fichiers/csv/')\n#######################################################################################\n#\n\nCSV = 'class;temps;nom;club;f1;cat\\n'\nBOLD = \"\\033[1m\"\nRESET = \"\\033[0;0m\"\n#\n#####################################################\n# classes\nclass Factory(object):\n \"\"\"docstring for Factory\"\"\"\n def __init__(self):\n super().__init__()\n print('objets : ', self.objets)\n\n @staticmethod\n def get_factory(which):\n if which == 'pdf':\n return PdfFactory()\n elif which == 'all':\n return AllFactory()\n elif which == 'csv':\n return CsvFactory()\n elif which == 'htm':\n return HtmFactory()\n elif which == 'txt':\n return TxtFactory()\n elif which == 'xlsx':\n return XlsxFactory()\n elif which == 'course':\n return CourseFactory()\n else:\n return CalendrierFactory()\n\n def create_file(self):\n raise NotImplementedError()\n\n\nclass AllFactory(object):\n def genClass(self, options):\n return All()\n\n\nclass CalendrierFactory(object):\n def genClass(self, options):\n return Calendrier()\n\n\nclass PdfFactory(object):\n def genClass(self, options):\n return Pdf()\n\n\nclass CsvFactory(object):\n def genClass(self, options):\n return Csv()\n\n\nclass HtmFactory(object):\n def genClass(self, options):\n return Htm()\n\n\nclass TxtFactory(object):\n def genClass(self):\n return Txt()\n\n\nclass XlsxFactory(object):\n def genClass(self, options):\n return Xlsx()\n\n\nclass CourseFactory(object):\n def genClass(self, options):\n return Course()\n\n\nclass All(Tools):\n \"\"\"Traitement de tous les fichiers du repertoire:\n - on parcours le repertoire et on extrait les noms de fichiers\n - creation d'un dico avec nom, extensions\n \"\"\"\n\n def start(self):\n if self.ext == '*':\n print('traitement de tous les fichiers')\n else:\n print('{}Traitement des fichiers {} :{}'.format(BOLD, self.ext, RESET))\n # self.lst_fic = glob('fichiers/source/*{}'.format(self.ext))\n self.lst_fic = [fic for fic in os.listdir('fichiers/source/') if fic.endswith('.{}'.format(self.ext))]\n for fic in self.lst_fic:\n print('{} ---> {}{}'.format(BOLD, fic, RESET))\n f = Factory.get_factory(self.ext)\n c = f.genClass()\n c.options = self.params(fic)\n c.start()\n\n def params(self, fic):\n fic, ext = os.path.splitext(self.lst_fic[0])\n fic = fic.split('/')[-1]\n _dic = {}\n _dic['ficpdf'] = '{}{}.pdf'.format(FICDIR, fic)\n _dic['ficcsv'] = '{}{}.csv'.format(FICDIR, fic)\n _dic['fictxt'] = '{}{}.txt'.format(FICDIR, fic)\n _dic['fichtm'] = '{}{}.htm'.format(FICDIR, fic)\n return _dic\n\n\nclass Pdf(Tools):\n \"\"\"Gestion d'un fichier pdf :\n - on le convertit avec pdftotext\n - creation d'un fichier csv (avec application des regex)\n \"\"\"\n def start(self):\n self.coureurs = self.pdftoliste()\n if self.checkCoureurs(self.coureurs):\n self.writeCsv(self.coureurs, self.fickikou)\n print(BOLD, \" <{}> : correct\".format(self.ficpdf), RESET)\n print(BOLD, \" : a transférer sur KiKourou\".format(self.fickikou), RESET)\n # sauvegarde des fichiers de source vers sv_fic_source\n fic = 'mv {}* {}sv_fic_source'.format(self.ficcsv[:-4], REPWORK)\n sv = os.system(fic)\n else:\n print(BOLD, '\\nFichier {} pourri'.format(self.ficpdf), RESET)\n print(BOLD, 'Modifier le fic {} et relancer'.format(self.ficcsv), RESET)\n self.writeCsv(self.coureurs, self.ficcsv)\n for cle, valeur in self.anos.items():\n print(BOLD, \"\\nAnomalie de type : \", cle, RESET)\n for ano in valeur:\n print(' {}'.format(ano)) \n\n #if self.pdftocsv():\n # print('- Fichier {} traité.\\n- Fichier {} créé.'.format(self.ficpdf, self.ficcsv))\n # if self.encodage_fichier(self.ficcsv) and self.csvtotxt():\n # print('- Fichier {} créé.'.format(self.fictxt))\n # self.csvdef()\n # return True\n\n\nclass Xlsx(Tools):\n \"\"\"Gestion d'un fichier xlsx :\n - utilisation du script xls2csv.py\n - chargement/formatage des coureurs en table\n - ecriture fichier si OK\"\"\"\n def start(self):\n self.coureurs = self.xlsxtoliste()\n if self.checkCoureurs(self.coureurs):\n self.writeCsv(self.coureurs, self.fickikou)\n print(BOLD, \" <{}> : correct\".format(self.ficxlsx), RESET)\n print(BOLD, \" : a transférer sur KiKourou\".format(self.fickikou), RESET)\n # sauvegarde des fichiers de source vers sv_fic_source\n fic = 'mv {}* {}sv_fic_source'.format(self.ficxlsx[:-4], REPWORK)\n sv = os.system(fic)\n else:\n print(BOLD, 'Fichier {} pourri'.format(self.ficxlsx), RESET)\n self.writeCsv(self.coureurs, self.ficcsv)\n for cle, valeur in self.anos.items():\n print(BOLD, \"\\nAnomalie de type : \", cle, RESET)\n for ano in valeur:\n print(' {}'.format(ano)) \n print(' {}'.format(ano)) \n\nclass Csv(Tools):\n \"\"\"Gestion d'un fichier csv :\n - lecture du csv\n - chargement/formatage des coureurs en table\n - ecriture fichier si OK\"\"\"\n def start(self):\n self.coureurs = self.csvtoliste()\n if self.checkCoureurs(self.coureurs):\n self.writeCsv(self.coureurs, self.fickikou)\n print(BOLD, \" <{}> : correct\".format(self.ficcsv), RESET)\n print(BOLD, \" : a transférer sur KiKourou\".format(self.fickikou), RESET)\n # sauvegarde des fichiers de source vers sv_fic_source\n fic = 'mv {}* {}sv_fic_source'.format(self.ficcsv[:-4], REPWORK)\n sv = os.system(fic)\n else:\n print(BOLD, 'Fichier {} pourri'.format(self.ficcsv), RESET)\n self.writeCsv(self.coureurs, self.ficcsv)\n for cle, valeur in self.anos.items():\n print(BOLD, \"\\nAnomalie de type : \", cle, RESET)\n for ano in valeur:\n print(' {}'.format(ano)) \n print(' {}'.format(ano)) \n\n\nclass Htm(Tools):\n \"\"\"Gestion d'un fichier htm :\n - lecture fichier html\n - creation d'un fichier csv (avec application des regex)\n - enfin, creation d'un fichier txt\n \"\"\"\n def start(self):\n if self.encodage_fichier(self.fichtm) and self.htmtocsv():\n print('- Fichier {} traité.\\n- Fichier {} créé.'.format(self.fichtm, self.ficcsv))\n if self.csvtotxt():\n print('- Fichier {} créé.'.format(self.fictxt))\n return True\n\n\nclass Txt(Tools):\n \"\"\"on passe d'un fichier txt a un fichier csv dans Fichiers/csv :\n - lecture txt : fictoliste\n - creation dictionnaire\n - ecriture fichier csv si aucune anomalie\n \"\"\"\n def start(self):\n print (self.options)\n return 'Objet Txt - Fichier : {}'.format(self.fichier)\n\n\nclass Course(Tools):\n \"\"\"a partir du numero de course :\n - calcul du nombre de participants\n - calcul du nombre de page à extraire\n - si option -f, ecriture d'un fichier\n \"\"\"\n def start(self):\n for epreuve in self.liste_epreuves():\n # url = 'http://bases.athle.com/asp.net/liste.aspx?frmbase=resultats&frmmode=1&frmespace=0&frmcompetition={}&frmepreuve={}'\n url = 'http://bases.athle.com/asp.net/liste.aspx?frmbase=resultats&frmmode=1&frmespace=0&frmcompetition={}&frmepreuve={}&frmposition={}'\n suite = True\n self.coureurs = []\n self.url_epreuve = url.format(self.numcourse, epreuve.lower(), 0)\n self.participants = self.nb_participants()\n self.nb_page = int(self.participants / 250) + 1\n self.fic_epreuve = '{}_{}.csv'.format(self.ficcsv[:-4], epreuve.lower().replace('+', '_'))\n print(BOLD, '\\nTraitement epreuve {} :'.format(self.fic_epreuve.split('/')[-1]), RESET)\n for page in range(0, self.nb_page):\n # sleep(2)\n # print('page {}/{}'.format( page, self.nb_page))\n self.url_epreuve = url.format(self.numcourse, epreuve.lower(), page)\n if self.nb_participants() > 0:\n self.coureurs += self.lec_html()\n else:\n print('- aucun participant trouvé pour la course n° {}'.format(self.numcourse))\n # tentative pour ne garder que le bon nombre de participants (probleme de la derniere page)\n self.coureurs = self.coureurs[ :self.participants +1 ]\n self.entete = 'class;temps;nom;club;cat'\n self.coureurs = [self.regFFA(';'.join(coureur)) for coureur in self.coureurs]\n self.coureurs = self.entete.split() + self.coureurs\n if self.check_format(): \n self.coureurs = self.listetodic()\n else:\n with open(self.fic_epreuve, 'w')as out:\n for c in self.coureurs:\n out.write('{}\\n'.format(c))\n print(BOLD + ' - probleme avec le fichier {} \\\n \\n - Corriger le fichier et relancer \\'./kikourou.py {}'.format(self.fic_epreuve, self.fic_epreuve) + RESET)\n for ano in self.anos_format:\n print('--> ', ano)\n print('')\n suite = False\n ###\n if suite:\n if self.checkCoureurs(self.coureurs):\n dest = self.fic_epreuve.replace('/source/', '/csv/')\n print(BOLD, ' - <{}> : correct'.format(self.fic_epreuve), RESET)\n print(BOLD, ' - : a transférer sur KiKourou'.format(dest), RESET)\n self.writeCsv(self.coureurs, dest)\n else:\n print(BOLD, ' - fichier {} pourri'.format(self.fic_epreuve), RESET)\n self.writeCsv(self.coureurs, self.fic_epreuve)\n for cle, valeur in self.anos.items():\n print(BOLD, ' - anomalie de type : ', cle, RESET)\n for ano in valeur:\n print(' {}'.format(ano)) \n\n def nb_participants(self):\n # html = urlopen('file:///home/paulo/nextcloud/kikourou/testCourse0.htm')\n html = urlopen(self.url_epreuve)\n soup = BeautifulSoup(html, 'lxml')\n nb = [i for i in soup.find(True, {'class': ['barCount']})]\n return int(re.sub(r'([0-9]+)( .*)', r'\\1', ''.join(nb)))\n\n def lec_html(self):\n coureur = []\n coureurs = []\n html = urlopen(self.url_epreuve)\n soup = BeautifulSoup(html, 'lxml')\n for tr in soup.findAll('tr'):\n coureur = [ td.text for td in tr.findAll('td', class_=[\"datas0\", \"datas1\"]) if '\\xa0' not in td]\n if coureur != []:\n coureurs.append(coureur)\n return coureurs\n\n def liste_epreuves(self):\n URL = 'http://bases.athle.com/asp.net/liste.aspx?frmbase=resultats&frmmode=1&frmespace=0&frmcompetition={}'\n html = urlopen(URL.format(self.numcourse))\n soup = BeautifulSoup(html, 'lxml')\n td = [ td for td in soup.findAll('td',{ \"class\" : \"barInputs\" }) ]\n options = td[3].findAll('option')\n ### si une seule épreuve à rechercher : \n ### http://bases.athle.com/asp.net/liste.aspx?frmbase=resultats&frmmode=1&frmespace=0&frmcompetition=192341&frmepreuve=13+km\n ### return ['13+km']\n return [ option.get('value') for option in options if option.get('value') ]\n\n def display(self):\n retour = ''\n for i in self.coureurs:\n if len(i) > 7:\n if retour == '':\n retour = u\"class: %-5s - Nom: %-30s - Temps: %-12s\" % (i[0], i[2], i[1])\n else:\n retour += u\"\\nclass: %-5s - Nom: %-30s - Temps: %-12s\" % (i[0], i[2], i[1])\n return retour\n\n\nclass Calendrier(Tools):\n \"\"\"docstring for Calendrier\"\"\"\n\n def nb_jour_mois(self):\n '''renvoi le nombre de jour du mois'''\n nj = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)[self.mois]\n if self.mois == 2 and ((self.annee % 4 == 0 and self.annee % 100 != 0) or self.annee % 400 == 0):\n return nj + 1\n return nj\n\n def start(self):\n self.liste_courses = self.consult_calendrier()\n if len(self.liste_courses) > 0:\n print(self.resultat())\n else:\n print('Aucune compétition trouvée avec ces paramètres:\\n- année : {} mois : {}\\n- departement : {}'.format(self.annee, self.mois, self.dept))\n\n def consult_calendrier(self):\n URL = 'http://bases.athle.com/asp.net/liste.aspx?frmpostback=true&frmbase=resultats&frmmode=2&frmespace=0&frmsaison={}&frmtype1=Hors+Stade&frmtype2=&frmtype3=&frmtype4=&frmniveau=&frmniveaulab=&frmligue=&frmdepartement={}&frmeprrch=&frmclub=&frmdate_j1={}&frmdate_m1={}&frmdate_a1={}&frmdate_j2={}&frmdate_m2={}&frmdate_a2={}'\n self.deb = 1\n url = URL.format(self.annee, self.dept, self.deb, self.mois, self.annee, self.nb_jour_mois(), self.mois, self.annee)\n ip = socket.gethostbyname(socket.getfqdn())\n html = urlopen(url)\n course = courses = []\n soup = BeautifulSoup(html, 'lxml')\n for tr in soup.findAll('tr'):\n course = []\n num = ''\n for td in tr.findAll('td', class_=[\"datasCMP0\", \"datasCMP1\"]):\n if td.text != '':\n course.append(td.text)\n if td.a:\n num = td.a.get('href')[-6:]\n participants = re.sub(r'(^.*- )([0-9]+)(.*)', r'\\2', td.a.get('title'))\n num = u'%s (%s coureurs)' % (num, participants)\n course.append(num)\n if len(course) > 6:\n courses.append(course)\n return courses\n\n def resultat(self):\n retour = ''\n for i in self.liste_courses:\n if len(i) > 8:\n if retour == '':\n retour = u\"date: %-9s - Course: %-45s - Numero : %-25s - Lieu: %-30s - Departement: %3s\" % (i[0], i[2], i[-1], i[3], i[5])\n else:\n retour += u\"\\ndate: %-9s - Course: %-45s - Numero : %-25s - Lieu: %-30s - Departement: %3s\" % (i[0], i[2], i[-1], i[3], i[5])\n return retour\n\n\n#\n# fonctions\ndef opt(argv):\n '''dictionnaire qui sera passé à la création des objets de la fabrique'''\n parser = argparse.ArgumentParser(prog='./parser.py', usage='%(prog)s [options]', description='Generation csv...')\n #parser.add_argument('fic', nargs='*', default='')\n subparsers = parser.add_subparsers(help='sub-command help')\n # gestion du numerotage automagique\n auto = False\n if 'auto' in argv:\n auto = True\n argv.remove('auto')\n\n #uniquement un nom de fichier\n if len(argv) == 1:\n #on recupere uniquement le nom du fichier\n dic = {}\n fic, _ = os.path.splitext(argv[0])\n fic = fic.split('/')[-1]\n ext = argv[0].split('.')[-1]\n dic['which'] = '{}'.format(ext)\n dic['ficpdf'] = '{}{}.pdf'.format(REPWORK, fic)\n dic['ficcsv'] = '{}{}.csv'.format(REPWORK, fic)\n dic['ficxlsx'] = '{}{}.xlsx'.format(REPWORK, fic)\n dic['fictxt'] = '{}{}.txt'.format(REPWORK, fic)\n dic['fichtm'] = '{}{}.htm'.format(REPWORK, fic)\n dic['fickikou'] = '{}{}.csv'.format(REPDEST, fic)\n if auto:\n dic['auto'] = True\n return dic\n elif len(argv) > 1:\n # recherche dans le calendrier\n parser_a = subparsers.add_parser('calendrier', help='Recherche dans le calendrier Base Athlé')\n parser_a.set_defaults(which='calendrier')\n parser_a.add_argument(\"-d\", \"--dept\", action=\"store\", dest=\"dept\", default='069', help=\"Departement a rechercher\")\n parser_a.add_argument(\"-m\", \"--mois\", action=\"store\", dest=\"mois\", default='6', type=int, help=\"Mois recherché en numerique\")\n parser_a.add_argument(\"-a\", \"--annee\", action=\"store\", dest=\"annee\", default='2017', type=int, help=\"Année recherchée\")\n \n # recherche resultat d'une course\n parser_b = subparsers.add_parser('course', help='Consultation d\\'une course')\n parser_b.set_defaults(which='course')\n parser_b.add_argument(\"-n\", \"--num\", action=\"store\", dest=\"numcourse\", help=\"Course a rechercher\")\n parser_b.add_argument(\"-f\", \"--fichier\", action=\"store\", dest=\"fichier\", default=None, help=\"Nom du fichier en sortie\")\n #traitage des options \n options = parser.parse_args()\n dic = dict(options._get_kwargs())\n if (dic['which'] == 'course' and not dic['fichier']) or (dic['which'] == 'calendrier') or (dic['which'] == 'all'):\n dic['ficcsv'] = dic['fictxt'] = dic['fichtm'] = None\n else:\n fic, ext = os.path.splitext(dic['fichier'])\n fic = fic.split('/')[-1]\n dic['ficpdf'] = '{}{}.pdf'.format(REPWORK, fic)\n dic['fictxt'] = '{}{}.txt'.format(REPWORK, fic)\n dic['fichtm'] = '{}{}.htm'.format(REPWORK, fic)\n dic['ficcsv'] = '{}{}.csv'.format(REPWORK, fic)\n dic['fickikou'] = '{}{}.csv'.format(REPDEST, fic)\n return dic\n else:\n parser.error('./parser.py -h [--help] pour obtenir la liste des options')\n#\n#####################################################\n#\n\n\ndef main(argv):\n #dictionnaire des options\n options = opt(argv)\n \n #utilisation de la fabrique : retourne un objet en fonction de l'extension du fichier transmis\n f = Factory.get_factory(options['which'])\n \n #creation/lancement objet\n c = f.genClass(options)\n c.options = options\n c.start()\n#\n#####################################################\n#\nif __name__ == '__main__':\n main(sys.argv[1:])\n#\n#####################################################\n","sub_path":"kikourou.py","file_name":"kikourou.py","file_ext":"py","file_size_in_byte":19435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"183792635","text":"import os\narchivo=open(\"index.html\",\"r\")\narchread=archivo.read()\nerrormensage=\"Building Instructions [Lego]-images\"\nthegoodone=\"./BuildingInstructions_images\"\nos.system(\"sudo cp -r Building\\ Instructions\\ \\[Lego\\]-images/ BuildingInstructions_images\")\nr=archread.replace(errormensage,thegoodone)\narchivo.close()\narchivo=open(\"index.html\",\"w\")\narchivo.write(r)\narchivo.close()","sub_path":"Rpi/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"67310519","text":"def C(n, k):\n result = 1\n K = k\n i = 0\n while i < K:\n result *= n\n n -= 1\n i += 1\n\n i = 1\n while i < K:\n result /= k\n k -= 1\n i += 1\n\n return (int)(result)\n\nwith open(\"input.txt\") as inputFile:\n Args = inputFile.read().split(\" \")\n N = (int)(Args[0])\n A = (int)(Args[1])\n B = (int)(Args[2])\n with open(\"output.txt\", \"w\") as outputFile:\n outputFile.write((str)(C(N + A, A) * C(N + B, B)))\n outputFile.close()\n inputFile.close()\n","sub_path":"401.py","file_name":"401.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"311766340","text":"# Data Setup\n# -----------------\n# Players\nplayers = [\"Player 1\", \"Player 2\", \"Player 3\"]\n\n# AFC Teams\nafc_east = {\"Buffalo Bills\": players, \"Miami Dolphins\": players, \"New England Patriots\": players,\n \"New York Jets\": players}\nafc_north = {\"Baltimore Ravens\": players, \"Cincinnati Bengals\": players, \"Cleveland Browns\": players,\n \"Pittsburgh Steelers\": players}\nafc_south = {\"Houston Texans\": players, \"Indianapolis Colts\": players, \"Jacksonville Jaguars\": players,\n \"Tennessee Titans\": players}\nafc_west = {\"Denver Broncos\": players, \"Kansas City Chiefs\": players, \"Oakland Raiders\": players,\n \"San Diego Chargers\": players}\n\n# NFC Teams\nnfc_east = {\"Dallas Cowboys\": players, \"New York Giants\": players, \"Philadelphia Eagles\": players,\n \"Washington Redskins\": players}\nnfc_north = {\"Chicago Bears\": players, \"Detroit Lions\": players, \"Green Bay Packers\": players,\n \"Minnesota Vikings\": players}\nnfc_south = {\"Atlanta Falcons\": players, \"Carolina Panthers\": players, \"New Orleans Saints\": players,\n \"Tampa Bay Buccaneers\": players}\nnfc_west = {\"Arizona Cardinals\": players, \"Los Angeles Rams\": players, \"San Francisco 49ers\": players,\n \"Seattle Seahawks\": players}\n\n# Conferences\nafc = {\"East\": afc_east, \"North\": afc_north, \"South\": afc_south, \"West\": afc_west}\nnfc = {\"East\": nfc_east, \"North\": nfc_north, \"South\": nfc_south, \"West\": nfc_west}\n\n# League\nnfl = {\"AFC\": afc, \"NFC\": nfc}\n\n\n# Setup\n# -----------------\n\ndef is_conference_of(string, data):\n \"\"\"Given a text string, test to see if a conference.\n\n >>> is_conference_of(\"test\",nfl)\n False\n\n >>> is_conference_of(\"AFC\",nfl)\n True\n\n >>> is_conference_of(\"NFC\",nfl)\n True\n\n \"\"\"\n\n for key in data.keys():\n if string == key:\n return True\n return False\n\n\ndef is_team(team_input, dataset):\n \"\"\"Given a text input test against list of teams.\n\n >>> is_team(\"Test\",nfl)\n False\n\n >>> is_team(\"Philadelphia Eagles\",nfl)\n True\n\n >>> is_team(\"Arizona Cardinals\",nfl)\n True\n\n \"\"\"\n\n for conference in dataset.values():\n for division in conference.values():\n for team in division.keys():\n if team_input == team:\n return True\n return False\n\n\ndef get_team_info(team_input, dataset):\n \"\"\"Given a team, return conference, division, and players.\n\n >>> get_team_info(\"Arizona Cardinals\",nfl)\n ('NFC', 'West', ['Player 1', 'Player 2', 'Player 3'])\n\n >>> get_team_info(\"Philadelphia Eagles\",nfl)\n ('NFC', 'East', ['Player 1', 'Player 2', 'Player 3'])\n\n >>> get_team_info(\"San Francisco 49ers\",nfl)\n ('NFC', 'West', ['Player 1', 'Player 2', 'Player 3'])\n\n >>> get_team_info(\"Pittsburgh Steelers\",nfl)\n ('AFC', 'North', ['Player 1', 'Player 2', 'Player 3'])\n\n \"\"\"\n\n # Setup\n team_conference = \"\"\n team_division = \"\"\n team_members = \"\"\n\n # Transform\n for conference_name, conference in dataset.items():\n for division_name, division in conference.items():\n for team_name, team_roster in division.items():\n if team_input == team_name:\n team_conference = conference_name\n team_division = division_name\n team_members = team_roster\n\n # Output\n return (team_conference, team_division, team_members)\n\n\ndef get_divisions(conference, dataset):\n \"\"\"Given a conference and dataset, return list of division_request\n\n >>> get_divisions(\"NFC\", nfl)\n ['East', 'North', 'South', 'West']\n\n >>> get_divisions(\"AFC\", nfl)\n ['East', 'North', 'South', 'West']\n\n \"\"\"\n\n # Transform\n results = list(dataset[conference].keys())\n results.sort()\n\n # Output\n return results # returns type sorted list\n\n\ndef get_teams(conference, division, dataset):\n \"\"\"Given a conference, division, and dataset return an ordered list of teams.\n\n >>> get_teams(\"NFC\",\"East\", nfl)\n ['Dallas Cowboys', 'New York Giants', 'Philadelphia Eagles', 'Washington Redskins']\n\n >>> get_teams(\"AFC\",\"East\", nfl)\n ['Buffalo Bills', 'Miami Dolphins', 'New England Patriots', 'New York Jets']\n \"\"\"\n\n # Transform\n team_list = list(dataset[conference][division].keys())\n team_list.sort()\n\n # Output\n return team_list\n\n\ndef main(dataset):\n # Setup\n team = False\n conference = False\n\n # Input\n while not (team or conference):\n user_input = input(\"Please Enter a team or conference: \\n\")\n try:\n if is_conference_of(user_input, dataset):\n conference = True\n elif is_team(user_input, dataset):\n team = True\n else:\n print(\"Not found, please try again.\")\n except TypeError:\n print(\"Team or conference not found please check your input and try again.\\n\")\n\n # Transform\n if team == True:\n results = get_team_info(user_input, dataset)\n unpack_conference, unpack_division, unpack_team_members = results\n format_team_members = \", \".join(unpack_team_members)\n string = \"{team} is in the {conference} {division} and has the players: {team_members}\".format(team=user_input,\n conference=unpack_conference,\n division=unpack_division,\n team_members=format_team_members)\n else:\n # Select division\n division_list = get_divisions(user_input, dataset)\n division_list_string = \", \".join(division_list)\n is_division = False\n while not is_division:\n division = input(\"Please select a division from {string}\\n\".format(string=division_list_string))\n try:\n # Return Teams\n list_of_teams = \", \".join(get_teams(user_input, division, dataset))\n is_division = True\n except KeyError:\n print(\"Error: Division not on list, try again.\")\n\n # Format string for output\n string = \"The teams in the {conference} {division} are the {list_of_teams}\".format(conference=user_input,\n division=division,\n list_of_teams=list_of_teams)\n\n # Output\n print(string)\n\n\nmain(nfl)\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n is_conference_of(\"NFC\", nfl)\n is_team(\"Test\", nfl)\n get_team_info(\"team\", nfl)\n\n# -----------------------------------------------------------------------------\n# Old Code Fragments Below\n# -----------------------------------------------------------------------------\n#\n# # Input\n# # -----------------\n#\n# # Transform\n# # -----------------\n#\n# team = False\n# conference = False\n#\n#\n# # Find Teams\n# def find_info(conference, division):\n# return nfl[conference][division]\n#\n#\n# # Find Conference and Division\n# def find_division(team):\n# for key, value in nfl.items():\n# for sub_key, sub_value in value.items():\n# for team_name in sub_value:\n# if team_name == team:\n# return (sub_key, key) # division,conference\n#\n#\n# # Output\n# # -----------------\n# if team:\n# return_valuesA, return_valuesB = find_division(user_input)\n# print(\"The conference is {conference} and the division is {division}\".format(conference = return_valuesA, division = return_valuesB))\n# # return find_division(user_input)\n# # return_conf_and_division\n# # Return Conference and Division\n# else:\n# conference = user_input\n# division = get_division()\n# print(\"Teams in division:\", \", \".join(find_info(conference, division)))\n# # Ask for division, return team list\n# # Determine Input Type: Team, Division, Conference\n#\n# if __name__ == \"__main__\":\n# import doctest\n#\n# doctest.testmod()\n# is_team(\"text\")\n","sub_path":"_assignments/python/nflteams/nflteams.py","file_name":"nflteams.py","file_ext":"py","file_size_in_byte":8192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"268083217","text":"import math\r\n\r\ndef Lcm(num1):\r\n lcm=num1[0]\r\n for i in range(1,len(num1)):\r\n lcm=lcm*num1[i]//math.gcd(lcm,num1[i])\r\n return lcm\r\n\r\ndef lcmgcd():\r\n while True:\r\n print(\"Enter 1 for LCM and GCD of Two numbers\\nEnter 2 for LCM and GCD of Three numbers\\nEnter 3 for back\")\r\n k=input(\"Enter here:\")\r\n try: \r\n key=int(k)\r\n except:\r\n print(\"Invalid key!\")\r\n \r\n if key==1:\r\n A=input(\"Enter first number:\")\r\n B=input(\"Enter second number:\")\r\n try:\r\n a=int(A)\r\n b=int(B)\r\n except:\r\n print(\"Error!\")\r\n break\r\n if a==0 or b==0:\r\n print(\"Zero not allowed!\")\r\n break\r\n gcd=math.gcd(a,b)\r\n print(\"GCD is:\",gcd)\r\n print(\"LCM is:\",int((int(A)*int(B))/gcd))\r\n if key==2:\r\n num=[]\r\n A=input(\"Enter first number:\")\r\n B=input(\"Enter second number:\")\r\n C=input(\"Enter third number:\")\r\n try:\r\n a=int(A)\r\n b=int(B)\r\n c=int(C)\r\n except:\r\n print(\"Error!\")\r\n break\r\n if a==0 or b==0 or c==0:\r\n print(\"Zero not allowed!\")\r\n break\r\n num.append(a)\r\n num.append(b)\r\n num.append(c)\r\n \r\n g=math.gcd(a,b)\r\n gcd=math.gcd(g,c)\r\n print(\"GCD is:\",gcd)\r\n print(\"LCM is:\",Lcm(num))\r\n if key==3:\r\n break\r\n else:\r\n print(\"Enter correct key!\")\r\n break\r\n\r\nlcmgcd()\r\n","sub_path":"LCM_GCD.py","file_name":"LCM_GCD.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"156576142","text":"import pymongo\n\nclient = pymongo.MongoClient(host='localhost', port=27017)\n\n# client = MongoClient('mongodb://localhost:27017/')\n\ndb = client.test\n# db = client['test']\n\ncollection = db.students\n\nresult = collection.remove({'name': 'Kevin'})\nprint(result)\n\nresult = collection.delete_one({'name': 'Kevin'})\nprint(result)\nprint(result.deleted_count)\nresult = collection.delete_many({'age': {'$lt': 25}})\nprint(result.deleted_count)\n","sub_path":"demo7.py","file_name":"demo7.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"348799028","text":"# -*- coding: utf-8 -*-\r\n\r\nfrom odoo import api, fields, models\r\nfrom random import randint\r\n\r\nclass Fuel(models.Model):\r\n _name = 'fuel.fuel'\r\n\r\n\r\n def _get_default_color(self):\r\n return randint(1, 11)\r\n\r\n name = fields.Char('Fuel')\r\n color = fields.Integer(string='Color Index', default=_get_default_color)\r\n active = fields.Boolean(default=True)\r\n\r\nclass FleetVehicleModel(models.Model):\r\n _inherit = 'fleet.vehicle.model'\r\n \r\n vehicle_type = fields.Selection([('cover_van', 'Covered Van'), ('car', 'Car'), ('bike', 'Motor Bike')], default='car', required=True)\r\n \r\n @api.depends('name', 'brand_id', 'vehicle_type')\r\n def name_get(self):\r\n ret_list = []\r\n for record in self:\r\n name = record.name\r\n if record.brand_id.name:\r\n name = record.brand_id.name + '/' + name\r\n if record.vehicle_type:\r\n name = name + '(' + record.vehicle_type + ')'\r\n ret_list.append((record.id, name))\r\n return ret_list\r\n\r\n\r\nclass FleetVehicle(models.Model): \r\n _inherit = 'fleet.vehicle'\r\n\r\n @api.onchange('driver_id')\r\n def on_change_driver_id(self):\r\n for i in self:\r\n if i.driver_id:\r\n i.driver_number = i.driver_id.mobile\r\n\r\n @api.onchange('helper_id')\r\n def on_change_future_driver_id(self):\r\n for i in self:\r\n if i.helper_id:\r\n i.helper_number = i.helper_id.mobile\r\n\r\n @api.onchange('department_id')\r\n def on_change_department_id(self):\r\n\r\n if self.department_id:\r\n return {'domain': {'vehicle_asign_id': [('department_id', '=', self.department_id.id)]}}\r\n \r\n registration_nbr = fields.Text('Vehicle Registration No')\r\n date_purchase = fields.Date('Vehicle Purchase Date')\r\n cubic_centimeter = fields.Float(\"Vehicle Capacity (CBM)\")\r\n vehicle_capacity = fields.Float(\"Vehicle Capacity (Ton)\")\r\n kanban_state = fields.Selection([\r\n ('done', 'USED'),\r\n ('blocked', 'IDLE'),\r\n ], string='Vehicle Status',\r\n copy=False, default='blocked', tracking=True\r\n )\r\n\r\n doc1 = fields.Binary('Registration Certificate')\r\n file_name = fields.Char(\"File Name\")\r\n doc2 = fields.Binary('Route permit')\r\n file_name2 = fields.Char(\"File Name\")\r\n doc3 = fields.Binary('Tax token')\r\n file_name3 = fields.Char(\"File Name\")\r\n doc4 = fields.Binary('Fitness')\r\n file_name4 = fields.Char(\"File Name\")\r\n doc5 = fields.Binary('Insurance')\r\n file_name5 = fields.Char(\"File Name\")\r\n\r\n tyres_count = fields.Integer(string='Tyres', compute='get_tyres_count')\r\n # fuel_type = fields.Selection([('gasoline', 'Petrol'),('lpg', 'CNG'),('diesel', 'Diesel'),('electric','Electric'),('hybrid','Hybrid')], string=\"Fuel Type\")\r\n fuel_type_ids = fields.Many2many('fuel.fuel', string=\"Fuel Type\")\r\n fuel_log_count = fields.Integer(string='Fuel Logs', compute='get_fuel_log_count')\r\n vehicle_seat = fields.Float('Seat/Capacity')\r\n # components_ids = fields.One2many('vehicle.components', 'vehicle_id', string='Components')\r\n vehicle_asign_id = fields.Many2one('hr.employee', string=\"Vehicle Assigned To\")\r\n#added fuel_type and rootes_count \r\n routes_count = fields.Integer(string='Tyres', compute='get_routes_count')\r\n component_count = fields.Integer(string='Component', compute='get_component_count')\r\n average_mileage = fields.Float(string='Average Mileage')\r\n driver_number = fields.Char('Driver Number')\r\n helper_id = fields.Many2one('res.partner', string='Helper Name')\r\n helper_number = fields.Char('Helper Number')\r\n department_id = fields.Many2one('hr.department', string='Department')\r\n driver_nid = fields.Char('Driver ID')\r\n vehicle_history_count = fields.Integer(string='Fuel Logs', compute='get_vehicle_history_count')\r\n tyres_amount = fields.Integer('No of Tyres')\r\n depot_id = fields.Many2one('stock.warehouse', string='Depot')\r\n progress = fields.Float(\"Docs Upload\", compute='_compute_progress', store=True, group_operator=\"avg\", help=\"Display Docs Attached.\")\r\n\r\n @api.depends('doc1', 'doc2', 'doc3','doc4','doc5')\r\n def _compute_progress(self):\r\n for task in self:\r\n task.progress = 0.0\r\n if task.doc1:\r\n task.progress += 20\r\n if task.doc2:\r\n task.progress += 20\r\n if task.doc3:\r\n task.progress += 20\r\n if task.doc4:\r\n task.progress += 20\r\n if task.doc5:\r\n task.progress += 20\r\n \r\n\r\n \r\n def open_vehicle_tyres(self):\r\n return {\r\n 'type': 'ir.actions.act_window',\r\n 'name': 'Tyres',\r\n 'view_mode': 'tree,form',\r\n 'res_model': 'vehicle.tyre.detail',\r\n 'domain': [('vehicle_id', '=', self.id)],\r\n 'context': {'default_vehicle_id': self.id} \r\n \r\n }\r\n\r\n def open_vehicle_component(self):\r\n return {\r\n 'type': 'ir.actions.act_window',\r\n 'name': 'Components',\r\n 'view_mode': 'tree,form',\r\n 'res_model': 'vehicle.components',\r\n 'domain': [('vehicle_id', '=', self.id)],\r\n 'context': {'default_vehicle_id': self.id} \r\n \r\n }\r\n\r\n def get_component_count(self):\r\n count = self.env['vehicle.components'].search_count([('vehicle_id', '=', self.id)])\r\n self.component_count = count\r\n \r\n \r\n def get_tyres_count(self):\r\n count = self.env['vehicle.tyre.detail'].search_count([('vehicle_id', '=', self.id)])\r\n self.tyres_count = count\r\n \r\n\r\n def open_vehicle_fuel_logs(self):\r\n return {\r\n 'type': 'ir.actions.act_window',\r\n 'name': 'Fuel Issue',\r\n 'view_mode': 'tree,form',\r\n 'res_model': 'fleet.vehicle.log.fuel',\r\n 'domain': [('vehicle_id', '=', self.id)], \r\n 'context': {'default_vehicle_id': self.id} \r\n\r\n }\r\n \r\n def get_fuel_log_count(self):\r\n count = self.env['fleet.vehicle.log.fuel'].search_count([('vehicle_id', '=', self.id)])\r\n self.fuel_log_count = count\r\n \r\n# Smart button for Routes \r\n def open_vehicle_routes(self):\r\n return {\r\n 'type': 'ir.actions.act_window',\r\n 'name': 'Routes',\r\n 'view_mode': 'tree,form',\r\n 'res_model': 'fleet.route.plan',\r\n 'domain': [('vehicle_id', '=', self.id)],\r\n 'context': {'default_vehicle_id': self.id} \r\n \r\n }\r\n \r\n# Routes Count \r\n def get_routes_count(self):\r\n count = self.env['fleet.route.plan'].search_count([('vehicle_id', '=', self.id)])\r\n self.routes_count = count\r\n\r\n def open_vehicle_history(self):\r\n return {\r\n 'type': 'ir.actions.act_window',\r\n 'name': 'Routes',\r\n 'view_mode': 'tree,form',\r\n 'res_model': 'vehicle.history',\r\n 'domain': [('vehicle_id', '=', self.id)],\r\n 'context': {'default_vehicle_id': self.id}\r\n\r\n }\r\n\r\n def get_vehicle_history_count(self):\r\n count = self.env['vehicle.history'].search_count([('vehicle_id', '=', self.id)])\r\n self.vehicle_history_count = count\r\n \r\n# Document Upload in Vehicle Service \r\n \r\nclass FleetVehicleLogServices(models.Model):\r\n _inherit = 'fleet.vehicle.log.services'\r\n \r\n doc = fields.Binary('Bill Upload')\r\n file_name = fields.Char(\"File Name\") \r\n\r\n ","sub_path":"olila_fleet/models/fleet.py","file_name":"fleet.py","file_ext":"py","file_size_in_byte":7572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"278230272","text":"class Solution:\n def minWindow(self, s1: str, s2: str) -> str:\n req = collections.Counter(s2)\n s1_c = collections.defaultdict(int)\n l, r, cur = 0, 0, 0\n res = [float('inf'), 0, 0]\n while r < len(s1):\n added = s1[r]\n s1_c[added] += 1\n if added in req and s1_c[added] == req[added]:\n cur += 1\n \n while l <= r and cur == len(req):\n if (r - l + 1) < res[0]:\n res = [r - l + 1, l, r]\n prev = s1[l]\n s1_c[prev] -= 1\n if prev in req and s1_c[prev] == req[prev] - 1:\n cur -= 1\n l += 1\n r += 1\n return s1[res[1]: res[2]+1] if res[0] != float('inf') else ''\n","sub_path":"Facebook/76.py","file_name":"76.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"179680249","text":"import matplotlib.pyplot as plt\nimport code.thinkdsp as thinkdsp\n\ncos_sig = thinkdsp.CosSignal(freq=440, amp=1.0, offset=0)\nsin_sig = thinkdsp.SinSignal(freq=880, amp=0.5, offset=0)\n\nmix = cos_sig+sin_sig\n\nwave = mix.make_wave(duration=0.5, start=0, framerate=11025)\n\nperiod = mix.period\nsegment = wave.segment(start=0, duration=period*1)\n\nsegment.plot()\nplt.show()","sub_path":"practice_11_27_2020.py","file_name":"practice_11_27_2020.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"564930910","text":"'''\nFunction:\n Implementation of Inferencer\nAuthor:\n Zhenchao Jin\n'''\nimport os\nimport cv2\nimport copy\nimport torch\nimport warnings\nimport argparse\nimport numpy as np\nimport torch.nn.functional as F\nfrom tqdm import tqdm\nfrom configs import BuildConfig\nfrom modules import (\n BuildDataset, BuildDistributedDataloader, BuildDistributedModel, BuildLoss, BuildBackbone, BuildSegmentor, BuildPixelSampler, \n Logger, initslurm, setrandomseed, touchdir, loadckpts, saveckpts, BuildOptimizer, BuildScheduler\n)\nwarnings.filterwarnings('ignore')\n\n\n'''parse arguments in command line'''\ndef parsecmdargs():\n parser = argparse.ArgumentParser(description='SSSegmentation is an open source supervised semantic segmentation toolbox based on PyTorch')\n parser.add_argument('--imagedir', dest='imagedir', help='images dir for testing multi images', type=str)\n parser.add_argument('--imagepath', dest='imagepath', help='imagepath for testing single image', type=str)\n parser.add_argument('--outputfilename', dest='outputfilename', help='name to save output image(s)', type=str, default='')\n parser.add_argument('--cfgfilepath', dest='cfgfilepath', help='config file path you want to use', type=str, required=True)\n parser.add_argument('--ckptspath', dest='ckptspath', help='checkpoints you want to resume from', type=str, required=True)\n args = parser.parse_args()\n return args\n\n\n'''Inferencer'''\nclass Inferencer():\n def __init__(self):\n self.cmd_args = parsecmdargs()\n self.cfg, self.cfg_file_path = BuildConfig(self.cmd_args.cfgfilepath)\n assert self.cmd_args.imagepath or self.cmd_args.imagedir, 'imagepath or imagedir should be specified'\n # open full fp32\n torch.backends.cuda.matmul.allow_tf32 = False\n torch.backends.cudnn.allow_tf32 = False\n '''start'''\n def start(self):\n cmd_args, cfg, cfg_file_path = self.cmd_args, self.cfg, self.cfg_file_path\n # touch work dir\n touchdir(cfg.SEGMENTOR_CFG['work_dir'])\n # cuda detect\n use_cuda = torch.cuda.is_available()\n # initialize logger_handle\n logger_handle = Logger(cfg.SEGMENTOR_CFG['logfilepath'])\n # build segmentor\n cfg.SEGMENTOR_CFG['backbone']['pretrained'] = False\n segmentor = BuildSegmentor(segmentor_cfg=cfg.SEGMENTOR_CFG, mode='TEST')\n if use_cuda: segmentor = segmentor.cuda()\n # build dataset\n dataset = BuildDataset(mode='TEST', logger_handle=logger_handle, dataset_cfg=cfg.SEGMENTOR_CFG['dataset'])\n # build palette\n palette = dataset.palette\n # load ckpts\n cmd_args.local_rank = 0\n ckpts = loadckpts(cmd_args.ckptspath)\n try:\n segmentor.load_state_dict(ckpts['model'])\n except Exception as e:\n logger_handle.warning(str(e) + '\\n' + 'Try to load ckpts by using strict=False')\n segmentor.load_state_dict(ckpts['model'], strict=False)\n # set eval\n segmentor.eval()\n # start to test\n inference_cfg = copy.deepcopy(cfg.SEGMENTOR_CFG['inference'])\n FloatTensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor\n if not cmd_args.imagedir:\n imagepaths = [cmd_args.imagepath]\n else:\n imagenames = os.listdir(cmd_args.imagedir)\n imagepaths = [os.path.join(cmd_args.imagedir, name) for name in imagenames]\n pbar = tqdm(range(len(imagepaths)))\n for idx in pbar:\n imagepath = imagepaths[idx]\n if imagepath.split('.')[-1] not in ['jpg', 'jpeg', 'png']: \n continue\n pbar.set_description('Processing %s' % imagepath)\n infer_tricks = inference_cfg['tricks']\n cascade_cfg = infer_tricks.get('cascade', {'key_for_pre_output': 'memory_gather_logits', 'times': 1, 'forward_default_args': None})\n sample_meta = dataset.read(imagepath, 'none.png')\n image = sample_meta['image']\n sample_meta = dataset.synctransforms(sample_meta)\n image_tensor = sample_meta['image'].unsqueeze(0).type(FloatTensor)\n for idx in range(cascade_cfg['times']):\n forward_args = None\n if idx > 0: \n output_list = [\n F.interpolate(outputs, size=output_list[-1].shape[2:], mode='bilinear', align_corners=segmentor.align_corners) for outputs in output_list\n ]\n forward_args = {cascade_cfg['key_for_pre_output']: sum(output_list) / len(output_list)}\n if cascade_cfg['forward_default_args'] is not None: \n forward_args.update(cascade_cfg['forward_default_args'])\n output_list = self.auginference(\n segmentor=segmentor,\n images=image_tensor,\n inference_cfg=inference_cfg,\n num_classes=cfg.SEGMENTOR_CFG['num_classes'],\n FloatTensor=FloatTensor,\n align_corners=segmentor.align_corners,\n forward_args=forward_args,\n )\n output_list = [\n F.interpolate(output, size=(sample_meta['height'], sample_meta['width']), mode='bilinear', align_corners=segmentor.align_corners) for output in output_list\n ]\n output = sum(output_list) / len(output_list)\n pred = (torch.argmax(output[0], dim=0)).cpu().numpy().astype(np.int32)\n mask = np.zeros((pred.shape[0], pred.shape[1], 3), dtype=np.uint8)\n for clsid, color in enumerate(palette):\n mask[pred == clsid, :] = np.array(color)[::-1]\n image = image * 0.5 + mask * 0.5\n image = image.astype(np.uint8)\n if cmd_args.outputfilename:\n cv2.imwrite(os.path.join(cfg.SEGMENTOR_CFG['work_dir'], cmd_args.outputfilename + '_%d' % idx + '.png'), image)\n else:\n cv2.imwrite(os.path.join(cfg.SEGMENTOR_CFG['work_dir'], imagepath.split('/')[-1].split('.')[0] + '.png'), image)\n '''inference with augmentations'''\n def auginference(self, segmentor, images, inference_cfg, num_classes, FloatTensor, align_corners, forward_args=None):\n infer_tricks, outputs_list = inference_cfg['tricks'], []\n for scale_factor in infer_tricks['multiscale']:\n images_scale = F.interpolate(images, scale_factor=scale_factor, mode='bilinear', align_corners=align_corners)\n outputs = self.inference(\n segmentor=segmentor, \n images=images_scale.type(FloatTensor), \n inference_cfg=inference_cfg, \n num_classes=num_classes, \n forward_args=forward_args,\n ).cpu()\n outputs_list.append(outputs)\n if infer_tricks['flip']:\n images_flip = torch.from_numpy(np.flip(images_scale.cpu().numpy(), axis=3).copy())\n outputs_flip = self.inference(\n segmentor=segmentor, \n images=images_flip.type(FloatTensor), \n inference_cfg=inference_cfg, \n num_classes=num_classes, \n forward_args=forward_args,\n )\n fixed_seg_target_pairs = inference_cfg.get('fixed_seg_target_pairs', None)\n if fixed_seg_target_pairs is None:\n for data_pipeline in self.cfg.SEGMENTOR_CFG['dataset']['train']['data_pipelines']:\n if 'RandomFlip' in data_pipeline: \n fixed_seg_target_pairs = data_pipeline[-1].get('fixed_seg_target_pairs', None)\n if fixed_seg_target_pairs is not None:\n outputs_flip_clone = outputs_flip.data.clone()\n for (pair_a, pair_b) in fixed_seg_target_pairs:\n outputs_flip[:, pair_a, :, :] = outputs_flip_clone[:, pair_b, :, :]\n outputs_flip[:, pair_b, :, :] = outputs_flip_clone[:, pair_a, :, :]\n outputs_flip = torch.from_numpy(np.flip(outputs_flip.cpu().numpy(), axis=3).copy()).type_as(outputs)\n outputs_list.append(outputs_flip)\n return outputs_list\n '''inference'''\n def inference(self, segmentor, images, inference_cfg, num_classes, forward_args=None):\n assert inference_cfg['mode'] in ['whole', 'slide']\n use_probs_before_resize = inference_cfg['tricks']['use_probs_before_resize']\n if inference_cfg['mode'] == 'whole':\n if forward_args is None:\n outputs = segmentor(images)\n else:\n outputs = segmentor(images, **forward_args)\n if use_probs_before_resize: \n outputs = F.softmax(outputs, dim=1)\n else:\n align_corners = segmentor.align_corners\n opts = inference_cfg['opts']\n stride_h, stride_w = opts['stride']\n cropsize_h, cropsize_w = opts['cropsize']\n batch_size, _, image_h, image_w = images.size()\n num_grids_h = max(image_h - cropsize_h + stride_h - 1, 0) // stride_h + 1\n num_grids_w = max(image_w - cropsize_w + stride_w - 1, 0) // stride_w + 1\n outputs = images.new_zeros((batch_size, num_classes, image_h, image_w))\n count_mat = images.new_zeros((batch_size, 1, image_h, image_w))\n for h_idx in range(num_grids_h):\n for w_idx in range(num_grids_w):\n x1, y1 = w_idx * stride_w, h_idx * stride_h\n x2, y2 = min(x1 + cropsize_w, image_w), min(y1 + cropsize_h, image_h)\n x1, y1 = max(x2 - cropsize_w, 0), max(y2 - cropsize_h, 0)\n crop_images = images[:, :, y1:y2, x1:x2]\n if forward_args is None:\n outputs_crop = segmentor(crop_images)\n else:\n outputs_crop = segmentor(crop_images, **forward_args)\n outputs_crop = F.interpolate(outputs_crop, size=crop_images.size()[2:], mode='bilinear', align_corners=align_corners)\n if use_probs_before_resize: \n outputs_crop = F.softmax(outputs_crop, dim=1)\n outputs += F.pad(outputs_crop, (int(x1), int(outputs.shape[3] - x2), int(y1), int(outputs.shape[2] - y2)))\n count_mat[:, :, y1:y2, x1:x2] += 1\n assert (count_mat == 0).sum() == 0\n outputs = outputs / count_mat\n return outputs\n\n\n'''debug'''\nif __name__ == '__main__':\n with torch.no_grad():\n client = Inferencer()\n client.start()","sub_path":"ssseg/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":10647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"609543450","text":"__author__ = 'Administrator'\n\nentity_information_file_path = \"../../data/resource/entity_information.txt\"\noutput_file_path = \"../../data/resource/wikipage_title_entity_id\"\n\ncoding = \"utf8\"\n\ntitle_entity_id_dic = {}\n\nfr = open(entity_information_file_path,'r',encoding = coding)\nfw = open(output_file_path,'w',encoding = coding)\n\nline = fr.readline()\nwhile(line):\n line = line.strip()\n if(line != ''):\n line_list = line.split(\"\\t\")\n entity_id = line_list[0].strip(\"\\\"\")\n title = line_list[3].strip(\"\\\"\")\n\n fw.write(\"{0}\\t{1}\\n\".format(title,entity_id))\n\n line = fr.readline()\n\nfr.close()\nfw.close()\n\n\n\n","sub_path":"src/tools/convert_title_id_to_title_entityid.py","file_name":"convert_title_id_to_title_entityid.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"573815340","text":"# -*- coding: utf-8 -*-\n\"\"\"\nfunction:\n@author: qinxunhui\ntime:\n\"\"\"\n\nimport xgboost as xgb\nimport json\nimport numpy as np\n\nfrom load_q_xianghai import load_q_info\nimport extract_feature\n\npath = 'D:/evaluation/data/测试数据/finance8000_q_extend_info_ex_with_type.txt'\nq_info_dic = load_q_info(path)\n\n\ndef gen_feature_label(json_path):\n with open(json_path, 'r') as file:\n data = json.load(file)\n label = [row['pass'] for row in data]\n\n feature = []\n for row in data:\n feature_one = extract_feature.get_all_feature(row, q_info_dic)\n feature.append(feature_one)\n\n label = np.array(label)\n feature = np.array(feature)\n return feature, label\n\n\ndef train_test():\n\n # 训练样本路径和测试样本路径\n json_path_train = \"D:\\evaluation\\data\\测试数据\\\\test_8_topN_22859_train.json\"\n json_path_test = \"D:\\evaluation\\data\\测试数据\\\\test_8_topN_22859_test.json\"\n\n model_path = \"finance8000_xgboost_scores_wmdr_type.model\"\n\n # xgboost param\n param = {\n 'booster': 'gbtree', #gbtree使用基于树的模型进行提升计算,gblinear使用线性模型进行提升计算\n 'learning_rate': 0.01, #学习率\n 'max_depth': 10, #树的最大深度。缺省值为6。通常取值:3-10。树的深度越大,则对数据的拟合程度越高\n 'min_child_weight': 1, #孩子节点中最小的样本权重和。如果一个叶子节点的样本权重和小于min_child_weight则拆分过程结束。即调大这个参数能够控制过拟合。\n 'gamma': 0.1, #gamma值【0-】值越大算法算法更conservation(保守),且其值依赖于loss function ,在模型中应该进行调参\n 'subsample': 0.7, #用于训练模型的子样本占整个样本集合的比例。如果设置为0.5则意味着XGBoost将随机的从整个样本集合中抽取出50%的子样本建立树模型,这能够防止过拟合。\n 'objective': 'binary:logistic', #目标函数类型,'binary:logistic'二分类的逻辑回归问题,输出为概率。\n 'scale_pos_weight': 1, #大于0的取值可以处理类别不平衡的情况。帮助模型更快收敛\n 'seed': 1000 #随机数的种子。缺省值为0。可以用于产生可重复的结果\n }\n\n plst = param.items()\n\n # 训练样本\n # feature_train, label_train = gen_feature_label(json_path_train)\n feature_train, label_train = gen_feature_label(json_path_train)\n\n # 测试样本\n # feature_test, label_test = gen_feature_label(json_path_test)\n feature_test, label_test = gen_feature_label(json_path_test)\n\n dtrain = xgb.DMatrix(feature_train, label=label_train)\n dtest = xgb.DMatrix(feature_test, label=label_test)\n evallist = [(dtest,'eval'), (dtrain,'train')]\n\n num_round = 20\n bst = xgb.train(plst, dtrain, num_round, evallist)\n bst.save_model(model_path)\n\n\nif __name__ == \"__main__\":\n # json_path_train = \"D:\\svn_algorithm\\standard\\测试平台算法评测\\code\\\\test_13_topN_22859_train.json\"\n # intent_path = \"../data/测试数据/finance8000_intent.txt\"\n # feature, label = gen_feature_label(json_path_train, intent_path)\n # print(feature, label)\n\n train_test()\n\n\n\n\n","sub_path":"train_xgboost.py","file_name":"train_xgboost.py","file_ext":"py","file_size_in_byte":3346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"310060673","text":"defaults = {\n \"Movement\": 5,\n \"max_bleeding_tokens\": 5,\n}\n\n\n#\n# these are the 'macro' options used when creating new settlements. See the\n# new_settlement_special() method of the settlements.Settlement model/class\n#\n\nspecials = {\n \"create_first_story_survivors\": {\n \"name\": \"First Story\",\n \"title\": 'Four \"First Story\" Survivors',\n \"desc\": 'Two male and two female survivors will be randomly generated and automatically added to the Departing Survivors group. Starting gear is added to Settlement Storage.',\n \"current_quarry\": \"White Lion (First Story)\",\n 'showdown_type': 'normal',\n \"random_survivors\": [\n {\"sex\": \"M\", \"Waist\": 1, \"departing\": True},\n {\"sex\": \"M\", \"Waist\": 1, \"departing\": True},\n {\"sex\": \"F\", \"Waist\": 1, \"departing\": True},\n {\"sex\": \"F\", \"Waist\": 1, \"departing\": True},\n ],\n \"storage\": [\n {\"name\": \"founding_stone\", \"quantity\": 4},\n {\"name\": \"cloth\", \"quantity\": 4},\n ],\n \"timeline_events\": [\n {\"ly\": 0, \"sub_type\": \"showdown_event\", \"name\": \"White Lion (First Story)\"},\n ],\n },\n\n \"create_seven_swordsmen\": {\n \"name\": \"Seven Swordsmen\",\n \"title\": \"Seven Swordsmen\",\n \"desc\": 'Seven survivors with the \"Ageless\" ability and Sword mastery will be randomly generated.',\n \"random_survivors\": [\n {\"sex\": \"R\", 'abilities_and_impairments': ['ageless','mastery_sword']},\n {\"sex\": \"R\", 'abilities_and_impairments': ['ageless','mastery_sword']},\n {\"sex\": \"R\", 'abilities_and_impairments': ['ageless','mastery_sword']},\n {\"sex\": \"R\", 'abilities_and_impairments': ['ageless','mastery_sword']},\n {\"sex\": \"R\", 'abilities_and_impairments': ['ageless','mastery_sword']},\n {\"sex\": \"R\", 'abilities_and_impairments': ['ageless','mastery_sword']},\n {\"sex\": \"R\", 'abilities_and_impairments': ['ageless','mastery_sword']},\n ],\n },\n\n}\n\n\n\n#\n# the survivors in the BCS PDF\n#\n\nbeta_challenge_scenarios = {\n \"adam\": {\n \"name\": \"Adam\",\n 'expansion': 'beta_challenge_scenarios',\n \"attribs\": {\n \"name\": \"Adam\",\n \"sex\": \"M\",\n \"survival\": 4,\n \"Insanity\": 4,\n \"Courage\": 6,\n \"Understanding\": 3,\n \"Weapon Proficiency\": 3,\n \"Strength\": 1,\n \"weapon_proficiency_type\": \"sword\",\n \"fighting_arts\": [\"timeless_eye\"],\n \"abilities_and_impairments\": [\"partner\", \"sword_specialization\"],\n },\n# \"storage\": [\n# \"Leather Mask\",\n# \"Leather Cuirass\",\n# \"Leather Bracers\",\n# \"Leather Skirt\",\n# \"Leather Boots\",\n# \"Scrap Sword\",\n# ],\n },\n \"anna\": {\n \"name\": \"Anna\",\n 'expansion': 'beta_challenge_scenarios',\n \"attribs\": {\n \"name\": \"Anna\",\n \"sex\": \"F\",\n \"survival\": 4,\n \"Insanity\": 4,\n \"Courage\": 3,\n \"Understanding\": 6,\n \"Weapon Proficiency\": 3,\n \"Evasion\": 1,\n \"weapon_proficiency_type\": \"spear\",\n \"fighting_arts\": [\"leader\"],\n \"abilities_and_impairments\": [\"partner\", \"spear_specialization\"],\n },\n# \"storage\": [\n# \"Leather Mask\",\n# \"Leather Cuirass\",\n# \"Leather Bracers\",\n# \"Leather Skirt\",\n# \"Leather Boots\",\n# \"King Spear\",\n# ],\n },\n \"paul_the_survivor\": {\n \"name\": \"Paul the Survivor\",\n 'expansion': 'beta_challenge_scenarios',\n \"attribs\": {\n \"name\": \"Paul\",\n \"sex\": \"M\",\n \"survival\": 5,\n \"Insanity\": 9,\n \"Courage\": 3,\n \"Understanding\": 3,\n \"fighting_arts\": [\"thrill_seeker\",\"clutch_fighter\",\"extra_sense\"],\n \"disorders\": [\"rageholic\",\"sworn_enemy\"],\n },\n \"storage\": [\n# \"Rawhide Pants\",\n# \"Rawhide Gloves\",\n# \"Rawhide Vest\",\n# \"Rawhide Boots\",\n# \"Bone Dagger\",\n# \"Scrap Sword\",\n# \"Piranha Helm\",\n# \"Petal Lantern\",\n ],\n },\n \"candy_and_cola\":{\n \"name\": \"Candy & Cola\",\n 'expansion': 'beta_challenge_scenarios',\n \"attribs\": {\"name\": \"Candy & Cola\", \"Movement\": 6, \"disorders\": [\"hyperactive\"], \"sex\": \"F\"},\n },\n \"kara_black\": {\n \"name\": \"Kara Black\",\n 'expansion': 'beta_challenge_scenarios',\n \"attribs\": {\"name\": \"Kara Black\", \"survival\": 3, \"Strength\": 1, \"fighting_arts\": [\"leader\",\"tough\"], \"sex\": \"F\"},\n# \"storage\": [\"Founding Stone\", \"Cloth\", \"Giant Stone Face\"],\n },\n \"messenger_of_the_first_story\": {\n \"name\": \"Messenger of the First Story\",\n 'expansion': 'beta_challenge_scenarios',\n \"attribs\": {\n \"name\": \"Messenger of the First Story\",\n \"sex\": \"F\",\n \"survival\": 6,\n \"Insanity\": 6,\n \"Courage\": 6,\n \"Strength\": 1,\n \"Evasion\": 1,\n \"Speed\": 1,\n \"fighting_arts\": [\"last_man_standing\"],\n },\n# \"storage\": [\n# \"Screaming Horns\",\n# \"Screaming Coat\",\n# \"Screaming Skirt\",\n# \"Screaming Bracers\",\n# \"Screaming Leg Warmers\",\n# \"Monster Grease\",\n# \"Cat Eye Circlet\",\n# \"Dried Acanthus\",\n# \"Arm of the First Tree\",\n# ],\n },\n \"messenger_of_courage\":{\n \"name\": \"Messenger of Courage\",\n 'expansion': 'beta_challenge_scenarios',\n \"attribs\": {\n \"name\": \"Messenger of Courage\",\n \"sex\": \"F\",\n \"survival\": 6,\n \"Insanity\": 9,\n \"Courage\": 9,\n \"Understanding\": 5,\n \"Strength\": 1,\n \"Evasion\": 2,\n \"Speed\": 2,\n \"hunt_xp\": 2,\n \"Weapon Proficiency\": 5,\n \"weapon_proficiency_type\": \"twilight_sword\",\n \"fighting_arts\": [\"last_man_standing\"],\n \"cursed_items\": [\"twilight_sword\"],\n \"abilities_and_impairments\": [\"twilight_sword_specialization\"],\n \"epithets\": [\"twilight_sword\"],\n },\n# \"storage\": [\n# \"Scout's Tunic\",\n# \"Fairy Bottle\",\n# \"Leather Skirt\",\n# \"Leather Boots\",\n# \"Leather Bracers\",\n# \"Feather Mantle\",\n# \"Twilight Sword\"\n# ],\n },\n \"messenger_of_humanity\":{\n \"name\": \"Messenger of Humanity\",\n 'expansion': 'beta_challenge_scenarios',\n \"attribs\": {\n \"name\": \"Messenger of Humanity\",\n \"sex\": \"M\",\n \"survival\": 10,\n \"abilities_and_impairments\": [\"bitter_frenzy\", \"solid\", \"grand_weapon_specialization\"],\n \"fighting_arts\": [\"berserker\", \"crossarm_block\", \"unconscious_fighter\"],\n \"disorders\": [\"rageholic\"],\n },\n# \"storage\": [\n# \"Lantern Helm\",\n# \"Lantern Cuirass\",\n# \"Lantern Greaves\",\n# \"Lantern Mail\",\n# \"Lantern Gauntlets\",\n# \"Beacon Shield\",\n# \"Dragon Slayer\"\n# \"Stone Arm\"\n# ],\n },\n \"snow_the_savior\":{\n \"name\": \"Snow the Savior\",\n 'expansion': 'beta_challenge_scenarios',\n \"attribs\": {\n \"name\": \"Snow\",\n \"sex\": \"F\",\n \"survival\": 6,\n \"Insanity\": 8,\n \"Courage\": 5,\n \"Understanding\": 5,\n \"fighting_arts\": [\"unconscious_fighter\"],\n \"abilities_and_impairments\": [\"red_glow\", \"blue_glow\", \"green_glow\"]\n },\n },\n\n}\n","sub_path":"v2/api/assets/survivors.py","file_name":"survivors.py","file_ext":"py","file_size_in_byte":7798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"287771470","text":"import aiohttp\nimport asyncio\nfrom pprint import pprint\nfrom parsel import Selector\nfrom concurrent.futures import ThreadPoolExecutor\n\n# py4seo variant\n# async def main():\n# session = aiohttp.ClientSession()\n# response = await session.get('http://python.org')\n# html = await response.text()\n# sel = Selector(text=html)\n# print(dir(sel))\n# await session.close()\n\ndomain = 'kartochki-domana.com.ua'\nqueue = asyncio.Queue()\nadded_prod_urls = set()\n\nloop = asyncio.get_event_loop()\nexecutor = ThreadPoolExecutor(max_workers=10)\n\n\ndef scrape_data(html):\n sel = Selector(text=html)\n title = sel.xpath('//h1[contains(@class, \"product_title\")]/text()').get()\n price = sel.xpath('//p[@class=\"price\"]/span[contains(@class, \"woocommerce-Price-amount\")]/text()').get()\n return title, price\n\n# My variant\nasync def worker(session):\n while not queue.empty():\n target_url = await queue.get()\n async with session.get(target_url) as response:\n html = await response.text()\n \n title, price = await loop.run_in_executor(executor, scrape_data, html)\n print(f'{title}: {price}')\n \n # [\n # (await queue.put(prod_url), added_prod_urls.add(prod_url))\n # for prod_url in prod_urls\n # if prod_url not in added_prod_urls\n # ]\n\n\nasync def main(): \n async with aiohttp.ClientSession() as session:\n response = await session.get('https://kartochki-domana.com.ua/ru/product-category/podarochnie-nabori/')\n html = await response.text()\n \n sel = Selector(text=html)\n prod_urls = sel.xpath('//h3[@class=\"product_title\"]/a/@href').getall()\n\n [\n (await queue.put(prod_url), added_prod_urls.add(prod_url))\n for prod_url in prod_urls\n if prod_url not in added_prod_urls\n ]\n \n print(queue.qsize())\n # pprint(added_prod_urls)\n \n tasks = []\n for _ in range(50):\n task = asyncio.Task(worker(session))\n tasks.append(task)\n await asyncio.gather(*tasks)\n\n\nif __name__ == '__main__':\n\n\n # task1 = asyncio.Task(coro())\n # task2 = asyncio.Task(main())\n\n # runer = asyncio.gather(task1, task2)\n\n # loop = asyncio.get_event_loop()\n # loop.run_until_complete(runer)\n\n\n # Run just 1 coroutine main()\n \n loop.run_until_complete(main())\n","sub_path":"17_1_Asyncron/6_asyncio_aiohttp_with_threads.py","file_name":"6_asyncio_aiohttp_with_threads.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"612931044","text":"# -*- coding: cp1254 -*-\n#sansa bağlı olmayan caprazlama anneden ve babadan eşit sayıda dna gelir\ndef Caprazla2(indes1,indes2,popilasyon):\n #print dizi\n #print dizi2\n #dizi=[1,2,3,4,5,6,7,8,9,12,3,4,5,6]\n #dizi2=[44,33,11,77,55,44,33,88,77,99,445,654,323,54]\n\n import random\n\n dizi3=[]\n dizi4=[]\n\n #dizi3 için\n secim=0\n for i in range(0,len(popilasyon[indes1])):\n if (i/2== i/2.0):\n dizi3.append(popilasyon[indes1][i])\n \n else:\n dizi3.append(popilasyon[indes2][i])\n\n #dizi4 için #sadece bir çaprazlamadan bir çocuk olduğunu varsayıyoruz\n## for i in range(0,len(dizi2)):\n## secim=random.randrange(2)\n## if (secim == 0):\n## dizi4.append(dizi[i])\n## else:\n## dizi4.append(dizi2[i])\n\n return dizi3\n#dizi1 ve dizi2 kendiyle bir seçilimde en fazla 4 kere çaprazlanmalı\n#yeni jenerasyon oluştuktan sonra dizi1 ve dizi2 silinmeli\n\n","sub_path":"caprazlama2.py","file_name":"caprazlama2.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"559442471","text":"from flask import Flask, jsonify, request\n\nfrom flask_swaggervalidator import decorators\n\n\napp = Flask(__name__)\n\n\n@app.route('/')\n@decorators.validate_swagger_request('api.say_hello')\n@decorators.validate_swagger_response('api.say_hello')\ndef say_hello():\n name = request.args.get('name', 'Unknown')\n data = {\n 'weekend_greeting': 'Welcome to the weekend, {}!'.format(name),\n 'pizza_party': 1\n }\n return jsonify(data)\n\n\nif __name__ == '__main__':\n app.debug = True\n app.run()\n","sub_path":"docs/examples/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"504501975","text":"from glue import custom_viewer\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\ncolor_points = custom_viewer('Color Plot', x='att', y='att', c='att')\n\ncmap = plt.get_cmap('spectral')\nnorm = mpl.colors.Normalize(vmin=0., vmax=1.)\n\n@color_points.plot_data\ndef show_scatter(axes, x, y, c, cmap=cmap, norm=norm):\n axes.scatter(x, y, marker='o', ms=5, c=c, cmap=cmap, norm=norm)\n\n@color_points.plot_subset\ndef show_points(axes, x, y, c, style):\n axes.scatter(x, y, marker='o', ms=6, mew=2, c=c, mec=style.color, cmap=cmap, norm=norm)\n\n","sub_path":"CfAHackDay/custom_plots.py","file_name":"custom_plots.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"9553182","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 11 10:50:28 2013\n\n@author: Mahmoudreza Aghighi\n\nmodule __FicksLawDiffusion__: Fick's Law Diffusion\n========================================================================\n\n.. warning:: The classes of this module should be loaded through the 'ALG.__init__.py' file.\n\n\"\"\"\n\nimport OpenPNM\nimport numpy as np\nimport scipy.sparse as sprs\nimport scipy.sparse.linalg as splin\nfrom __GenericAlgorithm__ import GenericAlgorithm\n\nclass FicksLawDiffusion(GenericAlgorithm):\n r\"\"\" \n \n FicksLawDiffusion - Class to run Fick's law mass transfer diffusion on constructed networks\n \n It returns conecentration gradient inside the network.\n An invasion algorithm should be used before running diffusion calculations.\n \n \n Parameters\n ----------\n - Alg:\n Algorithm for Non wetting phase configuration\n 'OP' , 'IP' and 'None' are possible options. \n - Pressure for 'OP':\n Applied pressure on the network which causes some pores and throats be invaded by non-wetting phase.\n It can be a single value or a list.\n The class will consider uninvaded conduits based on this pressure, as possible voids for gas diffusion.\n Every pore with Pc_invade greater than Pressure, will be considered as open pores \n - Psequence for 'IP':\n The desired sequence of invaded pores based on IP algorithm.\n The class will consider uninvaded conduits based on this sequence number, as possible voids for gas diffusion.\n It can be a single value or a list.\n Every pore with sequence number greater than Psequence, will be considered as open pores.\n - Pinvaded for 'None':\n It is a list which contains invaded pores and based on user's definition.\n \n -loglevel : int\n Level of the logger (10=Debug, 20=INFO, 30=Warning, 40=Error, 50=Critical) \n - Total_Conc: \n Total gas concentration\n - Diff_Coefficient:\n Diffision coefficient for diffusion of A through stagnant B(e.g. Oxygen through Nitrogen and Water vapor)\n \n Examples\n --------\n\n All of the variables in this class have default values, but users can define them too.\n >>>\n \n To Do:\n - Instead of sending (Pressure in OP) or (Psequence in IP) as inputs, this class should only accept \n a list of invaded voids.\n - loglevel and documentation is not complete yet.\n - For Applying Neumann boundary condition, a function is needed to consider mass conservation, sink or\n source terms and warn user about the applied values.\n \n \"\"\"\n \n def __init__(self,net=OpenPNM.NET.GenericNetwork(),loglevel=10,Alg='None',Pressure=[0],Psequence=[0],Pinvaded=[],**kwargs):\n r\"\"\"\n Initializing the class\n \"\"\"\n super(FicksLawDiffusion,self).__init__(net = net,**kwargs)\n self._logger.info(\"Create Fick's Diffusion Algorithm Object\")\n self.Alg = Alg\n self.Pressure = Pressure\n self.Psequence = Psequence\n self.Pinvaded = Pinvaded\n\n \n def _setup_for_FicksDiffusion(self):\n r\"\"\"\n Main features: Applying Boundary Conditions & Creating Transport Conductivities \n\n This function executes the essential mathods for building matrices in Linear solution \n \"\"\"\n self._logger.info(\"Create Diffusion Conductivities\") \n self._fill_Conductivity()\n self._logger.info(\"Applying Boundary Conditions\")\n self._Boundary_Pores_Conditions() \n\n def _Boundary_Pores_Conditions(self,FaceTypes=[4,1,4,4,1,4],FaceValues=[0,0.2,0,0,0.5,0],BList=[]):\n r\"\"\" \n - Assigning Type and Value for Boundary Pores.\n - Types of Boundary Values in FaceTypes:\n internal=0, Dirichlet=1, flux=2, periodic=3, insulated=4 mass_rate=5\n - In FaceValues, each item represents the value of that face according\n to the boundary condition type. Except for mass_rate condition which \n the value represents the total mass rate applied to the entire face,\n not just a single pore. \n For instance: if we have Facetypes[2]=1 and FaceValues[2]=0.75,it means\n that for face 3, concentration=0.75\n but if we have FaceTypes[4]=2 and FaceValues[4]=0.8, it means that\n for face 5, flux=0.8\n - Instead of applying boundary conditions to entire face, by using \n BLists, it is possible to apply BC to arbitrary pores. For instance:\n BLists = [(459,2,0.097),(2043,1,0.5)]\n It means that for Pore 459: flux=0.097 & for Pore 2043: Concentration=0.5\n \"\"\"\n self._net.pore_properties['BCtype'] = np.zeros(self._net.get_num_pores())\n self._net.pore_properties['BCvalue'] = np.zeros(self._net.get_num_pores())\n for i in range(1,7):\n self._net.pore_properties['BCtype'][self._net.pore_properties['type']==i] = FaceTypes[i-1]\n self._net.pore_properties['BCvalue'][self._net.pore_properties['type']==i] = FaceValues[i-1]\n if BList:\n for item in BList:\n pore = item[0]\n self._net.pore_properties['BCtype'][pore] = item[1]\n self._net.pore_properties['BCvalue'][pore] = item[2]\n \n def _Inv_Conduit(self,P_val): \n r\"\"\"\n creates a tlist containing which is useful to indicate the conduit is\n filled with invading fluid or not.\n \n \"\"\" \n \n if self.Alg=='None':\n self._logger.info(\"Invaded pores have already been determined\") \n else:\n if self.Alg=='OP':\n val_name = 'Pc_invaded'\n B_condition = self._net.pore_properties[val_name]P_val)\n \n self._net.set_pore_property(name=\"Concentration_at_\"+str(P_val),ndarray=Concentration)\n \n\n def _do_one_inner_iteration(self,P_val):\n \n if hasattr(self._net,'dry_coefficient_matrix'):\n self.logger.info('Dry matrix has already been created') \n else: \n setattr(self._net,\"dry_coefficient_matrix\",self._Coefficient_Matrix(P_val=0))\n \n if ((P_val==0)and(len(self.Pinvaded)==0)):\n A = self._net.dry_coefficient_matrix\n else:\n A = self._Coefficient_Matrix(P_val) \n \n if (self._net.pore_properties['BCtype']==2).any():\n B = np.zeros([self.A_dim,1])\n Dir_pores = np.array(range(self._net.get_num_pores()))[self._net.pore_properties['BCtype']==1]\n B[Dir_pores] = np.reshape(self._net.pore_properties['BCvalue'][Dir_pores],[len(Dir_pores),1])\n for item in len(self.extera_neu):\n F_type = np.unique(self._net.pore_properties['BCtype'][self._net.pore_properties['BCvalue']==self.extera_neu[item]])\n if F_type==1:\n Area = self._net.divisions[1]*self._net.divisions[2]*self._net.lattice_spacing\n elif F_type==2:\n Area = self._net.divisions[0]*self._net.divisions[1]*self._net.lattice_spacing\n elif F_type==3:\n Area = self._net.divisions[0]*self._net.divisions[2]*self._net.lattice_spacing\n elif F_type==4:\n Area = self._net.divisions[0]*self._net.divisions[2]*self._net.lattice_spacing\n elif F_type==5:\n Area = self._net.divisions[0]*self._net.divisions[1]*self._net.lattice_spacing\n elif F_type==6:\n Area = self._net.divisions[1]*self._net.divisions[2]*self._net.lattice_spacing \n B[self.A_dim-item,0] = - self.extera_neu[item]*Area\n else:\n A_dim = self._net.get_num_pores() \n B = np.reshape(self._net.pore_properties['BCvalue'],[A_dim,1])\n\n\n for i in range(0,self._net.get_num_pores()):\n if self._net.pore_properties['BCvalue'][i]!=0:\n neighbors = self._net.get_neighbor_pores(i)\n if np.in1d(neighbors,self.Pinvaded).all():\n B[i,0] = 0\n\n x = splin.spsolve(A,B) \n return(x)\n \n \n def _fill_Conductivity(self):\n r\"\"\"\n\n \"\"\"\n self._logger.info(\"Calculating Diffusion Conductivity for all of the Voids \")\n C = self._net.Total_Conc\n D = self._net.Diff_Coefficient\n self._net.set_throat_property(name=\"Cdiff\",ndarray=np.zeros(self._net.get_num_throats()))\n tcond = C*D*np.abs(( self._net.throat_properties['diameter'])**2/self._net.throat_properties['length'])\n pcond = C*D*np.abs((self._net.pore_properties['diameter'])**2/(self._net.pore_properties['diameter']/2))\n for i in range(self._net.get_num_throats()):\n PNeighbors = self._net.get_connected_pores(i)\n if (self._net.pore_properties['type'][PNeighbors[0]]!=0):\n self._net.throat_properties['Cdiff'][i] = (1/tcond[i]+1/pcond[PNeighbors[1]]+1/pcond[PNeighbors[1]])**(-1)\n elif (self._net.pore_properties['type'][PNeighbors[1]]!=0):\n self._net.throat_properties['Cdiff'][i] = (1/pcond[PNeighbors[0]]+1/pcond[PNeighbors[0]]+1/tcond[i])**(-1)\n else:\n self._net.throat_properties['Cdiff'][i] = (1/pcond[PNeighbors[0]]+1/tcond[i]+1/pcond[PNeighbors[1]])**(-1)\n \n \n def _Coefficient_Matrix(self,P_val):\n \n # Determine open and closed conduits for mass transfer \n if hasattr(self._net,'dry_coefficient_matrix'):\n \n if ((len(self.Pinvaded)>0)or(P_val>0)):\n self._Inv_Conduit(P_val)\n list_name = 'CdiffWet'\n# if P_val>0:\n# if self.Alg=='OP':\n# val_name = 'Pc_invaded' \n# elif self.Alg=='IP':\n# val_name = 'IP_Pseq'\n# self.Pinvaded = np.array(range(self._net.get_num_pores()))[self._net.pore_properties[val_name]P_val)) \n# else:\n temp_list = np.multiply(self._net.throat_properties['Cdiff'],self._net.throat_properties['UninvadedConduits']) \n self._net.set_throat_property(name=list_name,ndarray=temp_list)\n else:\n list_name = 'Cdiff'\n # Filling coefficient matrix\n\n nodes = self._net.throat_properties[list_name]>0 \n tpore1 = self._net.throat_properties['connections'][:,0]\n tpore2 = self._net.throat_properties['connections'][:,1]\n row = np.append(tpore1[nodes],tpore1[-nodes])\n col = np.append(tpore2[nodes],tpore2[-nodes])\n data= np.append(self._net.throat_properties[list_name][nodes],np.ones([len(tpore1[-nodes])])*1e-30)\n \n\n pnum = np.array(range(self._net.get_num_pores()))\n pdry = tpore2[nodes] \n loc1 = np.in1d(tpore2,pdry[np.in1d(pdry,pnum[self._net.pore_properties['BCtype']!=1])])\n modified_tpore2_dry = tpore2[loc1]\n modified_tpore1_dry = tpore1[loc1] \n row = np.append(row,modified_tpore2_dry) \n col = np.append(col,modified_tpore1_dry)\n data = np.append(data,self._net.throat_properties[list_name][loc1])\n \n pwet = tpore2[-nodes]\n loc2 = np.in1d(tpore2,pwet[np.in1d(pwet,pnum[self._net.pore_properties['BCtype']!=1])])\n modified_tpore2_wet = tpore2[loc2]\n modified_tpore1_wet = tpore1[loc2] \n row = np.append(row,modified_tpore2_wet) \n col = np.append(col,modified_tpore1_wet)\n data = np.append(data,np.ones([len(modified_tpore2_wet)])*1e-30)\n \n if (self._net.pore_properties['BCtype']==2).any():\n self.extera_neu = np.unique(self._net.pore_properties['BCvalue'][self._net.pore_properties['BCtype']==2])\n self.A_dim = self._net.get_num_pores()+ len(self.extera_neu)\n extera_neu = self.extera_neu\n A_dim = self.A_dim\n\n for item in len(extera_neu):\n loc_neu = np.in1d(tpore2,pnum[self._net.pore_properties['BCvalue']==extera_neu[item]])\n neu_tpore2 = tpore2[loc_neu] \n row = np.append(row,neu_tpore2) \n col = np.append(col,np.ones([len(neu_tpore2)])*(A_dim-item))\n data = np.append(data,np.ones([len(neu_tpore2)])*1e-18)\n \n row = np.append(row,np.ones([len(neu_tpore2)])*(A_dim-item)) \n col = np.append(col,neu_tpore2)\n data = np.append(data,np.ones([len(neu_tpore2)])*1e-18)\n \n else:\n A_dim = self._net.get_num_pores()\n \n # Adding positions for diagonal\n \n row = np.append(row,range(0,A_dim))\n col = np.append(col,range(0,A_dim))\n data = np.append(data,np.zeros((A_dim,1)))\n\n a = sprs.coo.coo_matrix((data,(row,col)),(A_dim,A_dim))\n A = a.tocsr() \n \n for i in range(0,A_dim): \n if self._net.pore_properties['BCtype'][i]==1:\n A[i,i] = 1 \n else:\n A[i,i] = -np.sum(A[i,:][np.nonzero(A[i,:])])\n \n return(A)","sub_path":"OpenPNM/ALG/__FicksLawDiffusion__.py","file_name":"__FicksLawDiffusion__.py","file_ext":"py","file_size_in_byte":15827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"254219617","text":"# performs geometric functions\n\ndef menu():\n\t\"\"\"displays program options\"\"\"\n\tprint(\"\\tGeometry Calculator\\n\")\n\tprint(\"Welcome! This program makes simple geometry calculations.\")\n\tprint(\"\\nSelect one of the following:\")\n\t# these can probably be rewritten as a dict\n\tprint(\"1: Area\")\n\tprint(\"2: Perimeter\")\n\tprint(\"3: Volume\")\n\t\n\t# string is default input type--no need to convert to int later\n\tmenu_list = ['1','2','3']\n\n\tmenu_choice = input()\n\t# input validation\n\twhile menu_choice not in menu_list:\n\t\tmenu_choice = input(\"Enter a valid selection: \")\n\tif menu_choice == '1':\n\t\tarea()\n\telif menu_choice == '2':\n\t\tperimeter()\n\telif menu_choice == '3':\n\t\tvolume()\n\t\t\ndef area():\n\t\"\"\"displays shape selection for area calculations\"\"\"\n\t# rewrite as dict\n\tprint(\"\\nSelect one of the following shapes: \")\n\tprint(\"1: Square\")\n\tprint(\"2: Rectangle\")\n\tprint(\"3: Parallelogram\")\n\tprint(\"4: Trapezoid\")\n\tprint(\"5: Circle\")\n\n\tarea_list = ['1','2','3','4','5','6']\n\n\tarea_choice = input()\n\t# input validation\n\twhile area_choice not in area_list:\n\t\tarea_choice = input(\"Enter a valid selection: \")\n\tif area_choice == '1':\n\t\tprint(\"The area of the square is:\", square_area())\n\telif area_choice == '2':\n\t\tprint(\"The area of the rectangle is:\", rectangle())\n\telif area_choice == '3':\n\t\tprint(\"The area of the parallelogram is:\", parallelogram())\n\telif area_choice == '4':\n\t\tprint(\"The area of the trapezoid is:\", trapezoid())\n\telif area_choice == '5':\n\t\tprint(\"The area of the circle is:\", circle())\n\ndef perimeter():\n\t\"\"\"calculates the perimter of a shape given side lengths\"\"\"\n\t# validate input for number of sides\n\t# loops until int received\n\twhile True:\n\t\ttry:\n\t\t\tsides = int(input(\"How many sides does the shape have? \"))\n\t\t\tbreak\n\t\texcept ValueError:\n\t\t\tprint(\"Enter a valid integer.\")\n\t\t\tcontinue\n\n\t# incrementer for number sides\n\tcounter = 0\n\n\t# counter for perimeter\n\tperimeter = 0\n\n\t# loop for n in number sides\n\tfor num in range(sides):\n\t\t\n\t\twhile True:\n\t\t\t# loop input for side length until int received\n\t\t\ttry:\n\t\t\t\tprint(\"Enter the length of side number \", counter + 1, \": \", sep='',end='')\n\t\t\t\tside_length = float(input())\n\t\t\t\tbreak\n\t\t\texcept ValueError:\n\t\t\t\tprint(\"Please enter a valid integer.\")\n\t\t\t\tcontinue\n\t\t# add side length to perimeter, increment counter\n\t\tperimeter += side_length\n\t\tcounter += 1\n\n\tprint(\"The perimeter is:\", perimeter)\n\ndef volume():\n\t# rewrite as dict--the whole list below can iterate over the dict\n\tprint(\"\\n\\tVolume Calculator\")\n\tprint(\"\\nSelect one of the following shapes: \")\n\tprint(\"1: Cube\")\n\tprint(\"2: Rectangular prism\")\n\tprint(\"3: Cylinder\")\n\tprint(\"4: Pyramid\")\n\tprint(\"5: Cone\")\n\tprint(\"6: Sphere\")\n\tprint(\"7: Elipsoid\")\n\n\tvol_list = ['1','2','3','4','5','6']\n\n\tvol_choice = input()\n\t# input validation\n\twhile vol_choice not in vol_list:\n\t\tvol_choice = input(\"Enter a valid selection: \")\n\tif vol_choice == '1':\n\t\tprint(\"The volume of the cube is:\", cube())\n\telif vol_choice == '2':\n\t\tprint(\"The volume of the rectangular prism is:\", rect_prism())\n\telif vol_choice == '3':\n\t\tprint(\"The volume of the cylinder is:\", cylinder())\n\telif vol_choice == '4':\n\t\tprint(\"The volume of the pyramid is:\", pyramid())\n\telif vol_choice == '5':\n\t\tprint(\"The volume of the cone is:\", cone()())\n\telif vol_choice == '6':\n\t\tprint(\"The volume of the sphere is:\", sphere())\n\telif vol_choice == '7':\n\t\tprint(\"The volume of the elipsoid is:\", elipsoid())\n\ndef square_area():\n\t\"\"\"calculates the area of a square\"\"\"\n\t# get length--these while True loops/exceptions disallow all but int/float input\n\twhile True:\n\t\ttry:\n\t\t\tlength = float(input(\"Enter the side length: \"))\n\t\t\tbreak\n\t\texcept ValueError:\n\t\t\tprint(\"Please enter a valid number.\")\n\t\t\tcontinue\n\treturn length ** 2\n\ndef rectangle():\n\t\"\"\"calculates the area of a rectangle\"\"\"\n\t# get length\n\twhile True:\n\t\ttry:\n\t\t\tlength = float(input(\"Enter the length: \"))\n\t\t\tbreak\n\t\texcept ValueError:\n\t\t\tprint(\"Please enter a valid number.\")\n\t\t\tcontinue\n\t# get width\n\twhile True:\n\t\ttry:\n\t\t\twidth = float(input(\"Enter the width: \"))\n\t\t\tbreak\n\t\texcept ValueError:\n\t\t\tprint(\"Please enter a valid number.\")\n\t\t\tcontinue\n\treturn length * width\n\ndef parallelogram():\n\t\"\"\"calcluates the area of a parallelogram\"\"\"\n\twhile True:\n\t\t# get base\n\t\ttry:\n\t\t\tbase = float(input(\"Enter the length of the base: \"))\n\t\t\tbreak\n\t\texcept ValueError:\n\t\t\tprint(\"Please enter a valid number.\")\n\t\t\tcontinue\n\twhile True:\n\t\t# get height\n\t\ttry:\n\t\t\theight = float(input(\"Enter the height: \"))\n\t\t\tbreak\n\t\texcept ValueError:\n\t\t\tprint(\"Please enter a valid number.\")\n\t\t\tcontinue\n\treturn base * height\n\ndef trapezoid():\n\t\"\"\"calculates the area of a trapezoid\"\"\"\n\t# get base1\n\twhile True:\n\t\ttry:\n\t\t\tbase1 = float(input(\"Enter the length of the first base: \"))\n\t\t\tbreak\n\t\texcept ValueError:\n\t\t\tprint(\"Please enter a valid number.\")\n\t\t\tcontinue\n\t# get base2\n\twhile True:\n\t\ttry:\n\t\t\tbase2 = float(input(\"Enter the length of the second base: \"))\n\t\t\tbreak\n\t\texcept ValueError:\n\t\t\tprint(\"Please enter a valid number.\")\n\t\t\tcontinue\n\t# get height\n\twhile True:\n\t\ttry:\n\t\t\theight = float(input(\"Enter the height: \"))\n\t\t\tbreak\n\t\texcept ValueError:\n\t\t\tprint(\"Please enter a valid number.\")\n\t\t\tcontinue\n\treturn height / 2 * (base1 + base2)\n\ndef cube():\n\t\"\"\"calculates the area of a cube\"\"\"\n\t# get and cube length\n\twhile True:\n\t\ttry:\n\t\t\tlength = float(input(\"Enter the side length: \"))\n\t\t\tbreak\n\t\texcept ValueError:\n\t\t\tprint(\"Please enter a valid number.\")\n\t\t\tcontinue\n\treturn length ** 3\n\ndef circle():\n\t\"\"\"calculates the area of a circle\"\"\"\n\t# eventually improve accuracy with a better representation of pi\n\twhile True:\n\t\ttry:\n\t\t\tradius = float(input(\"Enter the radius: \"))\n\t\t\tbreak\n\t\texcept ValueError:\n\t\t\tprint(\"Please enter a valid number.\")\n\t\t\tcontinue\n\treturn 3.14 * radius ** 2\n\ndef circumference(radius):\n\t\"\"\"calculates the circumference of a circle\"\"\"\n\treturn radius * 2 * 3.14\n\n","sub_path":"geometry.py","file_name":"geometry.py","file_ext":"py","file_size_in_byte":5787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"492037917","text":"__author__ = 'sw'\nfrom flask import Blueprint,request\nfrom flask.ext.mongoengine import mongoengine\nfrom iotServer.models import Device,TokenRef,Sensor,DeviceData\nfrom iotServer.api1.helper import succ,erro,succ_doc\n\napi_sensor=Blueprint('api_sensor',__name__)\n\n@api_sensor.route('/sensor/',methods=['GET'])\ndef datapoint_crtate(sensor_symbol=None):\n if not sensor_symbol:\n return erro('no sensor_symbol provided. ')\n\n (_type,instance)=TokenRef.get_ref(request.headers.get('token'))\n\n if _type is not 'device':\n return erro('only support device token . ')\n\n sensors = instance.sensors\n args = request.args\n ticks={}\n\n for arg in args:\n if arg in sensors:\n ticks[arg]=args.get(arg)\n\n if len(ticks) > 0:\n try:\n DeviceData(device = instance,ticks=ticks).save()\n return succ('succ.')\n except Exception as err:\n return erro(err)\n else:\n return erro('nothing saved.')\n\n@api_sensor.route('/sensor/',methods=['POST'])\ndef sensor_crtate(sensor_symbol=None):\n if not sensor_symbol:\n return erro('no sensor_symbol provided. ')\n\n arg=request.args\n sensor_name=arg.get('name')\n sensor_type=arg.get('type')\n if not (sensor_type and sensor_type):\n return erro('no sensor_type sensor_name provided. ')\n\n sensor_type = sensor_type.upper()\n\n (_type,instance)=TokenRef.get_ref(request.headers.get('token'))\n if _type is not 'device':\n return erro('only support device token . ')\n\n sensors = instance.sensors or {}\n sensor = Sensor(name=sensor_name,type=sensor_type)\n sensors[sensor_symbol]=sensor\n\n try:\n instance.update(sensors=sensors)\n return succ_doc(sensor)\n except Exception as err:\n return erro(err)\n\n","sub_path":"iotServer/api1/sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"483838146","text":"import tcod as tc\nfrom logic.logger import OperationLog\nfrom logic.move import MoveType\nfrom logic.patterns.command import Command\nfrom logic.states import State\n\n\nclass KeysHandler:\n @staticmethod\n def inventory_keys(engine, key):\n if key in [tc.event.K_ESCAPE, tc.event.K_i, tc.event.K_d]:\n if engine.prev_state.value:\n engine.curr_state.value = engine.prev_state.value\n else:\n engine.curr_state.value = State.PLAYER_TURN\n return OperationLog()\n\n if key == tc.event.K_1:\n return OperationLog([{'inv_index': 0}])\n if key == tc.event.K_2:\n return OperationLog([{'inv_index': 1}])\n if key == tc.event.K_3:\n return OperationLog([{'inv_index': 2}])\n\n return OperationLog()\n\n @staticmethod\n def user_input(engine):\n for event in tc.event.get():\n # debug\n if engine.info.DEBUG:\n if event.type != \"MOUSEMOTION\":\n print(event)\n # quit\n if event.type == \"QUIT\":\n engine.IS_GAME = False\n # нажатие клавивиши\n if event.type == \"KEYDOWN\":\n # передача управления в инвентарь\n if engine.curr_state.value != State.PLAYER_DEAD and \\\n engine.curr_state.value in [State.SHOWING_MENU, State.DROP_ITEM]:\n return Command(KeysHandler.inventory_keys, engine, event.sym)\n\n if event.sym == tc.event.K_ESCAPE:\n # выход из инвентаря\n if engine.curr_state.value == (State.SHOWING_MENU, State.DROP_ITEM):\n engine.curr_state.value = engine.prev_state.value\n else:\n # выход из игры\n engine.IS_GAME = False\n if engine.curr_state.value != State.PLAYER_DEAD:\n if event.sym == tc.event.K_UP:\n return KeysHandler.create_command(engine, MoveType.UP)\n if event.sym == tc.event.K_DOWN:\n return KeysHandler.create_command(engine, MoveType.DOWN)\n if event.sym == tc.event.K_LEFT:\n return KeysHandler.create_command(engine, MoveType.LEFT)\n if event.sym == tc.event.K_RIGHT:\n return KeysHandler.create_command(engine, MoveType.RIGHT)\n if event.sym == tc.event.K_g:\n return Command(engine.player.get_item, engine.get_entities())\n if event.sym == tc.event.K_i:\n # выход из меню инвентаря\n if engine.curr_state.value == State.SHOWING_MENU:\n engine.curr_state.value = engine.prev_state.value\n return Command(lambda arg: arg, OperationLog())\n # вход в меню инвентаря\n return Command(lambda arg: arg, OperationLog([{'show_menu': True}]))\n if event.sym == tc.event.K_d:\n # выход из drop меню инвентаря\n if engine.curr_state.value == State.DROP_ITEM:\n engine.curr_state.value = engine.prev_state.value\n return Command(lambda arg: arg, OperationLog())\n # вход в drop меню инвентаря\n return Command(lambda arg: arg, OperationLog([{'drop_menu': True}]))\n\n return Command(lambda arg: arg, OperationLog())\n\n @staticmethod\n def create_command(engine, move_type):\n return Command(engine.player.mv_handler.move, move_type,\n engine.map, engine.get_entities(), engine.curr_state)\n","sub_path":"test_data/projects/roguelike/project/engine/keys_handler.py","file_name":"keys_handler.py","file_ext":"py","file_size_in_byte":3942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"634810813","text":"from ..common.config import MARKET_NUMBER_DICT\nfrom jsonpath import jsonpath\nfrom retry import retry\nfrom typing import Dict, List, Union\nfrom tqdm import tqdm\nimport multitasking\nimport pandas as pd\nfrom ..utils import to_numeric\nfrom ..shared import session\nfrom .config import (EASTMONEY_QUOTE_FIELDS,\n EASTMONEY_REQUEST_HEADERS,\n EASTMONEY_KLINE_FIELDS,\n EASTMONEY_HISTORY_BILL_FIELDS)\nfrom ..utils import get_quote_id\n\n\n@to_numeric\ndef get_realtime_quotes_by_fs(fs: str) -> pd.DataFrame:\n \"\"\"\n 获取沪深市场最新行情总体情况\n\n Returns\n -------\n DataFrame\n 沪深市场最新行情信息(涨跌幅、换手率等信息)\n\n \"\"\"\n\n fields = \",\".join(EASTMONEY_QUOTE_FIELDS.keys())\n params = (\n ('pn', '1'),\n ('pz', '1000000'),\n ('po', '1'),\n ('np', '1'),\n ('fltt', '2'),\n ('invt', '2'),\n ('fid', 'f3'),\n ('fs', fs),\n ('fields', fields)\n )\n url = 'http://push2.eastmoney.com/api/qt/clist/get'\n json_response = session.get(url,\n headers=EASTMONEY_REQUEST_HEADERS,\n params=params).json()\n df = pd.DataFrame(json_response['data']['diff'])\n df = df.rename(columns=EASTMONEY_QUOTE_FIELDS)\n df = df[EASTMONEY_QUOTE_FIELDS.values()]\n df['行情ID'] = df['市场编号'].astype(str)+'.'+df['代码'].astype('str')\n df['市场类型'] = df['市场编号'].astype(str).apply(\n lambda x: MARKET_NUMBER_DICT.get(x))\n\n return df\n\n\n@to_numeric\ndef get_quote_history_single(code: str,\n beg: str = '19000101',\n end: str = '20500101',\n klt: int = 101,\n fqt: int = 1,\n **kwargs) -> pd.DataFrame:\n \"\"\"\n 获取单只股票、债券 K 线数据\n\n \"\"\"\n\n fields = list(EASTMONEY_KLINE_FIELDS.keys())\n columns = list(EASTMONEY_KLINE_FIELDS.values())\n fields2 = \",\".join(fields)\n if kwargs.get('quote_id_mode'):\n quote_id = code\n else:\n quote_id = get_quote_id(code)\n params = (\n ('fields1', 'f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13'),\n ('fields2', fields2),\n ('beg', beg),\n ('end', end),\n ('rtntype', '6'),\n ('secid', quote_id),\n ('klt', f'{klt}'),\n ('fqt', f'{fqt}'),\n )\n\n url = 'https://push2his.eastmoney.com/api/qt/stock/kline/get'\n\n json_response = session.get(\n url, headers=EASTMONEY_REQUEST_HEADERS, params=params).json()\n klines: List[str] = jsonpath(json_response, '$..klines[:]')\n if not klines:\n columns.insert(0, '代码')\n columns.insert(0, '名称')\n return pd.DataFrame(columns=columns)\n\n rows = [kline.split(',') for kline in klines]\n name = json_response['data']['name']\n code = quote_id.split('.')[-1]\n df = pd.DataFrame(rows, columns=columns)\n df.insert(0, '代码', code)\n df.insert(0, '名称', name)\n\n return df\n\n\ndef get_quote_history_multi(codes: List[str],\n beg: str = '19000101',\n end: str = '20500101',\n klt: int = 101,\n fqt: int = 1,\n tries: int = 3,\n **kwargs\n ) -> Dict[str, pd.DataFrame]:\n \"\"\"\n 获取多只股票、债券历史行情信息\n\n \"\"\"\n\n dfs: Dict[str, pd.DataFrame] = {}\n total = len(codes)\n\n @multitasking.task\n @retry(tries=tries, delay=1)\n def start(code: str):\n _df = get_quote_history_single(\n code,\n beg=beg,\n end=end,\n klt=klt,\n fqt=fqt,\n **kwargs)\n dfs[code] = _df\n pbar.update(1)\n pbar.set_description_str(f'Processing => {code}')\n\n pbar = tqdm(total=total)\n for code in codes:\n start(code)\n multitasking.wait_for_tasks()\n pbar.close()\n return dfs\n\n\ndef get_quote_history(codes: Union[str, List[str]],\n beg: str = '19000101',\n end: str = '20500101',\n klt: int = 101,\n fqt: int = 1,\n **kwargs) -> Union[pd.DataFrame, Dict[str, pd.DataFrame]]:\n \"\"\"\n 获取股票、ETF、债券的 K 线数据\n\n Parameters\n ----------\n codes : Union[str,List[str]]\n 股票、债券代码 或者 代码构成的列表\n beg : str, optional\n 开始日期,默认为 ``'19000101'`` ,表示 1900年1月1日\n end : str, optional\n 结束日期,默认为 ``'20500101'`` ,表示 2050年1月1日\n klt : int, optional\n 行情之间的时间间隔,默认为 ``101`` ,可选示例如下\n\n - ``1`` : 分钟\n - ``5`` : 5 分钟\n - ``15`` : 15 分钟\n - ``30`` : 30 分钟\n - ``60`` : 60 分钟\n - ``101`` : 日\n - ``102`` : 周\n - ``103`` : 月\n\n fqt : int, optional\n 复权方式,默认为 ``1`` ,可选示例如下\n\n - ``0`` : 不复权\n - ``1`` : 前复权\n - ``2`` : 后复权\n\n Returns\n -------\n Union[DataFrame, Dict[str, DataFrame]]\n 股票、债券的 K 线数据\n\n - ``DataFrame`` : 当 ``codes`` 是 ``str`` 时\n - ``Dict[str, DataFrame]`` : 当 ``codes`` 是 ``List[str]`` 时\n\n \"\"\"\n\n if isinstance(codes, str):\n return get_quote_history_single(codes,\n beg=beg,\n end=end,\n klt=klt,\n fqt=fqt,\n **kwargs)\n\n elif hasattr(codes, '__iter__'):\n codes = list(codes)\n return get_quote_history_multi(codes,\n beg=beg,\n end=end,\n klt=klt,\n fqt=fqt,\n **kwargs)\n raise TypeError(\n '代码数据类型输入不正确!'\n )\n\n\n@to_numeric\ndef get_history_bill(code: str) -> pd.DataFrame:\n \"\"\"\n 获取单支股票、债券的历史单子流入流出数据\n\n Parameters\n ----------\n code : str\n 股票、债券代码\n\n Returns\n -------\n DataFrame\n 沪深市场单只股票、债券历史单子流入流出数据\n\n \"\"\"\n\n fields = list(EASTMONEY_HISTORY_BILL_FIELDS.keys())\n columns = list(EASTMONEY_HISTORY_BILL_FIELDS.values())\n fields2 = \",\".join(fields)\n quote_id = get_quote_id(code)\n params = (\n ('lmt', '100000'),\n ('klt', '101'),\n ('secid', quote_id),\n ('fields1', 'f1,f2,f3,f7'),\n ('fields2', fields2),\n\n )\n url = 'http://push2his.eastmoney.com/api/qt/stock/fflow/daykline/get'\n json_response = session.get(url,\n headers=EASTMONEY_REQUEST_HEADERS,\n params=params).json()\n\n klines: List[str] = jsonpath(json_response, '$..klines[:]')\n if not klines:\n columns.insert(0, '代码')\n columns.insert(0, '名称')\n return pd.DataFrame(columns=columns)\n rows = [kline.split(',') for kline in klines]\n name = jsonpath(json_response, '$..name')[0]\n code = quote_id.split('.')[-1]\n df = pd.DataFrame(rows, columns=columns)\n df.insert(0, '代码', code)\n df.insert(0, '名称', name)\n\n return df\n\n\n@to_numeric\ndef get_today_bill(code: str) -> pd.DataFrame:\n \"\"\"\n 获取单只股票最新交易日的日内分钟级单子流入流出数据\n\n Parameters\n ----------\n code : str\n 股票、债券代码\n\n Returns\n -------\n DataFrame\n 单只股票、债券最新交易日的日内分钟级单子流入流出数据\n\n\n \"\"\"\n quote_id = get_quote_id(code)\n params = (\n ('lmt', '0'),\n ('klt', '1'),\n ('secid', quote_id),\n ('fields1', 'f1,f2,f3,f7'),\n ('fields2', 'f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61,f62,f63'),\n )\n url = 'http://push2.eastmoney.com/api/qt/stock/fflow/kline/get'\n json_response = session.get(url,\n headers=EASTMONEY_REQUEST_HEADERS,\n params=params).json()\n columns = ['时间', '主力净流入', '小单净流入', '中单净流入', '大单净流入', '超大单净流入']\n name = jsonpath(json_response, '$..name')[0]\n code = quote_id.split('.')[-1]\n klines: List[str] = jsonpath(json_response, '$..klines[:]')\n if not klines:\n columns.insert(0, '代码')\n columns.insert(0, '名称')\n return pd.DataFrame(columns=columns)\n rows = [kline.split(',') for kline in klines]\n df = pd.DataFrame(rows, columns=columns)\n df.insert(0, '代码', code)\n df.insert(0, '名称', name)\n return df\n","sub_path":"efinance/common/getter.py","file_name":"getter.py","file_ext":"py","file_size_in_byte":9014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"244334454","text":"#!/usr/bin/env python\n# \n\nimport os, sys, numpy\n\nimport astropy\nimport astropy.io.ascii as asciitable\n\nimport scipy\nfrom scipy import interpolate\n\nfrom copy import copy\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import ScalarFormatter, FuncFormatter, LogLocator, FormatStrFormatter\n\n\n# define my_axis_formatter\ndef format_axis_tick_values(x_array):\n str_array = []\n for x in x_array:\n if x >= 100 or x <= -100:\n str_item = '%1.0f'%(x)\n else:\n str_item = '%1.1f'%(x)\n str_array.append(str_item)\n return str_array\n\n\n# set up color\ncmap = matplotlib.cm.get_cmap('plasma_r') # 'jet' #. 'gist_heat_r' (same as Eric J.-A. paper)\nnormalize = matplotlib.colors.Normalize(vmin=0.0, vmax=1.0)\n\n\n# Read data\n#differential_curve_1_2 = asciitable.read('Completeness_sim_Sbeam_1.0_2.0/datatable_MC_sim_completeness_differential.txt', names=['snr','incomp','aa','bb'], fill_values=[('-99',numpy.nan)])\n#differential_curve_2_3 = asciitable.read('Completeness_sim_Sbeam_2.0_3.0/datatable_MC_sim_completeness_differential.txt', names=['snr','incomp','aa','bb'], fill_values=[('-99',numpy.nan)])\n#differential_curve_3_4 = asciitable.read('Completeness_sim_Sbeam_3.0_4.0/datatable_MC_sim_completeness_differential.txt', names=['snr','incomp','aa','bb'], fill_values=[('-99',numpy.nan)])\n#differential_curve_4_5 = asciitable.read('Completeness_sim_Sbeam_4.0_5.0/datatable_MC_sim_completeness_differential.txt', names=['snr','incomp','aa','bb'], fill_values=[('-99',numpy.nan)])\ndifferential_curve_1p0_1p5 = asciitable.read('Completeness_sim_Sbeam_1.0_1.5/datatable_MC_sim_completeness_differential.S_total_sim_to_rms_noise.txt', names=['snr','incomp','aa','bb'], fill_values=[('-99',numpy.nan)])\ndifferential_curve_1p5_2p0 = asciitable.read('Completeness_sim_Sbeam_1.5_2.0/datatable_MC_sim_completeness_differential.S_total_sim_to_rms_noise.txt', names=['snr','incomp','aa','bb'], fill_values=[('-99',numpy.nan)])\ndifferential_curve_2p0_2p5 = asciitable.read('Completeness_sim_Sbeam_2.0_2.5/datatable_MC_sim_completeness_differential.S_total_sim_to_rms_noise.txt', names=['snr','incomp','aa','bb'], fill_values=[('-99',numpy.nan)])\ndifferential_curve_2p5_3p0 = asciitable.read('Completeness_sim_Sbeam_2.5_3.0/datatable_MC_sim_completeness_differential.S_total_sim_to_rms_noise.txt', names=['snr','incomp','aa','bb'], fill_values=[('-99',numpy.nan)])\ndifferential_curve_3p0_3p5 = asciitable.read('Completeness_sim_Sbeam_3.0_3.5/datatable_MC_sim_completeness_differential.S_total_sim_to_rms_noise.txt', names=['snr','incomp','aa','bb'], fill_values=[('-99',numpy.nan)])\ndifferential_curve_3p5_4p0 = asciitable.read('Completeness_sim_Sbeam_3.5_4.0/datatable_MC_sim_completeness_differential.S_total_sim_to_rms_noise.txt', names=['snr','incomp','aa','bb'], fill_values=[('-99',numpy.nan)])\ndifferential_curve_4p0_4p5 = asciitable.read('Completeness_sim_Sbeam_4.0_4.5/datatable_MC_sim_completeness_differential.S_total_sim_to_rms_noise.txt', names=['snr','incomp','aa','bb'], fill_values=[('-99',numpy.nan)])\ndifferential_curve_4p5_5p0 = asciitable.read('Completeness_sim_Sbeam_4.5_5.0/datatable_MC_sim_completeness_differential.S_total_sim_to_rms_noise.txt', names=['snr','incomp','aa','bb'], fill_values=[('-99',numpy.nan)])\n#print(differential_curve_1_2)\n\n#differential_cube = numpy.column_stack((\n# 1.0-differential_curve_1_2['incomp'].data,\n# 1.0-differential_curve_2_3['incomp'].data,\n# 1.0-differential_curve_3_4['incomp'].data,\n# 1.0-differential_curve_4_5['incomp'].data))\ndifferential_cube = numpy.column_stack((\n (differential_curve_1p0_1p5['incomp']).data,\n (differential_curve_1p5_2p0['incomp']).data,\n (differential_curve_2p0_2p5['incomp']).data,\n (differential_curve_2p5_3p0['incomp']).data,\n (differential_curve_3p0_3p5['incomp']).data,\n (differential_curve_3p5_4p0['incomp']).data,\n (differential_curve_4p0_4p5['incomp']).data,\n (differential_curve_4p5_5p0['incomp']).data))\nprint((1.0-differential_curve_1p0_1p5['incomp']).data)\nprint(differential_cube.T)\nprint(differential_cube.shape)\nprint(len(differential_curve_1p0_1p5['snr'].data))\nx_array = numpy.power(10, numpy.linspace(numpy.log10(1.0),numpy.log10(1000.0),16)) # differential_curve_1p0_1p5['snr'].data\ny_array = numpy.linspace(1.0,5.0,9)\nprint(x_array)\nprint(y_array)\n\n\n# transpose so that each column is a different SNRpeak and each row is a different Theta_beam\ndifferential_cube = differential_cube.T\n\n\n\n# interpolate\nnx = differential_cube.shape[1]\nny = differential_cube.shape[0]\nxx, yy = numpy.meshgrid(numpy.arange(nx), numpy.arange(ny))\npts = numpy.array([[i,j] for i in range(nx) for j in range(ny)])\nvals = differential_cube.flatten()\nmask1 = ~numpy.isnan(vals) # valid values to interpolate with\npts1 = pts[mask1]\nvals1 = vals[mask1]\nprint('pts.shape', pts.shape)\nprint('vals.shape', vals.shape)\n#mask2 = numpy.logical_and(numpy.isnan(vals), numpy.logical_and(xx.flatten()>=7, yy.flatten()>=2)) # invalid values to interpolate for\n#pts2 = pts[mask2]\n#vals2 = vals[mask2]\nmask2 = numpy.logical_or(numpy.logical_or(numpy.logical_or(\\\n numpy.logical_and(xx.flatten()==9, yy.flatten()==2), \n numpy.logical_and(xx.flatten()==10, yy.flatten()==5)), \n numpy.logical_and(xx.flatten()==10, yy.flatten()==6)), \n numpy.logical_and(xx.flatten()==12, yy.flatten()==6)) # invalid values to interpolate for\npts2 = pts[mask2]\ndifferential_cube_original = copy(differential_cube)\ndifferential_cube_interpolated = differential_cube.flatten()\ndifferential_cube_interpolated[mask2] = interpolate.griddata(pts1, vals1, pts2, method='nearest')\ndifferential_cube = differential_cube_interpolated.reshape(differential_cube.shape)\nprint('differential_cube.shape', differential_cube.shape)\n# \n#nx = differential_cube.shape[1]\n#ny = differential_cube.shape[0]\n#x = numpy.arange(nx)\n#y = numpy.arange(ny)\n#xx, yy = numpy.meshgrid(x, y)\n#zz = differential_cube\n#print('xx.shape', xx.shape)\n#print('yy.shape', yy.shape)\n#print('zz.shape', zz.shape)\n#mask = (~numpy.isnan(zz))\n#xxx = xx[mask]\n#yyy = yy[mask]\n#zzz = zz[mask]\n#print('xxx.shape', xxx.shape)\n#print('yyy.shape', yyy.shape)\n#print('zzz.shape', zzz.shape)\n#fff = interpolate.interp2d(xxx, yyy, zzz, kind='linear')\n#differential_cube_interpolated = fff(x, y)\n#print('differential_cube_interpolated.shape', differential_cube_interpolated.shape)\n#differential_cube_original = differential_cube\n#differential_cube = differential_cube_interpolated.reshape(differential_cube.shape)\n#print('differential_cube.shape', differential_cube.shape)\n\n\n\n# make plot\nfig = plt.figure(figsize=(5.5,3.0))\nax = fig.add_subplot(1,1,1)\nax.imshow(differential_cube, cmap=cmap, norm=normalize, aspect=1.0, origin='lower') # , extent=[-0.5, len(x_array)-0.5, 1.0, 5.0]\nplt.xticks(numpy.arange(-0.5,len(x_array)-0.5,1), rotation=45)\nplt.yticks(numpy.arange(-0.5,len(y_array)-0.5,1))\nax.set_xticklabels(format_axis_tick_values(x_array))\nax.set_yticklabels(format_axis_tick_values(y_array))\nax.set_xlabel(r'$S_{\\mathrm{total,sim.}}\\,/\\,\\mathrm{rms\\,noise}$', fontsize=15)\nax.set_ylabel(r'$\\Theta_{\\mathrm{beam,sim.,convol.}}$', fontsize=15)\nax.yaxis.labelpad = 10\nax.tick_params(axis='x', direction='in')\nax.tick_params(axis='y', direction='in')\n\n\n\n# Show more label\nax.text(1.00, 1.04, r'FULL$\\,-\\,$PYBDSF', transform=ax.transAxes, va='center', ha='right', fontsize=13.5)\n\n\n# Now adding the colorbar\ncax = fig.add_axes([0.85, 0.27, 0.03, 0.65]) # l,b,w,h\ncbar = matplotlib.colorbar.ColorbarBase(cax, cmap=cmap, norm=normalize, ticks=[1.0, 0.8, 0.6, 0.4, 0.2, 0.0])\ncbar.ax.set_yticklabels(['0%','20%','40%','60%','80%','100%'])\ncbar.ax.set_ylim(1.0,0.0)\ncbar.ax.tick_params(axis='y', direction='in')\ncbar.ax.text(4.3, 0.48, 'Completeness', transform=cbar.ax.transAxes, rotation=90, va='center', ha='center', fontsize=14)\n\n\n# Save figure\nfig.subplots_adjust(bottom=0.20, left=0.15, right=0.84, top=0.97)\nfig.savefig('Plot_Completeness_blocks_for_various_source_sizes.S_total_sim_to_rms_noise.pdf')\n\nos.system('open Plot_Completeness_blocks_for_various_source_sizes.S_total_sim_to_rms_noise.pdf')\n\n\n\n\n","sub_path":"Pipeline/a3cosmos-MC-simulation-completeness-analysis-tools/backups/a_dzliu_code_plot_completeness_blocks_for_various_source_sizes_versus_S_total_sim_to_rms_noise_obsolete_20190506.py","file_name":"a_dzliu_code_plot_completeness_blocks_for_various_source_sizes_versus_S_total_sim_to_rms_noise_obsolete_20190506.py","file_ext":"py","file_size_in_byte":8129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"173449557","text":"import requests, sys\n\nif len(sys.argv) != 2:\n print(\"data not val, help: \\npython3 sms.py (Phone Number)\")\n sys.exit()\nelse:\n phone = sys.argv[1].strip()\n phone_shad = phone.replace(\"0\",\"98\")\n while True:\n try:\n hamyarzaban_data = {'phone':phone}\n hamyarzaban = requests.post(\"https://hamyarzaban.com/wp-content/themes/hamyarzaban/sms.php\")\n print(f\"ham status: {hamyarzaban}\")\n except:\n print(\"ham not\")\n try:\n snaptrip_data = {\"lang\":\"fa\",\"country_id\":\"860\",\"password\":\"fhj5tvT6D9jWkPw\",\"mobile_phone\":phone,\"country_code\":\"+98\"}\n snaptrip = requests.post(\"https://www.snapptrip.com/register\", json=snaptrip_data)\n print(f\"snap trip status: {snaptrip}\")\n except:\n print(\"snap trip not\")\n try:\n alibaba_data = {\"phoneNumber\":phone}\n alibaba = requests.post(\"https://ws.alibaba.ir/api/v3/account/mobile/otp\", json=alibaba_data)\n print(f\"alibaba status: {alibaba}\")\n except:\n print(\"alibaba not\")\n try:\n data_snap_food = {'cellphone':phone,'captcha':'111'}\n snap_food = requests.post(\"https://snappfood.ir/auth/login_with_no_pass\", data=data_snap_food)\n print(f\"snapfood status: {snap_food}\")\n except:\n print(\"snap food not\")\n try:\n data_snap = {\"type\":2,\"phone\":phone}\n snap = requests.post(\"https://api.snapp.ir/api/v1/sms/link\", data=data_snap)\n print(f\"snap status: {snap}\")\n except:\n print(\"snap not\")\n try:\n data_shad = {\"api_version\":\"3\",\"method\":\"sendCode\",\"data\":{\"phone_number\":phone_shad,\"send_type\":\"SMS\"}}\n shad = requests.post(\"https://shadmessenger103.iranlms.ir/\", json=data_shad)\n print(f\"shad status: {shad}\")\n except:\n print(\"shad not\")\n try:\n data_tp30 = {\"credential\":{\"phoneNumber\":phone,\"role\":\"PASSENGER\"}}\n tp30 = requests.post(\"https://tap33.me/api/v2/user\", json=data_tp30)\n print(f\"tp30 status: {tp30}\")\n except:\n print(\"tp30 not\")\n try:\n devar_data = {\"phone\":phone}\n devar = requests.post(\"https://api.divar.ir/v5/auth/authenticate\", json=devar_data)\n print(f\"devar status: {devar}\")\n except:\n print(\"devar not\")\n try:\n data_snapfood2 = {'cellphone':phone}\n snapfood2 = requests.post(\"https://snappfood.ir/customer/app-dl/send\", data=data_snapfood2)\n print(f\"snap food 2 status: {snapfood2}\")\n except:\n print(\"snap food 2 not\")","sub_path":"sms.py","file_name":"sms.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"385000239","text":"from Login import Ui_Form\nfrom Common_Function import *\n\n\nclass Login_class(Ui_Form,Farther,Windows_Move,QMainWindow):\n\n def __init__(self):\n super().__init__()\n self.setupUi(self)\n self.center()\n # 透明处理,移动需要拖动数字\n self.setWindowFlags(QtCore.Qt.FramelessWindowHint | QtCore.Qt.SubWindow | QtCore.Qt.WindowStaysOnTopHint)\n self.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)\n\n self.lineEdit.setFocus()\n\n self.set_gif(':/images/dou5.gif',self.lab_background)\n #self.set_gif(':/images/yunye.gif', self.lab_background)\n\n # my_list = ['1','2','3']\n # my_str,ok = QInputDialog.getItem(self,\"下拉框\",'提示',my_list)\n # print(my_str,ok)\n\n #界面的退出按钮\n def Exit(self):\n os._exit(0)\n # exit(1)\n # return\n\n\n #一个确认的按钮的函数\n def Login_Reslute(self):\n\n text, ok = QInputDialog.getText(self, \"title\", \"User name:\", QLineEdit.Normal, '>>>:')\n\n # if self.lineEdit.text()=='123':\n # return '管理员账号'\n # else:\n # image_file, _ = QFileDialog.getOpenFileName(self, 'Open file', 'C:\\\\',\n # 'Image files (*.jpg *.gif *.png *.jpeg)')\n\n\nif __name__==\"__main__\":\n app = QtWidgets.QApplication(argv)\n MainWindow = QtWidgets.QMainWindow()\n\n Login_son = Login_class()\n Login_son.show()\n\n exit(app.exec_())","sub_path":"Login_monther.py","file_name":"Login_monther.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"337445105","text":"import numpy as np\nimport tensorflow as tf\nfrom progressbar import ProgressBar\nimport train_dataset\nimport config\nfrom embedding_graph_dataset import dataset\n\n# load data\npath = r'D:\\data\\new_data'\np = ProgressBar(max_value=9713)\ndata = dataset(path)\n\n# start session\n\nwith tf.Graph().as_default():\n config_ = tf.ConfigProto()\n config_.gpu_options.allow_growth = True\n sess = tf.Session(config=config_)\n with sess.as_default():\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n model = train_dataset.model_tf(data.num_vocab, data.num_nodes)\n global_step = tf.Variable(0, trainable=False)\n # c = tf.train.exponential_decay(config.lr, global_step, 30, 0.9, staircase=False)\n opt = tf.train.AdamOptimizer(learning_rate=0.01)\n train_op = opt.minimize(model.loss, global_step)\n sess.run(tf.global_variables_initializer())\n # summary_writer = tf.summary.FileWriter(\"./logs\", )\n\n # training\n print('start training.......')\n\n for epoch in range(config.num_epoch):\n loss_epoch = 0\n p.init()\n for _c in p(range(9713)):\n node_a, node_b, contents, time, polarity = next(data.generate_batches())\n\n feed_dict = {\n model.Text_a: contents,\n model.Node_a: node_a,\n model.Node_b: node_b,\n model.Time_a: time,\n model.Polarity_a: polarity\n }\n\n # run the graph\n # merge = tf.summary.merge_all()\n _, loss_batch = sess.run([train_op, model.loss], feed_dict=feed_dict)\n\n loss_epoch += loss_batch\n\n # def variable_summaries(var, name):\n # with tf.name_scope('summaries'):\n # mean = tf.reduce_mean(var)\n # tf.summary.scalar('mean/' + name, mean)\n # variable_summaries(loss_epoch, \"loss\")\n print('epoch: ', epoch + 1, ' loss: ', loss_epoch)\n\n # file = open('embed.txt', 'wb')\n # batches = data.generate_batches(mode='add')\n # num_batch = len(batches)\n # embed = [[] for _ in range(data.num_nodes)]\n # for i in range(num_batch):\n # batch = batches[i]\n #\n # node1, node2, node3 = zip(*batch)\n # node1, node2, node3 = np.array(node1), np.array(node2), np.array(node3)\n # text1, text2, text3 = data.text[node1], data.text[node2], data.text[node3]\n #\n # feed_dict = {\n # model.Text_a: text1,\n # model.Text_b: text2,\n # # model.Text_neg: text3,\n # model.Node_a: node1,\n # model.Node_b: node2,\n # # model.Node_neg: node3\n # }\n\n # run the graph\n # convA, convB, TA, TB = sess.run([model.gruA, model.gruB, model.N_A, model.N_B], feed_dict=feed_dict)\n # for i in range(config.batch_size):\n # em = list(convA[i]) + list(TA[i])\n # embed[node1[i]].append(em)\n # em = list(convB[i]) + list(TB[i])\n # embed[node2[i]].append(em)\n # for i in range(data.num_nodes):\n # if embed[i]:\n # # print embed[i]\n # tmp = np.sum(embed[i], axis=0) / len(embed[i])\n # str_ = ' '.join(map(str, tmp)) + '\\n'\n # file.write(bytes(str_, encoding='utf-8'))\n # else:\n # file.write(bytes(\"\\n\", encoding='utf-8'))\n","sub_path":"new_train.py","file_name":"new_train.py","file_ext":"py","file_size_in_byte":3759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"147991997","text":"#! /usr/bin/env python\n\n# $Id$\n# Author: David Goodger \n# Copyright: This module has been placed in the public domain.\n\n\"\"\"\nTests for docutils/readers/python/moduleparser.py.\n\"\"\"\n\nfrom __init__ import DocutilsTestSupport\n\n\ndef suite():\n s = DocutilsTestSupport.PythonModuleParserTestSuite()\n s.generateTests(totest, testmethod='test_token_parser_rhs')\n return s\n\ntotest = {}\n\ntotest['expressions'] = [\n['''a = 1''', '''1'''],\n['''a = b = 1''', '''1'''],\n['''\\\na = (\n 1 + 2\n + 3\n )\n''',\n'''(1 + 2 + 3)'''],\n['''\\\na = \"\"\"\\\\\nline one\nline two\"\"\"\n''',\n'''\"\"\"\\\\\\nline one\\nline two\"\"\"'''],\n['''a = `1`''', '''`1`'''],\n['''a = `1`+`2`''', '''`1` + `2`'''],\n]\n\n\nif __name__ == '__main__':\n import unittest\n unittest.main(defaultTest='suite')\n","sub_path":"sandbox/davidg/test/test_readers/test_python/test_token_parser.py","file_name":"test_token_parser.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"5135117","text":"import database\nimport random\nimport csv\nfrom pathlib import Path\n\nfrom helpers.hashing import EmbedImage\nfrom discord.ext import commands\nfrom discord.ext.commands import Bot, Cog\nfrom discord.ext.tasks import loop\n\nmons = []\n\n\n# pylint: disable=no-self-use\nclass Fieldwork(Cog):\n def __init__(self, bot: Bot):\n self.time = ''\n self.bot = bot\n if bot is not None:\n self.db = bot.get_cog('database')\n if not self.db:\n self.db = database.Database(None)\n self.observe_random_mon.start()\n\n @loop(seconds=90)\n async def observe_random_mon(self) -> None:\n if not mons:\n load()\n self.time = 'night' if self.time == 'day' else 'day'\n dex, name = mons.pop()\n url = f\"https://server.poketwo.net/image?species={dex}&time={self.time}\"\n img = EmbedImage(url)\n phash = img.phash\n print(f'{phash}={name}')\n pkmn = self.db.get_pokemon_image_by_phash(phash)\n if not pkmn.pokemon:\n pkmn.pokemon = self.db.get_pokemon_by_name(name)\n pkmn.save()\n print(f'Learned that {phash} is {name} from fieldwork')\n\ndef isnumber(v):\n try:\n int(v)\n except ValueError:\n return False\n return True\n\ndef load() -> None:\n path = Path.cwd() / \"data\" / \"pokemon.csv\"\n\n with open(path, encoding='utf-8') as f:\n reader = csv.DictReader(f)\n data = list(\n {k: int(v) if isnumber(v) else v for k, v in row.items() if v != \"\"}\n for row in reader\n )\n mons.extend([(p['id'], p.get('name.en', p.get('slug'))) for p in data])\n random.shuffle(mons)\n\ndef setup(bot: commands.Bot) -> None:\n bot.add_cog(Fieldwork(bot))\n","sub_path":"fieldwork/seeker.py","file_name":"seeker.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"401808547","text":"'''\nGiven an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.\nExample 1:\nInput: [1,4,3,2]\n\nOutput: 4\nExplanation: n is 2, and the maximum sum of pairs is 4.\nNote:\n1.n is a positive integer, which is in the range of [1, 10000].\n2.All the integers in the array will be in the range of [-10000, 10000].\n'''\n# May 27, 2017\nclass Solution(object):\n def arrayPairSum(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n def partition(a, left, right, pivotIndex):\n temp = a[right];\n a[right] = a[pivotIndex];\n a[pivotIndex] = temp;\n storeIndex = left;\n for i in range(left, right):\n if a[i] <= a[right]:\n temp = a[i];\n a[i] = a[storeIndex];\n a[storeIndex] = temp;\n storeIndex += 1;\n temp = a[storeIndex];\n a[storeIndex] = a[right];\n a[right] = temp;\n return storeIndex;\n \n def quickSort(a, left, right):\n if right > left:\n pivotNewIndex = partition(a, left, right, (right+left)/2);\n quickSort(a, left, pivotNewIndex-1);\n quickSort(a, pivotNewIndex+1, right);\n return; \n \n quickSort(nums, 0, len(nums)-1);\n \n sum = 0;\n for i in range(0, len(nums)-1, 2):\n sum += nums[i];\n \n return sum;\n\n# Self-review, May 28, 2017\n# Why do I implement quick sort myself rather than use sort function?\n# sorted is a built-in function, return a new container\n# sort is a property of container, sort within the container\n'''\nclass Solution(object):\n def arrayPairSum(self, nums):\n \"\"\"\n\t:type nums: List[int]\n\t:rtype: int\n\t\"\"\"\n\treturn sum(sorted(nums)[::2]);\n'''\n","sub_path":"array_partition_I.py","file_name":"array_partition_I.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"11756476","text":"\nimport sys\nimport argparse\n\nimport math\nimport numpy as np\nfrom scipy import interpolate\n\nfrom util import date, arcinfo\nfrom util.arg_parsing import add_argument\n\n\n# Some physical constants\nyear_in_sec = 365.25 * 24 * 60 * 60\nrho = 917 * 1.0e-6 / year_in_sec**2\ng = 9.81 * year_in_sec**2\nA0 = 3.985e-13 * year_in_sec * 1.0e18\nQ = 6.0e4\nT = 273 - 13\nR = 8.3144\nA = A0 * math.exp(-Q / (R * T))\n\n\n# ------------------------\ndef surface_slope(x, y, s):\n \"\"\"\n \"\"\"\n\n ny, nx = np.shape(s)\n dx = x[1] - x[0]\n dy = x[1] - y[0]\n\n dsdx = np.zeros((ny, nx), dtype = np.float64)\n dsdy = np.zeros((ny, nx), dtype = np.float64)\n\n for i in range(1, ny - 1):\n for j in range(1, nx - 1):\n dsdx[i, j] = 0.5 * (s[i, j+1] - s[i, j-1]) / dx\n dsdy[i, j] = 0.5 * (s[i+1, j] - s[i-1, j]) / dx\n\n ds = np.sqrt(dsdx**2 + dsdy**2)\n\n avg = np.average(ds)\n stddev = np.std(ds)\n\n # Cutoff for the surface slope\n mva = avg + 0.25 * stddev\n\n for i in range(ny):\n for j in range(nx):\n ds[i, j] = min(ds[i, j], mva)\n\n return ds\n\n\n# --------------------------------------------\ndef guess_basal_fields(x, y, s, b, u, v, frac):\n \"\"\"\n Inputs:\n x : list of horizontal coordinates of the grid\n y : list of vertical coordinates of the grid\n s : array of ice surface elevations\n b : array of ice bed elevations\n u : array of ice velocities in the x-direction\n v : array of ice velocities in the y-direction\n frac : optional parameter; the fraction of the driving stress that the\n basal shear stress is assumed to support\n\n Outputs:\n beta : basal sliding coefficient, under the shallow ice approximation\n ub : basal sliding velocity in the x-direction\n vb : basal sliding velocity in the y-direction\n \"\"\"\n\n ny, nx = np.shape(u)\n ds = surface_slope(x, y, s)\n\n #---------------------------------------------------------\n # Compute the bed sliding velocities & friction parameter\n ub = np.zeros((ny, nx), dtype = np.float64)\n vb = np.zeros((ny, nx), dtype = np.float64)\n beta = np.zeros((ny, nx), dtype = np.float64)\n\n q = 0.0\n speed = 0.0\n\n for i in range(1, ny - 1):\n for j in range(1, nx - 1):\n if u[i, j] != -2.0e+9:\n alpha = frac\n h = max(s[i, j] - b[i, j], 0.0)\n q = A * (rho * g * h)**3 * ds[i, j]**3 / 2\n speed = np.sqrt(u[i, j]**2 + v[i, j]**2)\n\n basal_speed = speed - alpha**3*h*q\n if basal_speed <= 0.0:\n basal_speed = min(10.0, 0.1 * speed)\n alpha = ((speed - basal_speed) / (h*q))**(1.0/3)\n\n # The basal sliding velocities are assumed to have the same\n # direction as the surface velocities, only with lower speed\n # according to a rough SIA-like approximation.\n ub[i, j] = basal_speed/speed * u[i, j]\n vb[i, j] = basal_speed/speed * v[i, j]\n\n # Since we've already guessed the sliding speed and the\n # x-z strain rate from the SIA, the boundary condition\n # tau_xz = -beta**2 * u (resp. tau_yz, v)\n # gives us the value of beta consistent with the guesses\n # we've already made.\n beta[i, j] = np.nanmin([(2*alpha**3*q / (A*basal_speed**3))**(1.0/6), 0.0])\n else:\n ub[i, j] = -2.0e+9\n vb[i, j] = -2.0e+9\n beta[i, j] = -2.0e+9\n\n\n def fill_to_boundary(phi):\n phi[0, :] = phi[1, :]\n phi[-1, :] = phi[-2, :]\n phi[:, 0] = phi[:, 1]\n phi[:, -1] = phi[:, -2]\n\n fill_to_boundary(beta)\n fill_to_boundary(ub)\n fill_to_boundary(vb)\n\n return beta, ub, vb\n\n\n# -----------------------\ndef main(day, year, frac):\n directory = \"data/processed/\"\n\n d = date.closest_date(year + day / 365.25,\n directory,\n file_prefix = \"u-\")\n\n x, y, u, _ = arcinfo.read(directory + \"u-\" + d + \".txt\")\n _, _, v, _ = arcinfo.read(directory + \"v-\" + d + \".txt\")\n\n ny, nx = np.shape(u)\n\n xs, ys, ss, _ = arcinfo.read(directory + \"zsDEM-\" + d + \".txt\")\n xb, yb, bb, _ = arcinfo.read(directory + \"zbDEM.txt\")\n\n # Smooth the ice surface elevation\n for i in range(1, len(ys) - 1):\n for j in range(1, len(xs) - 1):\n ss[i, j] = (4 * ss[i, j] +\n ss[i+1, j] + ss[i-1, j] +\n ss[i, j+1] + ss[i, j-1]) / 8.0\n\n sf = interpolate.RectBivariateSpline(xs, ys, ss.T)\n bf = interpolate.RectBivariateSpline(xb, yb, bb.T)\n\n s = np.zeros((ny, nx), dtype = np.float64)\n b = np.zeros((ny, nx), dtype = np.float64)\n\n for i in range(ny):\n for j in range(nx):\n s[i, j] = sf(x[j], y[i])\n b[i, j] = bf(x[j], y[i])\n\n del sf, bf, xs, ys, ss, xb, yb, bb\n\n\n beta, ub, vb = guess_basal_fields(x, y, s, b, u, v, frac)\n\n for i in range(ny):\n for j in range(nx):\n if beta[i, j] != -2.0e+9:\n beta[i, j] = max(beta[i, j], 0.015)\n\n arcinfo.write(directory + \"beta-\" + d + \".txt\", x, y, beta, -2.0e+9)\n arcinfo.write(directory + \"ub-\" + d + \".txt\", x, y, ub, -2.0e+9)\n arcinfo.write(directory + \"vb-\" + d + \".txt\", x, y, vb, -2.0e+9)\n\n\n# --------------------------\ndef add_cmdline_args(parser):\n add_argument(parser,\n \"-y\", \"--year\", required = True,\n help = \"Year for inversion\")\n add_argument(parser,\n \"-d\", \"--day\", required = True,\n help = \"day of year for inversion\")\n add_argument(parser,\n \"-f\", \"--frac\", required = True,\n help = \"% of driving stress to guess basal shear\")\n\n\n# -----------------------\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n add_cmdline_args(parser)\n args, _ = parser.parse_known_args(sys.argv[1:])\n\n main(float(args.day), float(args.year), float(args.frac))\n","sub_path":"data/initial_guesses.py","file_name":"initial_guesses.py","file_ext":"py","file_size_in_byte":6044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"207804280","text":"import sys, os, glob\n\n# Find JPEG images in every folder and append list of images to next index\ndef findImages(image_paths, owd):\n file_list = []\n for path in image_paths:\n print(path)\n os.chdir(path)\n print(glob.glob(\"*.JPEG\"))\n file_list.append(glob.glob(path + \"*.JPEG\"))\n os.chdir(owd)\n return file_list\n\ndef writeFile(output_file, image_list):\n with open(output_file, 'w') as file:\n for index, images in enumerate(image_list):\n for image in images:\n file.write(os.path.basename(image) + \" \" + str(index) + \"\\n\")\n\ndef main():\n if (len(sys.argv) < 3):\n return\n\n owd = os.getcwd()\n output_file = str(sys.argv[1])\n print(sys.argv[2:])\n image_paths = sys.argv[2:]\n image_list = findImages(image_paths, owd)\n writeFile(output_file, image_list)\n\n# py preprocess.py outputfile /path/to/images/\nif __name__ == \"__main__\":\n main()\n","sub_path":"colorization/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"604051983","text":"#!/usr/bin/env python\r\n# This file is part of tcollector.\r\n# Copyright (C) 2010 The tcollector Authors.\r\n#\r\n# This program is free software: you can redistribute it and/or modify it\r\n# under the terms of the GNU Lesser General Public License as published by\r\n# the Free Software Foundation, either version 3 of the License, or (at your\r\n# option) any later version. This program is distributed in the hope that it\r\n# will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty\r\n# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser\r\n# General Public License for more details. You should have received a copy\r\n# of the GNU Lesser General Public License along with this program. If not,\r\n# see .\r\n\r\nimport os\r\nimport sys\r\nimport time\r\n\r\ntry:\r\n import json\r\nexcept ImportError:\r\n json = None\r\n\r\nimport utils\r\nfrom hadoop_http import HadoopHttp\r\n\r\n\r\nREPLACEMENTS = {\r\n \"datanodeactivity-\": [\"activity\"],\r\n \"fsdatasetstate-ds-\": [\"fs_data_set_state\"],\r\n \"rpcdetailedactivityforport\": [\"rpc_activity\"],\r\n \"rpcactivityforport\": [\"rpc_activity\"]\r\n}\r\n\r\n\r\nclass HadoopDataNode(HadoopHttp):\r\n \"\"\"\r\n Class that will retrieve metrics from an Apache Hadoop DataNode's jmx page.\r\n\r\n This requires Apache Hadoop 1.0+ or Hadoop 2.0+.\r\n Anything that has the jmx page will work but the best results will com from Hadoop 2.1.0+\r\n \"\"\"\r\n\r\n def __init__(self):\r\n super(HadoopDataNode, self).__init__('hadoop', 'datanode', 'localhost', 50075)\r\n\r\n def emit(self):\r\n step = os.path.realpath(__file__).split(\"/\")[-1].split(\"_\", 2)[0]\r\n current_time = int(time.time())\r\n metrics = self.poll()\r\n for context, metric_name, value in metrics:\r\n for k, v in REPLACEMENTS.iteritems():\r\n if any(c.startswith(k) for c in context):\r\n context = v\r\n self.emit_metric(context, current_time, metric_name, value, step)\r\n self.print_metric()\r\n\r\n\r\ndef main(args):\r\n utils.drop_privileges()\r\n if json is None:\r\n utils.err(\"This collector requires the `json' Python module.\")\r\n return 13 # Ask tcollector not to respawn us\r\n datanode_service = HadoopDataNode()\r\n datanode_service.emit()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n sys.exit(main(sys.argv))","sub_path":"chapter8/60_hadoop_datanode.py","file_name":"60_hadoop_datanode.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"222137809","text":"S = input()\nK = int(input())\nN = len(S)\n\nbef = \"\"\nstart = 0\nl = []\nfor i, s in enumerate(S):\n if bef==\"\":\n start = i\n elif bef!=s:\n l.append(i-start)\n start = i\n bef = s\nl.append(i-start+1)\n\nif len(set(S))==1:\n print((N*K)//2)\nelse:\n if S[0]==S[-1]:\n ans = (l[0]//2)+(l[-1]//2)+((l[0]+l[-1])//2)*(K-1)\n else:\n ans = (l[0]//2)*K+(l[-1]//2)*K\n for i in l[1:-1]:\n ans += (i//2)*K\n print(ans)\n","sub_path":"problems/AGC039/agc039_a.py","file_name":"agc039_a.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"419967192","text":"# 최댓값 구하기\n# 입력: 숫자가 n개 들어 있는 리스트\n# 출력: 숫자가 n개중 최댓값\n\n\ndef find_max(a):\n n = len(a)\n max_v = a[0]\n\n for i in range(1, n): # 인덱스를 생각해서 n-1까지 비교해야 한다.\n if a[i] > max_v:\n max_v = a[i]\n return max_v\n\nv = [17, 92, 18, 33, 58, 7, 33, 42]\n\nprint (find_max(v))\n","sub_path":"ch01_basic_algorithm/02.find-the-max/p02-1-findmax-jin.py","file_name":"p02-1-findmax-jin.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"119952334","text":"#!/usr/bin/env python\n# /etc/init.d/sample.py\n### BEGIN INIT INFO\n# Provides: watcherAuto.py\n# Required-Start: $remote_fs $syslog\n# Required-Stop: $remote_fs $syslog\n# Default-Start: 2 3 4 5\n# Default-Stop: 0 1 6\n# Short-Description: Start daemon at boot time\n# Description: Enable service provided by daemon.\n### END INIT INFO\n\nimport requests, json, ast\nfrom picamera import PiCamera\nfrom time import sleep\nfrom playsound import playsound\nfrom datetime import datetime\n\ncamera = PiCamera()\n\nwhile True:\n \n # file name\n dateStamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')\n file_name = '/home/pi/picsCatDetector/picture_{}.jpg'.format(dateStamp) \n\n # Take picture\n camera.start_preview()\n camera.capture(file_name)\n camera.stop_preview()\n\n url = 'http://0.0.0.0:5000/api'\n url = 'http://35.200.240.45:80/api'\n files = {'image': open(file_name, 'rb')}\n r = requests.post(url, files=files)\n print(r.text)\n\n dicOut = ast.literal_eval(r.text)\n proba = dicOut['probaCat']\n\n if proba > 0.95:\n playsound('vaccum1.mp3')\n","sub_path":"watcher/watcherAuto.bak.py","file_name":"watcherAuto.bak.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"630044312","text":"#!/usr/bin/env python\n\nfrom collections import defaultdict, Counter\nfrom random import randint, choice\n\nwith open('log2_512') as f:\n x = [list(map(int, line.strip().split(','))) for line in f.readlines()]\n\n# base, hash value\n\nbase_to_hash = defaultdict(set)\nhash_to_base = defaultdict(set)\n\nbest_result = 512\nwhile best_result > 40:\n result = []\n for r in x:\n base_to_hash[r[0]].add(r[1])\n hash_to_base[r[1]].add(r[0])\n\n while any([len(base_to_hash[i]) for i in base_to_hash]):\n best_size = 0\n best_base = -1\n if randint(0, 100) > 80:\n c = Counter()\n for i in base_to_hash:\n c.update(list(base_to_hash[i]))\n least_common = c.most_common()[-1]\n for i in hash_to_base[least_common[0]]:\n if len(base_to_hash[i]) > best_size and randint(0, 100) > 10:\n best_size = len(base_to_hash[i])\n best_base = i\n #if len(base_to_hash[i]) == best_size and i < best_base and randint(0, 100) > 10:\n # best_base = i\n else:\n for i in base_to_hash:\n if len(base_to_hash[i]) > best_size and randint(0, 100) > 10:\n best_size = len(base_to_hash[i])\n best_base = i\n #if len(base_to_hash[i]) == best_size and i < best_base and randint(0, 100) > 10:\n # best_base = i\n if best_base == -1:\n continue\n vals = set(list(base_to_hash[best_base]))\n result.append((best_base, vals))\n for i in base_to_hash:\n base_to_hash[i] -= vals\n\n if len(result) < best_result:\n best_result = len(result)\n arr = [-1 for _ in range(512)]\n bases = [0 for _ in range(best_result)]\n i = 0\n for r in result:\n best_base, vals = r\n for v in vals:\n arr[v] = i\n bases[i] = best_base\n i += 1\n count = sum([x == -1 for x in arr])\n print(arr)\n print(bases)\n print(len(result), best_result)\n","sub_path":"bench/hash2/512/512.py","file_name":"512.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"443984226","text":"def transform_scalars(dataset):\n \"\"\"3D Reconstruct from a tilt series using Direct Fourier Method\"\"\"\n\n from tomviz import utils\n import numpy as np\n\n # Get Tilt angles\n tilt_angles = utils.get_tilt_angles(dataset)\n\n data_py = utils.get_array(dataset)\n if data_py is None:\n raise RuntimeError(\"No scalars found!\")\n\n recon = dfm3(data_py,tilt_angles,np.size(data_py,0)*2)\n print('Reconsruction Complete')\n\n # Set the result as the new scalars.\n utils.set_array(dataset, recon)\n\n # Mark dataset as volume\n utils.mark_as_volume(dataset)\n\nimport pyfftw\nimport numpy as np\n\ndef dfm3(input,angles,Npad):\n # input: aligned data\n # angles: projection angles\n # N_pad: size of padded projection.\n\n input = np.double(input)\n (Nx,Ny,Nproj) = input.shape\n angles = np.double(angles)\n cen = np.floor(Ny/2.0)\n cen_pad = np.floor(Npad/2.0)\n pad_pre = np.ceil((Npad-Ny)/2.0); pad_post = np.floor((Npad-Ny)/2.0)\n \n # Initialization\n Nz = Ny\n w = np.zeros((Nx,Ny,np.int(Nz/2+1))) #store weighting factors\n v = pyfftw.n_byte_align_empty((Nx,Ny,Nz/2+1),16,dtype='complex128')\n v = np.zeros(v.shape) + 1j*np.zeros(v.shape)\n recon = pyfftw.n_byte_align_empty((Nx,Ny,Nz),16,dtype='float64')\n recon_fftw_object = pyfftw.FFTW(v,recon,direction='FFTW_BACKWARD',axes=(0,1,2))\n\n p = pyfftw.n_byte_align_empty((Nx,Npad),16,dtype='float64')\n pF = pyfftw.n_byte_align_empty((Nx,Npad/2+1),16,dtype='complex128')\n p_fftw_object = pyfftw.FFTW(p,pF,axes=(0,1))\n\n dk = np.double(Ny)/np.double(Npad)\n\n for a in range(0, Nproj):\n #print angles[a]\n ang = angles[a]*np.pi/180\n projection = input[:,:,a] #2D projection image\n p = np.lib.pad(projection,((0,0),(pad_pre,pad_post)),'constant',constant_values=(0,0)) #pad zeros\n p = np.fft.ifftshift(p) \n p_fftw_object.update_arrays(p,pF)\n p_fftw_object()\n\n probjection_f = pF.copy()\n if ang<0:\n probjection_f = np.conj(pF.copy())\n probjection_f[1:,:] = np.flipud(probjection_f[1:,:])\n ang = np.pi+ang\n\n # Bilinear extrapolation\n for i in range(0, np.int(np.ceil(Npad/2))+1):\n ky = i*dk; #kz = 0;\n ky_new = np.cos(ang)*ky #new coord. after rotation\n kz_new = np.sin(ang)*ky \n sy = abs(np.floor(ky_new) - ky_new) #calculate weights\n sz = abs(np.floor(kz_new) - kz_new)\n for b in range(1,5): #bilinear extrapolation\n pz,py,weight = bilinear(kz_new,ky_new,sz,sy,Ny,b)\n if (py>=0 and py=0 and pz None: ...\n\nclass H2Server:\n sock: Any = ...\n conn: Any = ...\n root: Any = ...\n flow_control_events: Any = ...\n def __init__(self, sock: Any, root: Any) -> None: ...\n async def run(self) -> None: ...\n async def request_received(self, headers: Any, stream_id: Any) -> None: ...\n async def send_file(self, file_path: Any, stream_id: Any) -> None: ...\n async def _send_file_data(self, fileobj: Any, stream_id: Any) -> None: ...\n async def wait_for_flow_control(self, stream_id: Any) -> None: ...\n async def window_updated(self, event: Any) -> None: ...\n","sub_path":"Result/4079files/uninferred/2408-Uninferred.pyi","file_name":"2408-Uninferred.pyi","file_ext":"pyi","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"350561872","text":"from aiohttp import web\nfrom aiopg.sa import create_engine\nfrom os import path\nimport logging\nimport sys\nimport argparse\n\nfrom paysys.settings import Settings\nfrom paysys.db_utils import apply_migrations, make_uri\n\nROOT = path.abspath(path.join(path.dirname(__file__), '..'))\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--config', dest='config', default=path.join(ROOT, 'config.json'))\nargs = parser.parse_args()\n\n\nasync def on_startup(app):\n config = Settings()\n config.load_json(path.join(ROOT, 'default_config.json'))\n config.load_json(args.config)\n\n conn_uri = make_uri(config.section('postgres'))\n print(conn_uri)\n apply_migrations(conn_uri)\n\n app['config'] = config\n app['engine'] = await create_engine(conn_uri)\n app['logger'] = init_logger()\n\n\nasync def close_pg(app):\n app['engine'].close()\n await app['engine'].wait_closed()\n\n\ndef init_logger():\n logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s: %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n level=logging.INFO,\n stream=sys.stdout)\n return logging.getLogger('')\n\n\napp = web.Application()\napp.on_startup.append(on_startup)\napp.on_cleanup.append(close_pg)\n","sub_path":"paysys/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"417067168","text":"print(\"Today we will be finding the median of a list.\")\nprint(\"User enter a length for your list:\")\n\n# users list length and list\nlist_length = int(input())\nnumber_list = []\n\n# asking the user to input the amount of numbers they wanted and adding them the list\nfor i in range(list_length):\n print(\"User enter a number:\")\n users_num = float(input())\n number_list.append(users_num)\n\n# creating a function to find median\n\ndef median():\n remainder = list_length % 2 # finds remainder\n print(remainder)\n sorted_list = sorted(number_list) # sorts list\n print(sorted_list, \"is your list sorted in ascending order\")\n if remainder == 1: # if remainder = 1, slices at halfway point, and prints\n slice_position = (list_length + 1)//2 - 1\n print(sorted_list[slice_position], \"is the median of your list\")\n if remainder == 0: # if remainder = 0, slices at 2 positions - half and half + 1\n sorted_list = sorted(number_list) # sorts list\n slice_position2 = list_length/2\n median1 = sorted_list(slice_position2)\n median2 = sorted_list(slice_position2 - 1)\n print((median1 + median2)/2)\n\nmedian()","sub_path":"Median.py","file_name":"Median.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"562011674","text":"#!/usr/bin/env checkio --domain=py run the-lancers\n\n# \n# END_DESC\n\nclass Warrior(object):\n def __init__(self, *args, **kwargs):\n self.health = 50\n self.attack = 5\n self.defense = 0\n\n def damage(self, opponent):\n dealt_damage = self.attack - opponent.defense\n if opponent.defense < self.attack:\n opponent.health -= dealt_damage\n\n @property\n def is_alive(self):\n if self.health > 0:\n return True\n else:\n return False\n\n def __str__(self):\n return \"health: \" + str(self.health) + \"attack: \" + str(self.attack)\n\n\nclass Rookie(Warrior):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.health = 50\n self.attack = 1\n\n\nclass Knight(Warrior):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.health = 50\n self.attack = 7\n\n\nclass Defender(Warrior):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.health = 60\n self.attack = 3\n self.defense = 2\n\n\nclass Vampire(Warrior):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.health = 40\n self.attack = 4\n self.defense = 0\n self.vampirism = 0.5\n\n # special damage - curing self\n def damage(self, opponent):\n dealt_damage = self.attack - opponent.defense\n if opponent.defense < self.attack:\n opponent.health -= dealt_damage\n self.health += dealt_damage * self.vampirism\n\n\nclass Lancer(Warrior):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.health = 50\n self.attack = 6\n self.defense = 0\n\n # special damage - damage one opponent behind\n def damage(self, opponent1, opponent2=None):\n dealt_damage = self.attack - opponent1.defense\n if opponent1.defense < self.attack:\n opponent1.health -= dealt_damage\n if opponent2:\n if opponent2.defense < self.attack:\n opponent2.health -= dealt_damage * 0.5\n\n\ndef fight(unit1, unit2):\n # if fight is a duet only\n while unit1.is_alive and unit2.is_alive:\n unit1.damage(unit2)\n if unit2.is_alive:\n unit2.damage(unit1)\n if not unit1.is_alive:\n # print(\"u1 is dead\")\n # print(\"u1: \" + str(unit_1.health) + \", u2: \" + str(unit_2.health))\n return False\n else:\n # print(\"u2 is dead\")\n # print(\"u1: \" + str(unit_1.health) + \", u2: \" + str(unit_2.health))\n return True\n\n\nclass Army:\n def __init__(self):\n self._members = []\n self._it = iter(self._members)\n\n def __iter__(self):\n return self\n\n def __next__(self):\n try:\n return next(self._it)\n except StopIteration:\n raise\n\n def add_units(self, cls, units: int):\n for _ in range(0, units):\n self._members.append(cls())\n\n @property\n def members(self):\n return self._members\n\n @property\n def anyalive(self):\n for x in self._members:\n if x.is_alive:\n return True\n else:\n return False\n\n\nclass Battle:\n def __init__(self):\n pass\n\n def fight(self, army1: Army, army2: Army):\n\n try:\n team1f = next(army1)\n except StopIteration:\n return False\n else:\n try:\n team2f = next(army2)\n except StopIteration:\n return True\n\n try:\n team1b = next(army1)\n except StopIteration:\n team1b = None\n\n try:\n team2b = next(army2)\n except StopIteration:\n team2b = None\n\n while team1f.is_alive and team2f.is_alive:\n # team 1 forward is attacking\n if team1f is Lancer:\n team1f.damage(team2f, team2b)\n else:\n team1f.damage(team2f)\n\n # check team 2 backup is exist and still alive\n if team2b:\n if not team2b.is_alive:\n try:\n team2b = next(army2)\n except StopIteration:\n team2b = None\n\n # check team 2 forward is still alive\n if team2f.is_alive:\n # then, attack team 1 and see if he's alive\n if team2f is Lancer:\n team2f.damage(team1f, team1b)\n else:\n team2f.damage(team1f)\n\n # check team 1 backup is exist and still alive\n if team1b:\n if not team1b.is_alive:\n try:\n team1b = next(army1)\n except StopIteration:\n team1b = None\n\n # check team 1 forward is still alive\n if not team1f.is_alive:\n # print(\"team1f is dead: \" + str(type(team1f)))\n if team1b:\n team1f = team1b\n try:\n team1b = next(army1)\n except StopIteration:\n team1b = None\n else:\n continue\n\n else:\n # print(\"team2f is dead: \" + str(type(team2f)))\n if team2b:\n team2f = team2b\n try:\n team2b = next(army2)\n except StopIteration:\n team2b = None\n\n if army1.anyalive and not army2.anyalive:\n # print(\"army1 wins\")\n return True\n else:\n # print(\"army2 wins\")\n return False\n\n\nif __name__ == '__main__':\n # These \"asserts\" using only for self-checking and not necessary for auto-testing\n\n # fight tests\n chuck = Warrior()\n bruce = Warrior()\n carl = Knight()\n dave = Warrior()\n mark = Warrior()\n bob = Defender()\n mike = Knight()\n rog = Warrior()\n lancelot = Defender()\n eric = Vampire()\n adam = Vampire()\n richard = Defender()\n ogre = Warrior()\n freelancer = Lancer()\n vampire = Vampire()\n\n assert fight(chuck, bruce) == True\n assert fight(dave, carl) == False\n assert chuck.is_alive == True\n assert bruce.is_alive == False\n assert carl.is_alive == True\n assert dave.is_alive == False\n assert fight(carl, mark) == False\n assert carl.is_alive == False\n assert fight(bob, mike) == False\n assert fight(lancelot, rog) == True\n assert fight(eric, richard) == False\n assert fight(ogre, adam) == True\n assert fight(freelancer, vampire) == True\n assert freelancer.is_alive == True\n\n # battle tests\n my_army = Army()\n my_army.add_units(Defender, 2)\n my_army.add_units(Vampire, 2)\n my_army.add_units(Lancer, 4)\n my_army.add_units(Warrior, 1)\n\n enemy_army = Army()\n enemy_army.add_units(Warrior, 2)\n enemy_army.add_units(Lancer, 2)\n enemy_army.add_units(Defender, 2)\n enemy_army.add_units(Vampire, 3)\n\n army_3 = Army()\n army_3.add_units(Warrior, 1)\n army_3.add_units(Lancer, 1)\n army_3.add_units(Defender, 2)\n\n army_4 = Army()\n army_4.add_units(Vampire, 3)\n army_4.add_units(Warrior, 1)\n army_4.add_units(Lancer, 2)\n\n battle = Battle()\n\n assert battle.fight(my_army, enemy_army) == True\n assert battle.fight(army_3, army_4) == False\n print(\"Coding complete? Let's try tests!\")","sub_path":"py_checkio_solutions/Incinerator/the_lancers.py","file_name":"the_lancers.py","file_ext":"py","file_size_in_byte":7597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"134044195","text":"from typing import Dict, Tuple, Sequence, List, NoReturn\n\nfrom api_analyzer.analyzer.softwares.software_info_interface import SoftwareInfoInterface\nfrom api_analyzer.analyzer.analyzer_base import AnalyzerBase\nfrom api_analyzer.analyzer.softwares.imagemagick import ImageMagick\nfrom common.text_parser import TextParser\nfrom common.common import Common\n\n\nclass AnalyzerFacade:\n\n def __init__(self, software_info:SoftwareInfoInterface):\n self.analyzer = AnalyzerBase(software_info)\n\n def save_to_file(self, fileoutput, sorted_by_version):\n filename = fileoutput.split(\".\")[0] + \"_all.\" + fileoutput.split(\".\")[1]\n self.analyzer.save_to_file(filename, sorted_by_version)\n\n def version_data_from_list(self, list_cves):\n summary = self.analyzer.get_summary(list_cves)\n sorted_by_version = self.analyzer.convert_to_version_cve_dict(summary)\n return sorted_by_version\n\n def version_data_from_file(self, filename, files_save=True, fileoutput=\"sorted.json\"):\n list_cves = TextParser().get_cve_list_from_file(filename)\n sorted_by_version = self.version_data_from_list(list_cves)\n\n if files_save:\n self.save_to_file(fileoutput, sorted_by_version)\n\n return sorted_by_version\n\n\nif __name__ == \"__main__\":\n file_with_cves = \"/backend/api_analyzer/analyzer\\\\imagemagic_cve.txt\"\n image_magick = ImageMagick()\n analyzer_facade = AnalyzerFacade(image_magick)\n sorted_by_version = analyzer_facade.version_data_from_file(filename=file_with_cves)\n","sub_path":"backend/api_analyzer/analyzer/analyzer_facade.py","file_name":"analyzer_facade.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"628275142","text":"import math\n\nfrom flask import (\n Blueprint, render_template, request\n)\nfrom sqlalchemy import or_\n\nfrom .models import Book\nfrom .utils import paginate\nfrom .settings import ABANDONED, SINGLE_CP\n\n\nPAGE_SIZE = 10\n\nbp = Blueprint('web_app', __name__)\n\n\n# 主页\n@bp.route('/')\n@bp.route('/index')\n# @bp.route('/')\ndef index(page=1):\n query = Book.query.filter(Book.book_type < SINGLE_CP)\n query = query.filter(Book.status < ABANDONED)\n query = query.order_by(Book.pub_date.desc())\n total = math.ceil(query.count() / PAGE_SIZE)\n books = query.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE)\n return render_template('index.html',\n books=books,\n pagination=paginate(page, total))\n\n\n@bp.route('/search')\ndef search():\n kw = request.args.get('kw')\n books = Book.query.filter(or_(Book.book_name == kw,\n Book.author == kw,\n Book.hero == kw,\n Book.heroine == kw)).all()\n return render_template('search.html',\n books=books)\n\n\n@bp.route('/contact')\ndef contact():\n return render_template('contact.html')\n\n\n@bp.route('/help')\ndef help():\n return render_template('help.html')\n\n\ndef page_not_found(e):\n return render_template('404.html', data='页面'), 404\n\n\ndef server_error(e):\n return render_template('500.html'), 500\n","sub_path":"novel/web_app.py","file_name":"web_app.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"350474886","text":"class Solution:\n def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:\n \n result = []\n idx = 0\n \n while idx COMPRAS - DETALLES\")\n #\n # for detalle in DetalleFactura.objects.all():\n # if detalle.detalles.exists():\n # detalle.factura = detalle.detalles.all()[0]\n # detalle.save()\n # print(\"Detalle Venta: {}\".format(detalle.id))\n #\n # print(\"COMPLETED -> VENTAS - DETALLES\")\n\n # for detalle in DetalleSolicitudCompra.objects.all():\n # if detalle.solicitudcompra_set.exists():\n # detalle.solicitud = detalle.solicitudcompra_set.all()[0]\n # detalle.save()\n # print(\"Detalle Solicitud Compra: {}\".format(detalle.id))\n #\n # print(\"COMPLETED -> SOLICITUD COMPRAS - DETALLES\")\n\n # Analizar despues (si eliminar estos detalles de factura sin factura asociada)\n # DetalleFactura.objects.filter(factura__isnull=True).count()\n\n # Actualizar Facturas (campo Usuario) a partir de sus sesiones de caja para luego eliminar models SesionCaja y Caja\n # for factura in Factura.objects.order_by('-id'):\n # if factura.sesioncaja and factura.sesioncaja.caja and factura.sesioncaja.caja.usuario:\n # factura.usuario = factura.sesioncaja.caja.usuario\n # print(\"Updated user -> fact: {}\".format(factura.id))\n # else:\n # factura.usuario = User.objects.get(pk=7) # user andres (admin group)\n # print(\"Andres user -> fact: {}\".format(factura.id))\n # factura.save()\n # print(\"FINISHED UPDATE FACTURAS - USUARIOS\")\n\n # # Actualizar Inventario Real para todas las bodegas existentes (si no existe se crea con cantidad en cero)\n # for producto in Producto.objects.filter(ventas_por_mayor=True):\n #\n # for bodega in Bodega.objects.all():\n #\n # if not InventarioReal.objects.filter(producto=producto, bodega=bodega).exists():\n #\n # # get last Costo CIF\n # ultimo_costo_cif = 0\n # if HistorialCifProducto.objects.filter(producto=producto).exists():\n # ultimo_costo_cif = HistorialCifProducto.objects.filter(producto=producto).order_by('-id')[0].cif\n #\n # # get last Costo FOB\n # ultimo_costo_fob = 0\n # if HistorialFobProducto.objects.filter(producto=producto).exists():\n # ultimo_costo_fob = HistorialFobProducto.objects.filter(producto=producto).order_by('-id')[0].fob\n #\n # inventarioreal = InventarioReal(producto=producto,\n # cantidad=0,\n # costo=ultimo_costo_cif,\n # costofob=ultimo_costo_fob,\n # valor=0,\n # bodega=bodega)\n # inventarioreal.save()\n #\n # print(\"Updated Bodega {} en Inv {}\".format(bodega.nombre, inventarioreal.id))\n #\n # # Actualizar Inventarios de costos cif basados las ultimas transacciones cif registradas para los productos\n # for inventario in InventarioReal.objects.filter(producto__ventas_por_mayor=True).order_by('-id'):\n # change_cif, change_fob = inventario.actualizar_costos_valor()\n # if change_cif:\n # print('Updated CIF ({})'.format(inventario.producto.codigo))\n # if change_fob:\n # print('Updated FOB ({})'.format(inventario.producto.codigo))\n\n for traslado in TrasladoInventario.objects.order_by('-id'):\n usuario = \"andresg\"\n if traslado.usuario:\n usuario = traslado.usuario.username\n\n fecha = datetime.now()\n if traslado.fecha:\n fecha = traslado.fecha\n\n traslado.solicitado = True\n traslado.aprobado = True\n traslado.recibido = True\n\n traslado.solicitado_observaciones = traslado.observaciones\n\n traslado.solicitado_fecha = fecha\n traslado.solicitado_usuario = usuario\n\n traslado.aprobado_fecha = fecha\n traslado.aprobado_usuario = usuario\n\n traslado.recibido_fecha = fecha\n traslado.recibido_usuario = usuario\n\n traslado.save()\n print(traslado.id)\n","sub_path":"scripts.py","file_name":"scripts.py","file_ext":"py","file_size_in_byte":7686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"422741378","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]\n# Embedded file name: T:\\InGame\\Gameplay\\Scripts\\Server\\whims\\whim_set.py\n# Compiled at: 2019-02-20 22:33:37\n# Size of source mod 2**32: 14884 bytes\nfrom aspirations.aspiration_tuning import AspirationBasic\nfrom aspirations.aspiration_types import AspriationType\nfrom event_testing import objective_tuning\nfrom event_testing.resolver import DoubleSimResolver\nfrom interactions import ParticipantType\nfrom relationships.relationship_tests import TunableRelationshipTest\nfrom sims import genealogy_tracker\nfrom sims4.localization import TunableLocalizedStringFactory\nfrom sims4.tuning.instances import lock_instance_tunables\nfrom sims4.tuning.tunable import TunableEnumEntry, TunableReference, TunableVariant, OptionalTunable, TunableRange\nfrom sims4.utils import classproperty, constproperty\nfrom situations.situation_goal import TunableWeightedSituationGoalReference\nfrom statistics.commodity import RuntimeCommodity, CommodityTimePassageFixupType\nimport services, sims4.tuning.tunable\nlogger = sims4.log.Logger('Whimset', default_owner='jjacobson')\n\nclass GeneTargetFactory(sims4.tuning.tunable.TunableFactory):\n\n @staticmethod\n def factory(sim_info, relationship):\n family_member_sim_id = sim_info.get_relation(relationship)\n if family_member_sim_id is None:\n return\n family_member_sim_info = services.sim_info_manager().get(family_member_sim_id)\n if family_member_sim_info is not None:\n if family_member_sim_info.is_baby or family_member_sim_info.is_instanced():\n return family_member_sim_info\n\n FACTORY_TYPE = factory\n\n def __init__(self, **kwargs):\n (super().__init__)(description='\\n This option tests for completion of a tuned Achievement.\\n ', \n relationship=TunableEnumEntry(genealogy_tracker.FamilyRelationshipIndex, genealogy_tracker.FamilyRelationshipIndex.FATHER), **kwargs)\n\n\nclass RelationTargetFactory(sims4.tuning.tunable.TunableFactory):\n\n @staticmethod\n def factory(sim_info, relationship_test):\n relationship_match = None\n for relation in sim_info.relationship_tracker:\n relation_sim_info = services.sim_info_manager().get(relation.get_other_sim_id(sim_info.sim_id))\n if not relation_sim_info is not None or relation_sim_info.is_baby or relation_sim_info.is_instanced():\n resolver = DoubleSimResolver(sim_info, relation_sim_info)\n relationship_match = resolver(relationship_test)\n if relationship_match:\n return relation_sim_info\n\n FACTORY_TYPE = factory\n\n def __init__(self, **kwargs):\n (super().__init__)(description='\\n This option tests for completion of a tuned Achievement.\\n ', \n relationship_test=TunableRelationshipTest(description='\\n The relationship state that this goal will complete when\\n obtained.\\n ',\n locked_args={'subject':ParticipantType.Actor, \n 'tooltip':None, \n 'target_sim':ParticipantType.TargetSim, \n 'num_relations':0}), **kwargs)\n\n\nclass TunableWhimSetTargetVariant(TunableVariant):\n\n def __init__(self, *args, **kwargs):\n (super().__init__)(args, genealogy_target=GeneTargetFactory(), \n relationship_target=RelationTargetFactory(), \n default='genealogy_target', **kwargs)\n\n\nclass WhimSetBaseMixin:\n INSTANCE_TUNABLES = {'force_target':OptionalTunable(description='\\n Upon WhimSet activation, use this option to seek out and set a\\n specific target for this set. If the desired target does not exist\\n or is not instanced on the lot, WhimSet will not activate.\\n ',\n tunable=TunableWhimSetTargetVariant()), \n 'secondary_target':OptionalTunable(description='\\n Upon WhimSet activation, define a Sim that is used as a flavor\\n target, such that text can reference it. For example, a Dare whim\\n might use this field such that a \"Flirt with Bobby\" whim has a\\n \"(From Being Dared by Frank)\" origin.\\n ',\n tunable=TunableWhimSetTargetVariant()), \n 'whims':sims4.tuning.tunable.TunableList(description='\\n List of weighted goals.',\n tunable=TunableWeightedSituationGoalReference(pack_safe=True)), \n 'connected_whims':sims4.tuning.tunable.TunableMapping(description='\\n A tunable list of whims that upon a goal from this list succeeding will activate.',\n key_type=TunableReference((services.get_instance_manager(sims4.resources.Types.SITUATION_GOAL)), description='The goal to map.'),\n value_type=sims4.tuning.tunable.TunableList(description='\\n A tunable list of whim sets that upon this whim goal completing will activate',\n tunable=sims4.tuning.tunable.TunableReference(description='\\n These Aspiration Whim Sets become active automatically upon completion of this whim.',\n manager=(services.get_instance_manager(sims4.resources.Types.ASPIRATION)),\n class_restrictions='AspirationWhimSet'))), \n 'connected_whim_sets':sims4.tuning.tunable.TunableList(description='\\n A tunable list of whim sets that upon a goal from this list succeeding will activate',\n tunable=sims4.tuning.tunable.TunableReference(description='\\n These Aspiration Whim Sets become active automatically upon completion of a whim from this set.',\n manager=(services.get_instance_manager(sims4.resources.Types.ASPIRATION)),\n class_restrictions='AspirationWhimSet')), \n 'whim_reason':TunableLocalizedStringFactory(description=\"\\n The reason that shows in the whim tooltip for the reason that this\\n whim was chosen for the sim.\\n \\n 0 (Number): The most relevant numerical value pertaining to the\\n completion of this goal. This is usually the number of iterations\\n required to complete it although it could also be other values such as\\n the price of the item that the user is required to purchase.\\n \\n 1 (Sim): The Sim who owns the goal.\\n \\n 2 (Sim): The Sim the goal is directed at.\\n \\n 3 (Sim): The goal's secondary SimInfo, if one exists.\\n \"), \n 'cooldown_timer':sims4.tuning.tunable.TunableRange(description='\\n Number of Sim minutes this set of Whims is de-prioritized after de-activation.',\n tunable_type=float,\n minimum=0,\n maximum=3600,\n default=60)}\n\n @constproperty\n def aspiration_type():\n return AspriationType.WHIM_SET\n\n @classmethod\n def get_priority(cls, sim_info):\n raise NotImplementedError\n\n @classmethod\n def activate(cls, whims_tracker, chained, target):\n pass\n\n @classproperty\n def deactivate_on_completion(cls):\n return cls in cls.connected_whim_sets\n\n\nclass AspirationWhimSet(WhimSetBaseMixin, AspirationBasic):\n INSTANCE_TUNABLES = {'objectives':sims4.tuning.tunable.TunableList(description='\\n A Set of objectives for completing an aspiration.',\n tunable=sims4.tuning.tunable.TunableReference(description='\\n One objective for an aspiration',\n manager=(services.get_instance_manager(sims4.resources.Types.OBJECTIVE))),\n unique_entries=True), \n 'activated_priority':sims4.tuning.tunable.TunableRange(description='\\n Priority for this set to be chosen if triggered by contextual events.',\n tunable_type=int,\n minimum=0,\n maximum=10,\n default=6), \n 'priority_decay_rate':sims4.tuning.tunable.TunableRange(description=\"\\n The decay rate of a whimset's priority. A whimset's priority will\\n only decay when a whim of that whimset is active. A whimset's\\n priority will converge to the whimset's base priority.\\n \",\n tunable_type=float,\n default=0.01,\n minimum=0.0), \n 'timeout_retest':sims4.tuning.tunable.TunableReference(description='\\n Tuning an objective here will re-test the WhimSet for contextual\\n relevance upon active timer timeout; If the objective test passes,\\n the active timer will be refreshed. Note you can only use tests\\n without data passed in, other types will result in an assert on\\n load.\\n ',\n manager=services.get_instance_manager(sims4.resources.Types.OBJECTIVE),\n allow_none=True), \n 'chained_priority':sims4.tuning.tunable.TunableRange(description='\\n Priority for this set to be chosen if triggered by a previous whim set.',\n tunable_type=int,\n minimum=0,\n maximum=15,\n default=11)}\n priority_commodity = None\n\n @classmethod\n def _tuning_loaded_callback(cls):\n commodity = RuntimeCommodity.generate(cls.__name__)\n commodity.decay_rate = cls.priority_decay_rate\n commodity.convergence_value = 0\n commodity.remove_on_convergence = False\n commodity.visible = False\n if cls.activated_priority > cls.chained_priority:\n commodity.max_value_tuning = cls.activated_priority\n else:\n commodity.max_value_tuning = cls.chained_priority\n commodity.min_value_tuning = 0\n commodity.initial_value = 0\n commodity._time_passage_fixup_type = CommodityTimePassageFixupType.DO_NOT_FIXUP\n cls.priority_commodity = commodity\n\n @classmethod\n def _verify_tuning_callback(cls):\n if cls.activated_priority == 0:\n if cls.chained_priority == 0:\n logger.error('No priority tuned for value greater than 0 in {}', cls)\n for objective in cls.objectives:\n if objective.objective_completion_type == objective_tuning.SimInfoStatisticObjectiveTrack:\n logger.error(\"{} Objective in {} Whim Set tuned with incorrect Objective test type; use 'iterations', 'unique_locations', or 'unique targets'.\", objective, cls)\n if not objective.resettable:\n logger.error('{} Objective in {} Whim Set tuned as a Whim Aspiration Objective but not tuned as resettable. All Aspriation Whim Set objectives must be resettable.', objective, cls)\n\n if cls.timeout_retest is not None:\n if cls.timeout_retest.objective_test.USES_EVENT_DATA or cls.timeout_retest.objective_test.USES_DATA_OBJECT:\n logger.error('Bad Tuning! {} Objective Test {} in Whim Set being used as a timeout_retest cannot use event or object data.', cls.timeout_retest.objective_test, cls)\n\n @classmethod\n def get_priority(cls, sim_info):\n whimset_priority_stat = sim_info.get_statistic((cls.priority_commodity), add=False)\n if whimset_priority_stat is None:\n return 0\n return whimset_priority_stat.get_user_value()\n\n\nlock_instance_tunables(AspirationWhimSet, do_not_register_events_on_load=False, screen_slam=None)\n\nclass ObjectivelessWhimSet(WhimSetBaseMixin, AspirationBasic):\n INSTANCE_TUNABLES = {'priority': TunableRange(description='\\n The priority of this whim set.\\n ',\n tunable_type=float,\n minimum=0,\n default=5)}\n REMOVE_INSTANCE_TUNABLES = ('objective_completion_type', )\n\n @classmethod\n def get_priority(cls, sim_info):\n return cls.priority\n\n @constproperty\n def update_on_load():\n return False\n\n @classproperty\n def deactivate_on_completion(cls):\n return False\n\n\nlock_instance_tunables(ObjectivelessWhimSet, do_not_register_events_on_load=True, objectives=(), screen_slam=None)","sub_path":"Scripts/simulation/whims/whim_set.py","file_name":"whim_set.py","file_ext":"py","file_size_in_byte":11856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"627826807","text":"#!/usr/bin/env python3\n\"\"\"Run TriFinger back-end using multi-process robot data.\"\"\"\nimport argparse\nimport logging\nimport pathlib\nimport sys\n\nimport robot_interfaces\nimport robot_fingers\n\n\ndef main():\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument(\n \"--max-number-of-actions\",\n \"-a\",\n type=int,\n required=True,\n help=\"\"\"Maximum numbers of actions that are processed. After this the\n backend shuts down automatically.\n \"\"\",\n )\n parser.add_argument(\n \"--cameras\", \"-c\", action=\"store_true\", help=\"Run camera backend.\",\n )\n parser.add_argument(\n \"--fake-object-tracker\",\n action=\"store_true\",\n help=\"Run fake object tracker backend\",\n )\n parser.add_argument(\n \"--robot-logfile\",\n type=str,\n help=\"\"\"Path to a file to which the robot data log is written. If not\n specified, no log is generated.\n \"\"\",\n )\n parser.add_argument(\n \"--camera-logfile\",\n type=str,\n help=\"\"\"Path to a file to which the camera data is written. If not\n specified, no log is generated.\n \"\"\",\n )\n parser.add_argument(\n \"--ready-indicator\",\n type=str,\n metavar=\"READY_INDICATOR_FILE\",\n help=\"\"\"Path to a file that will be created once the backend is ready\n and will be deleted again when it stops (before storing the logs).\n \"\"\",\n )\n args = parser.parse_args()\n\n log_handler = logging.StreamHandler(sys.stdout)\n logging.basicConfig(\n format=\"[TRIFINGER_BACKEND %(levelname)s %(asctime)s] %(message)s\",\n level=logging.DEBUG,\n handlers=[log_handler]\n )\n\n if args.cameras:\n logging.info(\"Start camera backend\")\n import trifinger_cameras\n\n CAMERA_TIME_SERIES_LENGTH = 100\n\n camera_data = trifinger_cameras.tricamera.MultiProcessData(\n \"tricamera\", True, CAMERA_TIME_SERIES_LENGTH\n )\n camera_driver = trifinger_cameras.tricamera.TriCameraDriver(\n \"camera60\", \"camera180\", \"camera300\"\n )\n camera_backend = trifinger_cameras.tricamera.Backend( # noqa\n camera_driver, camera_data\n )\n\n logging.info(\"Camera backend ready.\")\n\n logging.info(\"Start robot backend\")\n\n # Use robot-dependent config file\n config_file_path = \"/etc/trifingerpro/trifingerpro.yml\"\n\n # Storage for all observations, actions, etc.\n history_size = args.max_number_of_actions + 1\n robot_data = robot_interfaces.trifinger.MultiProcessData(\n \"trifinger\", True, history_size=history_size\n )\n\n if args.robot_logfile:\n robot_logger = robot_interfaces.trifinger.Logger(robot_data)\n\n # The backend sends actions from the data to the robot and writes\n # observations from the robot to the data.\n backend = robot_fingers.create_trifinger_backend(\n robot_data,\n config_file_path,\n max_number_of_actions=args.max_number_of_actions,\n )\n\n # Initializes the robot (e.g. performs homing).\n backend.initialize()\n\n logging.info(\"Robot backend is ready\")\n\n if args.fake_object_tracker:\n import trifinger_object_tracking.py_object_tracker as object_tracker\n\n object_tracker_data = object_tracker.Data(\"object_tracker\", True)\n object_tracker_backend = object_tracker.FakeBackend( # noqa\n object_tracker_data\n )\n\n if args.cameras and args.camera_logfile:\n camera_fps = 100\n robot_rate_hz = 1000\n episode_length_s = args.max_number_of_actions / robot_rate_hz\n # Compute camera log size based on number of robot actions plus a\n # 10% buffer\n log_size = int(camera_fps * episode_length_s * 1.1)\n\n logging.info(\"Initialize camera logger with buffer size %d\", log_size)\n camera_logger = trifinger_cameras.tricamera.Logger(\n camera_data, log_size\n )\n\n # if specified, create the \"ready indicator\" file to indicate that the\n # backend is ready\n if args.ready_indicator:\n pathlib.Path(args.ready_indicator).touch()\n\n if args.cameras and args.camera_logfile:\n backend.wait_until_first_action()\n camera_logger.start()\n logging.info(\"Start camera logging\")\n\n backend.wait_until_terminated()\n\n # delete the ready indicator file to indicate that the backend has shut\n # down\n if args.ready_indicator:\n pathlib.Path(args.ready_indicator).unlink()\n\n if args.cameras and args.camera_logfile:\n logging.info(\n \"Save recorded camera data to file %s\", args.camera_logfile\n )\n camera_logger.stop_and_save(args.camera_logfile)\n\n if args.robot_logfile:\n logging.info(\"Save robot data to file %s\", args.robot_logfile)\n if args.max_number_of_actions:\n end_index = args.max_number_of_actions\n else:\n end_index = -1\n robot_logger.write_current_buffer(\n args.robot_logfile, start_index=0, end_index=end_index\n )\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/trifinger_backend.py","file_name":"trifinger_backend.py","file_ext":"py","file_size_in_byte":5112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"416444983","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 4 17:34:57 2020\n\n@author: omen\n\"\"\"\n\nfrom tkinter import *\nfrom tkinter import filedialog\n \nfrom PIL import Image,ImageTk\nimport os\n\nimport IPython.display as ipd\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy import stats\nimport seaborn as sns\nimport sklearn as skl\nfrom sklearn.preprocessing import MinMaxScaler\nimport sklearn.utils, sklearn.preprocessing, sklearn.decomposition, sklearn.svm\nimport librosa\nimport librosa.display\nimport pandas as pd\nimport numpy as np\n\n\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.utils import shuffle\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.decomposition import PCA\n\nimport matplotlib.pyplot as plt\n\npd.set_option('max_info_columns', 999)\npd.options.display.max_rows = 200\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Flatten, Dropout\nfrom keras.models import Model\nfrom keras import backend as K\nfrom keras.utils.generic_utils import get_custom_objects\nfrom keras.layers import Activation\nfrom keras.utils.np_utils import to_categorical\nimport tensorflow as tf\nfrom sklearn.preprocessing import StandardScaler\n\n\n\nimport utils\n\n\ndef columns():\n feature_sizes = dict(chroma_stft=12, chroma_cqt=12, chroma_cens=12,\n tonnetz=6, mfcc=20, rms=1, zcr=1,\n spectral_centroid=1, spectral_bandwidth=1,\n spectral_contrast=7, spectral_rolloff=1)\n moments = ('mean', 'std', 'skew', 'kurtosis', 'median', 'min', 'max')\n\n columns = []\n for name, size in feature_sizes.items():\n for moment in moments:\n it = ((name, moment, '{:02d}'.format(i+1)) for i in range(size))\n columns.extend(it)\n\n names = ('feature', 'statistics', 'number')\n columns = pd.MultiIndex.from_tuples(columns, names=names)\n\n # More efficient to slice if indexes are sorted.\n return columns.sort_values()\n\n\ndef compute_features(DIR):\n\n features = pd.Series(index=columns(), dtype=np.float32)\n\n # Catch warnings as exceptions (audioread leaks file descriptors).\n \n\n def feature_stats(name, values):\n features[name, 'mean'] = np.mean(values, axis=1)\n features[name, 'std'] = np.std(values, axis=1)\n features[name, 'skew'] = stats.skew(values, axis=1)\n features[name, 'kurtosis'] = stats.kurtosis(values, axis=1)\n features[name, 'median'] = np.median(values, axis=1)\n features[name, 'min'] = np.min(values, axis=1)\n features[name, 'max'] = np.max(values, axis=1)\n\n try:\n \n \n x, sr = librosa.load(DIR, sr=None, mono=True) # kaiser_fast\n\n f = librosa.feature.zero_crossing_rate(x, frame_length=2048, hop_length=512)\n feature_stats('zcr', f)\n\n cqt = np.abs(librosa.cqt(x, sr=sr, hop_length=512, bins_per_octave=12,\n n_bins=7*12, tuning=None))\n assert cqt.shape[0] == 7 * 12\n assert np.ceil(len(x)/512) <= cqt.shape[1] <= np.ceil(len(x)/512)+1\n\n f = librosa.feature.chroma_cqt(C=cqt, n_chroma=12, n_octaves=7)\n feature_stats('chroma_cqt', f)\n f = librosa.feature.chroma_cens(C=cqt, n_chroma=12, n_octaves=7)\n feature_stats('chroma_cens', f)\n f = librosa.feature.tonnetz(chroma=f)\n feature_stats('tonnetz', f)\n\n del cqt\n stft = np.abs(librosa.stft(x, n_fft=2048, hop_length=512))\n assert stft.shape[0] == 1 + 2048 // 2\n assert np.ceil(len(x)/512) <= stft.shape[1] <= np.ceil(len(x)/512)+1\n del x\n\n f = librosa.feature.chroma_stft(S=stft**2, n_chroma=12)\n feature_stats('chroma_stft', f)\n\n f = librosa.feature.rms(S=stft)\n feature_stats('rms', f)\n\n f = librosa.feature.spectral_centroid(S=stft)\n feature_stats('spectral_centroid', f)\n f = librosa.feature.spectral_bandwidth(S=stft)\n feature_stats('spectral_bandwidth', f)\n f = librosa.feature.spectral_contrast(S=stft, n_bands=6)\n feature_stats('spectral_contrast', f)\n f = librosa.feature.spectral_rolloff(S=stft)\n feature_stats('spectral_rolloff', f)\n\n mel = librosa.feature.melspectrogram(sr=sr, S=stft**2)\n del stft\n f = librosa.feature.mfcc(S=librosa.power_to_db(mel), n_mfcc=20)\n feature_stats('mfcc', f)\n\n except Exception as e:\n print('{}'.format(repr(e)))\n\n return features\n\ndef generate_matrix(DIR):\n X = compute_features(DIR)\n Y = compute_features('predict_samples/bourrage.mp3')\n X = X.to_frame().T\n X2 = Y.to_frame().T\n\n X = pd.concat([X,X2])\n print(X.head())\n X = StandardScaler().fit_transform(X)\n np.save(\"03.npy\", X)\n \ndef load_matrix(loaded_model):\n Xtesst1 =np.load(\"03.npy\",allow_pickle=True)\n Xtest2 = MinMaxScaler().fit_transform(Xtesst1)\n y = loaded_model.predict(Xtest2)\n return y\ndef show_plot(y_X):\n dict_genres = {'Electronic':0, 'Experimental':1, 'Folk':2, 'Hip-Hop':3, \n 'Instrumental':4,'International':5, 'Pop' :6, 'Rock': 7 }\n key_list = list(dict_genres.keys()) \n val_list = list(dict_genres.values()) \n j = 0\n a = max(y_X[0])\n print(a)\n for i in range(len(y_X[0])-1):\n if y_X[0][i] == a:\n j = i \n df = pd.DataFrame({'genre':['Electronic', 'Experimental', 'Folk', 'Hip-Hop', \n 'Instrumental','International', 'Pop' , 'Rock'], '%':y_X[0]*100})\n ax = df.plot.bar(x='genre', y='%', rot=0)\n ax.get_figure().savefig('4.png')\n \n \n \n#------------------------------------------------------------------------------------------------------------------------\n\ndef popup():\n win = Toplevel()\n win.wm_title(\"Plot\")\n image = PhotoImage(file=\"4.png\")\n label = Label(win,image=image)\n label.pack()\n win.mainloop()\n\n\nclass Interface(Frame):\n\n def __init__(self, fenetre, **kwargs):\n Frame.__init__(self, fenetre, width=1200, height=800, **kwargs)\n self.pack(fill=BOTH)\n \n self.message = Label(self, text=\"UPLOAD AN MP3 TRACK\")\n self.message.pack()\n \n self.bouton_Generate = Button(self, text=\"Generate\", fg=\"red\",command=self.Generate)\n self.bouton_Generate.pack(side=\"right\")\n \n self.bouton_showPlot = Button(self, text=\"showPlot\", fg=\"red\",command=popup)\n self.bouton_showPlot.pack(side=\"left\")\n \n self.bouton_browse = Button(self, text=\"Browse\",command=self.load_file)\n self.bouton_browse.pack(side=\"right\")\n \n self.bouton_clear = Button(self, text=\"Clear\",command=self.clear)\n self.bouton_clear.pack(side=\"left\")\n \n \n def load_file(self):\n \n self.file_name = filedialog.askopenfilename(filetypes = [(\"mp3 files\",\"*.mp3\"),(\"all files\",\"*.*\")])\n \n def Generate(self):\n d = self.file_name\n \n generate_matrix(d)\n model = loaded_model = tf.keras.models.load_model('final_model.h5')\n Y = load_matrix(model)\n show_plot(Y)\n print(\"end generating\")\n \n def clear(self):\n self.label.destroyè()\n \n \n \n \n\n \n \nfenetre = Tk()\nfenetre.geometry(\"200x100\")\ninterface = Interface(fenetre)\ninterface.mainloop()\ninterface.destroy()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"518832465","text":"from itertools import product\n\nn = int(input())\nn_len = len(str(n))\nans = 0\nfor i in range(3,n_len):\n ite = product(range(3),repeat=i)\n for it in ite:\n if 0 in it and 1 in it and 2 in it:\n ans += 1\n\n\nnum_d = {0:7,1:5,2:3}\nite = product(range(3),repeat=n_len)\nfor it in ite:\n if 0 in it and 1 in it and 2 in it:\n curr_num = 0\n for i,j in enumerate(it):\n curr_num += num_d[j]*(10**(n_len-1-i))\n if curr_num <= n: \n ans+=1\n\nprint(ans)","sub_path":"2_kakomon/abc042-125/abc114_c2.py","file_name":"abc114_c2.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"634477896","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom myTorch.utils import my_variable\nfrom myTorch.memory import RNNCell, GRUCell, LSTMCell, TARDISCell\n\n\nclass RecurrentBlocksWorldMatrix(nn.Module):\n\n\tdef __init__(self, obs_dim, action_dim, use_gpu=False, rnn_type=\"LSTM\"):\n\t\tsuper(self.__class__, self).__init__()\n\n\t\tself._obs_dim = obs_dim\n\t\tself._action_dim = action_dim\n\t\tself._use_gpu = use_gpu\n\t\tself._rnn_input_size = 512\n\t\tself._rnn_hidden_size = 1024\n\t\tself._rnn_type = rnn_type\n\t\tself._is_rnn_policy = True\n\t\tif self._rnn_type == \"LSTM\": \n\t\t\tself._rnn = LSTMCell(input_size=self._rnn_input_size, hidden_size=self._rnn_hidden_size, use_gpu=use_gpu)\n\t\telif self._rnn_type == \"GRU\":\n\t\t\tself._rnn = GRUCell(input_size=self._rnn_input_size, hidden_size=self._rnn_hidden_size, use_gpu=use_gpu)\n\t\tself._hidden = None\n\n\t\tself._conv1 = nn.Conv2d(self._obs_dim[0], 16, kernel_size=2, stride=1)\n\t\tself._bn1 = nn.BatchNorm2d(16)\n\t\tself._conv2 = nn.Conv2d(16, 32, kernel_size=2, stride=1)\n\t\tself._bn2 = nn.BatchNorm2d(32)\n\t\tself._conv3 = nn.Conv2d(32, 32, kernel_size=2, stride=1)\n\t\tself._bn3 = nn.BatchNorm2d(32)\n\t\tself._conv4 = nn.Conv2d(32, 32, kernel_size=4, stride=1)\n\t\tself._bn4 = nn.BatchNorm2d(32)\n\t\tself._fc1 = nn.Linear(512, 256)\n\t\tself._fc2 = nn.Linear(256, 256)\n\t\tself._fc3 = nn.Linear(256, self._rnn_input_size)\n\n\t\tself._fcv = nn.Linear(self._rnn_hidden_size, 1)\n\t\tself._fcp = nn.Linear(self._rnn_hidden_size, self._action_dim)\n\n\tdef _conv_to_linear(self, obs):\n\t\tif len(obs.shape) < 4:\n\t\t\tobs = obs.unsqueeze(0)\n\t\tx = F.relu(self._bn1(self._conv1(obs)))\n\t\tx = F.relu(self._bn2(self._conv2(x)))\n\t\tx = F.relu(self._bn3(self._conv3(x)))\n\t\tx = F.relu(self._bn4(self._conv4(x)))\n\t\tx = F.relu(self._fc1(x.view(x.size(0), -1)))\n\t\tx = F.relu(self._fc2(x))\n\t\tx = F.relu(self._fc3(x))\n\t\treturn x\n\n\tdef reset_hidden(self, batch_size):\n\t\tself._hidden = {}\n\t\tself._hidden[\"h\"] = my_variable(torch.zeros(batch_size, self._rnn_hidden_size), use_gpu=self._use_gpu)\n\t\t\n\t\tif self._rnn_type == \"LSTM\":\n\t\t\tself._hidden[\"c\"] = my_variable(torch.zeros(batch_size, self._rnn_hidden_size), use_gpu=self._use_gpu)\n\n\tdef forward(self, obs, update_hidden_state):\n\t\tif self._hidden is None:\n\t\t\tself.reset_hidden(obs.shape[0])\n\n\t\tx = self._conv_to_linear(obs)\n\t\thidden_next = self._rnn(x, self._hidden)\n\t\tif update_hidden_state:\n\t\t\tself._hidden = hidden_next\n\t\tp = self._fcp(hidden_next[\"h\"])\n\t\tv = self._fcv(hidden_next[\"h\"])\n\t\treturn p, v\n\n\tdef update_hidden(self, mask):\n\t\tfor k in self._hidden:\n\t\t\tself._hidden[k] = mask.expand(-1,self._rnn_hidden_size) * self._hidden[k]\n\n\tdef detach_hidden(self):\n\t\tfor k in self._hidden:\n\t\t\thidden_value = self._hidden[k].data.cpu().numpy()\n\t\t\tself._hidden[k] = my_variable(torch.from_numpy(hidden_value), use_gpu=self._use_gpu)\n\t\t\n\t@property\n\tdef action_dim(self):\n\t\treturn self._action_dim\n\n\t@property\n\tdef obs_dim(self):\n\t\treturn self._obs_dim\n\n\t@property\n\tdef use_gpu(self):\n\t\treturn self._use_gpu\n\n\t@property\n\tdef is_rnn_policy(self):\n\t\treturn self._is_rnn_policy\n\n\tdef get_attributes(self):\n\t\treturn (self._obs_dim, self._action_dim, self._use_gpu, self._rnn_type)\n\n\tdef get_params(self):\n\t\treturn self.state_dict()\n\n\tdef set_params(self, state_dict):\n\t\tself.load_state_dict(state_dict)\n\n\tdef make_inference_net(self):\n\t\tinference_net = self.__class__(*self.get_attributes())\n\t\tif self._use_gpu == True:\n\t\t\t\tinference_net.cuda()\n\t\tinference_net.set_params(self.get_params())\n\t\treturn inference_net\n\n\nif __name__==\"__main__\":\n\tp, v = RecurrentCartPole(50,10)\n\timport pdb; pdb.set_trace()\n\n","sub_path":"myTorch/rllib/a2c/a2c_networks/recurrent_blocksworld_matrix.py","file_name":"recurrent_blocksworld_matrix.py","file_ext":"py","file_size_in_byte":3555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"187993071","text":"'''\n@Author: your name\n@Date: 2019-11-27 17:23:40\n@LastEditTime: 2019-11-27 17:49:56\n@LastEditors: Please set LastEditors\n@Description: In User Settings Edit\n@FilePath: \\leetcode\\104.二叉树的最大深度.py\n'''\n#\n# @lc app=leetcode.cn id=104 lang=python3\n#\n# [104] 二叉树的最大深度\n#递归 \n\n# @lc code=start\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\nclass Solution:\n def maxDepth(self, root: TreeNode):\n if root == None :#结束递归的条件\n return 0\n else:\n left_height = self.maxDepth(root.left)\n right_height = self.maxDepth(root.right)\n return max(left_height,right_height)+1\n\n\n# @lc code=end\n\n","sub_path":"easy/104.二叉树的最大深度.py","file_name":"104.二叉树的最大深度.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"565437976","text":"import datetime\n\nclass Conta:\n \n __slots__ = ['_numero','_cliente','_saldo','_limite','_historico','_data_abertura']\n\n _numero_conta = 0\n\n def __init__(self, cliente, saldo, limite):\n #self._numero = numero\n self._cliente = cliente\n self._saldo = saldo\n self._limite = limite\n self._historico = Historico()\n self._data_abertura = datetime.datetime.now()\n Conta._numero_conta += 1\n\n def deposita(self, valor,transferencia = False,conta = None):\n self._saldo += valor\n if not transferencia:\n self._historico.insere(f\"Deposito de {valor}\")\n else:\n self._historico.insere(f\"Recebida transferencia de {conta._numero} no valor de {valor}\")\n\n \n def saca(self, valor):\n if(self._saldo < valor):\n return False\n else: \n self._saldo -= valor\n self._historico.insere(f\"Saque: {valor}\")\n return True\n \n def transfere_para(self, destino,valor):\n retirou = self.saca(valor)\n\n if(retirou):\n destino.deposita(valor,True,self)\n self._historico.insere(f\"Transferido para {destino.numero} o valor {valor}\")\n \n return retirou\n\n\n def extrato(self):\n print(\"numero: {} \\nsaldo:{}\".format(self._numero,self._saldo))\n self._historico.mostra()\n\nclass Cliente:\n\n def __init__(self, nome, sobrenome, cpf):\n self.nome = nome\n self.sobrenome = sobrenome\n self.cpf = cpf\n\nclass Historico:\n\n def __init__(self):\n self.movimentacoes = []\n \n def mostra(self):\n for movimentacao in self.movimentacoes:\n print(movimentacao)\n\n def insere(self,mensagem):\n self.movimentacoes.append(mensagem)\n\n\n\n\n ","sub_path":"conta.py","file_name":"conta.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"84043478","text":"import csv\nimport os\n\n\ncontent = os.listdir()\n\nbyte_str = b'\\x88A\\xde\\x87\\x00H`\\xb9V7\\xb0\\xfe?\\xda\\x0e\\xd7\\xb0\\xf3\\xac\\x8c'\ncon = byte_str\nwith open('list.csv','w', encoding='UTF-8') as f:\n # for x in con:\n f.write(byte_str)\n f.close()","sub_path":"test_file.py","file_name":"test_file.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"574424890","text":"import numpy as np\n\nSEG_DURATION = 1000.0\nSERVER_START_UP_TH = 2000.0\t\t\t\t# <========= TO BE MODIFIED. TEST WITH DIFFERENT VALUES\n# ADD_DELAY = 3000.0\nRANDOM_SEED = 10\nMS_IN_S = 1000.0\nKB_IN_MB = 1000.0\n# New bitrate setting, 6 actions, correspongding to 240p, 360p, 480p, 720p, 1080p and 1440p(2k)\nBITRATE = [300.0, 500.0, 1000.0, 2000.0, 3000.0, 6000.0]\n# BITRATE = [300.0, 6000.0]\n# BITRATE = [500.0, 2000.0, 5000.0, 8000.0, 16000.0]\t# 5 actions\n\nBITRATE_LOW_NOISE = 0.7\nBITRATE_HIGH_NOISE = 1.3\nRATIO_LOW_2 = 2.0\t\t\t\t# This is the lowest ratio between first chunk and the sum of all others\nRATIO_HIGH_2 = 10.0\t\t\t# This is the highest ratio between first chunk and the sum of all others\nRATIO_LOW_5 = 0.75\t\t\t\t# This is the lowest ratio between first chunk and the sum of all others\nRATIO_HIGH_5 = 1.0\t\t\t# This is the highest ratio between first chunk and the sum of all others\nEST_LOW_NOISE = 0.98\nEST_HIGH_NOISE = 1.02\n\n\nclass Live_Server(object):\n\tdef __init__(self, seg_duration, start_up_th, randomSeed = RANDOM_SEED):\n\t\tnp.random.seed(randomSeed)\n\t\tself.seg_duration = seg_duration\n\t\tself.time = start_up_th + np.random.randint(1,seg_duration)\n\t\tself.start_up_th = start_up_th\n\t\tself.current_seg_idx = -1\n\t\tself.segs = []\t\n\t\tself.current_seg_size = [[] for i in range(len(BITRATE))]\n\t\tself.init_encoding()\n\t\n\n\tdef init_encoding(self):\n\t\t# assert self.ratio\n\t\tself.encoding_update(0.0, self.time)\n\t\tself.next_delivery = []\n\t\tself.generate_next_delivery()\n\n\tdef get_next_delivery(self):\n\t\treturn self.next_delivery\n\n\tdef clean_next_delivery(self):\n\t\tself.next_delivery = []\n\n\tdef get_time(self):\n\t\treturn self.time\n\n\tdef generate_next_delivery(self):\n\t\tself.next_delivery = self.segs.pop(0)\n\t\t\n\tdef encoding_update(self, starting_time, end_time):\n\t\ttemp_time = starting_time\n\t\twhile True:\n\t\t\tnext_time = (int(temp_time/self.seg_duration) + 1) * self.seg_duration\n\t\t\tif next_time > end_time:\n\t\t\t\tbreak\n\t\t\t# Generate segs and insert to encoding buffer\n\t\t\ttemp_time = next_time\n\t\t\tself.current_seg_idx += 1\n\t\t\tself.generate_seg_size()\n\t\t\t\t# print self.current_seg_size\n\t\t\tself.segs.append([self.current_seg_idx, \\\n\t\t\t\t\t\t\t\tself.current_seg_size])\t# for 1s segment\n\t\t\t\n\tdef update(self, downloadig_time):\n\t\tpre_time = self.time\n\t\tself.time += downloadig_time\n\t\tself.encoding_update(pre_time, self.time)\n\t\treturn self.time\n\n\tdef sync_encoding_buffer(self):\n\t\ttarget_encoding_len = 0\n\t\tnew_heading_time = 0.0\n\t\tmissing_count = 0\n\t\ttarget_encoding_len = self.start_up_th/self.seg_duration\n\t\twhile not len(self.segs) == target_encoding_len:\n\t\t\tself.segs.pop(0)\n\t\t\tmissing_count += 1\n\t\tnew_heading_time = self.segs[0][0] * self.seg_duration\n\t\treturn new_heading_time, missing_count\n\n\tdef generate_seg_size(self):\n\t\tself.current_seg_size = [[] for i in range(len(BITRATE))]\n\t\tencoding_coef = 1.0\n\t\testimate_seg_size = [x * encoding_coef for x in BITRATE]\n\t\tself.current_seg_size = estimate_seg_size \n\n\n\tdef wait(self):\n\t\tnext_available_time = (int(self.time/self.seg_duration) + 1) * self.seg_duration\n\t\tself.encoding_update(self.time, next_available_time)\n\t\tassert len(self.segs) == 1\n\t\ttime_interval = next_available_time - self.time\n\t\tself.time = next_available_time\n\t\treturn time_interval \n\n\tdef test_reset(self, start_up_th):\n\t\tself.time = start_up_th + np.random.randint(1,self.seg_duration)\t\t# start from 2000ms\t\n\t\tself.start_up_th = start_up_th\n\t\tself.current_seg_idx = -1\n\t\tself.segs = []\t\n\t\tself.current_seg_size = [[] for i in range(len(BITRATE))]\n\t\tself.encoding_update(0.0, self.time)\n\t\tself.next_delivery = []\n\t\t# self.delay_tol = start_up_th\n\tdef check_segs_empty(self):\n\t\tif len(self.segs) == 0:\n\t\t\treturn True\n\t\telse: return False\n\ndef main():\n\tserver = Live_Server(seg_duration=SEG_DURATION, start_up_th=SERVER_START_UP_TH)\n\tserver.init_encoding()\n\tprint(server.segs, server.time)\n\tprint(server.next_delivery)\n\n\nif __name__ == '__main__':\n\tmain()","sub_path":"mpc_seg_LQR/live_server_seg.py","file_name":"live_server_seg.py","file_ext":"py","file_size_in_byte":3857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"341489049","text":"import sys\nsys.stdin = open('input.txt', 'r')\n\nT = int(input())\n\nfor a in range(T):\n sudoku = []\n for b in range(9):\n sudoku.append(list(map(int, input().split())))\n\n result = 1 # 처음에 스도쿠가 올바른 검증이 되었���고 가정하고 시작\n \n # 가로줄 검사(자료들의 길이로 판별하는 방법) => set()은 중복 요소를 하나로 줄여준다.\n for c in range(9):\n if len(sudoku[c]) != len(set(sudoku[c])):\n result = 0\n break\n\n if result: # 앞에서 0이 나오면 나머지 검사 할 필요 없음\n # 세로줄 검사(0~9까지의 총합으로 판별하는 방법)\n for d in range(9):\n col_list = []\n for e in range(9):\n col_list.append(sudoku[e][d])\n if sum(col_list) != 45:\n result = 0\n break\n\n if result: # 앞에서 0이 나오면 나머지 검사 할 필요 없음\n compare_list = [num for num in range(1, 10)]\n # 3 X 3 형태 검사 (0~9가 모두 있는지 체크하는 방법)\n for f in range(0, 9, 3):\n for g in range(0, 9, 3):\n tri_tri_list = []\n for h in range(f, f+3):\n for i in range(g, g+3):\n tri_tri_list.append(sudoku[h][i])\n if compare_list != sorted(tri_tri_list):\n result = 0\n break\n if not result:\n break\n \n # 끝까지 검사했을 때 오류 없으면 result = 1 그대로 유지됨\n \n print('#{} {}'.format(a + 1, result))","sub_path":"02_algorithm/sw_expert_academy/code_problem/D2/1974.스도쿠 검증/1974.py","file_name":"1974.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"480158061","text":"#!/usr/local/bin/python\r\n# -*- coding: utf-8 -*-\r\nfrom django.http import HttpResponse, HttpResponseRedirect\r\nfrom django.shortcuts import render_to_response\r\nfrom django.template import RequestContext\r\nfrom models import *\r\n\r\nimport calendars\r\nfrom datetime import datetime, date, timedelta\r\n\r\ndef display(request, year, template='calendar.html', extra_context={}):\r\n if not year:\r\n year = datetime.now().year\r\n else:\r\n year = int(year)\r\n \r\n yeartable = calendars.Year(year)\r\n \r\n yeartable.fill_bookings(Item.objects.filter_authorized(request.user))\r\n \r\n context = {'yeartable':yeartable,\r\n 'date_update':date_update(),\r\n 'bookables_by_family':prepare_families(request.session, user=request.user),\r\n 'can_edit':True, 'filter':request.session['filter']}\r\n context.update(extra_context)\r\n response = render_to_response(template, context,\r\n context_instance=RequestContext(request))\r\n return response\r\n\r\ndef edit(request, year, template='calendar.html', extra_context={}):\r\n yeartable = calendars.Year(int(year))\r\n \r\n yeartable.fill_bookings((Item.objects.get(name='Zone A'),))\r\n \r\n context = {'yeartable':yeartable,\r\n 'date_update':date_update(),\r\n 'bookables_by_family':prepare_families(request.session, user=request.user, update_checkboxes=False, edit=True),\r\n 'can_edit':True, 'filter':request.session['filter']}\r\n context.update(extra_context)\r\n response = render_to_response(template, context,\r\n context_instance=RequestContext(request))\r\n return response\r\n\r\ndef add_booking(request, days):\r\n return None\r\n\r\ndef display_filter(request, year, id, value):\r\n if not request.session.has_key('filter'):\r\n request.session['filter'] = {}\r\n if value=='false':\r\n request.session['filter'][id] = False\r\n else:\r\n del request.session['filter'][id]\r\n request.session.modified = True\r\n\r\n return HttpResponseRedirect('../../../')\r\n #return HttpResponse(str(request.session['filter']))\r\n\r\ndef edit_set(request, year, id, days):\r\n datelist = []\r\n for day in days.split(','):\r\n y,m,d = day.split('-')\r\n datelist.append( date(int(y), int(m), int(d)) )\r\n \r\n ranges = get_date_ranges(datelist)\r\n data_object = Item.objects.get(pk=int(id))\r\n for dmin, dmax in ranges:\r\n Booking.objects.create(item=data_object,\r\n user=request.user,\r\n start=dmin, end=dmax)\r\n return HttpResponseRedirect('../../../../')\r\n #return HttpResponse(str(ranges))\r\n\r\ndef prepare_families(session, user=None, update_checkboxes=True, edit=False):\r\n if not session.has_key('filter'):\r\n session['filter'] = {}\r\n flist = []\r\n filter = session['filter']\r\n \r\n for f in GroupItem.objects.all().order_by('sort_order'):\r\n if user:\r\n if edit: permission_name='add'\r\n else: permission_name='read'\r\n oblist = list(Item.objects.filter_authorized(user, permission_name=permission_name).filter(group=f))\r\n else:\r\n oblist = list(f.item_set.all())\r\n \r\n flist.append({'name':f.name, 'items':oblist})\r\n if edit and user:\r\n for ob in oblist:\r\n ob.editable = ob.is_editable_by(user)\r\n if update_checkboxes:\r\n for ob in oblist:\r\n if filter.has_key(u'%d' % ob.pk):\r\n ob.checked = \"\"\r\n else:\r\n ob.checked = \"checked\"\r\n return flist\r\n\r\ndef get_date_ranges(datelist):\r\n dmin = datelist[0]\r\n dmax = dmin\r\n ranges = []\r\n j1 = timedelta(days=1)\r\n for day in datelist[1:]:\r\n if day == dmax + j1:\r\n dmax = day\r\n else:\r\n ranges.append((dmin, dmax))\r\n dmin, dmax = day, day\r\n ranges.append((dmin, dmax))\r\n return ranges\r\n\r\ndef date_update():\r\n return Booking.objects.all().order_by('-date')[0].date","sub_path":"django_booking/booking/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"392339306","text":"import os\nimport time\n\nimport numpy as np\nimport torch\nimport torch.utils.data as data\nfrom scipy.misc import imread\nfrom skimage.transform import AffineTransform, warp\n\nfrom bluntools.image_ops import normalize, adjust_intensity\n\n\ndef _transform(*inputs):\n \"\"\"Affine Transform\"\"\"\n\n *images, lb = *inputs,\n lb = lb.astype(np.float)\n\n bounds = np.deg2rad(3)\n radian = np.random.uniform(low=-bounds, high=bounds)\n factor = np.random.uniform(low=0.9, high=1.1, size=2)\n _trans = np.random.uniform(low=-7, high=7, size=2)\n\n tform = AffineTransform(scale=factor, rotation=radian, shear=radian, translation=_trans)\n *images, lb = [warp(item, tform, mode='reflect', preserve_range=True) for item in [*images, lb]]\n\n return (*images, lb.astype(np.uint8))\n\n\nclass DatasetFromFolder(data.Dataset):\n def __init__(self, mode='train', data_dir='./data/base/', split_index=[40, 47]):\n \"\"\"\n 1. Read one data from file (e.g. using scipy.misc.imread).\n 2. Preprocess the data (e.g. customized functions or torchvision.Transform).\n 3. Return a data pair (e.g. image and label).\n \n Arguments:\n data_dir: path to images and labels, (e.g. 'data_dir/train_image', 'data_dir/train_label')\n split_index: split dataset into train, var, and test subsets\n mode: determine read in which subsets\n \n Assume:\n Filename format: 'X.bmp'\n \"\"\"\n super(DatasetFromFolder, self).__init__()\n assert len(split_index) == 2, \"3 subsets (train, val, test) should have 2 split points.\"\n\n data_dir = [os.path.join(p, 'train_image/') for p in data_dir]\n\n train_image_names = []\n for d in list(data_dir):\n train_image_names += [os.path.join(d, name) for name in os.listdir(d)]\n\n # Set random seed for fixed split\n np.random.seed(7)\n np.random.shuffle(train_image_names)\n\n self.train, self.val, self.test = np.split(train_image_names, split_index)\n\n # self.train, self.val, self.test = np.split(sorted(train_image_names,\n # key=lambda name: int(name[: -4])), split_index)\n\n self.image_path = eval('self.' + mode)\n self.label_path = [p.replace('image', 'label') for p in self.image_path]\n\n def __getitem__(self, index):\n # IMPORTANT, set random seed for ramdom augment\n np.random.seed(int(time.time()))\n\n # Load gray image\n im, lb = [imread(p[index]).squeeze() for p in [self.image_path, self.label_path]]\n\n # Pre-process\n im = normalize(im)\n lb = (lb > 0).astype(np.float32)\n\n # Transform\n im = adjust_intensity(im, low=0.8, high=1.2)\n im, lb = _transform(im, lb)\n\n # inputs: (N, C, H, W)\n im, lb = [item[np.newaxis, ...] for item in [im, lb]]\n\n # Convert to Tensor\n return [torch.from_numpy(item) for item in [im, lb]]\n\n def __len__(self):\n return len(self.image_path)\n\n# --------------------------------------------------------------------------------------------------------------\n# Test for inputs\n# --------------------------------------------------------------------------------------------------------------\n#\n# training_data_loader = data.DataLoader(dataset=DatasetFromFolder(), num_workers=4, batch_size=4, shuffle=True)\n# im, lb = next(iter(training_data_loader))\n# print(im.size())\n\n\n# --------------------------------------------------------------------------------------------------------------\n# Visualize\n# --------------------------------------------------------------------------------------------------------------\n#\n# import visdom\n# vis = visdom.Visdom()\n# vis.images(im.numpy(), opts=dict(title='Random selected images', caption='Shape: {}'.format(im.size())))\n# vis.images(lb.numpy(), opts=dict(title='Random selected labels', caption='Shape: {}'.format(im.size())))\n","sub_path":"Example-Rectus-Femoris-Segmentation/inputs.py","file_name":"inputs.py","file_ext":"py","file_size_in_byte":3948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"614748196","text":"# Copyright 2015, Kay Hayen, mailto:kay.hayen@gmail.com\n#\n# Part of \"Nuitka\", an optimizing Python compiler that is compatible and\n# integrates with CPython, but also works on its own.\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\"\"\" XML node tree handling\n\nMeans to create XML elements from Nuitka tree nodes and to convert the\nXML tree to ASCII or output it.\n\"\"\"\n\nfrom nuitka.utils import Utils\n\nfrom . import Tracing\n\ntry:\n import lxml.etree\n\n Element = lxml.etree.Element\nexcept ImportError:\n lxml = None\n Element = None\n\ndef toString(xml):\n return lxml.etree.tostring(xml, pretty_print = True)\n\ndef dump(xml):\n value = toString(xml).rstrip()\n\n if Utils.python_version >= 300:\n value = value.decode(\"utf-8\")\n\n Tracing.printLine(value)\n","sub_path":"nuitka/TreeXML.py","file_name":"TreeXML.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"566398108","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2015 FingerApp Studio, Inc.\n\nimport errno\nimport logging\nimport logging.handlers\nimport os\n\nfrom memory.shared.controller import SharedManager\nfrom logger.formatter import LogFormatter\n\n\nclass LogManager:\n access = None\n application = None\n general = None\n dblog = None\n\n options = dict(\n log_file_max_size=1024 * 1024,\n log_file_num_backups=100,\n log_to_stderr=False\n )\n\n @staticmethod\n def _enable_pretty_logging(logger=None, options=None, task_id=0):\n if options is None:\n return\n if options[\"logging\"] == \"none\":\n return\n\n if logger is None:\n logger = logging.getLogger()\n\n logger.setLevel(\n getattr(logging, options[\"logging\"].upper()))\n\n if options[\"log_file_prefix\"]:\n channel = logging.handlers.RotatingFileHandler(\n filename=options[\"log_file_prefix\"],\n maxBytes=options[\"log_file_max_size\"],\n backupCount=options[\"log_file_num_backups\"])\n channel.setFormatter(\n LogFormatter(task_id=task_id, color=False))\n logger.addHandler(channel)\n\n # Not used with our LogManager, just keep for possible laster use\n if (LogManager.options[\"log_to_stderr\"] or\n (LogManager.options[\"log_to_stderr\"] is None and\n not logger.handlers)):\n channel = logging.StreamHandler()\n channel.setFormatter(\n LogFormatter(task_id=task_id, color=True))\n logger.addHandler(channel)\n\n @staticmethod\n def _build_canonical_file_path(base_path, filename):\n try:\n if not os.path.isdir(base_path):\n os.makedirs(base_path, 0o755)\n except OSError as e:\n if e.errno == errno.EEXIST and os.path.isdir(base_path):\n pass\n else:\n raise\n\n canonical_file_path = base_path\n if not canonical_file_path.endswith(\"/\"):\n canonical_file_path += \"/\"\n canonical_file_path += filename\n\n return canonical_file_path\n\n @staticmethod\n def enable_access_log():\n # load config\n config_m = SharedManager.get_config()\n config = config_m.config\n task_id = config_m.task_id\n\n LogManager.access = logging.getLogger(\"tornado.access\")\n canonical_file_path = LogManager._build_canonical_file_path(\n base_path=config.logging.access.path,\n filename=config.logging.access.filename\n )\n LogManager.options[\"logging\"] = config.logging.access.level\n LogManager.options[\"log_file_prefix\"] = canonical_file_path\n LogManager._enable_pretty_logging(\n logger=LogManager.access,\n options=LogManager.options,\n task_id=task_id\n )\n\n @staticmethod\n def enable_application_log():\n # load config\n config_m = SharedManager.get_config()\n config = config_m.config\n task_id = config_m.task_id\n\n LogManager.application = logging.getLogger(\"tornado.application\")\n canonical_file_path = LogManager._build_canonical_file_path(\n base_path=config.logging.application.path,\n filename=config.logging.application.filename\n )\n LogManager.options[\"logging\"] = config.logging.application.level\n LogManager.options[\"log_file_prefix\"] = canonical_file_path\n LogManager._enable_pretty_logging(\n logger=LogManager.application,\n options=LogManager.options,\n task_id=task_id\n )\n\n @staticmethod\n def enable_general_log():\n # load config\n config_m = SharedManager.get_config()\n config = config_m.config\n task_id = config_m.task_id\n\n LogManager.general = logging.getLogger(\"tornado.general\")\n canonical_file_path = LogManager._build_canonical_file_path(\n base_path=config.logging.general.path,\n filename=config.logging.general.filename\n )\n LogManager.options[\"logging\"] = config.logging.general.level\n LogManager.options[\"log_file_prefix\"] = canonical_file_path\n LogManager._enable_pretty_logging(\n logger=LogManager.general,\n options=LogManager.options,\n task_id=task_id\n )\n\n @staticmethod\n def enable_http_log():\n # access log\n LogManager.enable_access_log()\n\n # application log\n LogManager.enable_application_log()\n\n # general log\n LogManager.enable_general_log()\n\n @staticmethod\n def enable_db_log():\n # load config\n config_m = SharedManager.get_config()\n config = config_m.config\n task_id = config_m.task_id\n\n LogManager.dblog = logging.getLogger(\"pushgram.mysql\")\n canonical_file_path = LogManager._build_canonical_file_path(\n base_path=config.logging.mysql.path,\n filename=config.logging.mysql.filename\n )\n LogManager.options[\"logging\"] = config.logging.mysql.level\n LogManager.options[\"log_file_prefix\"] = canonical_file_path\n LogManager._enable_pretty_logging(\n logger=LogManager.dblog,\n options=LogManager.options,\n task_id=task_id\n )\n\n @staticmethod\n def _get_access():\n if not LogManager.access:\n LogManager.enable_access_log()\n return LogManager.access\n\n @staticmethod\n def _get_application():\n if not LogManager.application:\n LogManager.enable_application_log()\n return LogManager.application\n\n @staticmethod\n def _get_general():\n if not LogManager.general:\n LogManager.enable_general_log()\n return LogManager.general\n\n @staticmethod\n def _get_dblog():\n if not LogManager.dblog:\n LogManager.enable_db_log()\n return LogManager.dblog\n\n @staticmethod\n def get_instance(logger_name):\n if logger_name is None:\n return None\n\n logger_map = {\n \"access\": LogManager._get_access,\n \"application\": LogManager._get_application,\n \"general\": LogManager._get_general,\n \"dblog\": LogManager._get_dblog\n }\n if logger_name in logger_map:\n return logger_map[logger_name]()\n else:\n return logging.getLogger()\n","sub_path":"logger/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":6431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"614179037","text":"from dsbox.template.template import DSBoxTemplate \nfrom d3m.metadata.problem import TaskKeyword \nfrom dsbox.template.template_steps import TemplateSteps \nfrom dsbox.schema import SpecializedProblem \nimport typing \nimport numpy as np # type: ignore \nclass DataAugmentRegressionTemplate(DSBoxTemplate):\n def __init__(self):\n DSBoxTemplate.__init__(self)\n\n self.template = {\n \"name\": \"data_augment_regression_template\",\n \"taskType\": TaskKeyword.REGRESSION.name,\n \"taskSubtype\": {TaskKeyword.UNIVARIATE.name, TaskKeyword.MULTIVARIATE.name, \"NONE\"},\n \"inputType\": \"table\", # See SEMANTIC_TYPES.keys() for range of values\n \"output\": \"model_step\", # Name of the final step generating the prediction\n \"target\": \"extract_target_step\", # Name of the step generating the ground truth\n \"steps\": [\n {\n \"name\": \"to_dataframe_step\",\n \"primitives\": [\"d3m.primitives.data_transformation.dataset_to_dataframe.Common\"],\n \"inputs\": [\"template_input\"]\n },\n {\n \"name\": \"common_profiler_step\",\n \"primitives\": [\"d3m.primitives.schema_discovery.profiler.Common\"],\n \"inputs\": [\"to_dataframe_step\"]\n },\n {\n \"name\": \"extract_attribute_step\",\n \"primitives\": [{\n \"primitive\": \"d3m.primitives.data_transformation.extract_columns_by_semantic_types.Common\",\n \"hyperparameters\":\n {\n 'semantic_types': (\n 'https://metadata.datadrivendiscovery.org/types/PrimaryKey',\n 'https://metadata.datadrivendiscovery.org/types/Attribute',),\n 'use_columns': (),\n 'exclude_columns': ()\n }\n }],\n \"inputs\": [\"common_profiler_step\"]\n },\n {\n \"name\": \"extract_target_step\",\n \"primitives\": [{\n \"primitive\": \"d3m.primitives.data_transformation.extract_columns_by_semantic_types.Common\",\n \"hyperparameters\":\n {\n 'semantic_types': (\n 'https://metadata.datadrivendiscovery.org/types/TrueTarget',),\n 'use_columns': (),\n 'exclude_columns': ()\n }\n }],\n \"inputs\": [\"to_dataframe_step\"]\n },\n {\n \"name\": \"target_process_step\",\n \"primitives\": [{\n \"primitive\": \"d3m.primitives.data_transformation.to_numeric.DSBOX\",\n \"hyperparameters\": {\n \"drop_non_numeric_columns\": [False]\n }\n }],\n \"inputs\": [\"extract_target_step\"]\n },\n {\n \"name\": \"profile_step\",\n \"primitives\": [\"d3m.primitives.schema_discovery.profiler.DSBOX\"],\n \"inputs\": [\"extract_attribute_step\"]\n },\n {\n \"name\": \"clean_step\",\n \"primitives\": [\n \"d3m.primitives.data_preprocessing.do_nothing.DSBOX\"\n ],\n \"inputs\": [\"profile_step\"]\n },\n {\n \"name\": \"encode_text_step\",\n \"primitives\": [\n {\n \"primitive\": \"d3m.primitives.feature_construction.corex_text.DSBOX\",\n \"hyperparameters\":\n {\n 'n_hidden': [(10)],\n 'threshold': [(500)],\n 'n_grams': [(1)],\n 'max_df': [(.9)],\n 'min_df': [(.02)],\n }\n },\n ],\n \"inputs\": [\"clean_step\"]\n },\n {\n \"name\": \"encoder_step\",\n \"primitives\": [\n \"d3m.primitives.data_cleaning.label_encoder.DSBOX\"\n ],\n \"inputs\": [\"encode_text_step\"]\n },\n {\n \"name\": \"impute_step\",\n \"primitives\": [\"d3m.primitives.data_preprocessing.mean_imputation.DSBOX\"],\n \"inputs\": [\"encode_text_step\"]\n },\n {\n \"name\": \"model_step\",\n \"primitives\": [\n {\n \"primitive\" : \"d3m.primitives.regression.gradient_boosting.SKlearn\",\n \"hyperparameters\":\n {\n 'use_semantic_types': [True],\n 'add_index_columns': [True],\n }\n },\n ],\n \"inputs\": [\"encode_text_step\", \"target_process_step\"]\n },\n\n\n ]\n }\n\n\n","sub_path":"python/dsbox/template/template_files/not_loaded/DataAugmentRegressionTemplate.py","file_name":"DataAugmentRegressionTemplate.py","file_ext":"py","file_size_in_byte":5161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"381099858","text":"print('Exercício 5.4')\r\n\r\ndef maximo():\r\n p=0 \r\n x=[]\r\n t=[]\r\n while p<5:\r\n y=(input('Digite um número: '))\r\n x.append(y)\r\n p+=1\r\n print(x)\r\n pro=input('Digite um valor que deve ser encontrado na lista: ')\r\n if pro in x :\r\n print('Sim,este número está na sua lista.')\r\n else:\r\n print('Este número não está em sua lista.')\r\n\r\n## for k in x: \r\n## if k==pro:\r\n## print('Temos esse número na Lista')\r\n## else:\r\n## print('Não temos esse número na lista')\r\n## \r\n## print(pro) \r\nmaximo()\r\n","sub_path":"Ex5.4.py","file_name":"Ex5.4.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"367467212","text":"import requests\nfrom bs4 import BeautifulSoup\n\nimport os\nimport sys\nfrom googleapiclient import discovery as d\nfrom googleapiclient.errors import HttpError\nfrom oauth2client.tools import argparser\n#https://open.spotify.com/playlist/18rXN0wAkX2q3A6ynu8aZ5?si=9BoYLhuZQXOJzEqtrO32rQ\n\ndef getSongs(url):\n if(\"spotify.com/playlist\" not in url): \n raise Exception(\"Must be a spotify playlist url\")\n \n try:\n spl = BeautifulSoup(requests.get(url).text, 'html.parser').prettify().split(\"\\n\")\n\n songs = []\n index = 0\n for j in spl:\n if(\"music:song\\\"\" in j):\n songLink = j.split(\"\\\"\")[1]\n song = BeautifulSoup(requests.get(songLink).text, 'html.parser').prettify().split('\\n')\n for i in song:\n if(\"twitter:title\" in i):\n title = i.split(\"\\\"\")[1]\n if(\"twitter:audio:artist_name\" in i):\n artist = i.split(\"\\\"\")[1]\n if(\"twitter:image\" in i):\n image = i.split(\"\\\"\")[1]\n songs.append([title, artist, image])\n index += 1\n return songs\n except requests.exceptions.RequestException as e:\n print(e)\n \n\ndef getYoutubeLinks(songs):\n songUrls = []\n SERVICE = \"youtube\"\n API = \"v3\"\n\n songLinks = []\n with open(os.path.join(sys.path[0], \"key.txt\")) as f:\n keys = []\n for i in f:\n keys.append(i.strip(\"\\n\"))\n\n currKey = 0\n for i in songs:\n while(currKey < len(keys)):\n try:\n youtube = d.build(SERVICE, API, developerKey=keys[currKey])\n response = youtube.search().list(\n q = i[0] + \" \" + i[1],\n type = \"video\",\n part = \"id, snippet\",\n maxResults = 1\n ).execute()\n songLinks.append([response[\"items\"][0][\"snippet\"][\"title\"], \"https://www.youtube.com/watch?v=\" + response[\"items\"][0][\"id\"][\"videoId\"], i[2]])\n break\n except HttpError as e:\n currKey += 1\n pass \n return songLinks\n \ndef main():\n print(\"Enter spotify playlist\")\n # url = input()\n url = \"https://open.spotify.com/playlist/18rXN0wAkX2q3A6ynu8aZ5?si=9BoYLhuZQXOJzEqtrO32rQ\"\n songs = getSongs(url)\n if(not songs):\n print(\"Error: Invalid playlist link\") \n else:\n links = getYoutubeLinks(songs)\n if(not links):\n print(\"Error: quota reached, try again tomorrow\")\n else:\n for i in links:\n print(i[0] + \" \" + i[1] + \" \" + i[2])\n\nif __name__ == \"__main__\":\n main()","sub_path":"spotbot.py","file_name":"spotbot.py","file_ext":"py","file_size_in_byte":2799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"548778395","text":"\n\n#calss header\nclass _CORUSCATING():\n\tdef __init__(self,): \n\t\tself.name = \"CORUSCATING\"\n\t\tself.definitions = [u'flashing brightly', u'extremely intelligent and exciting or humorous: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_coruscating.py","file_name":"_coruscating.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"596083190","text":"\"\"\"Contains tools to read kpoints and bands from EIGENVALUE files.\"\"\"\n\nimport re\n\nimport numpy as np\n\nfrom .parser import BaseParser\n\n\nclass EigParser(BaseParser):\n \"\"\"Contains regex and functions to find grammar elements in EIGENVALUE files.\"\"\"\n\n def __init__(self, filename):\n res = self.parse_eigenval(filename)\n self.header = res[0]\n self.kpoints = res[1]\n self.bands = res[2]\n\n @classmethod\n # pylint: disable=too-many-locals\n def parse_eigenval(cls, filename):\n \"\"\"Parse a VASP EIGENVAL file and extract metadata and a band structure data array\"\"\"\n with open(filename) as eig:\n line_0 = cls.line(eig, int) # read header\n line_1 = cls.line(eig, float) # \"\n line_2 = cls.line(eig, float) # \"\n coord_type = cls.line(eig) # \"\n name = cls.line(eig) # read name line (can be empty)\n param_0, num_kp, num_bands = cls.line(eig, int) # read: ? #kp #bands\n data = eig.read() # rest is data\n num_ions, num_atoms, p00, num_spins = line_0\n data = re.split(cls.empty_line, data) # list of data blocks\n data = [[line.split() for line in block.splitlines()] for block in data]\n kpoints = np.zeros((num_kp, 4))\n bands = np.zeros((num_spins, num_kp, num_bands))\n for k, field in enumerate(data): # iterate over data blocks\n kpbs = filter(None, field) # throw away empty lines\n kpi = map(float, kpbs.pop(0)) # first line of block is kpoints -> pop\n kpoints[k] = kpi\n for point in kpbs: # rest are band energies\n bands[:, k, int(point[0]) - 1] = point[1:num_spins + 1] # place energy value in bands[kp, nb] (BandstrucureData format)\n header = {} # build header dict\n header[0] = line_0\n header[1] = line_1\n header[2] = line_2\n header['n_ions'] = num_ions\n header['n_atoms'] = num_atoms\n header['p00'] = p00\n header['nspin'] = num_spins\n header['cartesian'] = coord_type.startswith(('c', 'C'))\n header['name'] = name\n header['some_num'] = param_0\n header['n_bands'] = num_bands\n header['n_kp'] = num_kp\n\n return header, kpoints, bands\n","sub_path":"aiida_vasp/io/eigenval.py","file_name":"eigenval.py","file_ext":"py","file_size_in_byte":2267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"233401248","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport logging\n\nlogger = logging.getLogger('TEST-LOG') #定义一个输出日志的函数名字,自定义,默认输出到当前屏幕\nlogger.setLevel(logging.DEBUG) #设置最低输出等级\nlogger.warning('这是测试')\n\npm = logging.StreamHandler() #向当前屏幕输出信息\npm.setLevel(logging.WARNING) #设定屏幕最低输出等级,低于这个等级的就不会向屏幕输出\n\nwj = logging.FileHandler('测试.log',encoding='utf-8') #向文件输出信息,即是写入文件,默认方式为a+\nwj.setLevel(logging.WARNING) #设定错误级别以上的才写入文件\n\nformatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s %(lineno)d','%m/%d/%Y %I:%M:%S %p') #设定输出格式,时间 信息等级 信息 第几行代码\n\npm.setFormatter(formatter) #设置屏幕的输出格式为上面formatter设置的格式\nwj.setFormatter(formatter) #设置文件的输出格式为上面formatter设置的格式\n\nlogger.addHandler(pm) #添加向屏幕输出信息\nlogger.addHandler(wj) #添加向文件写入信息\n\nlogger.info('测试这个会不会输出-info')\nlogger.warning('测试这个会不会输出-warning')\nlogger.error('测试这个会不会输出-error')","sub_path":"Modular_two/log多输出.py","file_name":"log多输出.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"425400292","text":"from BaseLayers import *\n\n\nclass MultiGpuModel(nn.DataParallel):\n \"\"\"\n Wrapper to model class for using multi-gpu model.\n \"\"\"\n def __getattr__(self, name):\n try:\n return super().__getattr__(name)\n except AttributeError:\n return getattr(self.module, name)\n\n\nclass DDNet(nn.Module):\n\n def __init__(self, params):\n super().__init__()\n self.inputs_channels = params['inputs_channels_list']\n self.kernels = params['kernels_list']\n self.num_levels = params['num_levels']\n self.base_num_filters = params['base_num_filters']\n self.bottleneck_layers = params['bottleneck_layers']\n self.out_channels = params['out_channels']\n self.attention = params['attention']\n self.attention_heads = params['attention_heads']\n\n assert len(self.kernels) == len(self.inputs_channels), 'Kernels list and inputs channels list must be the ' \\\n 'same length '\n\n # Encoder\n self.encoders = nn.ModuleList([])\n for c, k in zip(self.inputs_channels, self.kernels):\n axes = {(1, 9): 'x', (9, 1): 'y', (3, 3): 'xy'}\n self.encoders.append(Encoder(c, k, self.num_levels, self.base_num_filters, self.attention, self.attention_heads, axes=axes[k]))\n\n # Bottleneck\n self.bottleneck = Bottleneck(self.bottleneck_layers, 2**(self.num_levels - 1)*self.base_num_filters * len(self.inputs_channels),\n 2**self.num_levels*self.base_num_filters)\n\n # Decoder\n self.decoder = Decoder((2**self.num_levels)*self.base_num_filters, len(self.inputs_channels), self.num_levels, 3)\n self.final_layer = FinalLayer(self.base_num_filters, self.out_channels)\n\n def forward(self, x):\n enc_out = None\n skips = [[]] * self.num_levels\n for i, enc in enumerate(self.encoders):\n s, e = enc(x[i])\n\n for j, level in enumerate(s):\n skips[j] = level if not len(skips[j]) else torch.cat([skips[j], level], dim=1)\n\n enc_out = e if enc_out is None else torch.cat([enc_out, e], dim=1)\n\n bottleneck_out = self.bottleneck(enc_out)\n dec_out = self.decoder(bottleneck_out, skips)\n out_cube = self.final_layer(dec_out)\n\n return out_cube\n\n\n\n","sub_path":"Models.py","file_name":"Models.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"628309896","text":"from functools import reduce\ndef is_valid_email(s):\n address = s[:s.find('@')]\n domain = s[s.find('@')+1:s.find('.')]\n extension = s[s.find('.')+1:]\n #print(address)\n #print(domain)\n #print(extension)\n #print(reduce(And,[element.isalnum() or element == '-' or element =='_' for element in address]) and domain.isalnum() and len(extension) == 3 and extension.isalnum())\n return reduce(And,[element.isalnum() or element == '-' or element =='_' for element in address]) and domain.isalnum() and len(extension) == 3 and extension.isalnum()\ndef And(a,b):\n return a and b\n\nN = int(input())\nL = []\nfor i in range(N):\n L.append(input())\n #print()\n #print(L)\nnew_L = list(filter(is_valid_email,L))\nnew_L.sort()\nprint(new_L)\n","sub_path":"Python/valid_email.py","file_name":"valid_email.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"345553673","text":"# -*- coding: utf-8 -*-\n\nimport pygame\n\nCOLOR_DEFAULT_BUTTON = (150, 150, 150)\nCOLOR_DEFAULT_BUTTON_TEXT = (255, 255, 255)\nCOLOR_PRESSED_BUTTON_TEXT = (255, 0, 0)\nCOLOR_MOD_BUTTON_TEXT = (0, 255, 0)\nBUTTON_TEXT_MARGIN_LEFT = 4\n\nclass Command:\n \"\"\"\n A command.\n \"\"\"\n def __init__(self, cmd_name: str, arguments: dict):\n self.cmd_name = cmd_name\n self.arguments = arguments\n\n def execute(self, bid: int, context: dict):\n \"\"\"Execute the command.\"\"\"\n pass\n\n @classmethod\n def cmd_nop(cls):\n return cls(cmd_name=\"nop\", arguments={})\n\n\nclass GuiRctElement:\n def __init__(self, pos_x: int, pos_y: int, width: int, height: str):\n self.pos_x = pos_x\n self.pos_y = pos_y\n self.width = width\n self.height = height\n\n def draw(self):\n raise NotImplementedError()\n\n\nclass ModeButton(GuiRctElement):\n def __init__(\n self,\n pos_x: int,\n pos_y: int,\n width: int,\n height: int,\n bid: int,\n title: str,\n cmd_push: Command,\n cmd_release: Command\n ):\n self.bid = bid\n self.title = title\n self.default_cmd_push = cmd_push\n self.default_cmd_release = cmd_release\n self.down = False\n self.reset()\n super().__init__(pos_x, pos_y, width, height)\n\n def draw(self, context):\n text_color = COLOR_DEFAULT_BUTTON_TEXT if not self.down else COLOR_PRESSED_BUTTON_TEXT\n if self.cmd_push is not self.default_cmd_push:\n text_color = COLOR_MOD_BUTTON_TEXT\n text = context[\"font_main\"].render(self.title, True, text_color)\n pygame.draw.rect(\n context[\"screen\"],\n COLOR_DEFAULT_BUTTON,\n (self.pos_x, self.pos_y, self.width, self.height),\n )\n context[\"screen\"].blit(text, (self.pos_x + BUTTON_TEXT_MARGIN_LEFT, self.pos_y))\n\n def push(self, context: dict):\n self.down = True\n self.cmd_push.execute(self.bid, context)\n\n def release(self, context):\n self.down = False\n self.cmd_release.execute(self.bid, context)\n\n def reset(self):\n self.cmd_push = self.default_cmd_push\n self.cmd_release = self.default_cmd_release\n\n def set_commands(self, cmd_push, cmd_release):\n self.cmd_push = cmd_push\n self.cmd_release = cmd_release\n\n def set_cmd_push(self, cmd_push):\n self.cmd_push = cmd_push\n\n\ndef construct_test_button(pos_x: int, pos_y: int, bid: int, title: str):\n btn = ModeButton(\n pos_x,\n pos_y,\n width=50,\n height=20,\n bid=bid,\n title=title,\n cmd_push=Command.cmd_nop(),\n cmd_release=Command.cmd_nop(),\n )\n return btn\n","sub_path":"hsampler/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":2723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"27376469","text":"import os\nimport csv\n\n#filepath = os.path.join(\"Resources\", \"employees.csv\")\nfilepath = \"employee_data1.csv\"\nfilename = \"new_employee_data.csv\"\n#filepath2 = \"C:\\\\Users\\\\Hannah\\\\Desktop\\\\UT Data 2018 HW\\May 5 Python\\\\employee_data2.csv\"\n#filename2 = \"employee_data2\"\n\ndef reformat_date(yyyymmdd):\n date_parts = yyyymmdd.split(\"-\")\n yyyy = date_parts[0]\n mm = date_parts[1]\n dd = date_parts[2]\n return mm + \"/\" + dd + \"/\" + yyyy \n\ndef mask_ssn(social):\n return \"***-**-\" + social[-4:]\n\ndef get_abbreviation(full_state):\n us_state_abbrev = {\n 'Alabama': 'AL',\n 'Alaska': 'AK',\n 'Arizona': 'AZ',\n 'Arkansas': 'AR',\n 'California': 'CA',\n 'Colorado': 'CO',\n 'Connecticut': 'CT',\n 'Delaware': 'DE',\n 'Florida': 'FL',\n 'Georgia': 'GA',\n 'Hawaii': 'HI',\n 'Idaho': 'ID',\n 'Illinois': 'IL',\n 'Indiana': 'IN',\n 'Iowa': 'IA',\n 'Kansas': 'KS',\n 'Kentucky': 'KY',\n 'Louisiana': 'LA',\n 'Maine': 'ME',\n 'Maryland': 'MD',\n 'Massachusetts': 'MA',\n 'Michigan': 'MI',\n 'Minnesota': 'MN',\n 'Mississippi': 'MS',\n 'Missouri': 'MO',\n 'Montana': 'MT',\n 'Nebraska': 'NE',\n 'Nevada': 'NV',\n 'New Hampshire': 'NH',\n 'New Jersey': 'NJ',\n 'New Mexico': 'NM',\n 'New York': 'NY',\n 'North Carolina': 'NC',\n 'North Dakota': 'ND',\n 'Ohio': 'OH',\n 'Oklahoma': 'OK',\n 'Oregon': 'OR',\n 'Pennsylvania': 'PA',\n 'Rhode Island': 'RI',\n 'South Carolina': 'SC',\n 'South Dakota': 'SD',\n 'Tennessee': 'TN',\n 'Texas': 'TX',\n 'Utah': 'UT',\n 'Vermont': 'VT',\n 'Virginia': 'VA',\n 'Washington': 'WA',\n 'West Virginia': 'WV',\n 'Wisconsin': 'WI',\n 'Wyoming': 'WY',\n }\n return us_state_abbrev[full_state]\n\nnew_employee_data = []\n\n\nwith open(filepath) as csvfile:\n reader = csv.DictReader(csvfile)\n\n for row in reader:\n print(row)\n full_name = row[\"Name\"]\n name_parts = full_name.split(\" \")\n first_name = name_parts[0]\n last_name = name_parts[1]\n new_employee_data.append({\n \"Emp ID\": row[\"Emp ID\"],\n \"DOB\": reformat_date(row[\"DOB\"]),\n \"First Name\": first_name,\n \"Last Name\": last_name,\n \"SSN\": mask_ssn(row[\"SSN\"]),\n \"State\": get_abbreviation(row[\"State\"])\n })\n print(new_employee_data)\n\n# Grab the filename from the original path\n\n\n# Write updated data to csv file\ncsvpath = os.path.join(\"output\", filename)\nwith open(csvpath, \"w\") as csvfile:\n fieldnames = [\"Emp ID\", \"First Name\", \"Last Name\", \"SSN\", \"DOB\", \"State\"]\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n writer.writerows(new_employee_data)\n","sub_path":"PyBoss/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"524313930","text":"\"\"\"\nGiven an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.\n\nHere, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.\n\nFollow up:\n\nCould you solve this problem without using the library's sort function?\nCould you come up with a one-pass algorithm using only O(1) constant space?\n\nInput: nums = [2,0,2,1,1,0]\nOutput: [0,0,1,1,2,2]\n\n\"\"\"\n\nclass Solution:\n def sortColors(self, nums: List[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n low=mid=0\n high=len(nums)-1\n while(mid<=high):\n if(nums[mid]==0):\n nums[low],nums[mid]=nums[mid],nums[low]\n low+=1\n mid+=1\n elif(nums[mid]==1):\n mid+=1\n else:\n nums[mid],nums[high]=nums[high],nums[mid]\n high-=1\n return nums\n\n# Time Complexity = O(n)\n# Space Complexity = O(1)\n","sub_path":"sortColors.py","file_name":"sortColors.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"254070355","text":"import math\r\n\r\nclass IFLeg:\r\n def __init__(self, wpt):\r\n self.type = 'IF'\r\n self.seq = 0\r\n self.waypoint = wpt\r\n self.routeSeq = 0\r\n\r\n\r\n def message(self):\r\n message = \"SEQ=\" + str(self.seq) + \" TYPE=\" + self.type + \" ID=\" + self.waypoint.id + \" LAT=\" + self.waypoint.latitude + \" LONG=\" + self.waypoint.longitude\r\n return message\r\n\r\nclass TFLeg:\r\n def __init__(self, Wpt1, Wpt2, seq, minaltitude, maxaltitude, RouteSeq):\r\n self.type = 'TF'\r\n self.seq = seq\r\n self.routeSeq = RouteSeq\r\n self.waypointStart = Wpt1\r\n self.waypoint = Wpt2\r\n self.course = int(self.calcul_course())\r\n self.distance = int(self.calcul_distance())\r\n\r\n if minaltitude != \"\":\r\n self.minaltitude = minaltitude\r\n else:\r\n self.minaltitude = \"FL000\"\r\n\r\n if maxaltitude != \"\":\r\n self.maxaltitude = maxaltitude\r\n else:\r\n self.maxaltitude = \"FL460\"\r\n\r\n def setSeq(self, newSeq):\r\n self.seq = newSeq\r\n pass\r\n\r\n def calcul_course(self):\r\n latA, longA = math.radians(self.waypointStart.norm_latitude), math.radians(self.waypointStart.norm_longitude)\r\n latB, longB = math.radians(self.waypoint.norm_latitude), math.radians(self.waypoint.norm_longitude)\r\n X = math.cos(latB)*math.sin(longB-longA)\r\n Y = math.cos(latA)*math.sin(latB) - math.sin(latA)*math.cos(latB)*math.cos(longB-longA)\r\n course = math.atan2(X, Y)\r\n return math.degrees(course)%360\r\n\r\n def calcul_distance(self):\r\n latA, longA = math.radians(self.waypointStart.norm_latitude), math.radians(self.waypointStart.norm_longitude)\r\n latB, longB = math.radians(self.waypoint.norm_latitude), math.radians(self.waypoint.norm_longitude)\r\n distance = 60 * math.degrees(math.acos(math.cos(latA)*math.cos(latB)*math.cos(longB-longA) + math.sin(latA)*math.sin(latB)))\r\n return distance\r\n\r\n def message(self):\r\n message = \"SEQ=\" + str(self.seq) + \" TYPE=\" + self.type + \" ID=\" + self.waypoint.id + \" WPT_TYPE=\" + self.waypoint.type + \" LAT=\" + self.waypoint.latitude + \" LONG=\" + self.waypoint.longitude + \" COURSE=\" + str(self.course) + \" DISTANCE=\" + str(self.distance) + \" FLmin=\" + self.minaltitude + \" FLmax=\" + self.maxaltitude\r\n #message = \"ID=\" + self.waypoint.id + \" SEQ=\" + str(self.seq) + \" LAT=\" + self.waypoint.latitude + \" LON=\" + self.waypoint.longitude + \" COURSE=\" + str(self.course) + \" FLY=\" + self.waypoint.type + \" FLmin=\" + self.minaltitude + \" FLmax=\" + self.maxaltitude + \" SPEEDmax=000\"\r\n return message","sub_path":"FPLN_LEGS/Leg.py","file_name":"Leg.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"202589783","text":"from sheetfu.client import SpreadsheetApp\nfrom sheetfu.model import Spreadsheet, Sheet, Range\nfrom tests.utils import mock_range_instance, mock_spreadsheet_instance, mock_google_sheets_responses\nfrom tests.utils import open_fixture\nimport json\n\n\nclass TestModelClients:\n\n http_sheets_mocks = mock_range_instance()\n\n client = SpreadsheetApp(http=http_sheets_mocks)\n spreadsheet = client.open_by_id('some_id')\n sheet = spreadsheet.get_sheet_by_name(\"people\")\n my_range = sheet.get_range(1, 1)\n\n def test_instances(self):\n assert isinstance(self.client, SpreadsheetApp)\n assert isinstance(self.spreadsheet, Spreadsheet)\n assert isinstance(self.sheet, Sheet)\n assert isinstance(self.my_range, Range)\n\n def test_client_is_in_every_object(self):\n assert self.client is self.spreadsheet.client\n assert self.client is self.sheet.client\n assert self.client is self.my_range.client\n\n\nclass TestSpreadsheet:\n\n http_sheets_mocks = mock_spreadsheet_instance([\"add_sheets.json\"])\n spreadsheet = SpreadsheetApp(http=http_sheets_mocks).open_by_id('some_id')\n\n def test_get_sheets(self):\n sheets = self.spreadsheet.sheets\n assert len(sheets) == 2\n for sheet in sheets:\n assert isinstance(sheet, Sheet)\n\n def test_create_sheets(self):\n self.spreadsheet.create_sheets([\"test_sheet\", \"test_sheet_2\"])\n assert len(self.spreadsheet.sheets) == 4\n\n def test_add_sheets_from_response(self):\n dummy_response_create = json.loads(open_fixture(\"add_sheets.json\"))\n self.spreadsheet._add_sheets_from_response(response=dummy_response_create, reply_type=\"addSheet\")\n assert len(self.spreadsheet.sheets) == 6\n dummy_response_duplicate = json.loads(open_fixture(\"duplicate_sheets.json\"))\n self.spreadsheet._add_sheets_from_response(response=dummy_response_duplicate, reply_type=\"duplicateSheet\")\n assert len(self.spreadsheet.sheets) == 7\n\n\nclass TestGettersFromDataRange:\n\n fixtures = ['get_backgrounds.json', 'get_notes.json', 'get_fonts.json']\n http_sheets_mocks = mock_range_instance(fixtures)\n client = SpreadsheetApp(http=http_sheets_mocks)\n data_range = client.open_by_id('spreadsheet id').get_sheet_by_name('people').get_data_range()\n\n def test_a1_notation_is_right(self):\n assert self.data_range.a1 == \"A1:D21\"\n\n def test_get_backgrounds(self):\n backgrounds = self.data_range.get_backgrounds()\n assert type(backgrounds) == list\n assert len(backgrounds) == self.data_range.coordinates.number_of_rows\n for row in backgrounds:\n assert len(row) == self.data_range.coordinates.number_of_columns\n\n\nclass TestCellRange:\n\n http_sheets_mocks = mock_range_instance()\n client = SpreadsheetApp(http=http_sheets_mocks)\n data_range = client.open_by_id('spreadsheet id').get_sheet_by_name('people').get_data_range()\n\n def test_a1(self):\n assert self.data_range.a1 == 'A1:D21'\n\n def test_get_cell(self):\n assert self.data_range.get_cell(1, 1).a1 == 'A1'\n assert self.data_range.get_cell(1, 2).a1 == 'B1'\n assert self.data_range.get_cell(2, 1).a1 == 'A2'\n\n\nclass TestGridRange:\n\n http_sheets_mocks = mock_spreadsheet_instance()\n spreadsheet = SpreadsheetApp(http=http_sheets_mocks).open_by_id('some_id')\n sheet = spreadsheet.sheets[0]\n\n def test_grid_range_one_cell(self):\n cell = self.sheet.get_range_from_a1('A1')\n assert cell.a1 == 'A1'\n cell_grid_range = cell.get_grid_range()\n assert cell_grid_range['startRowIndex'] == 0\n assert cell_grid_range['endRowIndex'] == 1\n assert cell_grid_range['startColumnIndex'] == 0\n assert cell_grid_range['endColumnIndex'] == 1\n\n def test_grid_range_multiple_cells(self):\n range_ = self.sheet.get_range_from_a1('A3:B4')\n assert range_.a1 == 'A3:B4'\n grid_range = range_.get_grid_range()\n assert grid_range['startRowIndex'] == 2\n assert grid_range['endRowIndex'] == 4\n assert grid_range['startColumnIndex'] == 0\n assert grid_range['endColumnIndex'] == 2\n\n","sub_path":"tests/test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":4143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"88011025","text":"#!/usr/bin/python\n\nfrom __future__ import absolute_import, division, print_function\nimport PyU4V\nfrom ansible.module_utils.basic import *\nfrom ansible.module_utils.urls import *\n__metaclass__ = type\n#TODO Add checks to make sure SRDF is not already in requested state\n\nANSIBLE_METADATA = {'metadata_version': '1.0',\n 'status': ['preview'],\n 'supported_by': 'VMAX REST API Community '\n 'https://community.emc.com/docs/DOC-56447'\n }\nDOCUMENTATION = r'''\n---\nmodule: dellpmax_manage_srdf\n\ncontributors: Paul Martin, Rob Mortell\n\nsoftware versions=ansible 2.6.3\n python version = 2.7.15rc1 (default, Apr 15 2018,\n\nshort_description: \n - Module to control SRDF state of storage group, supported actions are \n failover, failback, split, suspend, establish. Requires that storage \n group must exist and have RDF replication already configured and \n running. Single Site SRDF support only in module. \n \n\n\n\nnotes:\n - This module has been tested against UNI 9.0. Every effort has been\n made to verify the scripts run with valid input. These modules\n are a tech preview. Additional error handling will be added at a later\n date, base functionality only right now.\n\nRequirements:\n - Ansible, Python 2.7, Unisphere for PowerMax version 9.0 or higher.\n VMAX All Flash, VMAX3, or PowerMax storage Array\n\nplaybook options:\n Note:- Some Options are repeated across modules, we will look at\n reducing these in future work, however you can use variables in your\n playbook at the outset and reference in the task to reduce error,\n this also allows flexibility in versioning within a single playbook.\n\n unispherehost:\n description:\n - Full Qualified Domain Name or IP address of Unisphere for\n PowerMax host.\n required:True\n\n universion:\n -description:\n - Integer, version of unipshere software\n https://{HostName|IP}:8443/univmax/restapi/{version}/{resource}\n 90 is the release at time of writing module.\n -required:True\n verifycert:\n description:\n -Boolean, securitly check on ssl certificates\n required:True\n\n required: True\n sgname:\n description:\n - Storage Group name\n required:True\n array_id:\n description:\n - Integer 12 Digit Serial Number of PowerMAX or VMAX array.\n required:True\n \n'''\n\nEXAMPLES = r'''\n- name: Create SnapVX SnapShot of existing Storage Group\n hosts: localhost\n connection: local\n no_log: True\n vars:\n unispherehost: '192.168.156.63'\n universion: \"90\"\n verifycert: False\n user: 'smc'\n password: 'smc'\n\n\n tasks:\n - name: Split SRDF\n dellpmax_manage_srdf:\n unispherehost: \"{{unispherehost}}\"\n universion: \"{{universion}}\"\n verifycert: \"{{verifycert}}\"\n user: \"{{user}}\"\n password: \"{{password}}\"\n array_id: '000197600156'\n sgname: 'Ansible_SG'\n action: 'Split'\n'\n\nRETURN = r'''\n\n\n\ndef main():\n changed = False\n module = AnsibleModule(\n argument_spec=dict(\n unispherehost=dict(required=True),\n universion=dict(type='int', required=False),\n verifycert=dict(type='bool', required=True),\n user=dict(type='str', required=True),\n password=dict(type='str', required=True, no_log=True),\n array_id=dict(type='str', required=True),\n sgname=dict(type='str', required=True),\n action=dict(type='str',choices=['Establish','Suspend','Split',\n 'Failover','Failback'],\n required=True)\n )\n )\n # Make REST call to Unisphere Server and execute SRDF control operation\n\n conn = PyU4V.U4VConn(server_ip=module.params['unispherehost'], port=8443,\n array_id=module.params['array_id'],\n u4v_version=module.params['universion'],\n verify=module.params['verifycert'],\n username=module.params['user'],\n password=module.params['password'])\n\n rep=conn.replication\n rdf_sglist = rep.get_storage_group_rep_list(has_srdf=True)\n\n if module.params['sgname'] in rdf_sglist:\n rdfg_list = rep.get_storagegroup_srdfg_list(module.params['sgname'])\n if len(rdfg_list)<=1:\n rdfg = rdfg_list[0]\n rep.modify_storagegroup_srdf(storagegroup_id=module.params['sgname']\n , action=module.params['action'], rdfg=rdfg)\n changed = True\n else:\n module.fail_json(changed=changed,\n msg='Specified Storage Group has mult-site RDF Protection '\n 'Ansible Module currently supports single Site SRDF '\n 'please use Unishpere for PowerMax UI for SRDF group '\n 'managment')\n\n else:\n\n module.fail_json(msg='Specified Storage Group is not currently SRDF '\n 'Protected')\n\n\n module.exit_json(changed=changed)\n\nif __name__ == '__main__':\n main()\n","sub_path":"library/dellpmax_manage_srdf.py","file_name":"dellpmax_manage_srdf.py","file_ext":"py","file_size_in_byte":5231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"428557101","text":"# -*- coding: utf-8 -*-\n\nimport sys, docx, os, re\n\nimport functools\nfrom PyQt5 import QtGui\n\nfrom PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QTextEdit, QPushButton, \\\n QAction, QLineEdit, QFileDialog, QTabWidget, QVBoxLayout, QHBoxLayout, QLabel, QCheckBox, QShortcut\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtCore import pyqtSlot, Qt\n\n\nclass App(QMainWindow):\n def __init__(self):\n super().__init__()\n self.title = 'Parse'\n self.left = 10\n self.top = 10\n self.width = 1280\n self.height = 720\n self.table_widget = MyTableWidget(self)\n self.setCentralWidget(self.table_widget)\n self.initUI()\n\n def initUI(self):\n self.setWindowTitle(self.title)\n self.setWindowIcon(QIcon('image.png'))\n self.setGeometry(self.left, self.top, self.width, self.height)\n # Initialize menu\n main_menu = self.menuBar()\n open_menu = main_menu.addMenu('Open')\n save_menu = main_menu.addMenu('Save as..')\n # Initialize buttons\n self.shortcut_o = QShortcut(QtGui.QKeySequence('Ctrl+O'), self)\n self.shortcut_o.activated.connect(self.open_file)\n open_button = QAction('Open', self)\n open_button.setShortcut('Ctrl+O')\n open_button.triggered.connect(self.open_file)\n\n self.shortcut_s = QShortcut(QtGui.QKeySequence('Ctrl+S'), self)\n self.shortcut_s.activated.connect(self.save_as)\n save_button = QAction('Save as...', self)\n save_button.setShortcut('Ctrl+S')\n save_button.triggered.connect(self.save_as)\n\n open_menu.addAction(open_button)\n save_menu.addAction(save_button)\n self.show()\n\n def keyPressEvent(self, e):\n if e.key() == Qt.Key_Escape:\n self.close()\n\n def open_file(self):\n file_path = QFileDialog.getOpenFileName(self, 'Open file', filter='Word Files *.docx;;Text files (*.txt)')\n # file_path = ('/home/anton/Downloads/Telegram Desktop/51st State Master Set.docx', 'Word Files *.docx')\n if file_path[0]:\n if file_path[1] == 'Text files (*.txt)':\n with open(file_path[0], 'r') as file:\n data = file.read()\n self.table_widget.set_main_text(data)\n else:\n doc = docx.Document(file_path[0])\n fullText = []\n for para in doc.paragraphs:\n fullText.append(para.text)\n self.table_widget.set_main_text('\\n'.join(fullText))\n self.table_widget.clean_textboxs()\n\n def save_as(self):\n file_path = QFileDialog.getSaveFileName(self, 'Save file', filter='Word Files *.docx;;Text files (*.txt)')\n if file_path[0]:\n if file_path[1] == 'Text files (*.txt)':\n if os.path.exists(file_path[0]):\n with open(file_path[0], 'w') as file:\n file.write(self.table_widget.get_main_text())\n else:\n with open(file_path[0] + '.txt', 'w') as file:\n file.write(self.table_widget.get_main_text())\n else:\n doc = docx.Document()\n doc.add_paragraph(self.table_widget.get_main_text())\n path = re.findall(r'.*(?:\\\\|\\/)(.*?)(?:\\.docx|$)', file_path[0])[0]\n doc.save(path + '.docx')\n\n\nclass MyTableWidget(QWidget):\n def __init__(self, parent):\n super(QWidget, self).__init__(parent)\n self.layout = QVBoxLayout(self)\n # Initialize tab screen\n self.tabs = QTabWidget()\n self.tab1 = QWidget()\n self.tab2 = QWidget()\n self.tab3 = QWidget()\n self.tab4 = QWidget()\n # Add tabs\n self.tabs.addTab(self.tab1, \"Overview\")\n self.tabs.addTab(self.tab2, \"Rus\")\n self.tabs.addTab(self.tab3, \"Ukr\")\n self.tabs.addTab(self.tab4, \"Photos\")\n # Create first tab\n self.tab1.layout = QVBoxLayout(self)\n self.textbox_main = QTextEdit(self)\n self.tab1.layout.addWidget(self.textbox_main)\n self.tab1.setLayout(self.tab1.layout)\n # Create second tab\n self.tab2.layout = QVBoxLayout(self)\n self.textbox_rus2 = QTextEdit(self)\n self.tab2.layout.addWidget(self.textbox_rus2)\n self.textbox_rus1 = QTextEdit(self)\n self.tab2.layout.addWidget(self.textbox_rus1)\n self.tab2.setLayout(self.tab2.layout)\n # Create third tab\n self.tab3.layout = QVBoxLayout(self)\n self.textbox_ukr2 = QTextEdit(self)\n self.tab3.layout.addWidget(self.textbox_ukr2)\n self.textbox_ukr1 = QTextEdit(self)\n self.tab3.layout.addWidget(self.textbox_ukr1)\n self.tab3.setLayout(self.tab3.layout)\n # Create fourth tab\n self.tab4.layout = QVBoxLayout(self)\n self.tab4.setLayout(self.tab4.layout)\n self.lbl_g_name = QLabel('Game name: ', self)\n self.lbl_p_name = QLabel('\\tPhoto name: ', self)\n self.lbl_quantity = QLabel('\\tQuantity: ', self)\n self.lbl_folder = QLabel('\\tFolder: ', self)\n self.tab4_line1 = QLineEdit(self)\n self.tab4_line2 = QLineEdit(self)\n self.tab4_line3 = QLineEdit(self)\n self.tab4_line4 = QLineEdit(self)\n\n self.photo_layout = QHBoxLayout(self)\n self.tab4.layout.addLayout(self.photo_layout)\n self.btn_create = QPushButton('Create', self)\n self.btn_create.setStyleSheet(\"background-color: red; color: black\")\n self.btn_create.clicked.connect(self.photos)\n\n self.photo_layout.addWidget(self.lbl_g_name)\n self.photo_layout.addWidget(self.tab4_line1)\n self.photo_layout.addWidget(self.lbl_p_name)\n self.photo_layout.addWidget(self.tab4_line2)\n self.photo_layout.addWidget(self.lbl_quantity)\n self.photo_layout.addWidget(self.tab4_line3)\n self.photo_layout.addWidget(self.lbl_folder)\n self.photo_layout.addWidget(self.tab4_line4)\n self.photo_layout.addWidget(self.btn_create)\n\n self.textbox_photos = QTextEdit(self)\n self.tab4.layout.addWidget(self.textbox_photos)\n # Create fields\n self.lbl_number = QLabel('Number: ', self)\n self.lbl_photo = QLabel('\\tPhoto name: ', self)\n self.lbl_rules = QLabel('\\tRules name: ', self)\n self.line1 = QLineEdit(self)\n self.line2 = QLineEdit(self)\n self.line3 = QLineEdit(self)\n self.line1.setSizePolicy(40, 10)\n\n self.cb = QCheckBox('Rules', self)\n self.cb.stateChanged.connect(self.add_rules)\n self.btn_parse = QPushButton('Parse', self)\n self.btn_parse.setStyleSheet(\"background-color: red; color: black\")\n self.btn_parse.clicked.connect(self.add_data)\n # Add Wingets to HLayout\n self.h_layout = QHBoxLayout(self)\n self.h_layout.addWidget(self.lbl_number)\n self.h_layout.addWidget(self.line1)\n self.h_layout.addWidget(self.lbl_photo)\n self.h_layout.addWidget(self.line2)\n self.h_layout.addWidget(self.cb)\n self.h_layout.addWidget(self.lbl_rules)\n self.h_layout.addWidget(self.line3)\n self.h_layout.addWidget(self.btn_parse)\n self.line3.hide()\n self.lbl_rules.hide()\n self.layout.addLayout(self.h_layout)\n self.layout.addWidget(self.tabs)\n\n self.setLayout(self.layout)\n\n def clean_textboxs(self):\n self.textbox_rus2.clear()\n self.textbox_ukr1.clear()\n self.textbox_ukr2.clear()\n self.textbox_rus1.clear()\n\n def add_rules(self, state):\n if state == Qt.Checked:\n self.lbl_rules.setHidden(False)\n self.line3.setHidden(False)\n else:\n self.lbl_rules.setHidden(True)\n self.line3.setHidden(True)\n\n def get_main_text(self):\n return self.textbox_main.toPlainText()\n\n def set_main_text(self, text):\n self.textbox_main.setText(text)\n\n def add_data(self):\n self.clean_textboxs()\n number = self.line1.text()\n imgname = self.line2.text()\n rules_name = self.line3.text()\n overviews = self.textbox_main.toPlainText().split('&&')\n dict_rus = self.parse_rus(overviews[0])\n rus_html_code = ' ' \\\n '{1}

Тип: {2}
' \\\n 'Издатель: {3}
Время игры: {4}
' \\\n 'Кол-во игроков: {5}
Возраст: {6}
Язык: {7}
' \\\n '
'.format(number, dict_rus['Art text'], dict_rus['Type'], dict_rus['Publisher'],\n dict_rus['Time'], dict_rus['Quantity'], dict_rus['Age'], dict_rus['Language'],\n imgname, dict_rus['Name'])\n\n if self.cb.checkState() == Qt.Checked:\n rus_html_code += 'Скачать правила к настольной игре %s

' % (\n number, rules_name, dict_rus['Name'])\n\n rus_html_code += dict_rus['Main text'] + '
'\n rus_html_code += '
Содержание настольной игры «%s»:
' % dict_rus['Name']\n for x in dict_rus['Components']:\n rus_html_code += ' – %s
' % x\n\n rus_html_code += '
Купить настольную игру «%s»  в Киеве или в Украине можно,' \\\n ' оформив заказ у нас на сайте, добавив товар "В Корзину", или позвонив ' \\\n 'по телефону (044) 383-63-67.' % dict_rus['Name']\n\n self.textbox_rus1.insertPlainText(rus_html_code)\n self.textbox_rus2.insertHtml(rus_html_code)\n\n dict_ukr = self.parse_ukr(overviews[1])\n ukr_html_code = ' ' \\\n ' {1}

Тип: {2}
' \\\n 'Видавництво: {3}
Час гри: {4}
' \\\n 'Кiлькiсть гравцiв: {5}
Вiк: {6}
Мова: {7}
' \\\n '
'.format(number, dict_ukr['Art text'], dict_ukr['Type'], dict_ukr['Publisher'],\n dict_ukr['Time'], dict_ukr['Quantity'],\n dict_ukr['Age'], dict_ukr['Language'], imgname, dict_ukr['Name'])\n\n if self.cb.checkState() == Qt.Checked:\n ukr_html_code += 'Скачати правила до настiльної гри %s

' % (\n number, rules_name, dict_ukr['Name'])\n\n ukr_html_code += dict_ukr['Main text'] + '
'\n ukr_html_code += '
До складу настільної гри «%s» входить:
' % dict_ukr['Name']\n for x in dict_ukr['Components']:\n ukr_html_code += ' – %s
' % x\n\n ukr_html_code += '
Придбати настільну гру «%s» ' \\\n 'у Києві чи в Україні досить просто. Достатньо натиснути кнопочку' \\\n ' "В Корзину" та оформити замовлення на нашому сайті, ' \\\n 'або зателефонувати нам за номером (044) 383-63-67.' % dict_ukr['Name']\n\n self.textbox_ukr1.insertPlainText(ukr_html_code)\n self.textbox_ukr2.insertHtml(ukr_html_code)\n\n def parse_ukr(self, data):\n parsed = dict()\n parsed['Name'] = re.search(r'^\\s*(.*)', data).groups()[0]\n parsed['Art text'] = re.search(r'^\\s*.*\\s*([\\s\\S]*)\\sТип:', data).groups()[0]\n t = re.search(r'Тип:\\s*(.*)', data).groups()[0]\n parsed['Type'] = self.links(t)\n parsed['Publisher'] = re.search(r'(?:Видавництво:|Видавець:)\\s*(.*)', data).groups()[0]\n parsed['Time'] = re.search(r'Час гри:\\s*(.*)', data).groups()[0]\n parsed['Quantity'] = re.search(r'Кількість гравців:\\s*(.*)', data).groups()[0]\n parsed['Age'] = re.search(r'Вік:\\s*(.*)', data).groups()[0]\n parsed['Language'] = re.search(r'Мова:\\s*(.*)', data).groups()[0]\n text = \\\n re.search(r'Мова:.*\\s*([\\s\\S]*?)\\s*(?:Компоненти:|До складу.*:|Комплектація:|Вміст.*:)', data).groups()[0]\n parsed['Main text'] = self.manipulations(text, parsed['Name'], 'Увага!')\n components = \\\n re.search(r'(?:Компоненти:|До складу.*:|Комплектація:|Вміст.*:)([\\s\\S]*?)\\s*(?:Купить|$)', data).groups()[0]\n components = self.links(components)\n parsed['Components'] = self.del_extra(components)\n return parsed\n\n def parse_rus(self, data):\n parsed = dict()\n parsed['Name'] = re.search(r'^(.*)', data).groups()[0]\n parsed['Art text'] = re.search(r'^.*\\s*([\\s\\S]*)\\sТип:', data).groups()[0]\n t = re.search(r'Тип:\\s*(.*)', data).groups()[0]\n parsed['Type'] = self.links(t)\n parsed['Publisher'] = re.search(r'Издатель:\\s*(.*)', data).groups()[0]\n parsed['Time'] = re.search(r'Время игры:\\s*(.*)', data).groups()[0]\n parsed['Quantity'] = re.search(r'Кол-во игроков:\\s*(.*)', data).groups()[0]\n parsed['Age'] = re.search(r'Возраст:\\s*(.*)', data).groups()[0]\n parsed['Language'] = re.search(r'Язык:\\s*(.*)', data).groups()[0]\n text = re.search(r'Язык:.*\\s*([\\S\\s]*?)\\s*(?:Компоненты:|Содержание.*:|Комплектация:)', data).groups()[0]\n parsed['Main text'] = self.manipulations(text, parsed['Name'])\n components = \\\n re.search(r'(?:Компоненты:|Содержание настольной.*:|Комплектация:)([\\s\\S]*?)(?:Купить|$)', data).groups()[0]\n components = self.links(components)\n parsed['Components'] = self.del_extra(components)\n return parsed\n\n def manipulations(self, data, name, string='Внимание!'):\n data = self.links(data)\n data = data.replace(name, '%s' % name)\n data = data.replace(string, '%s' % string)\n return data\n\n def photos(self):\n self.textbox_photos.setText('')\n game_name = self.tab4_line1.text()\n imgname = self.tab4_line2.text()\n quantity = list(map(int, self.tab4_line3.text().split('-')))\n folder = self.tab4_line4.text()\n data = ''\n num = 2\n for x in quantity:\n temp, num = self.photo_text1(x, num)\n data += temp.format(folder, imgname, game_name)\n\n data.format()\n self.textbox_photos.insertPlainText(data)\n\n @staticmethod\n def photo_text1(quantity, num):\n data = '

'\n if num == 2:\n data += ' ' % (num, num)\n num += 1\n quantity -= 1\n for x in range(quantity):\n n = str(num).zfill(2)\n data += ' ' % (n, n)\n num += 1\n data += '

\\n\\n\\n'\n return data, num\n\n @staticmethod\n def del_extra(data):\n data = data.split('\\n')\n for x in list(data):\n if x is '':\n data.remove(x)\n for x, y in enumerate(data):\n data[x] = y.replace(';', '')\n for x, y in enumerate(data):\n data[x] = y.lstrip(' -')\n return data\n\n @staticmethod\n def links(data):\n link = re.findall(r'\\[(.*?) (\\/.*?)\\]', data)\n for x in link:\n data = data.replace('[%s %s]' % (x[0], x[1]),\n '%s' % (x[1], x[0], x[0]))\n return data\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = App()\n sys.exit(app.exec_())\n","sub_path":"Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":17043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"649017386","text":"from typing import List, Tuple, Dict\n\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]: \n \"\"\"\n 77. 组合\n 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。\n \"\"\" \n nums = list(range(1, k + 1)) + [n + 1] # init first combination\n result, j = [], 0\n while j < k:\n # add current combination\n result.append(nums[:k])\n # increase first nums[j] by one\n # if nums[j] + 1 != nums[j + 1]\n j = 0\n while j < k and nums[j + 1] == nums[j] + 1:\n nums[j] = j + 1\n j += 1\n nums[j] += 1 \n return result\n \n def combine2(self, n: int, k: int) -> List[List[int]]:\n def backtrack(first = 1, curr = []):\n # if the combination is done\n if len(curr) == k: \n result.append(curr[:])\n for i in range(first, n + 1):\n # add i into the current combination\n curr.append(i)\n # use next integers to complete the combination\n backtrack(i + 1, curr)\n # backtrack\n curr.pop()\n \n result = []\n backtrack()\n return result\n\n\nif __name__ == \"__main__\":\n solution = Solution()\n n=4\n k=2\n print(solution.combine2(n,k))","sub_path":"Week_03/combinations.py","file_name":"combinations.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"225707123","text":"import requests\n\n\nclass Test_CloseProject:\n url = \"https://airaapps.evalueserve.com/api/v1/automl/close/project/?token=apikey\"\n\n def test11(self):\n payload = {'ProjectID': 'PID100137',\n 'ProjectName': 'XYZ',\n 'apikey': 'd0f4ac5d0ddf6f4a7bcedce7904f054f',\n 'Keywords': 'XYZ'}\n files = []\n headers = {}\n\n response = requests.request(\"POST\", Test_CloseProject.url, headers=headers, data=payload, files=files)\n\n print(response.text)\n","sub_path":"APITesting/Test_CloseProject.py","file_name":"Test_CloseProject.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"163912661","text":"from .base import *\n\n\n\"\"\"\nSTATIC FILE CONFIGURATION\n\"\"\"\n\n# See: https://warehouse.python.org/project/whitenoise/\nSTATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'\n\n\n\"\"\"\nDJANGO STORAGES\n\"\"\"\n# See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html\nINSTALLED_APPS += (\n 'storages',\n)\n\nDEFAULT_FILE_STORAGE = 'popsseabar.MediaRootS3BotoStorage'\n\nAWS_ACCESS_KEY_ID = environ.get('AWS_ACCESS_KEY_ID')\nAWS_SECRET_ACCESS_KEY = environ.get('AWS_SECRET_ACCESS_KEY')\nAWS_STORAGE_BUCKET_NAME = environ.get('AWS_STORAGE_BUCKET_NAME')\nAWS_S3_CUSTOM_DOMAIN = environ.get('AWS_S3_CUSTOM_DOMAIN')\nAWS_QUERYSTRING_AUTH = False\nAWS_HEADERS = {\n 'Cache-Control': 'max-age=86400',\n}\n\n\"\"\"\nEMAIL CONFIGURATION\n\"\"\"\n# See: https://github.com/django-ses/django-ses\nEMAIL_BACKEND = 'django_ses.SESBackend'\n\n# AWS_SES_REGION_NAME = environ.get('AWS_SES_REGION_NAME')\n# AWS_SES_REGION_ENDPOINT = environ.get('AWS_SES_REGION_ENDPOINT')\nAWS_SES_RETURN_PATH = environ.get('AWS_SES_RETURN_PATH')\n","sub_path":"popsseabar/settings/production.py","file_name":"production.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"111187410","text":"# Licensed Materials - Property of IBM\n# Copyright IBM Corp. 2016\nimport unittest\nimport sys\nimport itertools\nimport os\nimport shutil\n\nfrom streamsx.topology.topology import *\nfrom streamsx.topology.tester import Tester\n\nimport test_vers\n\ndef s4():\n return ['one', 'two', 'three', 'four']\n\ndef removeArtifacts(submissionResult):\n if 'bundlePath' in submissionResult:\n os.remove(submissionResult['bundlePath'])\n if 'toolkitRoot' in submissionResult:\n shutil.rmtree(submissionResult['toolkitRoot'])\n if 'archivePath' in submissionResult:\n os.remove(submissionResult['archivePath'])\n\ndef assertBundlePath(test, submissionResult):\n test.assertIn('bundlePath', submissionResult)\n test.assertTrue(os.path.isfile(submissionResult['bundlePath']))\n\ndef assertToolkitRoot(test, submissionResult):\n test.assertIn('toolkitRoot', submissionResult)\n test.assertTrue(os.path.isdir(submissionResult['toolkitRoot']))\n\ndef assertArchivePath(test, submissionResult):\n test.assertIn('archivePath', submissionResult)\n test.assertTrue(os.path.isfile(submissionResult['archivePath']))\n\ndef verifyArtifacts(test):\n if test.test_config.get('topology.keepArtifacts', False):\n # KeepArtifacts is True\n assertToolkitRoot(test, test.result)\n if (test.test_config.get('topology.forceRemoteBuild', False) or\n 'STREAMS_INSTALL' not in os.environ or\n 'BUILD_ARCHIVE' == test.test_ctxtype):\n assertArchivePath(test, test.result)\n test.assertNotIn('bundlePath', test.result)\n elif 'TOOLKIT' == test.test_ctxtype:\n test.assertNotIn('bundlePath', test.result)\n test.assertNotIn('archivePath', test.result)\n else:\n assertBundlePath(test, test.result)\n test.assertNotIn('archivePath', test.result)\n else:\n # KeepArtifacts is False\n if 'TOOLKIT' == test.test_ctxtype:\n assertToolkitRoot(test, test.result)\n else:\n test.assertNotIn('toolkitRoot', test.result)\n if 'BUNDLE' == test.test_ctxtype:\n assertBundlePath(test, test.result)\n test.assertNotIn('archivePath', test.result)\n elif 'BUILD_ARCHIVE' == test.test_ctxtype:\n assertArchivePath(test, test.result)\n test.assertNotIn('bundlePath', test.result)\n else:\n test.assertNotIn('bundlePath', test.result)\n test.assertNotIn('archivePath', test.result)\n\n@unittest.skipIf(not test_vers.tester_supported(), \"Tester not supported\")\nclass TestToolkitMethodsNew(unittest.TestCase):\n\n def setUp(self):\n self.topo = Topology('test_ToolkitSource')\n self.topo.source(['Hello', 'Toolkit'])\n self.test_ctxtype = 'TOOLKIT'\n self.test_config = {}\n self.result = {}\n\n def tearDown(self):\n removeArtifacts(self.result)\n\n def test_NoKeepArtifacts(self):\n self.result = streamsx.topology.context.submit(self.test_ctxtype, self.topo, self.test_config)\n verifyArtifacts(self)\n\n def test_KeepArtifacts(self):\n self.test_config = {'topology.keepArtifacts': True}\n self.result = streamsx.topology.context.submit(self.test_ctxtype, self.topo, self.test_config)\n verifyArtifacts(self)\n\n@unittest.skipIf(not test_vers.tester_supported(), \"Tester not supported\")\nclass TestBuildArchiveMethodsNew(TestToolkitMethodsNew):\n\n def setUp(self):\n self.topo = Topology('test_BuildArchiveSource')\n self.topo.source(['Hello', 'BuildArchive'])\n self.test_ctxtype = 'BUILD_ARCHIVE'\n self.test_config = {}\n self.result = {}\n\n@unittest.skipIf(not test_vers.tester_supported(), \"Tester not supported\")\n@unittest.skipUnless('STREAMS_INSTALL' in os.environ, \"requires STREAMS_INSTALL\")\nclass TestBundleMethodsNew(TestToolkitMethodsNew):\n\n def setUp(self):\n self.topo = Topology('test_BundleSource')\n self.topo.source(['Hello', 'Bundle'])\n self.test_ctxtype = 'BUNDLE'\n self.test_config = {}\n self.result = {}\n\n@unittest.skipIf(not test_vers.tester_supported() , \"Tester not supported\")\nclass TestTopologyMethodsNew(unittest.TestCase):\n\n def setUp(self):\n Tester.setup_standalone(self)\n self.result = {}\n\n def tearDown(self):\n removeArtifacts(self.result)\n\n def test_TopologySourceList(self):\n topo = Topology('test_TopologySourceList')\n hw = topo.source(['Hello', 'Tester'])\n tester = Tester(topo)\n tester.contents(hw, ['Hello', 'Tester'])\n tester.test(self.test_ctxtype, self.test_config)\n self.result = tester.result['submission_result']\n verifyArtifacts(self)\n\n def test_TopologySourceFn(self):\n topo = Topology('test_TopologySourceFn')\n hw = topo.source(s4)\n tester = Tester(topo)\n tester.contents(hw, s4())\n tester.tuple_count(hw, len(s4()))\n self.test_config['topology.keepArtifacts'] = True\n tester.test(self.test_ctxtype, self.test_config)\n self.result = tester.result['submission_result']\n verifyArtifacts(self)\n\n def test_TopologySourceItertools(self):\n topo = Topology('test_TopologySourceItertools')\n hw = topo.source(itertools.repeat(9, 3))\n tester = Tester(topo)\n tester.contents(hw, [9, 9, 9])\n tester.test(self.test_ctxtype, self.test_config)\n\n@unittest.skipIf(not test_vers.tester_supported() , \"Tester not supported\")\nclass TestDistributedTopologyMethodsNew(TestTopologyMethodsNew):\n def setUp(self):\n Tester.setup_distributed(self)\n self.result = {}\n\n@unittest.skipIf(not test_vers.tester_supported() , \"Tester not supported\")\nclass TestBluemixTopologyMethodsNew(TestTopologyMethodsNew):\n def setUp(self):\n Tester.setup_streaming_analytics(self, force_remote_build=True)\n self.result = {}\n","sub_path":"test/python/topology/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":5882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"447852984","text":"#Rolling of a dice\n#Name=Kanav Gupta\n#Division=M\n#Roll no.=25\nimport random\nfrom random import randint as rt\ndef game(dice,faces):\n result=0\n for roll in range(0,dice):\n result+=rt(1,faces)\n return result\nresult=game(1,6)\nprint(result)\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"485450824","text":"import requests\nimport datetime\n\nstickers = [\n \"BIG\",\n \"Ninjas in Pyjamas\",\n \"Astralis\",\n \"Team Liquid\",\n \"Team Spirit\",\n \"FACEIT\",\n \"HellRaisers\",\n \"Cloud9\",\n \"Winstrike Team\",\n \"Rogue\",\n \"FaZe Clan\"\n]\n\n\ndef make_url(stick: str):\n \"\"\"\n gibt den Link der Steamapi zurück\n\n :param stick: der Sticker name\n :return: gibt den Link zurück\n \"\"\"\n url = \"https://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name=Sticker%20|%20\" + \\\n stick + \"%20|%20London%202018\"\n return url\n\n\ndef return_dir(url: str):\n \"\"\"\n gibt das dir mit den Daten der Website zurück\n\n :param url: url der API (+Info)\n :return: dir der Daten\n \"\"\"\n\n return requests.get(url).json()\n\n\nprint(datetime.datetime.now().strftime(\"%H:%S:%M\") + \": \")\nfor stick in stickers:\n myDir = return_dir(make_url(stick))\n if myDir and myDir.get(\"success\"):\n print(stick.title() + \": \" + myDir[\"lowest_price\"])\n else:\n print(stick.title() + \": NICHT GEFUNDEN!\")\n\n","sub_path":"goodcrawler.py","file_name":"goodcrawler.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"167117778","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 8 13:20:53 2018\n\n@author: yihangao\n\"\"\"\n\n#Import modules\nfrom __future__ import division\nimport random;\nimport numpy;\nimport math;\n\n#Global Variables\nPi = math.pi;\nE_Crit = 45; #Cirital energy in MeV\nT_P = 0.9525; #Thickness of the plate in cm \nT_G = 0.635; #Thickness of gaps in cm\nR_Det = 7.62; #Radius of detector in cm\nR_Fid = R_Det/2; #Maxium radius of electrons in cm\nX_0 = 8.9; #Radiation length in cm\nTheta_Max = Pi/6; #Maxium Polar angle\n\n\nN_Run = 100; #Total Number of runs persimulation\n\n\n#Function cacluates length particle will travel given an energy in MeV\ndef StoppingLen(E_Val):\n L_Stop = X_0*math.log(1 + E_Val/E_Crit);\n return L_Stop; #Stoping length in cm\n\n#Number of sparks\ndef N_Spark(L,Theta,Z_0):\n Num_Spark = 1 + math.floor((L*math.cos(Theta) - Z_0)/(T_P));\n return Num_Spark;\n\n#Escape length function (calculates escape length for given theta, r and phi)\ndef Escape_L(r,phi,theta):\n L_escp = -r*math.cos(phi) + math.sqrt(R_Det**2 - r**2)/(math.sin(theta)*(T_P/(T_P + T_G)));\n return L_escp;\n \n\n#Generate array of muon masses in MeV\nLowMuonMass = 90; #Lowest Muon mass\nHighMuonMass = 105; #Highest muon mass\nMassRuns = (HighMuonMass - LowMuonMass) + 1; #Number of different masses to be tested \nMuonMass_Array = numpy.linspace(LowMuonMass,HighMuonMass,MassRuns); #Muon mass array increments by 1 MeV (All masses are in MeV)\n\n#These matricies will keep track of the data from the simulations, each column corresponds to a different muon mass and each row corresponds to \n#run number\nSpark_Matrix = numpy.zeros((N_Run,MassRuns)); #Initialize an empty matrix corresponding to number of sparks\nEnergy_Matrix = numpy.zeros((N_Run,MassRuns)); #Initialize an empty matrix corresponding to electron energies\nRadius_Matrix = numpy.zeros((N_Run,MassRuns)); #Initialize an empty matrix corresponding to electron radius\n\n#Simulation loop\nfor i1 in range(0,MassRuns): #Loop over every muon mass\n for i2 in range(0,N_Run): #Run the simulation with a given muon of mass N times\n #Generate Electron Energy\n Electron_En = random.uniform(0,0.5*MuonMass_Array[i1]); #Energy is in MeV\n Energy_Matrix[i2,i1] = Electron_En; #Add electron energy to matrix\n \n #Generate electron radius, polar angle, azimuthal angle and thickness\n r_Val = random.uniform(0,R_Fid);\n Radius_Matrix[i2,i1] = r_Val; #Add radius to matrix\n Theta_Val = random.uniform(0,Theta_Max); #Generate polar angle\n Phi_Val = random.uniform(0,2*Pi); #Generate azimuthal angle\n Z_Val = random.uniform(0,T_P); #Generate a thickness in cm\n \n #Calculate length and escape length\n Len_Val = StoppingLen(Electron_En);\n Escp_Len = Escape_L(r_Val,Theta_Val,Phi_Val);\n \n #Compare escape length and Length\n if (Len_Val > Escp_Len):\n Len_Val = Escp_Len; #Set length to escape length\n \n #Calculate the number of sparks produced and add to data matrix\n Spark_Num = N_Spark(Len_Val,Theta_Val,Z_Val);\n Spark_Matrix[i2,i1] = Spark_Num;\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"301044626","text":"import pandas as pd\r\nfrom datetime import datetime, timedelta\r\nimport boto3\r\nimport s3fs\r\n\r\ns3client = boto3.client('s3', region_name='us-east-1')\r\n\r\n# Processing data from S3 Bucket\r\nsource_bucket = 'cannaspyglass-datalake-raw'\r\ndest_bucket = 'cannaspyglass-datalake-processed-dev'\r\n\r\n# Processing the data from Raw format to processed\r\ndef p_data(s_bucket, file_path, d_bucket, d_file):\r\n s3 = s3fs.S3FileSystem(anon=False)\r\n raw_df = pd.read_excel(f's3://{s_bucket}/{file_path}/', header=1, skipfooter=0)\r\n raw_df.columns = ['status', 'licenseNumber','entityName','city','state','postalCode','firstName', 'lastName', 'phone']\r\n raw_df[['status']] = raw_df[['status']].fillna('No')\r\n raw_df = raw_df.fillna('NA')\r\n raw_df[['status']] = raw_df[['status']].replace('ü', 'Yes')\r\n print(raw_df)\r\n with s3.open(f's3://{d_bucket}/{d_file}/','w') as f:\r\n raw_df.to_csv(f, index=False)\r\n\r\n\r\ndate = (datetime.today() - timedelta(0)).strftime('%Y%m%d')\r\nfilenames = ['cultivation_facility', 'dispensary_facility', 'infused_product_manufacturing_facility',\r\n 'laboratory_testing_facility', 'transportation_facility']\r\nfor file in filenames:\r\n try:\r\n source_filename = 'US/MO/CannabisLifecycle/' + file + '_' + date + '.xlsx'\r\n dest_filename = 'US/MO/CannabisLifecycle/' + file + '_' + date + '.csv'\r\n p_data(source_bucket, source_filename, dest_bucket, dest_filename)\r\n print(\"Processing has been successfully completed\")\r\n except:\r\n print(\"Processing Failed! Please check the source.\")\r\n","sub_path":"processing_draft2.py","file_name":"processing_draft2.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"612773516","text":"\nfrom functools import reduce # forward compatibility for Python 3\nimport operator\nfrom itertools import groupby\nfrom operator import add, itemgetter\n\ndef list_2_str(input_list=[], separator=\",\", log=False):\n \"\"\"\n * convert list to string\n ------------------------\n @ parameters: \n * input list contaning strings\n * separator used to convert list to string\n -----------------------------------------------\n @ outputs:\n * string (Joined if list not empty or \"\")\n \"\"\"\n if input_list:\n result_str = f\"{separator}\".join(map(str, input_list))\n if log:\n logger.debug(\n f'list {input_list} converted to string \"{result_str}\"'\n )\n return result_str\n else:\n logger.error(f'Empty list detected while converting to string ...')\n return \"\"\n\n\ndef merge_records_by(key, combine):\n \"\"\"Returns a function that merges two records rec_a and rec_b.\n The records are assumed to have the same value for rec_a[key]\n and rec_b[key]. For all other keys, the values are combined\n using the specified binary operator.\n \"\"\"\n return lambda rec_a, rec_b: {\n k: rec_a[k] if k == key else combine(rec_a[k], rec_b[k])\n for k in rec_a\n }\n\ndef merge_list_of_records_by(key, combine):\n \"\"\"\n Returns a function that merges a list of records, grouped by\n the specified key, with values combined using the specified\n binary operator.\n \n usage:\n a=[{'time': '25 APR', 'total': 10, 'high': 10}, \n {'time': '26 APR', 'total': 5, 'high': 5}]\n \n b=[{'time': '24 APR', 'total': 10, 'high': 10}, \n {'time': '26 APR', 'total': 15, 'high': 5}]\n\n merger = merge_list_of_records_by('time', add)\n \n print(merger(a + b))\n will print ..\n \n [\n {'time': '24 APR', 'total': 10, 'high': 10},\n {'time': '25 APR', 'total': 10, 'high': 10}, \n {'time': '26 APR', 'total': 20, 'high': 10}\n ]\n \"\"\"\n keyprop = itemgetter(key)\n return lambda lst: [\n reduce(merge_records_by(key, combine), records)\n for _, records in groupby(sorted(lst, key=keyprop), keyprop)\n ]\n\ndef count_frequency(my_list): \n \"\"\"\n count the frequency of elements in a list using a dictionary \n \n Args:\n my_list (list): List\n \n Returns:\n dict: Dictionary containing unique item and frequency\n Example::\n >> my_list = [\"happy\", \"neutral\", \"happy\"]\n >> count_frequency(my_list)\n {'happy': 2, 'neutral': 1}\n \"\"\"\n # Creating an empty dictionary \n freq = {} \n for items in my_list: \n freq[items] = my_list.count(items) \n return freq\n\n\ndef break_list2chunks(lst, n):\n \"\"\"\n Break a list into chunks of size N using list comprehension\n\n Args:\n lst (list): 1d list\n n (int): How many elements each output list should have \n Returns:\n list: 2D list\n \"\"\"\n return [\n lst[i * n:(i + 1) * n] for i in range((len(lst) + n - 1) // n )\n ]","sub_path":"nb_utils/list_manipulation.py","file_name":"list_manipulation.py","file_ext":"py","file_size_in_byte":3087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"526030029","text":"import gi\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk\n\nfrom pages import Page, SideBar, ResourceView, NewResourceAssistant\nimport skGui\n\n#import lib.scene\n\nclass ScenePage(Page):\n def __init__(self):\n super().__init__(orientation=Gtk.Orientation.HORIZONTAL)\n\n def initGUI(self):\n super().initGUI()\n\n self.sideBar.newItem.connect('clicked', createNewScene)\n\n\nclass AssistantDescriptionPage(Gtk.Box):\n def __init__(self, assistant):\n super().__init__(orientation=Gtk.Orientation.VERTICAL)\n\n self._assistant = assistant\n\n self.initGUI()\n\n def initGUI(self):\n row = Gtk.HBox()\n self.lbl_sceneN = Gtk.Label('Scene Number:')\n row.pack_start(self.lbl_sceneN, False, False, 5)\n self.edit_sceneN = Gtk.Entry()\n self.edit_sceneN.connect('changed', self.check_page_complete)\n row.pack_start(self.edit_sceneN, False, False, 5)\n self.lbl_sceneType = Gtk.Label('Scene Type:')\n row.pack_start(self.lbl_sceneType, False, False, 5)\n self.combo_sceneType = Gtk.ComboBoxText()\n self.combo_sceneType.append('internal', 'Internal')\n self.combo_sceneType.append('external', 'External')\n self.combo_sceneType.append('title', 'Title')\n self.combo_sceneType.set_active_id('external')\n row.pack_start(self.combo_sceneType, False, False, 5)\n\n self.lbl_sceneLocation = Gtk.Label('Location')\n row.pack_start(self.lbl_sceneLocation, False, False, 5)\n self.locationStore = Gtk.ListStore(str, str)\n self.locationStore.append(['none', 'None'])\n self.combo_sceneLocation = Gtk.ComboBox.new_with_model_and_entry(self.locationStore)\n self.combo_sceneLocation.set_id_column(0)\n self.combo_sceneLocation.set_entry_text_column(1)\n locationCompleter = Gtk.EntryCompletion(inline_completion=True)\n locationCompleter.set_model(self.locationStore)\n locationCompleter.set_text_column(1)\n self.combo_sceneLocation.get_child().set_completion(locationCompleter)\n self.combo_sceneLocation.get_child().connect('changed', self.check_page_complete)\n row.pack_start(self.combo_sceneLocation, False, False, 5)\n\n self.pack_start(row, False, False, 5)\n\n row = Gtk.HBox()\n self.lbl_description = Gtk.Label('Description:')\n row.pack_start(self.lbl_description, False, False, 5)\n\n self.pack_start(row, False, False, 5)\n\n self.edit_sceneDescription = Gtk.TextView()\n self.edit_sceneDescription.get_buffer().connect('changed', self.check_page_complete)\n self.edit_sceneDescription.set_left_margin(5)\n self.edit_sceneDescription.set_right_margin(5)\n self.edit_sceneDescription.set_top_margin(5)\n self.edit_sceneDescription.set_bottom_margin(5)\n\n self.pack_start(self.edit_sceneDescription, True, True, 5)\n\n def get_assistant(self):\n return self._assistant\n\n def check_page_complete(self, data):\n state = True\n if self.edit_sceneN.get_text() == '':\n state = False\n if self.edit_sceneDescription.get_buffer().get_char_count() == 0:\n state = False\n if self.combo_sceneLocation.get_child().get_text() == '':\n state = False\n\n self.set_page_complete(state)\n\n def set_page_complete(self, state):\n self.get_assistant().set_page_complete(self, state)\n\n\ndef createNewScene(data):\n assistant = NewResourceAssistant()\n\n index = assistant.add_page(AssistantDescriptionPage(assistant), 'Scene Description')\n #assistant.set_page_complete(assistant.get_nth_page(index), True)\n\n index = assistant.add_page(Gtk.Box(), 'Scene Settings')\n #assistant.set_page_complete(assistant.get_nth_page(index), True)\n\n assistant.show_all()\n","sub_path":"src/pages/scenes.py","file_name":"scenes.py","file_ext":"py","file_size_in_byte":3802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"204690939","text":"l=['a','b','c','d']\nprint \n(l[1])\nfor i in l:\n\tprint (i)\nprint(\"end\")\nlimit=10\nlimit = int (input(\"enter value\"))\n\nfor i in range(1, limit+1):\n\ts = \"\"\n\tfor j in range(0,i):\n\t\ts = s + \"*\"\n\tprint(s)\ndef hw(i):\n\tprint(i)\nhw(i=\"helloo\")\nhw(i=\"hey\")\nhw (i=\"hi!\")\nhw (i=\"seeya!\")\n\n\n","sub_path":"Programming Intro/loob.py","file_name":"loob.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"301063945","text":"from ibm_watson import ToneAnalyzerV3\nfrom ibm_cloud_sdk_core.authenticators import IAMAuthenticator\nfrom dotenv import load_dotenv\nimport os\nimport numpy as np\nimport time\n\nload_dotenv()\n\nIBM_API_KEY = os.environ['IBM_API_KEY']\n\ndef get(raw_text):\n \"\"\"\n Fetches tone information from IBM tone API for given text\n\n Args:\n raw_text (str): Text to analyze\n\n Returns:\n Raw API response object on success. Error on failure.\n \"\"\"\n authenticator = IAMAuthenticator(IBM_API_KEY)\n tone_analyzer = ToneAnalyzerV3(\n version='2020-02-25',\n authenticator=authenticator\n )\n tone_analyzer.set_service_url('https://api.us-south.tone-analyzer.watson.cloud.ibm.com/instances/39cb10a6-c500-45b2-8481-053a17155502')\n try:\n resp = tone_analyzer.tone(\n {'text': raw_text},\n content_type='application/json',\n sentences=False\n )\n if resp.status_code == 200:\n return resp.result\n else:\n return {'error': resp.status_code}\n except Exception as e:\n return {'error': e}\n\ndef extract_score_from_tones(tones, tone_id):\n \"\"\"\n Extracts specific tone score from array of tone values\n\n Args:\n tones (list): List of tone objects from IBM tone API\n tone_id (str): specific tone id\n\n Returns:\n Score as float if it exists. NaN if not.\n \"\"\"\n matching_tones = [t for t in tones if t['tone_id'] == tone_id]\n\n if not matching_tones:\n return np.nan\n\n return matching_tones[0]['score']\n\ndef extract_score(raw_tone, tone_id):\n \"\"\"\n Extracts specific tone score from raw tone API response\n\n Args:\n raw_tone (obj): Raw response object from IBM tone API\n tone_id (str): specific tone id\n\n Returns:\n Score as float if it exists. NaN if not.\n \"\"\"\n if not raw_tone.get('document_tone'):\n return np.nan\n\n tones = raw_tone.get('document_tone').get('tones')\n return extract_score_from_tones(tones, tone_id)\n","sub_path":"src/data/tone_analyzer.py","file_name":"tone_analyzer.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"149323238","text":"# -*- coding: utf-8 -*-\n# @Time : 18-10-31 下午9:08\n# @Author : Pugu\n# @FileName: plotting.py\n# @Software: PyCharm\n\nimport torch\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib.axes import Axes\nfrom typing import Dict, Optional, Tuple, List\n\nfrom bindsnet.analysis.plotting import plot_input, plot_spikes, plot_weights, plot_assignments, plot_performance\n\n\nclass Keys:\n ALL = \"all\"\n PROP = \"proportion\"\n NG = \"ngram\"\n\n\ndef plot_comparison(curves_list: List[Dict[str, List[float]]], names: List[str] = None,\n axes: Optional[Axes] = None,\n figsize: Tuple[int, int] = (7, 4), dx: int = 250):\n if len(curves_list) > 0:\n num_curves = len(curves_list)\n if isinstance(curves_list[0], dict):\n def check(keys, i):\n if i == 0:\n return check(list(curves_list[0].keys()), i + 1)\n if i >= num_curves:\n return True\n if isinstance(curves_list[i], dict):\n ks = list(curves_list[i].keys())\n if len(list(set(ks).difference(set(keys)))) == 0 and len(list(set(keys).difference(set(ks)))) == 0:\n return check(keys, i + 1)\n else:\n return False\n else:\n return False\n \n if not check([], 0):\n assert \"The list of curves is not correct\"\n return None\n pass\n else:\n assert \"The list of curves is not correct\"\n return None\n pass\n else:\n assert \"The list of curves is empty\"\n return None\n names = [] if names is None else names\n while len(names) < num_curves:\n names.append(\"curve\" + str(len(names) + 1))\n keys = list(curves_list[0].keys())\n num_keys = len(keys)\n xticks = len(curves_list[0][keys[0]]) * dx\n xstep = int(xticks // 10)\n figsize = (figsize[0], figsize[1] * num_keys)\n if not axes:\n _, axes = plt.subplots(nrows=num_keys, figsize=figsize)\n else:\n axes.clear()\n for i, key in enumerate(keys):\n for j, curves in enumerate(curves_list):\n axes[i].plot(np.arange(0, xticks, step=dx), [p for p in curves[key]], label=names[j])\n axes[i].set_ylim(bottom=0, top=100)\n axes[i].set_title(key)\n axes[i].set_xlabel(\"No. of examples\")\n axes[i].set_ylabel(\"Accuracy\")\n axes[i].set_xticks(range(0, xticks + xstep, xstep))\n axes[i].set_yticks(range(0, 110, 10))\n axes[i].legend()\n pass\n \n return axes\n","sub_path":"analyse/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":2639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"240774069","text":"'''\n An Utils module for all common and frequent tasks such as file handling etc..\n'''\nimport json\nimport requests\n\nclass Py_Utils:\n \n @staticmethod\n def get_api_result(api_url,*args):\n '''\n Given an API URL do a GET request call and return the result\n :param api_url: URL on which GET will be applied\n :param args: Contains username and password\n '''\n try:\n return requests.get(api_url,auth=(args[0],args[1]))\n except Exception as error:\n return {'data':'ERROR'}\n\n @staticmethod\n def validate_users_keys(user_inputs,required_inputs,user_names_array,check_user_exists=False):\n '''\n Check if the User supplies all the required inputs.\n If any of the user keys are not passed, return False.\n If the username is already available in the database ,then do not process.\n :param user_inputs: Inputs given by the User\n :param required_inputs: Expected inputs, mentioned as part of configs\n :param user_names_array: Array of usernames available in the database\n :param check_user_exists:\n Default Value: True\n When set as True \n -> Apply a check to verify the users attributes against required config attributes and \n Apply a check to verify if user is already part of the system.\n else\n -> Apply a check to verify the users attributes against required config attributes\n '''\n try:\n user_inputs_keys = sorted(list(user_inputs.keys()))\n required_inputs_keys = sorted(required_inputs)\n return user_inputs_keys == required_inputs_keys and str(user_inputs['user_name']).lower() not in user_names_array if bool(check_user_exists)\\\n else user_inputs_keys == required_inputs_keys\n except Exception as error:\n return False\n\n @staticmethod\n def post_api_result(api_url,*args):\n '''\n Given an API URL do a GET request call and return the result\n :param api_url: URL on which GET will be applied\n :param args: Contains username and password\n '''\n try:\n return requests.post(api_url,auth=(args[0],args[1]))\n except Exception as error:\n return {'data':'ERROR'}\n\n\n @staticmethod\n def read_json(json_file):\n ''' \n Read a json file and return the contents\n :param json_file: Full Path of the json file to be read\n @return: \n Success -> Json file contents as a dictionary. \n Exception -> Empty dictionary\n '''\n try:\n with open(json_file,'r') as reader:\n return json.load(reader)\n except Exception as error:\n return {}\n\n @staticmethod\n def write_json(json_file,contents):\n ''' \n Write the contents to the *json* file\n :param json_file: Full Path of the json file to be written to\n :param contents: Contents to be written to json file\n @return: \n Success -> Json file contents as a dictionary. \n Exception -> Empty dictionary\n '''\n try:\n with open(json_file,'w') as writer:\n return json.dump(contents,writer)\n except Exception as error:\n return {}\n\n @staticmethod\n def read_file(file_path):\n ''' \n Read any file and return the contents\n :param file_path: Full Path of the file to be read\n @return: \n Success -> File contents as an Array. \n Exception -> Empty dictionary\n '''\n try:\n with open(file_path,'r') as reader:\n for each_line in reader.readlines():\n yield each_line.split(',')\n except Exception as error:\n return {}\n\n @classmethod\n def populate_json_records(cls,csv_file_path,json_file_path,json_columns):\n '''\n Read the given csv file and populate the json file\n :param csv_file_path: Full path of the csv file\n :param json_file_path: Full path of the json file\n :param json_columns: Array of json columns\n @return:\n Success -> Write the contents to the final json file\n Exception ->Write empty array to the final json file\n '''\n try:\n csv_contents = list(cls.read_file(csv_file_path))\n json_contents = {\"records\":[{str(json_column):str(record) for record,json_column in zip(records,json_columns)} for records in csv_contents]}\n return cls.write_json(json_file=json_file_path,contents=json_contents)\n except Exception as error:\n return cls.write_json(json_file=json_file_path,contents={\"error\":[]})","sub_path":"core/utilities/pyutils.py","file_name":"pyutils.py","file_ext":"py","file_size_in_byte":4933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"383762305","text":"import re ##### For regular expression\nimport ast ######## The ast module helps Python applications to process trees of the Python abstract syntax grammar #############\n\ndef parse_aSHIIP_topology_with_size(topology_file_name, adjacent_matrix):\n '''Parse aSHIIP topology ::: arg1: Name of the topology file, arg2: adjacent_matrix'''\n topology_pointer = open(topology_file_name,'r+')\n size_found = False\n #################### Parser symbols ##############################\n number_of_node_symbol = 'Size :'\n\n for line in topology_pointer:\n line = line.replace('\\n','')\n if not size_found:\n if number_of_node_symbol in line:\n number_of_node = int(line.replace(' ','').split(':')[1])\n del adjacent_matrix[:]\n for i in range(number_of_node):\n adjacent_matrix.append([])\n print(\"Size of Topology : %s\"%(len(adjacent_matrix)))\n size_found = True\n else:\n start_with_digit = re.match('^\\d',line) ##################### Check if the string starts with a digit #####################################\n if start_with_digit is not None:\n line = line.replace(' ','')\n node_id = int(line[0:line.index('(')])\n adjacent_nodes = ast.literal_eval(line[line.index(')')+1:])\n for node_index in range(len(adjacent_nodes)):\n adjacent_nodes[node_index] -= 1\n adjacent_matrix[node_id-1] = adjacent_nodes\n\ndef parse_aSHIIP_topology(topology_file_name, adjacent_matrix):\n '''Parse aSHIIP topology ::: arg1: Name of the topology file, arg2: adjacent_matrix'''\n topology_pointer = open(topology_file_name, 'r+')\n del adjacent_matrix[:]\n for line in topology_pointer:\n line = line.replace('\\n', '')\n start_with_digit = re.match('^\\d',line) ##################### Check if the string starts with a digit #####################################\n if start_with_digit is not None:\n line = line.replace(' ', '')\n node_id = int(line[0:line.index('(')])\n adjacent_nodes = ast.literal_eval(line[line.index(')') + 1:])\n for node_index in range(len(adjacent_nodes)):\n adjacent_nodes[node_index] -= 1\n adjacent_matrix.append(adjacent_nodes)\n topology_pointer.close()\n # print('Adjacent %s'%(adjacent_matrix))\n\ndef parse_aSHIIP_topology_bi_directional(topology_file_name, adjacent_matrix,sort_node=False):\n '''Parse aSHIIP topology ::: arg1: Name of the topology file, arg2: adjacent_matrix'''\n topology_pointer = open(topology_file_name, 'r+')\n del adjacent_matrix[:]\n for line in topology_pointer:\n line = line.replace('\\n', '')\n start_with_digit = re.match('^\\d',line) ##################### Check if the string starts with a digit #####################################\n if start_with_digit is not None:\n line = line.replace(' ', '')\n node_id = int(line[0:line.index('(')])\n adjacent_nodes = ast.literal_eval(line[line.index(')') + 1:])\n for node_index in range(len(adjacent_nodes)):\n adjacent_nodes[node_index] -= 1\n adjacent_matrix.append(list(set(adjacent_nodes)))\n topology_pointer.close()\n\n for node_id in range(len(adjacent_matrix)):\n for adj_node in adjacent_matrix[node_id]:\n if node_id not in adjacent_matrix[adj_node]:\n adjacent_matrix[adj_node].append(node_id)\n\n if sort_node:\n for node_id in range(len(adjacent_matrix)):\n adjacent_matrix[node_id] = sorted(adjacent_matrix[node_id])\n\n # print(\"Adjacency Matrix %s\"%(adjacent_matrix))","sub_path":"ParseTopologyFile.py","file_name":"ParseTopologyFile.py","file_ext":"py","file_size_in_byte":3734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"266821317","text":"'''\r\nCreated on 27 janv. 2020\r\n\r\n@author: gresset6u\r\n'''\r\n\r\nimport tkinter as tk\r\n\r\nclass Application(tk.Frame):\r\n def __init__(self, master=None):\r\n tk.Frame.__init__(self, master)\r\n self.pack()\r\n self.createWidgets()\r\n def createWidgets(self):\r\n self.QUIT = tk.Button(self, text=\"QUIT\", fg=\"red\", command=root.destroy)\r\n self.QUIT.pack(side=\"left\")\r\n hi_there = tk.Button(self, text=\"Hello\", command=self.say_hi)\r\n hi_there.pack(side=\"left\")\r\n def say_hi(self):\r\n print(\"hi there, everyone!\")\r\n\r\nroot = tk.Tk()\r\napp = Application(master=root)\r\napp.mainloop()\r\n","sub_path":"PILS/Python/Tkinter2.py","file_name":"Tkinter2.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"134167061","text":"from BaseCmd import BaseCmd\n\nclass Bissness(BaseCmd):\n\t\"\"\"公司中常用地址\"\"\"\n\tdef __init__(self):\n\t\tself.cmds={\n\t\t\t\"41\":\"http://jira.up366.com:8090\",\n\t\t\t\"42\":\"http://jira.up366.com:8080\",\n\t\t\t\"43\":\"http://192.168.1.203:8998/jenkins/\",\n\t\t\t\"44\":\"http://www.ismartin.com\",\n\t\t\t\"45\":\"http://lsp.ismartin.com/manage/displayLesson.up?lessonId=47977628554756096\"\n\n\t\t}\n\t\tself.menu = \"\"\"\n公司常用\t\n|\t41. wiki\n|\t42. jira\n|\t43. jenkins\n|\t44. ismart地址\n|\t45. 直播地址\n-----------------------------------------------------------\n\t\t \"\"\"\n\n\tdef hanldeCmd(self,key):\n\t\tif key not in self.cmds.keys():\n\t\t\treturn False;\n\t\tself.openChrome(self.cmds[key]);","sub_path":"androidUtil/Bissness.py","file_name":"Bissness.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"425579189","text":"import json\nimport os\n\n\nclass Config:\n def __init__(self, file, default={}, auto_init=True,\n indent=4, sort_keys=True):\n self.file = file\n self.default = default\n self.data = {}\n self.indent = indent\n self.sort_keys = sort_keys\n if auto_init:\n self.init()\n\n def init(self):\n if os.path.isfile(self.file):\n self.load()\n else:\n self.data = self.default\n self.save()\n\n def get(self, key):\n if key in self.data.keys():\n return self.data[key]\n if key in self.default.keys():\n return self.default[key]\n\n def set(self, key, value):\n self.data[key] = value\n\n def save(self):\n open(self.file, 'w').write(json.dumps(\n self.data, indent=self.indent, sort_keys=self.sort_keys\n ))\n\n def load(self):\n if not os.path.isfile(self.file):\n return False\n try:\n self.data = json.load(open(self.file))\n except json.decoder.JSONDecodeError:\n return False\n","sub_path":"src/utils/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"473058408","text":"from bottle import static_file, get, route, run, template\nimport os\nimport json\nimport re\nimport sys\nimport argparse\n\n@route('/static/')\ndef static(filepath):\n return static_file(filepath,root='./static')\n\n@route('/')\ndef index():\n return template('index')\n\n@get('/img')\ndef getImg():\n directory = os.path.join(os.getcwd() + '/static/picture')\n files = os.listdir(directory)\n result = { 'img': [] }\n matcher = re.compile('.+(\\.jpg|\\.JPG|\\.JPEG|\\.jpeg)')\n for f in files:\n if matcher.match(f):\n #result['img'].append({ 'fname': f })\n result['img'].append(f)\n return json.dumps(result)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Image Slide Show')\n parser.add_argument('-H', '--host',\n action='store',\n nargs='?',\n const=None,\n default='localhost',\n type=str,\n choices=None,\n help='IP address or hostname that you want to open locate for web server (default: localhost)',\n metavar=None)\n parser.add_argument('-p', '--port',\n action='store',\n nargs='?',\n const=None,\n default='8080',\n type=str,\n choices=None,\n help='IP address or hostname that you want to open locate for web server (default: localhost)',\n metavar=None)\n args = parser.parse_args()\n\n run(host=args.host, port=args.port)\n","sub_path":"slick/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"194811128","text":"import os\n\n\ndef populate():\n print('Populating database')\n print('-------------------\\n')\n add_transductor_model()\n add_transductor()\n print('Finished database seed')\n\n\ndef add_transductor_model():\n print('Creating TR4020 transductor model')\n\n name = 'TR4020'\n model_code = '123456789'\n transport_protocol = 'UdpProtocol'\n serial_protocol = 'ModbusRTU'\n minutely_register_addresses = [\n [10, 1], [11, 1], [14, 1], [15, 1], [16, 1], [17, 1], [66, 2],\n [68, 2], [70, 2], [72, 2], [74, 2], [76, 2], [78, 2], [80, 2],\n [82, 2], [84, 2], [86, 2], [88, 2], [90, 2], [92, 2], [94, 2],\n [96, 2], [98, 2], [100, 2], [102, 2], [104, 2], [106, 2], [108, 2],\n [110, 2], [112, 2], [114, 2], [116, 2], [118, 2], [120, 2], [122, 2],\n [132, 2], [134, 2], [136, 2], [138, 2]\n ]\n quarterly_register_addresses = [\n [10, 1], [11, 1], [14, 1], [15, 1], [16, 1], [17, 1], [264, 2],\n [266, 2], [270, 2], [272, 2], [276, 2], [278, 2], [282, 2], [284, 2]\n ]\n monthly_register_addresses = [\n [10, 1], [11, 1], [14, 1], [15, 1], [16, 1], [17, 1], [156, 2],\n [158, 2], [162, 2], [164, 2], [168, 2], [170, 2], [174, 2], [176, 2],\n [180, 2], [182, 2], [186, 2], [188, 2], [420, 2], [422, 2], [424, 2],\n [426, 2], [428, 2], [430, 2], [432, 2], [434, 2], [444, 2], [446, 2],\n [448, 2], [450, 2], [452, 2], [454, 2], [456, 2], [458, 2], [516, 4],\n [520, 4], [524, 4], [528, 4], [540, 4], [544, 4], [548, 4], [552, 4]\n ]\n\n model, created = TransductorModel.objects.get_or_create(\n name=name,\n model_code=model_code,\n transport_protocol=transport_protocol,\n serial_protocol=serial_protocol,\n minutely_register_addresses=minutely_register_addresses,\n quarterly_register_addresses=quarterly_register_addresses,\n monthly_register_addresses=monthly_register_addresses\n )\n\n if created:\n print('Created TR4020')\n else:\n print('Transductor Model already existed')\n\n\ndef add_transductor():\n print('Creating transductor #1')\n transductor, created = EnergyTransductor.objects.get_or_create(\n serial_number='12345',\n ip_address='164.41.86.42',\n broken=False,\n active=True,\n model=TransductorModel.objects.get(name='TR4020'),\n firmware_version='12.1.3215',\n physical_location='Faculdade do gama prédio UED',\n geolocation_longitude=-15.989753,\n geolocation_latitude=-48.04542\n )\n\n if created:\n print('Created transductor #1')\n else:\n print('Transductor #1 already existed')\n\n print('Creating transductor #2')\n transductor2, created2 = EnergyTransductor.objects.get_or_create(\n serial_number='54321',\n ip_address='164.41.86.43',\n broken=False,\n active=True,\n model=TransductorModel.objects.get(name='TR4020'),\n firmware_version='12.1.3215',\n physical_location='Faculdade do gama prédio UED',\n geolocation_longitude=15.989533,\n geolocation_latitude=-48.04567\n )\n\n if created2:\n print('Created transductor #2')\n else:\n print('Transductor #2 already existed')\n\n\nif __name__ == '__main__':\n import django\n\n os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'smi.settings')\n django.setup()\n\n from transductor.models import EnergyTransductor\n from transductor_model.models import TransductorModel\n\n populate()\n\n print('Finished populating DB. YAY')\n print('-------------------\\n')\n","sub_path":"seed_db.py","file_name":"seed_db.py","file_ext":"py","file_size_in_byte":3555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"622348397","text":"import unittest\nimport os\nimport openfoodfacts\nimport requests\nimport requests_mock\n\n\nclass TestProducts(unittest.TestCase):\n\n def test_get_product(self):\n with requests_mock.mock() as mock:\n mock.get(\n 'https://world.openfoodfacts.org/api/v0/product/1223435.json',\n text='{\"name\":\"product_test\"}')\n res = openfoodfacts.get_product('1223435')\n self.assertEqual(res, {'name': 'product_test'})\n\n def test_get_by_trace(self):\n with requests_mock.mock() as mock:\n mock.get('https://world.openfoodfacts.org/trace/egg/1.json',\n text='{\"products\":[\"omelet\"]}')\n res = openfoodfacts.products.get_by_trace('egg')\n self.assertEqual(res, [\"omelet\"])\n\n def test_get_by_trace_pagination(self):\n with requests_mock.mock() as mock:\n mock.get('https://world.openfoodfacts.org/trace/egg/2.json',\n text='{\"products\":[\"omelet\"]}')\n res = openfoodfacts.products.get_by_trace('egg', 2)\n self.assertEqual(res, [\"omelet\"])\n\n def test_get_by_country(self):\n with requests_mock.mock() as mock:\n mock.get('https://world.openfoodfacts.org/country/france/1.json',\n text='{\"products\":[\"omelet\"]}')\n res = openfoodfacts.products.get_by_country('france')\n self.assertEqual(res, [\"omelet\"])\n\n def test_get_by_country_and_trace(self):\n res = openfoodfacts.products.get_by_facets({})\n self.assertEqual(res, [])\n\n with requests_mock.mock() as mock:\n mock.get(\n 'https://world.openfoodfacts.org/country/'\n 'france/trace/egg/1.json',\n text='{\"products\":[\"omelet\"]}')\n res = openfoodfacts.products.get_by_facets(\n {'trace': 'egg', 'country': 'france'})\n self.assertEqual(res, [\"omelet\"])\n\n def test_search(self):\n with requests_mock.mock() as mock:\n mock.get(\n 'https://world.openfoodfacts.org/cgi/search.pl?' +\n 'search_terms=kinder bueno&json=1&page=' +\n '1&page_size=20&sort_by=unique_scans',\n text='{\"products\":[\"kinder bueno\"], \"count\": 1}')\n res = openfoodfacts.products.search('kinder bueno')\n self.assertEqual(res[\"products\"], [\"kinder bueno\"])\n mock.get(\n 'https://world.openfoodfacts.org/cgi/search.pl?' +\n 'search_terms=banania&json=1&page=' +\n '2&page_size=10&sort_by=unique_scans',\n text='{\"products\":[\"banania\", \"banania big\"], \"count\": 2}')\n res = openfoodfacts.products.search(\n 'banania', page=2, page_size=10)\n self.assertEqual(res[\"products\"], [\"banania\", \"banania big\"])\n\n def test_advanced_search(self):\n with requests_mock.mock() as mock:\n mock.get(\n 'https://world.openfoodfacts.org/cgi/search.pl?' +\n 'search_terms=coke&tagtype_0=packaging&' +\n 'tag_contains_0=contains&tag_0=plastic&' +\n 'nutriment_0=energy&nutriment_compare_0=gt&' +\n 'nutriment_value_0=0&sort_by=unique_scans&' +\n 'page_size=20',\n text= '{\"products\":[\"Diet Coke\"], \"count\": 1}')\n res = openfoodfacts.products.advanced_search({\n \"search_terms\":\"coke\",\n \"tagtype_0\":\"packaging\",\n \"tag_contains_0\":\"contains\",\n \"tag_0\":\"plastic\",\n \"nutriment_0\":\"energy\",\n \"nutriment_compare_0\":\"gt\",\n \"nutriment_value_0\":\"0\",\n \"sort_by\":\"unique_scans\",\n \"page_size\":\"20\"\n })\n self.assertEqual(res[\"products\"],[\"Diet Coke\"])\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/products_test.py","file_name":"products_test.py","file_ext":"py","file_size_in_byte":3921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"77632724","text":"\n\n#calss header\nclass _BAGEL():\n\tdef __init__(self,): \n\t\tself.name = \"BAGEL\"\n\t\tself.definitions = [u'a type of bread that is small, hard, and in the shape of a ring: ', u'in tennis, a situation in which a player has won a set (= part of a match) by 6 games to 0.']\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/_bagel.py","file_name":"_bagel.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"153584453","text":"from django.http import request\nfrom base.forms.invoice_form import InvoiceForm\nfrom decimal import Decimal\n\nfrom django.http.response import HttpResponse\nfrom base.models.Invoice import Event\nfrom django.core.checks import messages\nfrom base.models import product\nfrom base.models.product import Product\nfrom django.contrib.auth import logout\nfrom django.shortcuts import redirect, render, get_object_or_404\nfrom base.models.Invoice import Invoice\nfrom base.models.order import Order, OrderItem\nfrom django.contrib import messages\nfrom django.contrib.auth.models import User\nfrom django.http import JsonResponse\nfrom base.forms.order_form import UpdateOrderForm\nfrom django.contrib.auth.decorators import login_required\n\n\ndef create_order(request):\n context = {\n 'products': Product.objects.all(),\n 'events': Event.objects.all()\n }\n return render(request, 'orders/add_order.html', context)\n\n\ndef get_product(request):\n product_id = request.GET.get('product')\n # Getting the data of that specific Product\n product = Product.objects.get(id=product_id)\n data = {\n 'rate': product.Price,\n }\n return JsonResponse(data)\n\n\ndef ajax_order_create(request):\n if request.method == 'POST':\n # Getting the data from form inputs from ajax.\n product = request.POST.get('product')\n quantity = request.POST.get('quantity')\n sub_total = request.POST.get('sub_total')\n # The String coming from ajax is e.g \"[\"40\", \"42\"]\", converting this to \"40\", \"42\"\n products = product[1:-1]\n quantities = quantity[1:-1]\n sub_totals = sub_total[1:-1]\n\n # Converting string to array using python split() method\n products_list = products.split(',')\n quantities_list = quantities.split(',')\n sub_totals_list = sub_totals.split(',')\n # Slicing the double quotes (\") from array indexes and converting them to decimals\n sub_totals_list = [x.strip(' \"') for x in sub_totals_list]\n sub_totals_list = [Decimal(i) for i in sub_totals_list]\n # Slicing the double quotes (\") from array indexes and converting them to int\n quantities_list = [x.strip(' \"') for x in quantities_list]\n quantities_list = [int(i) for i in quantities_list]\n # product_list contains the id's of products/items selected in form\n products_list = [x.strip(' \"') for x in products_list]\n products_list = [int(i) for i in products_list]\n # Creating the order object\n order = Order.objects.create(\n full_name='Abu Bakar',\n phn_number='03006890011',\n email='abubakar@gmail.com',\n address='Model Town Lahore'\n )\n for i in range(len(products_list)):\n OrderItem.objects.create(\n orderItem=order,\n products_id=products_list[i],\n price=sub_totals_list[i],\n quantity=quantities_list[i],\n )\n data = {'name': 'Abubakar'}\n return JsonResponse(data)\n\n# def add_order(request):\n# form = InvoiceForm()\n# if request.method == \"POST\":\n# form = InvoiceForm(request.POST or None)\n# if form.is_valid:\n# form.save()\n# #name = Product.objects.only('product_name').get(baseentity_ptr = request.POST.get('Product_id'))\n# sale = Product.objects.only('stock').get(baseentity_ptr = request.POST.get('Product_id'))\n# qty = int(request.POST.get(\"sold_Quantity\"))\n# sale.count_sold = sale.count_sold + qty\n# sale.save()\n# sale = Product.objects.only('stock').get(baseentity_ptr = request.POST.get('Product_id'))\n#\n# else:\n# HttpResponse(\"Error Occured\")\n#\n# context = [{\n# 'Product_id':Product.objects.only('product_name').get(baseentity_ptr = request.POST.get('Product_id')),\n# 'qty' : request.POST.get(\"sold_Quantity\"),\n# 'price' : request.POST.get(\"price\"),\n# 'total_price' : request.POST.get(\"total_price\"),\n# 'date' : request.POST.get('date_time'),\n# 'namount' : request.POST.get('namount'),\n# 'event' : Event.objects.only('event_name').get(id = request.POST.get('Event_Name'))\n# }]\n#\n# return render(request,'invoice/invoice.html',{'context':context})\n# return render(request,'orders/add_order.html',{'form':form,'data':Product.objects.all()})\n\ndef invoice(request):\n return render(request,'invoice/invoice.html',{'context':Invoice.objects.all()})\n@login_required(login_url='login')\ndef manageOrders(request):\n return render(request,'invoice/invoice.html',{'context':Invoice.objects.all()})\ndef viewOrder(request):\n return render(request,'orders/list_of_order.html',{'context':OrderItem.objects.all()})\n\ndef load_price(request):\n product_id = request.GET.get('product_id')\n price = Product.objects.only('Price').filter(baseentity_ptr=product_id).get()\n return render(request, 'orders/price.html', {'prices': price})\n # return JsonResponse(list(cities.values('id', 'name')), safe=False)\n\n@login_required(login_url='login')\ndef updateOrder(request,pk):\n order_item = get_object_or_404(OrderItem, pk=pk) # baseentity_ptr\n form = UpdateOrderForm(instance=order_item)\n if request.method == 'POST':\n form = UpdateOrderForm(request.POST, instance=order_item)\n if form.is_valid():\n form.save()\n return redirect('view-order')\n return render(request,'orders/update_order.html',{'form':form})\n \n@login_required(login_url='login')\ndef deleteOrder(request,pk):\n dell = OrderItem.objects.filter(baseentity_ptr=pk).delete()\n messages.success(request,\"Order Deleted Successfully\")\n return render(request, 'orders/list_of_order.html', {'context': OrderItem.objects.all(), 'dell': dell})\n","sub_path":"base/views/orderView.py","file_name":"orderView.py","file_ext":"py","file_size_in_byte":5838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"550533906","text":"\"\"\"\nPlotting routines\n\"\"\"\nfrom __future__ import absolute_import\nfrom .utility import *\nfrom . import colorconversion\n\n\ndef plot_points(points):\n \"\"\"\n Plots points in (x,y) space\n \"\"\"\n fig, ax = plt.subplots()\n ax.plot(points[:, 0], points[:, 1], 'ko')\n ax.axis('equal')\n ax.set_xlim([-1.1, 1.1])\n ax.set_ylim([-1.1, 1.1])\n plt.show()\n\n\ndef plot_lab_points(lab):\n \"\"\"\n Plots sequence of Lab colors in (a,b) plane\n \"\"\"\n rgb = colorconversion.lab_to_rgb(lab)\n fig, ax = plt.subplots()\n ax.scatter(lab[:, 1], lab[:, 2], s=60, c=rgb, edgecolors='none')\n ax.axis('equal')\n ax.set_xlim([-105., 105.])\n ax.set_ylim([-105., 105.])\n ax.set_xlabel('a')\n ax.set_ylabel('b')\n plt.show()\n\n\ndef plot_colorsequence_lines(rgb_colors):\n \"\"\"\n Plots a series of lines with given colors\n \"\"\"\n fig, ax = plt.subplots()\n ncolors = rgb_colors.shape[0]\n for i, c in enumerate(rgb_colors):\n y = float(i)/ncolors + 0.5/ncolors\n ax.plot([0, 1], [y, y], color=c, lw=4)\n plt.show()\n\n\ndef plot_cmap(cmap, ax=None, aspect=10.):\n if ax is None:\n fig, ax = plt.subplots()\n\n gradient = numpy.linspace(0, 1, 256)\n gradient = numpy.vstack((gradient, gradient))\n\n ax.imshow(gradient, aspect=aspect, cmap=cmap)\n pos = list(ax.get_position().bounds)\n x_text = pos[0] - 0.01\n y_text = pos[1] + pos[3]/2.\n fig.text(x_text, y_text, cmap.name, va='center', ha='right', fontsize=10)\n ax.set_axis_off()\n\n\ndef plot_cmap_list(cmap_list):\n nrows = len(cmap_list)\n fig, axes = plt.subplots(nrows=nrows)\n fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99)\n\n for ax, cmap in zip(axes, cmap_list):\n if isinstance(cmap, str):\n c = plt.get_cmap(c)\n else:\n c = cmap\n plot_cmap(cmap, ax)\n","sub_path":"amphora/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"123284972","text":"from time import sleep\n\ndef add_json_node(tx, label='Generic', properties=None):\n if properties is None:\n properties = dict()\n prop_set = '{' + ','.join('{key}:{{{key}}}'.format(key=k) for k in properties) + '}'\n query = 'MERGE (n:{label} '.format(label=label) + prop_set + ') RETURN n'\n return tx.run(query, **properties)\n\ndef get_count(tx, finder):\n # For instance:\n # finder = 'MATCH (n:Article) WHERE n.journal CONTAINS 'Experimental Biology'\n count_query = finder + ' WITH COUNT (n) AS count RETURN count LIMIT 1'\n count = tx.run(count_query)\n count = list(count.records())[0]['count']\n return count\n\ndef get_page_queries(query, count, page_size=1000, rate_limit=0.25):\n properties = dict()\n for i in range(count // page_size):\n properties['skip'] = i * page_size\n properties['limit'] = page_size\n page_query = query + ' SKIP {skip} LIMIT {limit}'\n yield page_query, properties\n sleep(rate_limit)\n\ndef page(tx, finder, query, properties=None, page_size=1000, rate_limit=0.25):\n if properties is None:\n properties = dict()\n # For instance:\n # query = MATCH (n:Article) WHERE n.abstract CONTAINS 'Aerodynamics'\n # finder = 'MATCH (n:Article) WHERE n.journal CONTAINS 'Experimental Biology'\n # WITH COUNT (n) AS count RETURN count LIMIT 1'\n count = get_count(tx, finder)\n for query, q_properties in get_page_queries(query, count, page_size=page_size, rate_limit=rate_limit):\n properties.update(q_properties)\n yield tx.run(query, **properties)\n","sub_path":"legacy/petal/mining/utils/neo.py","file_name":"neo.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"530163356","text":"from django.contrib import admin\n\nfrom .models import *\nfrom .forms import ReviewAdminForm\n\n\nclass CarAdmin(admin.ModelAdmin):\n list_display = ('brand', 'model', 'get_reviews')\n filter = ('brand', 'model')\n search_fields = ('brand', 'model')\n ordering = ('pk',)\n\n\nclass ReviewAdmin(admin.ModelAdmin):\n form = ReviewAdminForm\n list_display = ('car', 'title',)\n filter = ('title', 'car',)\n search_fields = ('car__model',)\n\n\nadmin.site.register(Car, CarAdmin)\nadmin.site.register(Review, ReviewAdmin)\n","sub_path":"site-form-works/car_admin/app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"540431475","text":"# imports\nfrom flask import Flask,jsonify\nfrom flask_mysqldb import MySQL\nfrom blueprints.location import location\nfrom blueprints.buses import buses\n\n\n# Initialize Application\napp = Flask(__name__)\n\n# Registering Blueprint\napp.register_blueprint(location,url_prefix = \"/location\")\napp.register_blueprint(buses,url_prefix = \"/buses\")\n\n# Database Configuration\napp.config['MYSQL_HOST'] = \"localhost\"\napp.config[\"MYSQL_USER\"] = \"root\"\napp.config[\"MYSQL_PASSWORD\"] = \"Krishna@7860\"\napp.config[\"MYSQL_DB\"] = \"busroute\"\napp.config[\"MYSQL_CURSORCLASS\"] = \"DictCursor\"\n\nmysql = MySQL(app)\n\n# @desc : Home Route\n# route: \"/\"\n# @param : null\n# return : JSON\n@app.route(\"/\")\ndef home():\n try:\n conn = mysql.connection.cursor()\n conn.execute(\"\"\"SELECT DATABASE()\"\"\")\n row = conn.fetchone()\n return jsonify(row),200\n except Exception as e:\n return jsonify({\"error\" : str(e)})\n finally:\n conn.close()\n\n\nif __name__ == \"__main__\" and __package__ is None:\n app.run(debug=True)","sub_path":"submissions/sm_108_krishna-kant/week_23/server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"153736925","text":"def readFile(file):\n name = file[:file.index('.')]\n ##print(name)\n f = open(file)\n fout = open(name+'.out','w')\n cases = int(f.readline().strip())\n for i in range(cases):\n case = f.readline().strip().split()\n n = int(case[0])\n s = int(case[1])\n p = int(case[2])\n scores = [int(x) for x in case[3:]]\n result = execute(i,n,s,p,scores)\n print(result)\n fout.write(result)\n\ndef execute(index,n,s,p,scores):\n print(index,n,s,p,scores)\n count=0\n tempS = s\n triplets = []\n\n for j in range(n):\n mean = int(scores[j]/3)\n remainder = scores[j]%3\n\n triplet = [mean for x in range(3)]\n\n c = 0\n while remainder > 0 :\n triplet[c] = triplet[c]+1\n remainder-=1\n c+=1\n\n triplets.append(triplet)\n\n ##add suprising\n for t in triplets:\n if t[0] >= p:\n count+=1\n continue\n elif (tempS > 0 and (p-t[0]) == 1 and t[0] == t[1] and t[1] > 0):\n #surprise case\n t[0]=t[0]+1\n t[1]=t[1]-1\n count+=1\n tempS-=1\n continue\n\n print(tempS)\n print(triplets)\n \n return ''.join(['Case #',str(index+1),': ',str(count),'\\n'])\n \n\n\nif __name__ == \"__main__\":\n readFile('B-small-attempt1.in')\n","sub_path":"solutions_1595491_0/Python/ToR/dancing_with_the_googlers.py","file_name":"dancing_with_the_googlers.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"1610786","text":"#!/usr/bin/env python3\n\nimport os, os.path\nimport sys\nimport socket\nimport time\n\n# Used to gracefully aborting stuff.. like a hippo exiting a stage\nclass AbandonShip(BaseException):\n\tpass\n\n# Default config values.\n_config = {\n\t'host': 'api.anidb.net',\n\t'port': '9000',\n\t'session': '~/.kiara.session',\n\t'database': '~/.kiara.db',\n}\n\ndef _config_items(file):\n\tfor line in map(lambda s: s.strip(), file.readlines()):\n\t\tif line.startswith('#') or not line:\n\t\t\tcontinue\n\t\tyield line.split(None, 1)\n\ndef load_config_file(file_name):\n\tglobal _config\n\ttry:\n\t\twith open(file_name, 'r') as fp:\n\t\t\t_config.update(_config_items(fp))\n\texcept: pass\nload_config_file('/etc/kiararc')\nload_config_file(os.path.expanduser('~/.kiararc'))\n\ndef check_config():\n\tconfig_ok = True\n\tfor key in 'host port user pass database session ' \\\n\t\t'basepath_movie basepath_series'.split():\n\t\tif not key in _config:\n\t\t\tprint('ERROR: Missing config variable:', key, file=sys.stderr)\n\t\t\tconfig_ok = False\n\treturn config_ok\n\ndef _send(msg):\n\tprint()\n\tdef inner():\n\t\tclient = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n\t\tclient.connect(os.path.expanduser(_config['session']))\n\t\tclient.sendall(bytes(msg, 'UTF-8'))\n\t\tdata = ''\n\t\twhile True:\n\t\t\tdata += str(client.recv(1024), 'UTF-8')\n\t\t\tif data == '---end---':\n\t\t\t\tclient.close()\n\t\t\t\treturn\n\t\t\tif '\\n' in data:\n\t\t\t\titem, data = data.split('\\n', 1)\n\t\t\t\tyield item\n\ttry:\n\t\tfor i in inner():\n\t\t\tyield i\n\texcept socket.error:\n\t\tprint('Unable to contact the backend. Will try to start one...')\n\t\tif os.fork():\n\t\t\t# Wait for it...\n\t\t\ttime.sleep(2)\n\t\t\t# Then try the command again. If it fails again, something we\n\t\t\t# cannot fix is wrong\n\t\t\tfor i in inner():\n\t\t\t\tyield i\n\t\t\treturn\n\t\t\tprint('Unable to start a new backend, sorry :(')\n\t\telse:\n\t\t\tfrom libkiara import backend\n\t\t\tbackend.serve(_config)\n\ndef ping():\n\twah = False\n\tfor l in _send('- ping'):\n\t\tprint(l)\n\t\twah = l == 'pong'\n\treturn wah\n\ndef process(file, watch=False, organize=False):\n\tq = 'a'\n\tif watch:\n\t\tq += 'w'\n\tif organize:\n\t\tq += 'o'\n\t\n\tfor line in _send(q + ' ' + file):\n\t\tprint(line)\n\ndef find_duplicates():\n\tfor line in _send('- dups'):\n\t\tprint(line)\n\ndef forget(*fids):\n\tfor line in _send('- forget ' + ' '.join(list(map(str, fids)))):\n\t\tprint(line)\n","sub_path":"libkiara/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"180912846","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# 3rd party imports\nimport numpy as np\n\nfrom cdflib import CDF, cdfepoch\n\n# Local imports\nfrom ..pyrf import ts_skymap, iso86012datetime64, datetime642ttns\n\n__author__ = \"Louis Richard\"\n__email__ = \"louisr@irfu.se\"\n__copyright__ = \"Copyright 2020-2021\"\n__license__ = \"MIT\"\n__version__ = \"2.3.7\"\n__status__ = \"Prototype\"\n\n\ndef get_dist(file_path, cdf_name, tint):\n r\"\"\"Read field named cdf_name in file and convert to velocity distribution\n function.\n\n Parameters\n ----------\n file_path : str\n Path of the cdf file.\n cdf_name : str\n Name of the target variable in the cdf file.\n tint : list of str\n Time interval.\n\n Returns\n -------\n out : xarray.Dataset\n Time series of the velocity distribution function if the target\n specie in the selected time interval.\n\n \"\"\"\n\n tmmode = cdf_name.split(\"_\")[-1]\n\n tint = list(datetime642ttns(iso86012datetime64(np.array(tint))))\n\n with CDF(file_path) as f:\n if tmmode == \"brst\":\n depend0_key = f.varattsget(cdf_name)[\"DEPEND_0\"]\n depend1_key = f.varattsget(cdf_name)[\"DEPEND_1\"]\n depend2_key = f.varattsget(cdf_name)[\"DEPEND_2\"]\n depend3_key = f.varattsget(cdf_name)[\"DEPEND_3\"]\n\n t = f.varget(depend0_key, starttime=tint[0], endtime=tint[1])\n t = cdfepoch.to_datetime(t, to_np=True)\n\n if not t.size:\n return None\n\n dist = f.varget(cdf_name, starttime=tint[0], endtime=tint[1])\n dist = np.transpose(dist, [0, 3, 1, 2])\n ph = f.varget(depend1_key, starttime=tint[0], endtime=tint[1])\n th = f.varget(depend2_key)\n en = f.varget(depend3_key, starttime=tint[0], endtime=tint[1])\n\n en0_name = \"_\".join([cdf_name.split(\"_\")[0],\n cdf_name.split(\"_\")[1], \"energy0\",\n cdf_name.split(\"_\")[-1]])\n en1_name = \"_\".join([cdf_name.split(\"_\")[0],\n cdf_name.split(\"_\")[1], \"energy1\",\n cdf_name.split(\"_\")[-1]])\n d_en_name = \"_\".join([cdf_name.split(\"_\")[0],\n cdf_name.split(\"_\")[1], \"energy_delta\",\n cdf_name.split(\"_\")[-1]])\n e_step_table_name = \"_\".join([cdf_name.split(\"_\")[0],\n cdf_name.split(\"_\")[1],\n \"steptable_parity\",\n cdf_name.split(\"_\")[-1]])\n\n step_table = f.varget(e_step_table_name,\n starttime=tint[0], endtime=tint[1])\n if d_en_name in f.cdf_info()[\"zVariables\"]:\n delta_plus_var = f.varget(d_en_name,\n starttime=tint[0], endtime=tint[1])\n delta_minus_var = f.varget(d_en_name,\n starttime=tint[0], endtime=tint[1])\n\n if en0_name not in f.cdf_info()[\"zVariables\"]:\n energy0 = en[1, :]\n energy1 = en[0, :]\n else:\n energy0 = f.varget(en0_name)\n energy1 = f.varget(en1_name)\n\n res = ts_skymap(t, dist, None, ph, th, energy0=energy0,\n energy1=energy1, esteptable=step_table)\n\n if \"delta_plus_var\" in locals() and \"delta_minus_var\" in locals():\n res.attrs[\"delta_energy_minus\"] = delta_minus_var\n res.attrs[\"delta_energy_plus\"] = delta_plus_var\n\n res.attrs = {**res.attrs, **f.varattsget(cdf_name)}\n\n elif tmmode == \"fast\":\n depend0_key = f.varattsget(cdf_name)[\"DEPEND_0\"]\n depend1_key = f.varattsget(cdf_name)[\"DEPEND_1\"]\n depend2_key = f.varattsget(cdf_name)[\"DEPEND_2\"]\n depend3_key = f.varattsget(cdf_name)[\"DEPEND_3\"]\n\n t = f.varget(depend0_key, starttime=tint[0], endtime=tint[1])\n\n dist = f.varget(cdf_name, starttime=tint[0], endtime=tint[1])\n dist = np.transpose(dist, [0, 3, 1, 2])\n ph = f.varget(depend1_key)\n th = f.varget(depend2_key)\n en = f.varget(depend3_key, starttime=tint[0], endtime=tint[1])\n res = ts_skymap(t, dist, en, ph, th)\n\n for k in f.varattsget(cdf_name):\n res.attrs[k] = f.varattsget(cdf_name)[k]\n\n for k in f.cdf_info():\n res.attrs[k] = f.cdf_info()[k]\n\n res.attrs[\"tmmode\"] = tmmode\n if \"_dis_\" in cdf_name:\n res.attrs[\"species\"] = \"ions\"\n else:\n res.attrs[\"species\"] = \"electrons\"\n return res\n","sub_path":"pyrfu/mms/get_dist.py","file_name":"get_dist.py","file_ext":"py","file_size_in_byte":4753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"329714925","text":"\nclass tree():\n def __init__(self):\n self.root=None\n\n def insert(self,node):\n end=False\n if self.root==None:\n self.root=node\n end=True\n present=self.root\n while end==False:\n if node.id>present.id and present.right_child==None:\n present.right_child=node\n end=True\n elif node.id>present.id and present.right_child!=None:\n present=present.right_child\n elif node.idcurrent.id:\n current=current.right_child\n else:\n current=current.left_child\n return current\n def change(self,node1,node2):\n node1.id=node2.id\n node1.name=node2.name\n node1.interest=node2.interest\n node1.gender=node2.gender\n node1.age=node2.age\n def delete(self, root, user):\n \n # Find the node to be deleted and remove it\n if not root:\n return root\n elif user.id < root.id:\n root.left_child = self.delete_node(root.left_child, user.id)\n elif user.id > root.id:\n root.right_child = self.delete_node(root.right_child, user.id)\n else:\n if root.left_child is None:\n temp = root.right_child\n root = None\n return temp\n elif root.right_child is None:\n temp = root.left_child\n root = None\n return temp\n temp = self.getMinValueNode(root.right_child)\n root.id = temp.id\n root.right_child = self.delete(root.right_child,\n temp.id)\n if root is None:\n return root\n def getMinValueNode(self, root):\n if root is None or root.left_child is None:\n return root\n return self.getMinValueNode(root.left_child)","sub_path":"server/btree.py","file_name":"btree.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"23588508","text":"#!/usr/bin/python\n\nimport ftplib\nimport re\nimport os\n\nHOST=r'alvspxw02'\nDIRN=r'8.5.4/'\n\nfile_filter=r'^sp_setup-\\d\\.\\d\\.\\d\\.\\d{3}\\.exe$'\n\n#ftp=ftplib.FTP(HOST)\nwith ftplib.FTP(HOST) as ftp:\n ftp.login('###\\###','###')\n ftp.cwd(DIRN)\n\n available_builds=[]\n for i in ftp.nlst():\n if re.match(file_filter,i):\n available_builds.append(i)\n\n latest_build=max(available_builds)\n\n if not os.path.exists(latest_build):\n ftp.retrbinary('RETR '+(latest_build),open(latest_build, 'wb').write)\n#ftp.close()\n\n","sub_path":"daily_get_build_windows.py","file_name":"daily_get_build_windows.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"645180743","text":"# Copyright 2018 the rules_flex 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# SPDX-License-Identifier: Apache-2.0\n\nTOOLCHAIN_TYPE = \"@rules_flex//flex:toolchain_type\"\n\nToolchainInfo = provider(fields = [\"files\", \"vars\", \"flex_executable\", \"flex_lexer_h\"])\n\ndef _flex_toolchain_info(ctx):\n toolchain = ToolchainInfo(\n flex_executable = ctx.executable.flex,\n flex_lexer_h = ctx.file.flex_lexer_h,\n files = depset(direct = [ctx.executable.flex]),\n vars = {\"FLEX\": ctx.executable.flex.path},\n )\n return [\n platform_common.ToolchainInfo(flex_toolchain = toolchain),\n platform_common.TemplateVariableInfo(toolchain.vars),\n ]\n\nflex_toolchain_info = rule(\n _flex_toolchain_info,\n attrs = {\n \"flex\": attr.label(\n mandatory = True,\n executable = True,\n cfg = \"host\",\n ),\n \"flex_lexer_h\": attr.label(\n mandatory = True,\n allow_single_file = [\".h\"],\n ),\n },\n provides = [\n platform_common.ToolchainInfo,\n platform_common.TemplateVariableInfo,\n ],\n)\n\ndef _flex_toolchain_alias(ctx):\n toolchain = ctx.toolchains[TOOLCHAIN_TYPE].flex_toolchain\n return [\n DefaultInfo(files = toolchain.files),\n toolchain,\n platform_common.TemplateVariableInfo(toolchain.vars),\n ]\n\nflex_toolchain_alias = rule(\n _flex_toolchain_alias,\n toolchains = [TOOLCHAIN_TYPE],\n provides = [\n DefaultInfo,\n ToolchainInfo,\n platform_common.TemplateVariableInfo,\n ],\n)\n","sub_path":"flex/internal/toolchain.bzl","file_name":"toolchain.bzl","file_ext":"bzl","file_size_in_byte":2065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"428698540","text":"\"\"\"\nQuest:\n You are given coins of different denominations and a total amount of money amount.\n Write a function to compute the fewest number of coins that you need to make up that amount.\n If that amount of money cannot be made up by any combination of the coins, return -1.\n\n Example 1:\n Input: coins = [1, 2, 5], amount = 11\n Output: 3\n Explanation: 11 = 5 + 5 + 1\n\n Example 2:\n Input: coins = [2], amount = 3\n Output: -1\n Note:\n You may assume that you have an infinite number of each kind of coin.\n\nSolution:\n - sort the coin array, then start from the largest?\n - no, because this is not real coins [1, 5, 10, 50, 100] like this, so we cannot use greedy algorithm\n - for a list [] of length = amount, each list[i] represent the least coins we need to reach the total i amount\n then for the next list[i+1], we could use dp to search 0 - i and get the result\n\"\"\"\n\n\nclass Solution:\n def coinChange(self, coins: 'List[int]', amount: 'int') -> 'int':\n MAX = float('inf') # here MAX means no solution to reach the amount i\n dp = [0] + [MAX] * amount\n\n for i in range(1, amount+1):\n dp[i] = min([dp[i-c] if i - c >= 0 else MAX for c in coins]) + 1\n\n return dp[amount] if dp[amount] != MAX else -1\n\n\ntest = Solution()\ncoins = [2]\namount = 3\nprint(test.coinChange(coins, amount))","sub_path":"coinChange_re.py","file_name":"coinChange_re.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"397274575","text":"import itertools\nimport json\nimport logging\nimport os\nimport numpy as np\nimport pandas as pd\nfrom scipy.special import expit, softmax\n\nimport torch\nfrom transformers.modeling_bert import BertForPreTraining, BertLayerNorm, ACT2FN, BertForQuestionAnswering\n\nfrom torch import nn\nfrom torch.nn import CrossEntropyLoss, MSELoss, BCEWithLogitsLoss\n\nfrom farm.data_handler.utils import is_json\nfrom farm.utils import convert_iob_to_simple_tags\n\nlogger = logging.getLogger(__name__)\n\n\nclass PredictionHead(nn.Module):\n \"\"\" Takes word embeddings from a language model and generates logits for a given task. Can also convert logits\n to loss and and logits to predictions. \"\"\"\n\n subclasses = {}\n\n def __init_subclass__(cls, **kwargs):\n \"\"\" This automatically keeps track of all available subclasses.\n Enables generic load() for all specific PredictionHead implementation.\n \"\"\"\n super().__init_subclass__(**kwargs)\n cls.subclasses[cls.__name__] = cls\n\n @classmethod\n def create(cls, prediction_head_name, layer_dims, class_weights=None):\n \"\"\"\n Create subclass of Prediction Head.\n\n :param prediction_head_name: Classname (exact string!) of prediction head we want to create\n :type prediction_head_name: str\n :param layer_dims: describing the feed forward block structure, e.g. [768,2]\n :type layer_dims: List[Int]\n :param class_weights: The loss weighting to be assigned to certain label classes during training.\n Used to correct cases where there is a strong class imbalance.\n :type class_weights: list[Float]\n :return: Prediction Head of class prediction_head_name\n \"\"\"\n # TODO make we want to make this more generic.\n # 1. Class weights is not relevant for all heads.\n # 2. Layer weights impose FF structure, maybe we want sth else later\n # Solution: We could again use **kwargs\n return cls.subclasses[prediction_head_name](\n layer_dims=layer_dims, class_weights=class_weights\n )\n\n def save_config(self, save_dir, head_num=0):\n \"\"\"\n Saves the config as a json file.\n\n :param save_dir: Path to save config to\n :type save_dir: str\n :param head_num: Which head to save\n :type head_num: int\n \"\"\"\n output_config_file = os.path.join(\n save_dir, f\"prediction_head_{head_num}_config.json\"\n )\n with open(output_config_file, \"w\") as file:\n json.dump(self.config, file)\n\n def save(self, save_dir, head_num=0):\n \"\"\"\n Saves the prediction head state dict.\n\n :param save_dir: path to save prediction head to\n :type save_dir: str\n :param head_num: which head to save\n :type head_num: int\n \"\"\"\n output_model_file = os.path.join(save_dir, f\"prediction_head_{head_num}.bin\")\n torch.save(self.state_dict(), output_model_file)\n self.save_config(save_dir, head_num)\n\n def generate_config(self):\n \"\"\"\n Generates config file from Class parameters (only for sensible config parameters).\n \"\"\"\n config = {}\n for key, value in self.__dict__.items():\n if is_json(value) and key[0] != \"_\":\n config[key] = value\n config[\"name\"] = self.__class__.__name__\n self.config = config\n\n @classmethod\n def load(cls, config_file):\n \"\"\"\n Loads a Prediction Head. Infers the class of prediction head from config_file.\n\n :param config_file: location where corresponding config is stored\n :type config_file: str\n :return: PredictionHead\n :rtype: PredictionHead[T]\n \"\"\"\n config = json.load(open(config_file))\n prediction_head = cls.subclasses[config[\"name\"]](**config)\n model_file = cls._get_model_file(config_file=config_file)\n logger.info(\"Loading prediction head from {}\".format(model_file))\n prediction_head.load_state_dict(torch.load(model_file, map_location=torch.device(\"cpu\")))\n return prediction_head\n\n def logits_to_loss(self, logits, labels):\n \"\"\"\n Implement this function in your special Prediction Head.\n Should combine logits and labels with a loss fct to a per sample loss.\n\n :param logits: logits, can vary in shape and type, depending on task\n :type logits: object\n :param labels: labels, can vary in shape and type, depending on task\n :type labels: object\n :return: per sample loss as a torch.tensor of shape [batch_size]\n \"\"\"\n raise NotImplementedError()\n\n def logits_to_preds(self, logits):\n \"\"\"\n Implement this function in your special Prediction Head.\n Should combine turn logits into predictions.\n\n :param logits: logits, can vary in shape and type, depending on task\n :type logits: object\n :return: predictions as a torch.tensor of shape [batch_size]\n \"\"\"\n raise NotImplementedError()\n\n def prepare_labels(self, **kwargs):\n \"\"\"\n Some prediction heads need additional label conversion.\n E.g. NER needs word level labels turned into subword token level labels.\n\n :param kwargs: placeholder for passing generic parameters\n :type kwargs: object\n :return: labels in the right format\n :rtype: object\n \"\"\"\n # TODO maybe just return **kwargs to not force people to implement this\n raise NotImplementedError()\n\n @classmethod\n def _get_model_file(cls, config_file):\n if \"config.json\" in config_file and \"prediction_head\" in config_file:\n head_num = int(\"\".join([char for char in os.path.basename(config_file) if char.isdigit()]))\n model_file = os.path.join(os.path.dirname(config_file), f\"prediction_head_{head_num}.bin\")\n else:\n raise ValueError(f\"This doesn't seem to be a proper prediction_head config file: '{config_file}'\")\n return model_file\n\n def _set_name(self, name):\n self.task_name = name\n\n\nclass RegressionHead(PredictionHead):\n def __init__(\n self,\n layer_dims,\n task_name=\"regression\",\n **kwargs,\n ):\n super(RegressionHead, self).__init__()\n # num_labels could in most cases also be automatically retrieved from the data processor\n self.layer_dims = layer_dims\n self.feed_forward = FeedForwardBlock(self.layer_dims)\n self.num_labels = 2\n self.ph_output_type = \"per_sequence_continuous\"\n self.model_type = \"regression\"\n self.loss_fct = MSELoss(reduction=\"none\")\n self.task_name = task_name\n self.generate_config()\n\n def forward(self, x):\n logits = self.feed_forward(x)\n return logits\n\n def logits_to_loss(self, logits, **kwargs):\n # Squeeze the logits to obtain a coherent output size\n label_ids = kwargs.get(self.label_tensor_name)\n return self.loss_fct(logits.squeeze(), label_ids.float())\n\n def logits_to_preds(self, logits, **kwargs):\n preds = logits.cpu().numpy()\n #rescale predictions to actual label distribution\n preds = [x * self.label_list[1] + self.label_list[0] for x in preds]\n return preds\n\n def prepare_labels(self, **kwargs):\n label_ids = kwargs.get(self.label_tensor_name)\n label_ids = label_ids.cpu().numpy()\n label_ids = [x * self.label_list[1] + self.label_list[0] for x in label_ids]\n return label_ids\n\n def formatted_preds(self, logits, samples, **kwargs):\n preds = self.logits_to_preds(logits)\n contexts = [sample.clear_text[\"text\"] for sample in samples]\n\n assert len(preds) == len(contexts)\n\n res = {\"task\": \"regression\", \"predictions\": []}\n for pred, context in zip(preds, contexts):\n res[\"predictions\"].append(\n {\n \"context\": f\"{context}\",\n \"pred\": pred[0]\n }\n )\n return res\n\n\nclass TextClassificationHead(PredictionHead):\n def __init__(\n self,\n layer_dims,\n class_weights=None,\n loss_ignore_index=-100,\n loss_reduction=\"none\",\n task_name=\"text_classification\",\n **kwargs,\n ):\n super(TextClassificationHead, self).__init__()\n # num_labels could in most cases also be automatically retrieved from the data processor\n self.layer_dims = layer_dims\n self.feed_forward = FeedForwardBlock(self.layer_dims)\n self.num_labels = self.layer_dims[-1]\n self.ph_output_type = \"per_sequence\"\n self.model_type = \"text_classification\"\n self.task_name = task_name #used for connecting with the right output of the processor\n self.class_weights = class_weights\n\n if class_weights:\n logger.info(f\"Using class weights for task '{self.task_name}': {self.class_weights}\")\n balanced_weights = nn.Parameter(torch.tensor(class_weights), requires_grad=False)\n else:\n balanced_weights = None\n\n self.loss_fct = CrossEntropyLoss(\n weight=balanced_weights,\n reduction=loss_reduction,\n ignore_index=loss_ignore_index,\n )\n\n self.generate_config()\n\n def forward(self, X):\n logits = self.feed_forward(X)\n return logits\n\n def logits_to_loss(self, logits, **kwargs):\n label_ids = kwargs.get(self.label_tensor_name)\n return self.loss_fct(logits, label_ids.view(-1))\n\n def logits_to_probs(self, logits, return_class_probs, **kwargs):\n softmax = torch.nn.Softmax(dim=1)\n probs = softmax(logits)\n if return_class_probs:\n probs = probs\n else:\n probs = torch.max(probs, dim=1)[0]\n probs = probs.cpu().numpy()\n return probs\n\n def logits_to_preds(self, logits, **kwargs):\n logits = logits.cpu().numpy()\n pred_ids = logits.argmax(1)\n preds = [self.label_list[int(x)] for x in pred_ids]\n return preds\n\n def prepare_labels(self, **kwargs):\n label_ids = kwargs.get(self.label_tensor_name)\n label_ids = label_ids.cpu().numpy()\n labels = [self.label_list[int(x)] for x in label_ids]\n return labels\n\n def formatted_preds(self, logits, samples, return_class_probs=False, **kwargs):\n preds = self.logits_to_preds(logits)\n probs = self.logits_to_probs(logits, return_class_probs)\n contexts = [sample.clear_text[\"text\"] for sample in samples]\n\n assert len(preds) == len(probs) == len(contexts)\n\n res = {\"task\": \"text_classification\", \"predictions\": []}\n for pred, prob, context in zip(preds, probs, contexts):\n if not return_class_probs:\n pred_dict = {\n \"start\": None,\n \"end\": None,\n \"context\": f\"{context}\",\n \"label\": f\"{pred}\",\n \"probability\": prob,\n }\n else:\n pred_dict = {\n \"start\": None,\n \"end\": None,\n \"context\": f\"{context}\",\n \"label\": \"class_probabilities\",\n \"probability\": prob,\n }\n\n res[\"predictions\"].append(pred_dict)\n return res\n\n\nclass MultiLabelTextClassificationHead(PredictionHead):\n def __init__(\n self,\n layer_dims,\n class_weights=None,\n loss_reduction=\"none\",\n task_name=\"text_classification\",\n pred_threshold=0.5,\n **kwargs,\n ):\n super(MultiLabelTextClassificationHead, self).__init__()\n # num_labels could in most cases also be automatically retrieved from the data processor\n self.layer_dims = layer_dims\n self.feed_forward = FeedForwardBlock(self.layer_dims)\n self.num_labels = self.layer_dims[-1]\n self.ph_output_type = \"per_sequence\"\n self.model_type = \"multilabel_text_classification\"\n self.task_name = task_name #used for connecting with the right output of the processor\n self.class_weights = class_weights\n self.pred_threshold = pred_threshold\n\n if class_weights:\n logger.info(f\"Using class weights for task '{self.task_name}': {self.class_weights}\")\n #TODO must balanced weight really be a instance attribute?\n self.balanced_weights = nn.Parameter(\n torch.tensor(class_weights), requires_grad=False\n )\n else:\n self.balanced_weights = None\n\n self.loss_fct = BCEWithLogitsLoss(pos_weight=self.balanced_weights,\n reduction=loss_reduction)\n\n self.generate_config()\n\n def forward(self, X):\n logits = self.feed_forward(X)\n return logits\n\n def logits_to_loss(self, logits, **kwargs):\n label_ids = kwargs.get(self.label_tensor_name).to(dtype=torch.float)\n loss = self.loss_fct(logits.view(-1, self.num_labels), label_ids.view(-1, self.num_labels))\n per_sample_loss = loss.mean(1)\n return per_sample_loss\n\n def logits_to_probs(self, logits, **kwargs):\n sigmoid = torch.nn.Sigmoid()\n probs = sigmoid(logits)\n probs = probs.cpu().numpy()\n return probs\n\n def logits_to_preds(self, logits, **kwargs):\n probs = self.logits_to_probs(logits)\n #TODO we could potentially move this to GPU to speed it up\n pred_ids = [np.where(row > self.pred_threshold)[0] for row in probs]\n preds = []\n for row in pred_ids:\n preds.append([self.label_list[int(x)] for x in row])\n return preds\n\n def prepare_labels(self, **kwargs):\n label_ids = kwargs.get(self.label_tensor_name)\n label_ids = label_ids.cpu().numpy()\n label_ids = [np.where(row == 1)[0] for row in label_ids]\n labels = []\n for row in label_ids:\n labels.append([self.label_list[int(x)] for x in row])\n return labels\n\n def formatted_preds(self, logits, samples, **kwargs):\n preds = self.logits_to_preds(logits)\n probs = self.logits_to_probs(logits)\n contexts = [sample.clear_text[\"text\"] for sample in samples]\n\n assert len(preds) == len(probs) == len(contexts)\n\n res = {\"task\": \"text_classification\", \"predictions\": []}\n for pred, prob, context in zip(preds, probs, contexts):\n res[\"predictions\"].append(\n {\n \"start\": None,\n \"end\": None,\n \"context\": f\"{context}\",\n \"label\": f\"{pred}\",\n \"probability\": prob,\n }\n )\n return res\n\n\nclass TokenClassificationHead(PredictionHead):\n def __init__(self, layer_dims, task_name=\"ner\", **kwargs):\n super(TokenClassificationHead, self).__init__()\n\n self.layer_dims = layer_dims\n self.feed_forward = FeedForwardBlock(self.layer_dims)\n self.num_labels = self.layer_dims[-1]\n self.loss_fct = CrossEntropyLoss(reduction=\"none\")\n self.ph_output_type = \"per_token\"\n self.model_type = \"token_classification\"\n self.task_name = task_name\n self.generate_config()\n\n def forward(self, X):\n logits = self.feed_forward(X)\n return logits\n\n def logits_to_loss(\n self, logits, initial_mask, padding_mask=None, **kwargs\n ):\n label_ids = kwargs.get(self.label_tensor_name)\n\n # Todo: should we be applying initial mask here? Loss is currently calculated even on non initial tokens\n active_loss = padding_mask.view(-1) == 1\n active_logits = logits.view(-1, self.num_labels)[active_loss]\n active_labels = label_ids.view(-1)[active_loss]\n\n loss = self.loss_fct(\n active_logits, active_labels\n ) # loss is a 1 dimemnsional (active) token loss\n return loss\n\n def logits_to_preds(self, logits, initial_mask, **kwargs):\n preds_word_all = []\n preds_tokens = torch.argmax(logits, dim=2)\n preds_token = preds_tokens.detach().cpu().numpy()\n # used to be: padding_mask = padding_mask.detach().cpu().numpy()\n initial_mask = initial_mask.detach().cpu().numpy()\n\n for idx, im in enumerate(initial_mask):\n preds_t = preds_token[idx]\n # Get labels and predictions for just the word initial tokens\n preds_word_id = self.initial_token_only(preds_t, initial_mask=im)\n preds_word = [self.label_list[pwi] for pwi in preds_word_id]\n preds_word_all.append(preds_word)\n return preds_word_all\n\n def logits_to_probs(self, logits, initial_mask, return_class_probs, **kwargs):\n # get per token probs\n softmax = torch.nn.Softmax(dim=2)\n token_probs = softmax(logits)\n if return_class_probs:\n token_probs = token_probs\n else:\n token_probs = torch.max(token_probs, dim=2)[0]\n token_probs = token_probs.cpu().numpy()\n\n # convert to per word probs\n all_probs = []\n initial_mask = initial_mask.detach().cpu().numpy()\n for idx, im in enumerate(initial_mask):\n probs_t = token_probs[idx]\n probs_words = self.initial_token_only(probs_t, initial_mask=im)\n all_probs.append(probs_words)\n return all_probs\n\n def prepare_labels(self, initial_mask, **kwargs):\n label_ids = kwargs.get(self.label_tensor_name)\n labels_all = []\n label_ids = label_ids.cpu().numpy()\n for label_ids_one_sample, initial_mask_one_sample in zip(\n label_ids, initial_mask\n ):\n label_ids = self.initial_token_only(\n label_ids_one_sample, initial_mask_one_sample\n )\n labels = [self.label_list[l] for l in label_ids]\n labels_all.append(labels)\n return labels_all\n\n @staticmethod\n def initial_token_only(seq, initial_mask):\n ret = []\n for init, s in zip(initial_mask, seq):\n if init:\n ret.append(s)\n return ret\n\n def formatted_preds(self, logits, initial_mask, samples, return_class_probs=False, **kwargs):\n preds = self.logits_to_preds(logits, initial_mask)\n probs = self.logits_to_probs(logits, initial_mask,return_class_probs)\n\n # align back with original input by getting the original word spans\n spans = []\n for sample, sample_preds in zip(samples, preds):\n word_spans = []\n span = None\n for token, offset, start_of_word in zip(\n sample.tokenized[\"tokens\"],\n sample.tokenized[\"offsets\"],\n sample.tokenized[\"start_of_word\"],\n ):\n if start_of_word:\n # previous word has ended unless it's the very first word\n if span is not None:\n word_spans.append(span)\n span = {\"start\": offset, \"end\": offset + len(token)}\n else:\n # expand the span to include the subword-token\n span[\"end\"] = offset + len(token.replace(\"##\", \"\"))\n word_spans.append(span)\n spans.append(word_spans)\n\n assert len(preds) == len(probs) == len(spans)\n\n res = {\"task\": \"ner\", \"predictions\": []}\n for preds_seq, probs_seq, sample, spans_seq in zip(\n preds, probs, samples, spans\n ):\n tags, spans_seq = convert_iob_to_simple_tags(preds_seq, spans_seq)\n seq_res = []\n for tag, prob, span in zip(tags, probs_seq, spans_seq):\n context = sample.clear_text[\"text\"][span[\"start\"] : span[\"end\"]]\n seq_res.append(\n {\n \"start\": span[\"start\"],\n \"end\": span[\"end\"],\n \"context\": f\"{context}\",\n \"label\": f\"{tag}\",\n \"probability\": prob,\n }\n )\n res[\"predictions\"].extend(seq_res)\n return res\n\n\nclass BertLMHead(PredictionHead):\n def __init__(self, hidden_size, vocab_size, hidden_act=\"gelu\", task_name=\"lm\", **kwargs):\n super(BertLMHead, self).__init__()\n\n self.hidden_size = hidden_size\n self.hidden_act = hidden_act\n self.vocab_size = vocab_size\n self.loss_fct = CrossEntropyLoss(reduction=\"none\", ignore_index=-1)\n self.num_labels = vocab_size # vocab size\n # TODO Check if weight init needed!\n # self.apply(self.init_bert_weights)\n self.ph_output_type = \"per_token\"\n\n self.model_type = \"language_modelling\"\n self.task_name = task_name\n self.generate_config()\n\n # NN Layers\n # this is the \"transform\" module in the pytorch-transformers repo\n self.dense = nn.Linear(self.hidden_size, self.hidden_size)\n self.transform_act_fn = ACT2FN[self.hidden_act]\n self.LayerNorm = BertLayerNorm(self.hidden_size, eps=1e-12)\n\n # this is the \"decoder\" in the pytorch-transformers repo\n # The output weights are the same as the input embeddings, but there is\n # an output-only bias for each token.\n self.decoder = nn.Linear(hidden_size,\n vocab_size,\n bias=False)\n self.bias = nn.Parameter(torch.zeros(vocab_size))\n\n @classmethod\n def load(cls, pretrained_model_name_or_path):\n\n if os.path.exists(pretrained_model_name_or_path) \\\n and \"config.json\" in pretrained_model_name_or_path \\\n and \"prediction_head\" in pretrained_model_name_or_path:\n config_file = os.path.exists(pretrained_model_name_or_path)\n # a) FARM style\n model_file = cls._get_model_file(config_file)\n config = json.load(open(config_file))\n prediction_head = cls(**config)\n logger.info(\"Loading prediction head from {}\".format(model_file))\n prediction_head.load_state_dict(torch.load(model_file, map_location=torch.device(\"cpu\")))\n else:\n # b) pytorch-transformers style\n # load weights from bert model\n # (we might change this later to load directly from a state_dict to generalize for other language models)\n bert_with_lm = BertForPreTraining.from_pretrained(pretrained_model_name_or_path)\n\n # init empty head\n head = cls(hidden_size=bert_with_lm.config.hidden_size,\n vocab_size=bert_with_lm.config.vocab_size,\n hidden_act=bert_with_lm.config.hidden_act)\n\n # load weights\n head.dense.load_state_dict(bert_with_lm.cls.predictions.transform.dense.state_dict())\n head.LayerNorm.load_state_dict(bert_with_lm.cls.predictions.transform.LayerNorm.state_dict())\n\n head.decoder.load_state_dict(bert_with_lm.cls.predictions.decoder.state_dict())\n head.bias.data.copy_(bert_with_lm.cls.predictions.bias)\n del bert_with_lm\n\n return head\n\n def set_shared_weights(self, shared_embedding_weights):\n self.decoder.weight = shared_embedding_weights\n\n def forward(self, hidden_states):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.transform_act_fn(hidden_states)\n hidden_states = self.LayerNorm(hidden_states)\n lm_logits = self.decoder(hidden_states) + self.bias\n return lm_logits\n\n def logits_to_loss(self, logits, **kwargs):\n lm_label_ids = kwargs.get(self.label_tensor_name)\n batch_size = lm_label_ids.shape[0]\n masked_lm_loss = self.loss_fct(\n logits.view(-1, self.num_labels), lm_label_ids.view(-1)\n )\n per_sample_loss = masked_lm_loss.view(-1, batch_size).mean(dim=0)\n return per_sample_loss\n\n def logits_to_preds(self, logits, **kwargs):\n logits = logits.cpu().numpy()\n lm_label_ids = kwargs.get(self.label_tensor_name).cpu().numpy()\n lm_preds_ids = logits.argmax(2)\n # apply mask to get rid of predictions for non-masked tokens\n assert lm_preds_ids.shape == lm_label_ids.shape\n lm_preds_ids[lm_label_ids == -1] = -1\n lm_preds_ids = lm_preds_ids.tolist()\n preds = []\n # we have a batch of sequences here. we need to convert for each token in each sequence.\n for pred_ids_for_sequence in lm_preds_ids:\n preds.append(\n [self.label_list[int(x)] for x in pred_ids_for_sequence if int(x) != -1]\n )\n return preds\n\n def prepare_labels(self, **kwargs):\n label_ids = kwargs.get(self.label_tensor_name)\n label_ids = label_ids.cpu().numpy().tolist()\n labels = []\n # we have a batch of sequences here. we need to convert for each token in each sequence.\n for ids_for_sequence in label_ids:\n labels.append([self.label_list[int(x)] for x in ids_for_sequence if int(x) != -1])\n return labels\n\n\nclass NextSentenceHead(TextClassificationHead):\n \"\"\"\n Almost identical to a TextClassificationHead. Only difference: we can load the weights from\n a pretrained language model that was saved in the pytorch-transformers style (all in one model).\n \"\"\"\n @classmethod\n def load(cls, pretrained_model_name_or_path):\n\n if os.path.exists(pretrained_model_name_or_path) \\\n and \"config.json\" in pretrained_model_name_or_path \\\n and \"prediction_head\" in pretrained_model_name_or_path:\n config_file = os.path.exists(pretrained_model_name_or_path)\n # a) FARM style\n #TODO validate saving/loading after switching to processor.tasks\n model_file = cls._get_model_file(config_file)\n config = json.load(open(config_file))\n prediction_head = cls(**config)\n logger.info(\"Loading prediction head from {}\".format(model_file))\n prediction_head.load_state_dict(torch.load(model_file, map_location=torch.device(\"cpu\")))\n else:\n # b) pytorch-transformers style\n # load weights from bert model\n # (we might change this later to load directly from a state_dict to generalize for other language models)\n bert_with_lm = BertForPreTraining.from_pretrained(pretrained_model_name_or_path)\n\n # init empty head\n head = cls(layer_dims=[bert_with_lm.config.hidden_size, 2], loss_ignore_index=-1, task_name=\"nextsentence\")\n\n # load weights\n head.feed_forward.feed_forward[0].load_state_dict(bert_with_lm.cls.seq_relationship.state_dict())\n del bert_with_lm\n\n return head\n\nclass FeedForwardBlock(nn.Module):\n \"\"\" A feed forward neural network of variable depth and width. \"\"\"\n\n def __init__(self, layer_dims, **kwargs):\n # Todo: Consider having just one input argument\n super(FeedForwardBlock, self).__init__()\n\n # If read from config the input will be string\n n_layers = len(layer_dims) - 1\n layers_all = []\n # TODO: IS this needed?\n self.output_size = layer_dims[-1]\n\n for i in range(n_layers):\n size_in = layer_dims[i]\n size_out = layer_dims[i + 1]\n layer = nn.Linear(size_in, size_out)\n layers_all.append(layer)\n self.feed_forward = nn.Sequential(*layers_all)\n\n def forward(self, X):\n logits = self.feed_forward(X)\n return logits\n\n\nclass QuestionAnsweringHead(PredictionHead):\n \"\"\"\n A question answering head predicts the start and end of the answer on token level.\n \"\"\"\n\n def __init__(self,\n layer_dims,\n task_name=\"question_answering\",\n no_answer_shift=0,\n top_n_predictions=3,\n context_size=100,\n **kwargs):\n \"\"\"\n :param layer_dims: dimensions of Feed Forward block, e.g. [768,2], for adjusting to BERT embedding. Output should be always 2\n :type layer_dims: List[Int]\n :param task_name: Name of task\n :type task_name: str\n :param no_answer_shift: How much we want to weight giving no answer compared to text answer\n We actually compare in logit space (sum of both start and end logit), so negative\n values result in less no answer predictions and vice versa. normal range = [-5,+5]\n :type no_answer_shift: int\n :param top_n_predictions: When we split a document into multiple passages we can return top n passage answers\n :type top_n_predictions: int\n :param context_size: When we format predictions back to string space we also return surrounding context\n of size context_size\n :type context_size: int\n :param kwargs: placeholder for passing generic parameters\n :type kwargs: object\n \"\"\"\n super(QuestionAnsweringHead, self).__init__()\n self.layer_dims = layer_dims\n self.feed_forward = FeedForwardBlock(self.layer_dims)\n self.num_labels = self.layer_dims[-1]\n self.ph_output_type = \"per_token_squad\"\n self.model_type = (\n \"span_classification\"\n ) # predicts start and end token of answer\n self.task_name = task_name\n self.no_answer_shift = no_answer_shift # how much we want to upweight no answer logit scores compared to text answer ones\n self.top_n_predictions = top_n_predictions #for how many passages we want to get predictions\n self.context_size = context_size\n self.max_ans_len = 1000 # disabling max ans len. Impact on squad performance seems minor\n # each answer is returned with surrounding context. In # characters surrounding the answer\n self.generate_config()\n\n\n @classmethod\n def load(cls, pretrained_model_name_or_path):\n \"\"\"\n Almost identical to a QuestionAnsweringHead. Only difference: we can load the weights from\n a pretrained language model that was saved in the pytorch-transformers style (all in one model).\n \"\"\"\n\n if os.path.exists(pretrained_model_name_or_path) \\\n and \"config.json\" in pretrained_model_name_or_path \\\n and \"prediction_head\" in pretrained_model_name_or_path:\n config_file = os.path.exists(pretrained_model_name_or_path)\n # a) FARM style\n model_file = cls._get_model_file(config_file)\n config = json.load(open(config_file))\n prediction_head = cls(**config)\n logger.info(\"Loading prediction head from {}\".format(model_file))\n prediction_head.load_state_dict(torch.load(model_file, map_location=torch.device(\"cpu\")))\n else:\n # b) pytorch-transformers style\n # load weights from bert model\n # (we might change this later to load directly from a state_dict to generalize for other language models)\n bert_qa = BertForQuestionAnswering.from_pretrained(pretrained_model_name_or_path)\n\n # init empty head\n head = cls(layer_dims=[bert_qa.config.hidden_size, 2], loss_ignore_index=-1, task_name=\"question_answering\")\n # load weights\n head.feed_forward.feed_forward[0].load_state_dict(bert_qa.qa_outputs.state_dict())\n del bert_qa\n\n return head\n\n def forward(self, X):\n \"\"\"\n One forward pass through the prediction head model, starting with language model output on token level\n\n :param X: Output of language model, of shape [batch_size, seq_length, LM_embedding_dim]\n :type X: torch.tensor\n :return: (start_logits, end_logits), logits for the start and end of answer\n :rtype: tuple[torch.tensor,torch.tensor]\n \"\"\"\n logits = self.feed_forward(X)\n start_logits, end_logits = logits.split(1, dim=-1)\n start_logits = start_logits.squeeze(-1)\n end_logits = end_logits.squeeze(-1)\n return (start_logits, end_logits)\n\n def logits_to_loss(self, logits, start_position, end_position, **kwargs):\n \"\"\"\n Combine predictions and labels to a per sample loss.\n\n :param logits: (start_logits, end_logits), logits for the start and end of answer\n :type logits: tuple[torch.tensor,torch.tensor]\n :param start_position: tensor with indices of START positions per sample\n :type start_position: torch.tensor\n :param end_position: tensor with indices of END positions per sample\n :type end_position: torch.tensor\n :param kwargs: placeholder for passing generic parameters\n :type kwargs: object\n :return: per_sample_loss: Per sample loss : )\n :rtype: torch.tensor\n \"\"\"\n (start_logits, end_logits) = logits\n\n if len(start_position.size()) > 1:\n start_position = start_position.squeeze(-1)\n if len(end_position.size()) > 1:\n end_position = end_position.squeeze(-1)\n # sometimes the start/end positions (the labels read from file) are outside our model predictions, we ignore these terms\n # TODO check if ignored_index is needed. We are checking for start + end validity during construction of samples\n ignored_index = start_logits.size(1)\n start_position.clamp_(0, ignored_index)\n end_position.clamp_(0, ignored_index)\n\n loss_fct = CrossEntropyLoss(ignore_index=ignored_index, reduction=\"none\")\n start_loss = loss_fct(start_logits, start_position)\n end_loss = loss_fct(end_logits, end_position)\n per_sample_loss = (start_loss + end_loss) / 2\n return per_sample_loss\n\n def logits_to_preds(self, logits, **kwargs):\n \"\"\"\n Get the predicted index of start and end token of the answer.\n\n :param logits: (start_logits, end_logits), logits for the start and end of answer\n :type logits: tuple[torch.tensor,torch.tensor]\n :param kwargs: placeholder for passing generic parameters\n :type kwargs: object\n :return: (start_idx, end_idx), start and end indices for all samples in batch\n :rtype: (torch.tensor,torch.tensor)\n \"\"\"\n\n # cast data into useful types/shapes\n (start_logits, end_logits) = logits\n start_logits = start_logits.cpu().numpy()\n end_logits = end_logits.cpu().numpy()\n num_per_batch = start_logits.shape[0]\n segment_ids = kwargs['segment_ids'].data.cpu().numpy()\n sample_ids = kwargs[\"sample_id\"].cpu().numpy()\n passage_shifts = kwargs[\"passage_shift\"].cpu().numpy()\n\n question_shifts = np.argmax(segment_ids > 0,axis=1)\n\n\n no_answer_sum = start_logits[:,0] + end_logits[:,0]\n best_answer_sum = np.zeros(num_per_batch)\n # check if start or end point to the context. Context starts at segment id == 1 (question comes before at segment ids == 0)\n context_start = np.argmax(segment_ids,axis=1)\n context_end = segment_ids.shape[1] - np.argmax(segment_ids[::-1],axis=1)\n start_proposals = self._get_best_textanswer_indices(start_logits, 3)\n end_proposals = self._get_best_textanswer_indices(end_logits, 3)\n best_indices = np.zeros((num_per_batch,2),dtype=int)\n for i_batch in range(num_per_batch):\n # for each sample create mesh of possible start + end combinations and their score as sum of logits\n mesh_idx = np.meshgrid(start_proposals[i_batch,:],end_proposals[i_batch])\n start_comb = mesh_idx[0].flatten()\n end_comb = mesh_idx[1].flatten()\n scores = start_logits[i_batch,start_comb] + end_logits[i_batch,end_comb]\n #iterate over combinations and eliminate impossible ones\n for idx in np.argsort(scores)[::-1]:\n start = start_comb[idx]\n end = end_comb[idx]\n if start < context_start[i_batch]:\n continue\n if end > context_end[i_batch]:\n continue\n if start > end:\n continue\n if(end - start > self.max_ans_len):\n continue\n # maybe need check weather start/end idx refers to start of word and not to a ##... continuation\n\n best_indices[i_batch,0] = start\n best_indices[i_batch,1] = end\n best_answer_sum[i_batch] = scores[idx]\n break # since we take most likely predictions first, we stop when finding a valid prediction\n\n # For each predicted text answer, we want to check weather this question could also be unanswerable with\n # the given passage\n # we need to compare the text answer logits with no-answer logits (at position 0)\n idx_no_answer = no_answer_sum + self.no_answer_shift >= best_answer_sum\n best_indices[idx_no_answer,:] = 0\n best_answer_sum[idx_no_answer] = no_answer_sum[idx_no_answer]\n\n # #probabilities computed through softmaxing logits. Currently unused in downstream code.\n # start_probs = softmax(start_logits, axis=1)\n # end_probs = softmax(end_logits, axis=1)\n # probabilities = (start_probs[range(best_indices.shape[0]), np.squeeze(best_indices[:, 0])] +\n # end_probs[range(best_indices.shape[0]), np.squeeze(best_indices[:, 1])]) / 2\n\n return (best_indices[:, 0], best_indices[:, 1], best_answer_sum, sample_ids, question_shifts, passage_shifts)\n\n def prepare_labels(self, start_position, end_position, **kwargs):\n \"\"\"\n We want to pack labels into a tuple, to be compliant with later functions\n\n :param start_position: indices of answer start positions (in token space)\n :type start_position: torch.tensor\n :param end_position: indices of answer end positions (in token space)\n :type end_position: torch.tensor\n :param kwargs: placeholder for passing generic parameters\n :type kwargs: object\n :return: tuplefied sample_id with corresponding positions\n :rtype: tuple(torch.tensor, torch.tensor,torch.tensor)\n \"\"\"\n return (kwargs[\"sample_id\"], start_position, end_position)\n\n def formatted_preds(self, logits, preds, samples):\n \"\"\"\n Format predictions into actual answer strings (substrings of context). Used for Inference!\n\n :param logits: palceholder to comply with LanguageModel.formatted_preds\n :type logits: None\n :param preds: predictions for each passage, coming from logits_to_preds()\n contains start_idxs, end_idxs, logit_sums, sample_ids, question_shifts, passage_shifts, probabilities\n :type preds: tuple( 7 numpy arrays )\n :param samples: converted samples, to get a hook onto the actual text\n :type samples: List[FARM.data_handler.samples.Sample]\n :param kwargs: placeholder for passing generic parameters\n :type kwargs: object\n :return: Answers to the (ultimate) questions\n :rtype: list(str)\n \"\"\"\n\n all_preds_passage_aggregated = self._aggregate_preds(preds=preds)\n\n result = {}\n result[\"task\"] = \"qa\"\n all_preds = []\n sample_id_to_index = dict([(sample.id,i) for i,sample in enumerate(samples)])\n for current_pred in all_preds_passage_aggregated:\n sampleid_i = current_pred[0, 3]\n try:\n current_sample = samples[sample_id_to_index[sampleid_i]]\n except Exception as e:\n current_sample = None\n logger.warning(f\"Sample id: {sampleid_i} could not be loaded. Error: {e} \")\n if current_sample is not None:\n passage_predictions = []\n for i in range(current_pred.shape[0]):\n passage_pred = {}\n s_i = current_pred[i,0]\n e_i = current_pred[i,1]\n logit_sum_i = current_pred[i,2]\n question_shift_i = current_pred[i,4]\n passage_shift_i = current_pred[i,5]\n passage_pred[\"score\"] = logit_sum_i\n passage_pred[\"probability\"] = -1 # TODO add probabilities that make sense : )\n try:\n #default to returning no answer\n start = 0\n end = 0\n context_start = 0\n answer = \"\"\n context = \"\"\n if(s_i + e_i > 0):\n current_start = int(s_i + passage_shift_i - question_shift_i)\n current_end = int(e_i + passage_shift_i - question_shift_i) + 1\n start = current_sample.tokenized[\"offsets\"][current_start]\n end = current_sample.tokenized[\"offsets\"][current_end]\n # we want the answer in original string space (containing newline, tab or multiple\n # whitespace. So we need to join doc tokens and work with character offsets\n temptext = \" \".join(current_sample.clear_text[\"doc_tokens\"])\n answer = temptext[start:end]\n answer = answer.strip()\n # sometimes we strip trailing whitespaces, so we need to adjust end\n end = start + len(answer)\n context_start = int(np.clip((start-self.context_size),a_min=0,a_max=None))\n context_end = int(np.clip(end +self.context_size,a_max=len(temptext),a_min=None))\n context = temptext[context_start:context_end]\n except IndexError as e:\n logger.info(e)\n passage_pred[\"answer\"] = answer\n passage_pred[\"offset_start\"] = start\n passage_pred[\"offset_end\"] = end\n passage_pred[\"context\"] = context\n passage_pred[\"offset_context_start\"] = start - context_start\n passage_pred[\"offset_context_end\"] = end - context_start\n passage_pred[\"document_id\"] = current_sample.clear_text.get(\"document_id\", None)\n passage_predictions.append(passage_pred)\n\n pred = {}\n pred[\"question\"] = current_sample.clear_text.question_text\n pred[\"question_id\"] = current_sample.clear_text.get(\"qas_id\", None)\n pred[\"ground_truth\"] = current_sample.clear_text.get(\"orig_answer_text\", None)\n pred[\"answers\"] = passage_predictions\n all_preds.append(pred)\n\n result[\"predictions\"] = all_preds\n return result\n\n def _aggregate_preds(self, preds):\n def create_answeridx_string(r):\n start = r[\"pred_start\"] + r[\"passage_shift\"]\n end = r[\"pred_end\"] + r[\"passage_shift\"]\n return f\"{start}-{end}\"\n\n data = {}\n data[\"pred_start\"] = np.concatenate([x[0] for x in preds])\n data[\"pred_end\"] = np.concatenate([x[1] for x in preds])\n data[\"logit_sum\"] = np.concatenate([x[2] for x in preds])\n data[\"sample_id\"] = np.concatenate([x[3] for x in preds])\n data[\"question_shift\"] = np.concatenate([x[4] for x in preds])\n data[\"passage_shift\"] = np.concatenate([x[5] for x in preds])\n df = pd.DataFrame(data=data)\n df.loc[:,\"answer_indices\"] = df.apply(lambda row: create_answeridx_string(row), axis=1)\n\n # we sometimes have multiple predictions for one sample (= paragraph question pair)\n # because we split the paragraph into smaller passages\n # we group all predictions by sample_id\n unique_sample_ids = df.sample_id.unique()\n max_per_sample = []\n for uid in unique_sample_ids:\n group = df.loc[df.sample_id == uid, :]\n idx_text_answers = (group.pred_start + group.pred_end) > 0\n # if we have a text answer in the group we want to discard all no text passages\n # Reasoning: consider how data is constructed from labels: If we split a document into 5 passages and\n # only passage no.3 has the text answer, all remaining passages are labeled as no answer.\n # We want the answer for passage no.3 without regarding the models output for the other passages.\n if np.sum(idx_text_answers) > 0:\n group = group.loc[idx_text_answers,:]\n if self.top_n_predictions == 1:\n max_pred = group.loc[group.logit_sum == np.max(group.logit_sum),:]\n if (max_pred.shape[0] > 1):\n logger.info(f\"Multiple predictions have the exact same probability of occuring: \\n{max_pred.head(5)}\")\n max_pred = max_pred.iloc[0, :]\n else:\n assert isinstance(self.top_n_predictions, int)\n sorted_group = group.sort_values(by=\"logit_sum\",ascending=False)\n filtered_group = sorted_group.drop_duplicates(keep=\"first\", subset=\"answer_indices\")\n max_pred = filtered_group.iloc[:self.top_n_predictions,:]\n max_per_sample.append(max_pred.values)\n return max_per_sample\n\n\n def _get_best_textanswer_indices(self, logits, n_best_size):\n \"\"\"Get the n-best logits from a numpy array without considering the zero index.\n zero index corresponds to no answer, which we deal with separately\"\"\"\n logits_without_zero = logits[:,1:]\n idx_without_zero = np.argsort(logits_without_zero,axis=1)[:,-n_best_size:]\n idx = idx_without_zero + 1\n return idx\n","sub_path":"farm/modeling/prediction_head.py","file_name":"prediction_head.py","file_ext":"py","file_size_in_byte":45855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"213945844","text":"#If you have downloaded the source code from this book’s companion Web site, you will find\n#the following files in the Chapter 07 folder:\n#• GirlNames.txt—This file contains a list of the 200 most popular names given to girls\n#born in the United States from the year 2000 through 2009.\n#• BoyNames.txt—This file contains a list of the 200 most popular names given to boys\n#born in the United States from the year 2000 through 2009.\n#Write a program that reads the contents of the two files into two separate lists. The user\n#should be able to enter a boy’s name, a girl’s name, or both, and the application will display\n#messages indicating whether the names were among the most popular.\n\nb_names = open('boys_names.txt','r')\nboys_name = b_names.read()\ng_names = open('girls_names.txt','r')\ngirls_names = g_names.read()\nall_names = boys_name + girls_names\nprint(all_names)\nboys_name_search = str(input(\"Enter a boy name : \")).lower()\ngirls_name_search = str(input(\"Enter a girl name : \")).lower()\nif boys_name_search in boys_name:\n print(\"You've entered a most popular name among boys name list.\")\nelse:\n print(\"Entered name is not in most popular boys name list\")\nif girls_name_search in girls_names:\n print(\"You've entered a most popular name among girls name list.\")\nelse:\n print(\"Entered name is not in most popular girls name list\")\nif boys_name_search in all_names and girls_name_search in all_names:\n print(\"You've entered a most popular names in boys name list and girls names list.\")\nelse:\n print(\"The names you've entered is not in neither boys nor in girls names lists\")\nb_names.close()\ng_names.close()\n\n","sub_path":"lesson_02/personal/chapter_7/08_names.py","file_name":"08_names.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"433373292","text":"import scrapy\n\nclass HackagePackage(scrapy.Item):\n name = scrapy.Field()\n description = scrapy.Field()\n link = scrapy.Field()\n\n def __init__(self, name: str, description: str, link: str) -> None:\n self.item['name'] = name\n self.item['description'] = description\n self.item['link'] = link\n\n\nclass HackageSpider(scrapy.Spider):\n name = 'hackagespider'\n start_urls = ['https://hackage.haskell.org/packages/browse']\n\n def parse_package_page(self, response):\n name = response.css('h1 a::text').get()\n description = response.css('h1 small::text').get()\n link = response.css('h1 a').attrib['href']\n\n package = HackagePackage(\n name=name,\n description=description,\n link=link\n )\n\n yield package\n\n def parse(self, response):\n for link in response.xpath('//table/tbody/tr/td[1]/a'):\n yield response.follow(link, self.parse_package_page)\n","sub_path":"scrapy/scrape-hackage/hackage-scrape.py","file_name":"hackage-scrape.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"291843841","text":"# -----------------------------------------------------------------------------\n# training script\n# -----------------------------------------------------------------------------\n\nimport torch, torchvision, torch.nn.functional as F\n\ntorch.cuda.empty_cache()\n\nimport argparse\nfrom tqdm import tqdm\nfrom pathlib import Path\n\nfrom Model import DeepInfoMaxLoss\n\nfrom torch.utils.data import DataLoader\nfrom data_classes.multiple_mnist import MultiMNIST\n\nif __name__ == \"__main__\":\n\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n batch_size = 256\n num_epochs = 1000\n num_workers = 4\n save_interval = 100\n version = \"cifar10_v2\"\n lr = 1e-4\n\n # image size (3,32,32)\n # batch size must be an even number\n # shuffle must be True\n # transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor(),])\n # # train_dataset = torchvision.datasets.cifar.CIFAR10(\"data\", download=True, transform=transform)\n # train_dataset = torchvision.datasets.mnist.MNIST('data', download=True, transform=transform)\n # train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True, drop_last=True, num_workers=num_workers)\n\n train_dataset = MultiMNIST(train=True, data_root='data', image_size=64, num_digits=4,\n channels=1, to_sort_label=True, dig_to_use=[0, 2, 4, 6],\n nxt_dig_prob=1.0, rand_dig_combine=False,\n split_dig_set=False)\n train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, drop_last=True)\n\n dim = DeepInfoMaxLoss(alpha=0.5, beta=1.0, gamma=0.1).to(device)\n optimizer = torch.optim.Adam(dim.parameters(), lr=lr)\n\n dim.train()\n for epoch in range(1, num_epochs + 1):\n Batch = tqdm(train_loader, total=len(train_dataset) // batch_size)\n for i, (data, target) in enumerate(Batch, 1):\n data = data.to(device)\n\n Y, M = dim.encoder(data)\n\n # shuffle batch to pair each element with another\n M_fake = torch.cat((M[1:], M[0].unsqueeze(0)), dim=0)\n print('m fake: ', M_fake.shape)\n\n # loss = dim(Y, M, M_fake)\n # Batch.set_description(f\"[{epoch:>3d}/{num_epochs:<3d}]Loss/Train: {loss.item():1.5e}\")\n # dim.zero_grad()\n # loss.backward()\n # optimizer.step()\n #\n # # checkpoint and save models\n # if epoch % save_interval == 0:\n # file = Path(f\"./Models/{version}/checkpoint_epoch_{epoch}.pkl\")\n # file.parent.mkdir(parents=True, exist_ok=True)\n # torch.save(dim.state_dict(), str(file))\n","sub_path":"Train.py","file_name":"Train.py","file_ext":"py","file_size_in_byte":2694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"586374256","text":"import numpy as np\nimport pandas as pd\nfrom scipy import stats\nfrom dateutil import parser\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MultipleLocator\nimport matplotlib.dates as mdates\nimport statistics\n\nDATA_PATH = '../processed_data/'\n\nprice_data = pd.read_csv(DATA_PATH + 'priceData.csv')\nnope_data = pd.read_csv(DATA_PATH + 'parsedNetDelta2020-08.csv')\ndf = pd.merge(nope_data, price_data, on=\"timestamp\")\n\ndeltaNope = 0.0\ndeltaNope2 = 0.0\ndeltaPrice = 0.0\nlastNope = 0.0\nlastDNope = 0.0\nlastDNope2 = 0.0\nlastPrice = 0.0\ndPriceLag = []\n\nfor index, row in df.iterrows():\n\n if (index == 0):\n df['deltaNope'] = 0.0\n df['deltaPrice'] = 0.0\n df['deltaNope2'] = 0.0\n df['dN-dN2'] = 0.0\n lastNope = row['NOPE_allVolume']\n lastPrice = row['active_underlying_price']\n lastDNope = 0.0\n lastDNope2 = 0.0\n continue\n else:\n # ignore the first entry in each day, as we just want to compare the data within a single day, and not the end\n # of the previous day to the open of the current\n if('9:35' in row['timestamp']):\n #print('Skipping entry:' , row['timestamp'])\n lastNope = row['NOPE_allVolume']\n lastPrice = row['active_underlying_price']\n lastDNope = 0.0\n lastDNope2 = 0.0\n continue\n\n deltaNope = lastNope - row['NOPE_allVolume']\n deltaPrice = lastPrice - row['active_underlying_price']\n deltaNope2 = lastDNope - deltaNope\n\n #print(deltaNope, deltaPrice)\n df.at[index, 'deltaNope'] = deltaNope\n df.at[index, 'deltaPrice'] = deltaPrice\n df.at[index, 'deltaNope2'] = deltaNope2\n\n # use a split interpolate on the second order to function as the modeled second order\n # this is a reduction of cubic spline interpolation used in forward forecasting signal processing\n df.at[index, 'dN-dN2'] = deltaNope - (0.5*lastDNope2 - 0.5*deltaNope2)\n\n dNope = df['deltaNope'].to_numpy()\n dNope2 = df['deltaNope2'].to_numpy()\n dN_sub_dN2 = df['dN-dN2'].to_numpy()\n dPrice = df['deltaPrice'].to_numpy()\n dNopeRaw = df['NOPE_allVolume'].to_numpy()\n\n # shift the data back by 1\n dPriceLag = np.delete(dPrice, 0, 0)\n dPriceLag = np.insert(dPriceLag, dPriceLag.size - 1, 0)\n\n # shift the data back by 2\n dPriceLag2 = np.delete(dPrice, 0, 0)\n dPriceLag2 = np.delete(dPriceLag2, 0, 0)\n dPriceLag2 = np.insert(dPriceLag2, dPriceLag2.size - 1, 0)\n dPriceLag2 = np.insert(dPriceLag2, dPriceLag2.size - 1, 0)\n\n # compute our various correlations\n dN_dP = stats.spearmanr(dNope, dPrice)\n df.at[index, 'corr'] = dN_dP[0]\n print(\"dNope p Value: \", str(dN_dP[1]))\n df.at[index, 'corrLag'] = stats.spearmanr(dNope, dPriceLag)[0]\n df.at[index, 'corrLag_2'] = stats.spearmanr(dNope, dPriceLag2)[0]\n df.at[index, 'corrRaw'] = stats.spearmanr(dNope, dNopeRaw)[0]\n\n dN2_dP = stats.spearmanr(dNope2, dPrice)\n df.at[index, 'corrD2'] = dN2_dP[0]\n print(\"dNope2 p Value: \", str(dN2_dP[1]))\n df.at[index, 'corrD2Lag'] = stats.spearmanr(dNope2, dPriceLag)[0]\n df.at[index, 'corrD2Lag_2'] = stats.spearmanr(dNope2, dPriceLag2)[0]\n\n dN_dN2_dP = stats.spearmanr(dN_sub_dN2, dPrice)\n df.at[index, 'corrdN_sub_dN2'] = dN_dN2_dP[0]\n print(\"dNope - dNope2 p Value: \", str(dN_dN2_dP[1]))\n\n\n dN_dN2_dP_t_plus_5 = stats.spearmanr(dN_sub_dN2, dPriceLag)\n df.at[index, 'corrdN_sub_dN2_lag'] = dN_dN2_dP_t_plus_5[0]\n print(\"dNope - dNope2 T+5 p Value: \", str(dN_dN2_dP_t_plus_5[1]))\n df.at[index, 'corrdN_sub_dN2_lag_2'] = stats.spearmanr(dN_sub_dN2, dPriceLag2)[0]\n\n\n lastNope = row['NOPE_allVolume']\n lastPrice = row['active_underlying_price']\n lastDNope = deltaNope\n lastDNope2 = deltaNope2\n\nfig, axs = plt.subplots(3, 1)\nfig.suptitle('Spearman R Rank Correlation \\n SPY Intra-day deltaNope vs. deltaPrice August 2020')\n\n#axs[3].scatter(df['timestamp'], df['deltaNope'], 2, 'red', label='dNope/dt')\n#axs[3].scatter(df['timestamp'], df['deltaNope2'], 2, 'yellow', label='dNope2/d2t')\n#axs[3].scatter(df['timestamp'], df['dN-dN2'], 2, 'pink', label='dNope/dt - est_dNope2/d2t')\n#axs[3].scatter(df['timestamp'], df['deltaPrice'], 2, 'blue', label='dPrice/dt')\n#axs[3].scatter(df['timestamp'], dPriceLag2, 2, 'pink', label='dPrice/dt')\n\naxs[0].plot(df['timestamp'], df['corr'], 'green', label='Cor(dNope(T),dPrice(T))')\naxs[0].plot(df['timestamp'], df['corrLag'], 'orange', label='Cor(dNope(T), dPrice(T+5))')\naxs[0].plot(df['timestamp'], df['corrLag_2'], 'red', label='Cor(dNope(T), dPrice(T+10))')\naxs[0].plot(df['timestamp'], df['corrRaw'], 'cyan', label='Cor(NOPE(T), dPrice(T))')\naxs[0].xaxis.set_ticks([i*100 for i in range(0,20)])\naxs[0].yaxis.set_ticks([i/4.0 for i in range(-4,4,1)])\naxs[0].get_xaxis().set_ticklabels([])\naxs[0].title.set_text('First Order Differential Analysis')\naxs[0].grid()\n\naxs[0].legend(loc=\"lower right\")\n#axs[0].xlabel(\"Time\")\n#axs[0].ylabel(\"Raw\")\n#axs[0].xticks(np.arange(0, 1605, 75))\n#axs[0].yticks(np.arange(-2.5, 2.5, 0.25))\n\n\naxs[1].plot(df['timestamp'], df['corrD2'], 'black', label='Cor(dNope2(T),dPrice(T))')\naxs[1].plot(df['timestamp'], df['corrD2Lag'], 'blue', label='Cor(dNope2(T),dPrice(T+5))')\naxs[1].plot(df['timestamp'], df['corrD2Lag_2'], 'green', label='Cor(dNope2(T),dPrice(T+10))')\naxs[1].xaxis.set_ticks([i*100 for i in range(0,20)])\naxs[1].yaxis.set_ticks([i/4.0 for i in range(-4,4,1)])\naxs[1].get_xaxis().set_ticklabels([])\naxs[1].title.set_text('Second Order Differential Analysis')\naxs[1].grid()\naxs[1].legend(loc=\"lower right\")\n\naxs[2].plot(df['timestamp'], df['corrdN_sub_dN2'], 'green', label='Cor((dNope - est_dNope2)(T) , dPrice(T))')\naxs[2].plot(df['timestamp'], df['corrdN_sub_dN2_lag'], 'red', label='Cor((dNope - est_dNope2)(T) , dPrice(T+5))')\naxs[2].plot(df['timestamp'], df['corrdN_sub_dN2_lag_2'], 'blue', label='Cor((dNope - est_dNope2)(T) , dPrice(T+10))')\naxs[2].xaxis.set_ticks([i*100 for i in range(0,20)])\naxs[2].yaxis.set_ticks([i/4.0 for i in range(-4,4,1)])\naxs[2].get_xaxis().set_ticklabels([])\naxs[2].title.set_text('Forward Projection First/Second Order Differential Analysis')\naxs[2].grid()\naxs[2].legend(loc=\"lower right\")\n\nplt.show()\n","sub_path":"scripts/differential_analysis.py","file_name":"differential_analysis.py","file_ext":"py","file_size_in_byte":6341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"135155176","text":"#!/usr/bin/python\r\n#coding:utf-8\r\n# ***************************************************************\r\n# 绘制正态分布曲线\r\n# author: pruce\r\n# email: 1756983926@qq.com\r\n# date: 20180919\r\n# ***************************************************************\r\n\r\nimport numpy as np\r\nimport matplotlib.mlab as mlab\r\nimport matplotlib.pyplot as plt\r\n\r\ndef normDistribution():\r\n mu, sigma , num_bins = 0, 1, 50\r\n x = mu + sigma * np.random.randn(1000000)\r\n # 正态分布的数据\r\n n, bins, patches = plt.hist(x, num_bins, normed=True, facecolor = 'black', alpha = 0.5)\r\n # 拟合曲线\r\n y = mlab.normpdf(bins, mu, sigma)\r\n plt.plot(bins, y, 'r--')\r\n plt.xlabel('Expectation')\r\n plt.ylabel('Probability')\r\n plt.title('$N(0,1)$')\r\n\r\n plt.subplots_adjust(left = 0.15)\r\n plt.show()\r\n\r\nnormDistribution()","sub_path":"scripts/statistics/PlotDistribution.py","file_name":"PlotDistribution.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"464313072","text":"from django.forms import *\nfrom models import *\n\nclass PersonForm(ModelForm):\n\n name = CharField()\n\n child1 = CharField()\n\n child2 = CharField()\n\n child3 = CharField()\n\n class Meta:\n model = Person\n\n def save(self, commit=True):\n # Are we saving a new model or editing an existing mode?\n is_new = self.instance.pk is None\n\n # We need to call cleaned_data to comply with cleaning methods of django models\n data = self.cleaned_data\n\n # if the record is new create a new model, otherwise take the model instance\n if is_new:\n parent = Person()\n else:\n parent = self.instance.person\n\n # save master table\n parent.name = data.get('name', '')\n parent.save()\n\n child1 = Child()\n child1.paren = parent\n child1.name = data['child1']\n child1.save()\n\n child2 = Child()\n child2.person = parent\n child2.name = data['child2']\n child2.save()\n\n child3 = Child()\n child3.person = parent\n child3.name = data['child3']\n child3.save()\n\n return parent\n","sub_path":"rahimi/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"512062138","text":"import calendar\r\n\r\nfrom django.http import Http404\r\nfrom django.shortcuts import render\r\nfrom django.utils.decorators import method_decorator\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.shortcuts import render_to_response\r\nfrom django.views.generic.base import TemplateView\r\n\r\nfrom . import helpers, utils\r\nfrom .decorators import jsonify\r\n\r\ndef indexView(request):\r\n \"\"\"\r\n \"\"\"\r\n return render(request, 'presence/start.html')\r\n\r\n\r\n\r\nclass WeekdayView(TemplateView):\r\n \"\"\"\r\n The ChangePasswordView class provides a template-based view used to change\r\n the password of a currently logged in user.\r\n \"\"\"\r\n template_name = 'presence/presence_weekday.html'\r\n\r\n\r\n @method_decorator(login_required)\r\n def get(self, request, *args, **kwargs):\r\n \"\"\"\r\n GET request handler.\r\n \"\"\"\r\n return render(request, self.template_name)\r\n\r\n# @method_decorator(login_required)\r\n# def weekday_view(request):\r\n# \"\"\"\r\n# \"\"\"\r\n# return render_to_response(request, 'presence/presence_weekday.html')\r\n\r\n@method_decorator(login_required)\r\ndef mean_time_view(request):\r\n \"\"\"\r\n \"\"\"\r\n return render_to_response(request, 'presence/mean_time_weekday.html')\r\n\r\n@method_decorator(login_required)\r\ndef start_end_view(request):\r\n \"\"\"\r\n \"\"\"\r\n return render_to_response(request, 'presence/presence_start_end.html')\r\n\r\n@jsonify\r\ndef api_view(request):\r\n \"\"\"\r\n \"\"\"\r\n\r\n data = utils.get_data()\r\n users_info = utils.get_user_data()\r\n return_data = [\r\n {\r\n 'user_id': user_id,\r\n 'name': user_data['name'],\r\n 'avatar': user_data['avatar']\r\n }\r\n for user_id, user_data in users_info.iteritems() if user_id in data\r\n ]\r\n\r\n\r\n return return_data\r\n\r\n@jsonify\r\ndef mean_time_weekday_view(request, user_id):\r\n \"\"\"\r\n \"\"\"\r\n\r\n user_id = int(user_id)\r\n\r\n data = utils.get_data()\r\n if user_id not in data:\r\n raise Http404\r\n\r\n weekdays = helpers.group_by_weekday(data[user_id])\r\n result = [(calendar.day_abbr[weekday], helpers.mean(intervals))\r\n for weekday, intervals in weekdays.items()]\r\n\r\n\r\n return result\r\n\r\n@jsonify\r\ndef presence_start_end_view(request, user_id):\r\n \"\"\"\r\n Returns mean arrival and departure time for each weekday.\r\n \"\"\"\r\n user_id = int(user_id)\r\n data = utils.get_data()\r\n if user_id not in data:\r\n raise Http404\r\n\r\n weekdays = helpers.group_start_end_times_by_weekday(data[user_id])\r\n result = [\r\n (\r\n calendar.day_abbr[weekday], helpers.mean(intervals['start']),\r\n helpers.mean(intervals['end'])\r\n )\r\n for weekday, intervals in weekdays.iteritems()\r\n ]\r\n\r\n return result\r\n\r\n@jsonify\r\ndef presence_weekday_view(request, user_id):\r\n \"\"\"\r\n Returns mean arrival and departure time for each weekday.\r\n \"\"\"\r\n user_id = int(user_id)\r\n data = utils.get_data()\r\n if user_id not in data:\r\n raise Http404\r\n\r\n weekdays = helpers.group_by_weekday(data[user_id])\r\n result = [(calendar.day_abbr[weekday], sum(intervals))\r\n for weekday, intervals in weekdays.items()]\r\n\r\n result.insert(0, ('Weekday', 'Presence (s)'))\r\n\r\n return result\r\n","sub_path":"djanalyzer/apps/presence/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"300180184","text":"import sys\nimport config\nimport db\nfrom PySide import QtGui\nfrom PySide.QtCore import QTimer\nfrom window import Ui_MainWindow\nfrom aggregate import Aggregate\nfrom export import Export\n\n\nclass Cache(object):\n def __init__(self):\n self.cache_window = QtGui.QMainWindow()\n self.ui = Ui_MainWindow()\n self.ui.setupUi(self.cache_window)\n self.cache_window.show()\n\n# Główna część programu\nif __name__ == \"__main__\":\n app = QtGui.QApplication(sys.argv)\n\n cache = Cache() # inicjalizacja okna programu\n configuration = config.Config() # wczytanie konfiguracji\n\n database = db.Db(ip=configuration.db_ip,\n port=configuration.db_port,\n user=configuration.db_user,\n password=configuration.db_password,\n database=configuration.db_name,\n ui=cache.ui) # otwarcie połączenia z bazą danych\n database.prepare(tank_table=configuration.db_tank_table,\n nozzle_table=configuration.db_nozzle_table) # przygotowanie bazy danych\n\n tank_aggregate = Aggregate(values=database.tank_table_values,\n ui=cache.ui) # lista agregacyjna zbiornika paliwa\n nozzle_aggregate = Aggregate(values=database.nozzle_table_values,\n ui=cache.ui) # lista agregacyjna pistoletu paliwowego\n\n export = Export(ui=cache.ui) # inicjalizacja eksportu\n\n # przeliczenie list agregatów\n tank_aggregate.compile_tank()\n nozzle_aggregate.compile_nozzle()\n\n # aktualizacja tablic gui\n tank_aggregate.update_tank_table()\n nozzle_aggregate.update_nozzle_table()\n\n # automatyczne aktualizowanie tablic\n timer = QTimer()\n timer.timeout.connect(database.get_new_data)\n timer.timeout.connect(tank_aggregate.compile_tank_update)\n timer.timeout.connect(nozzle_aggregate.compile_nozzle_update)\n timer.timeout.connect(tank_aggregate.update_tank_table)\n timer.timeout.connect(nozzle_aggregate.update_nozzle_table)\n timer.start(configuration.db_auto_update_interval)\n\n # event dla wyboru ilości krotek agregacji\n cache.ui.radioButton_5.clicked.connect(tank_aggregate.update_tank_table)\n cache.ui.radioButton_15.clicked.connect(tank_aggregate.update_tank_table)\n cache.ui.radioButton_30.clicked.connect(tank_aggregate.update_tank_table)\n cache.ui.radioButton_60.clicked.connect(tank_aggregate.update_tank_table)\n cache.ui.radioButton_5.clicked.connect(nozzle_aggregate.update_nozzle_table)\n cache.ui.radioButton_15.clicked.connect(nozzle_aggregate.update_nozzle_table)\n cache.ui.radioButton_30.clicked.connect(nozzle_aggregate.update_nozzle_table)\n cache.ui.radioButton_60.clicked.connect(nozzle_aggregate.update_nozzle_table)\n\n # event dla eksportu danych\n cache.ui.pushButton_export.clicked.connect(export.to_files)\n\n sys.exit(app.exec_())","sub_path":"cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"470750030","text":"# This file is part of the Reproducible and Reusable Data Analysis Workflow\n# Server (flowServ).\n#\n# Copyright (C) 2019-2020 NYU.\n#\n# flowServ is free software; you can redistribute it and/or modify it under the\n# terms of the MIT License; see LICENSE file for more details.\n\n\"\"\"The workflow repository maintains information about registered workflow\ntemplates. For each template additional basic information is stored in the\nunderlying database.\n\"\"\"\n\nimport errno\nimport git\nimport os\nimport shutil\nimport tempfile\n\nfrom contextlib import contextmanager\n\nfrom flowserv.model.base import WorkflowHandle\nfrom flowserv.model.workflow.manifest import WorkflowManifest\nfrom flowserv.model.workflow.repository import WorkflowRepository\n\nimport flowserv.error as err\nimport flowserv.util as util\nimport flowserv.model.constraint as constraint\n\n\"\"\" \"Default values for the max. attempts parameter and the ID generator\nfunction.\n\"\"\"\nDEFAULT_ATTEMPTS = 100\nDEFAULT_IDFUNC = util.get_short_identifier\n\n\nclass WorkflowManager(object):\n \"\"\"The workflow manager maintains information that is associated with\n workflow templates in a workflow repository.\n \"\"\"\n def __init__(\n self, session, fs, idfunc=None, attempts=None, tmpl_names=None\n ):\n \"\"\"Initialize the database connection, and the generator for workflow\n related file names and directory paths. The optional parameters are\n used to configure the identifier function that is used to generate\n unique workflow identifier as well as the list of default file names\n for template specification files.\n\n By default, short identifiers are used.\n\n Parameters\n ----------\n session: sqlalchemy.orm.session.Session\n Database session.\n fs: flowserv.model.workflow.fs.WorkflowFileSystem\n Generattor for file names and directory paths\n idfunc: func, optional\n Function to generate template folder identifier\n attempts: int, optional\n Maximum number of attempts to create a unique folder for a new\n workflow template\n tmpl_names: list(string), optional\n List of default names for template specification files\n \"\"\"\n self.session = session\n self.fs = fs\n # Initialize the identifier function and the max. number of attempts\n # that are made to generate a unique identifier.\n self.idfunc = idfunc if idfunc is not None else DEFAULT_IDFUNC\n self.attempts = attempts if attempts is not None else DEFAULT_ATTEMPTS\n\n def create_workflow(\n self, source, name=None, description=None, instructions=None,\n specfile=None, manifestfile=None, ignore_postproc=False\n ):\n \"\"\"Add new workflow to the repository. The associated workflow template\n is created in the template repository from either the given source\n directory or a Git repository. The template repository will raise an\n error if neither or both arguments are given.\n\n The method will look for a workflow description file in the template\n base folder with the name flowserv.json, flowserv.yaml, flowserv.yml\n (in this order). The expected structure of the file is:\n\n name: ''\n description: ''\n instructions: ''\n files:\n - source: ''\n target: ''\n specfile: '' or workflowSpec: ''\n\n An error is raised if both specfile and workflowSpec are present in the\n description file.\n\n Raises an error if no workflow name is given or if a given workflow\n name is not unique.\n\n Parameters\n ----------\n source: string\n Path to local template, name or URL of the template in the\n repository.\n name: string, default=None\n Unique workflow name\n description: string, default=None\n Optional short description for display in workflow listings\n instructions: string, default=None\n File containing instructions for workflow users.\n specfile: string, default=None\n Path to the workflow template specification file (absolute or\n relative to the workflow directory)\n manifestfile: string, default=None\n Path to manifest file. If not given an attempt is made to read one\n of the default manifest file names in the base directory.\n ignore_postproc: bool, default=False\n Ignore post-processing workflow specification if True.\n\n Returns\n -------\n flowserv.model.base.WorkflowHandle\n\n Raises\n ------\n flowserv.error.ConstraintViolationError\n flowserv.error.InvalidTemplateError\n flowserv.error.InvalidManifestError\n ValueError\n \"\"\"\n # If a repository Url is given we first clone the repository into a\n # temporary directory that is used as the workflow source directory.\n with clone(source) as sourcedir:\n manifest = WorkflowManifest.load(\n basedir=sourcedir,\n manifestfile=manifestfile,\n name=name,\n description=description,\n instructions=instructions,\n specfile=specfile,\n existing_names=[wf.name for wf in self.list_workflows()]\n )\n # Create identifier and folder for the workflow template. Create a\n # sub-folder for static template files that are copied from the\n # project folder.\n func = self.fs.workflow_basedir\n workflow_id, workflowdir = self.create_folder(dirfunc=func)\n staticdir = self.fs.workflow_staticdir(workflow_id)\n template = manifest.template(staticdir)\n # Copy files from the project folder to the template's static file\n # folder. By default all files in the project folder are copied.\n try:\n manifest.copyfiles(targetdir=staticdir)\n except (IOError, OSError, KeyError) as ex:\n shutil.rmtree(workflowdir)\n raise ex\n # Insert workflow into database and return the workflow handle.\n postproc_spec = template.postproc_spec if not ignore_postproc else None\n workflow = WorkflowHandle(\n workflow_id=workflow_id,\n name=manifest.name,\n description=manifest.description,\n instructions=manifest.instructions,\n workflow_spec=template.workflow_spec,\n parameters=template.parameters,\n modules=template.modules,\n postproc_spec=postproc_spec,\n result_schema=template.result_schema\n )\n self.session.add(workflow)\n # Set the static directory for the workflow handle.\n workflow.set_staticdir(staticdir)\n return workflow\n\n def create_folder(self, dirfunc):\n \"\"\"Create a new unique folder in a base directory using the internal\n identifier function. The path to the created folder is generated using\n the given directory function that takes a unique identifier as the only\n argument.\n\n Returns a tuple containing the identifier and the directory. Raises\n an error if the maximum number of attempts to create the unique folder\n was reached.\n\n Parameters\n ----------\n dirfunc: func\n Function to generate the path for the created folder\n\n Returns\n -------\n (id::string, subfolder::string)\n\n Raises\n ------\n ValueError\n \"\"\"\n identifier = None\n attempt = 0\n while identifier is None:\n # Create a new identifier\n identifier = self.idfunc()\n # Try to generate the subfolder. If the folder exists, set\n # identifier to None to signal failure.\n subfolder = dirfunc(identifier)\n if os.path.isdir(subfolder):\n identifier = None\n else:\n try:\n os.makedirs(subfolder)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n else:\n # Directory must have been created concurrently\n identifier = None\n if identifier is None:\n # Increase number of failed attempts. If the maximum number of\n # attempts is reached raise an errir\n attempt += 1\n if attempt > self.attempts:\n raise RuntimeError('could not create unique folder')\n return identifier, subfolder\n\n def delete_workflow(self, workflow_id):\n \"\"\"Delete the workflow with the given identifier.\n\n Parameters\n ----------\n workflow_id: string\n Unique workflow identifier\n\n Raises\n ------\n flowserv.error.UnknownWorkflowError\n \"\"\"\n # Get the workflow and workflow directory. This will raise an error if\n # the workflow does not exist.\n workflow = self.get_workflow(workflow_id)\n workflowdir = self.fs.workflow_basedir(workflow_id)\n # Delete the workflow from the database and commit changes.\n self.session.delete(workflow)\n self.session.commit()\n # Delete all files that are associated with the workflow if the changes\n # to the database were successful.\n if os.path.isdir(workflowdir):\n shutil.rmtree(workflowdir)\n\n def get_workflow(self, workflow_id):\n \"\"\"Get handle for the workflow with the given identifier. Raises\n an error if no workflow with the identifier exists.\n\n Parameters\n ----------\n workflow_id: string\n Unique workflow identifier\n\n Returns\n -------\n flowserv.model.base.WorkflowHandle\n\n Raises\n ------\n flowserv.error.UnknownWorkflowError\n \"\"\"\n # Get workflow information from database. If the result is empty an\n # error is raised\n workflow = self.session\\\n .query(WorkflowHandle)\\\n .filter(WorkflowHandle.workflow_id == workflow_id)\\\n .one_or_none()\n if workflow is None:\n raise err.UnknownWorkflowError(workflow_id)\n # Set the static directory for the workflow handle.\n workflow.set_staticdir(self.fs.workflow_staticdir(workflow_id))\n return workflow\n\n def list_workflows(self):\n \"\"\"Get a list of descriptors for all workflows in the repository.\n\n Returns\n -------\n list(flowserv.model.base.WorkflowHandle)\n \"\"\"\n workflows = list()\n for wf in self.session.query(WorkflowHandle).all():\n # Set the static directory for the workflow handle.\n wf.set_staticdir(self.fs.workflow_staticdir(wf.workflow_id))\n workflows.append(wf)\n return workflows\n\n def update_workflow(\n self, workflow_id, name=None, description=None, instructions=None\n ):\n \"\"\"Update name, description, and instructions for a given workflow.\n\n Raises an error if the given workflow does not exist or if the name is\n not unique.\n\n Parameters\n ----------\n workflow_id: string\n Unique workflow identifier\n name: string, optional\n Unique workflow name\n description: string, optional\n Optional short description for display in workflow listings\n instructions: string, optional\n Text containing detailed instructions for workflow execution\n\n Returns\n -------\n flowserv.model.base.WorkflowHandle\n\n Raises\n ------\n flowserv.error.ConstraintViolationError\n flowserv.error.UnknownWorkflowError\n \"\"\"\n # Get the workflow from the database. This will raise an error if the\n # workflow does not exist.\n workflow = self.get_workflow(workflow_id)\n # Update workflow properties.\n if name is not None:\n # Ensure that the name is a valid name.\n constraint.validate_name(name)\n # Ensure that the name is unique.\n wf = self.session\\\n .query(WorkflowHandle)\\\n .filter(WorkflowHandle.name == name)\\\n .one_or_none()\n if wf is not None and wf.workflow_id != workflow_id:\n msg = \"workflow '{}' exists\".format(name)\n raise err.ConstraintViolationError(msg)\n workflow.name = name\n if description is not None:\n workflow.description = description\n if instructions is not None:\n workflow.instructions = instructions\n return workflow\n\n\n# -- Helper Methods -----------------------------------------------------------\n\n@contextmanager\ndef clone(source, repository=None):\n \"\"\"Clone a workflow template repository. If source points to a directory on\n local disk it is returned as the 'cloned' source directory. Otherwise, it\n is assumed that source either references a known template in the global\n workflow template repository or points to a git repository. The repository\n is cloned into a temporary directory which is removed when the generator\n resumes after the workflow has been copied to the local repository.\n\n Returns the path to the resulting template source directory on the local\n disk.\n\n Parameters\n ----------\n source: string\n The source is either a path to local template directory, an identifer\n for a template in the global template repository, or the URL for a git\n repository.\n repository: flowserv.model.workflow.repository.WorkflowRepository,\n default=None\n Object providing access to the global workflow repository.\n\n Returns\n -------\n string\n \"\"\"\n if os.path.isdir(source):\n # Return the source if it references a directory on local disk.\n yield source\n else:\n # Clone the repository that matches the given source into a temporary\n # directory on local disk.\n if repository is None:\n repository = WorkflowRepository()\n repourl = repository.get(source)\n sourcedir = tempfile.mkdtemp()\n try:\n git.Repo.clone_from(repourl, sourcedir)\n yield sourcedir\n except (IOError, OSError, git.exc.GitCommandError) as ex:\n raise ex\n finally:\n # Make sure to cleanup by removing the created teporary folder.\n shutil.rmtree(sourcedir)\n","sub_path":"flowserv/model/workflow/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":14625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"210094908","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/10/15 10:59\n# @Author : wangmengmeng\n\"\"\"\ninput:输入包括一个字符串s,字符串s的长度length(1 ≤ length ≤ 50),s只含小写字母('a'-'z')\noutput:\n输出一个整数,表示所有碎片的平均长度,四舍五入保留两位小数。\n如样例所示: s = \"aaabbaaac\"\n所有碎片的平均长度 = (3 + 2 + 3 + 1) / 4 = 2.25\n\"\"\"\ns = input()\nn = len(s)\nk = 0\nfor i in range(n-1):\n if s[i] !=s[i+1]:\n k = k+1\nprint(float(n/(k+1)))","sub_path":"bishi/wangyi_1/test_3.py","file_name":"test_3.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"582261636","text":"# Copyright (c) 2011-2020 Eric Froemling\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 THE\n# SOFTWARE.\n# -----------------------------------------------------------------------------\n\"\"\"Hockey game and support classes.\"\"\"\n\n# ba_meta require api 6\n# (see https://ballistica.net/wiki/meta-tag-system)\n\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nimport ba\nfrom bastd.actor.playerspaz import PlayerSpaz\nfrom bastd.actor.scoreboard import Scoreboard\nfrom bastd.actor.powerupbox import PowerupBoxFactory\nfrom bastd.gameutils import SharedObjects\n\nif TYPE_CHECKING:\n from typing import Any, Sequence, Dict, Type, List, Optional, Union\n\n\nclass PuckDiedMessage:\n \"\"\"Inform something that a puck has died.\"\"\"\n\n def __init__(self, puck: Puck):\n self.puck = puck\n\n\nclass Puck(ba.Actor):\n \"\"\"A lovely giant hockey puck.\"\"\"\n\n def __init__(self, position: Sequence[float] = (0.0, 1.0, 0.0)):\n super().__init__()\n shared = SharedObjects.get()\n activity = self.getactivity()\n\n # Spawn just above the provided point.\n self._spawn_pos = (position[0], position[1] + 1.0, position[2])\n self.last_players_to_touch: Dict[int, Player] = {}\n self.scored = False\n assert activity is not None\n assert isinstance(activity, HockeyGame)\n pmats = [shared.object_material, activity.puck_material]\n self.node = ba.newnode('prop',\n delegate=self,\n attrs={\n 'model': activity.puck_model,\n 'color_texture': activity.puck_tex,\n 'body': 'puck',\n 'reflection': 'soft',\n 'reflection_scale': [0.2],\n 'shadow_size': 1.0,\n 'is_area_of_interest': True,\n 'position': self._spawn_pos,\n 'materials': pmats\n })\n ba.animate(self.node, 'model_scale', {0: 0, 0.2: 1.3, 0.26: 1})\n\n def handlemessage(self, msg: Any) -> Any:\n if isinstance(msg, ba.DieMessage):\n assert self.node\n self.node.delete()\n activity = self._activity()\n if activity and not msg.immediate:\n activity.handlemessage(PuckDiedMessage(self))\n\n # If we go out of bounds, move back to where we started.\n elif isinstance(msg, ba.OutOfBoundsMessage):\n assert self.node\n self.node.position = self._spawn_pos\n\n elif isinstance(msg, ba.HitMessage):\n assert self.node\n assert msg.force_direction is not None\n self.node.handlemessage(\n 'impulse', msg.pos[0], msg.pos[1], msg.pos[2], msg.velocity[0],\n msg.velocity[1], msg.velocity[2], 1.0 * msg.magnitude,\n 1.0 * msg.velocity_magnitude, msg.radius, 0,\n msg.force_direction[0], msg.force_direction[1],\n msg.force_direction[2])\n\n # If this hit came from a player, log them as the last to touch us.\n s_player = msg.get_source_player(Player)\n if s_player is not None:\n activity = self._activity()\n if activity:\n if s_player in activity.players:\n self.last_players_to_touch[s_player.team.id] = s_player\n else:\n super().handlemessage(msg)\n\n\nclass Player(ba.Player['Team']):\n \"\"\"Our player type for this game.\"\"\"\n\n\nclass Team(ba.Team[Player]):\n \"\"\"Our team type for this game.\"\"\"\n\n def __init__(self) -> None:\n self.score = 0\n\n\n# ba_meta export game\nclass HockeyGame(ba.TeamGameActivity[Player, Team]):\n \"\"\"Ice hockey game.\"\"\"\n\n name = 'Hockey'\n description = 'Score some goals.'\n available_settings = [\n ba.IntSetting(\n 'Score to Win',\n min_value=1,\n default=1,\n increment=1,\n ),\n ba.IntChoiceSetting(\n 'Time Limit',\n choices=[\n ('None', 0),\n ('1 Minute', 60),\n ('2 Minutes', 120),\n ('5 Minutes', 300),\n ('10 Minutes', 600),\n ('20 Minutes', 1200),\n ],\n default=0,\n ),\n ba.FloatChoiceSetting(\n 'Respawn Times',\n choices=[\n ('Shorter', 0.25),\n ('Short', 0.5),\n ('Normal', 1.0),\n ('Long', 2.0),\n ('Longer', 4.0),\n ],\n default=1.0,\n ),\n ]\n default_music = ba.MusicType.HOCKEY\n\n @classmethod\n def supports_session_type(cls, sessiontype: Type[ba.Session]) -> bool:\n return issubclass(sessiontype, ba.DualTeamSession)\n\n @classmethod\n def get_supported_maps(cls, sessiontype: Type[ba.Session]) -> List[str]:\n return ba.getmaps('hockey')\n\n def __init__(self, settings: dict):\n super().__init__(settings)\n shared = SharedObjects.get()\n self._scoreboard = Scoreboard()\n self._cheer_sound = ba.getsound('cheer')\n self._chant_sound = ba.getsound('crowdChant')\n self._foghorn_sound = ba.getsound('foghorn')\n self._swipsound = ba.getsound('swip')\n self._whistle_sound = ba.getsound('refWhistle')\n self.puck_model = ba.getmodel('puck')\n self.puck_tex = ba.gettexture('puckColor')\n self._puck_sound = ba.getsound('metalHit')\n self.puck_material = ba.Material()\n self.puck_material.add_actions(actions=(('modify_part_collision',\n 'friction', 0.5)))\n self.puck_material.add_actions(conditions=('they_have_material',\n shared.pickup_material),\n actions=('modify_part_collision',\n 'collide', False))\n self.puck_material.add_actions(\n conditions=(\n ('we_are_younger_than', 100),\n 'and',\n ('they_have_material', shared.object_material),\n ),\n actions=('modify_node_collision', 'collide', False),\n )\n self.puck_material.add_actions(conditions=('they_have_material',\n shared.footing_material),\n actions=('impact_sound',\n self._puck_sound, 0.2, 5))\n\n # Keep track of which player last touched the puck\n self.puck_material.add_actions(\n conditions=('they_have_material', shared.player_material),\n actions=(('call', 'at_connect',\n self._handle_puck_player_collide), ))\n\n # We want the puck to kill powerups; not get stopped by them\n self.puck_material.add_actions(\n conditions=('they_have_material',\n PowerupBoxFactory.get().powerup_material),\n actions=(('modify_part_collision', 'physical', False),\n ('message', 'their_node', 'at_connect', ba.DieMessage())))\n self._score_region_material = ba.Material()\n self._score_region_material.add_actions(\n conditions=('they_have_material', self.puck_material),\n actions=(('modify_part_collision', 'collide',\n True), ('modify_part_collision', 'physical', False),\n ('call', 'at_connect', self._handle_score)))\n self._puck_spawn_pos: Optional[Sequence[float]] = None\n self._score_regions: Optional[List[ba.NodeActor]] = None\n self._puck: Optional[Puck] = None\n self._score_to_win = int(settings['Score to Win'])\n self._time_limit = float(settings['Time Limit'])\n\n def get_instance_description(self) -> Union[str, Sequence]:\n if self._score_to_win == 1:\n return 'Score a goal.'\n return 'Score ${ARG1} goals.', self._score_to_win\n\n def get_instance_description_short(self) -> Union[str, Sequence]:\n if self._score_to_win == 1:\n return 'score a goal'\n return 'score ${ARG1} goals', self._score_to_win\n\n def on_begin(self) -> None:\n super().on_begin()\n\n self.setup_standard_time_limit(self._time_limit)\n self.setup_standard_powerup_drops()\n self._puck_spawn_pos = self.map.get_flag_position(None)\n self._spawn_puck()\n\n # Set up the two score regions.\n defs = self.map.defs\n self._score_regions = []\n self._score_regions.append(\n ba.NodeActor(\n ba.newnode('region',\n attrs={\n 'position': defs.boxes['goal1'][0:3],\n 'scale': defs.boxes['goal1'][6:9],\n 'type': 'box',\n 'materials': [self._score_region_material]\n })))\n self._score_regions.append(\n ba.NodeActor(\n ba.newnode('region',\n attrs={\n 'position': defs.boxes['goal2'][0:3],\n 'scale': defs.boxes['goal2'][6:9],\n 'type': 'box',\n 'materials': [self._score_region_material]\n })))\n self._update_scoreboard()\n ba.playsound(self._chant_sound)\n\n def on_team_join(self, team: Team) -> None:\n self._update_scoreboard()\n\n def _handle_puck_player_collide(self) -> None:\n collision = ba.getcollision()\n try:\n puck = collision.sourcenode.getdelegate(Puck, True)\n player = collision.opposingnode.getdelegate(PlayerSpaz,\n True).getplayer(\n Player, True)\n except ba.NotFoundError:\n return\n\n puck.last_players_to_touch[player.team.id] = player\n\n def _kill_puck(self) -> None:\n self._puck = None\n\n def _handle_score(self) -> None:\n \"\"\"A point has been scored.\"\"\"\n\n assert self._puck is not None\n assert self._score_regions is not None\n\n # Our puck might stick around for a second or two\n # we don't want it to be able to score again.\n if self._puck.scored:\n return\n\n region = ba.getcollision().sourcenode\n index = 0\n for index in range(len(self._score_regions)):\n if region == self._score_regions[index].node:\n break\n\n for team in self.teams:\n if team.id == index:\n scoring_team = team\n team.score += 1\n\n # Tell all players to celebrate.\n for player in team.players:\n if player.actor:\n player.actor.handlemessage(ba.CelebrateMessage(2.0))\n\n # If we've got the player from the scoring team that last\n # touched us, give them points.\n if (scoring_team.id in self._puck.last_players_to_touch\n and self._puck.last_players_to_touch[scoring_team.id]):\n self.stats.player_scored(\n self._puck.last_players_to_touch[scoring_team.id],\n 100,\n big_message=True)\n\n # End game if we won.\n if team.score >= self._score_to_win:\n self.end_game()\n\n ba.playsound(self._foghorn_sound)\n ba.playsound(self._cheer_sound)\n\n self._puck.scored = True\n\n # Kill the puck (it'll respawn itself shortly).\n ba.timer(1.0, self._kill_puck)\n\n light = ba.newnode('light',\n attrs={\n 'position': ba.getcollision().position,\n 'height_attenuated': False,\n 'color': (1, 0, 0)\n })\n ba.animate(light, 'intensity', {0: 0, 0.5: 1, 1.0: 0}, loop=True)\n ba.timer(1.0, light.delete)\n\n ba.cameraflash(duration=10.0)\n self._update_scoreboard()\n\n def end_game(self) -> None:\n results = ba.GameResults()\n for team in self.teams:\n results.set_team_score(team, team.score)\n self.end(results=results)\n\n def _update_scoreboard(self) -> None:\n winscore = self._score_to_win\n for team in self.teams:\n self._scoreboard.set_team_value(team, team.score, winscore)\n\n def handlemessage(self, msg: Any) -> Any:\n\n # Respawn dead players if they're still in the game.\n if isinstance(msg, ba.PlayerDiedMessage):\n # Augment standard behavior...\n super().handlemessage(msg)\n self.respawn_player(msg.getplayer(Player))\n\n # Respawn dead pucks.\n elif isinstance(msg, PuckDiedMessage):\n if not self.has_ended():\n ba.timer(3.0, self._spawn_puck)\n else:\n super().handlemessage(msg)\n\n def _flash_puck_spawn(self) -> None:\n light = ba.newnode('light',\n attrs={\n 'position': self._puck_spawn_pos,\n 'height_attenuated': False,\n 'color': (1, 0, 0)\n })\n ba.animate(light, 'intensity', {0.0: 0, 0.25: 1, 0.5: 0}, loop=True)\n ba.timer(1.0, light.delete)\n\n def _spawn_puck(self) -> None:\n ba.playsound(self._swipsound)\n ba.playsound(self._whistle_sound)\n self._flash_puck_spawn()\n assert self._puck_spawn_pos is not None\n self._puck = Puck(position=self._puck_spawn_pos)\n","sub_path":"assets/src/ba_data/python/bastd/game/hockey.py","file_name":"hockey.py","file_ext":"py","file_size_in_byte":14964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"3239105","text":"class Solution:\n def convert(self, s: str, numRows: int) -> str:\n if s == \"\":\n return \"\"\n if numRows <= 1:\n return s\n\n ls = [[] for _ in range(numRows)]\n num_range = list(range(numRows))\n temp = 0\n for char in s:\n curr = num_range[temp]\n ls[curr].append(char)\n if (temp + 1) > (numRows - 1):\n temp = 1\n num_range = list(reversed(num_range))\n else:\n temp+=1\n output = \"\"\n for el in ls:\n output += ''.join(el)\n return output\n","sub_path":"Leet_Code/Medium/6_Zig.py","file_name":"6_Zig.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"58124914","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 20 18:37:06 2020\n\n@author: Pierre-Marie EDLINGER\n\"\"\"\n\nfrom tkinter import *\nfrom tkinter.ttk import *\n\nimport ProgCreationFichierCLS as Prog\nimport FonctionsFichier as FF\n\nDERNIERELIGNE = 10\n\n# définition des gestionnaires\n# d'événements :\n\ndef choixFicDeTravail():\n varNomFicTravail.set(FF.getFichier())\n \"\"\"\n tF = eval(champTC.get())\n varTF.set(str(tF*1.8 +32))\n \"\"\"\n \ndef choixFicCaisse():\n varNomFicCaisses.set(FF.getFichier())\n \ndef choixRepFinal():\n varNomRep.set(FF.getRepertoire())\n \ndef fermeTout():\n global fenPrincipale\n fenPrincipale.quit()\n\ndef creerFichierModele():\n try :\n cheminFic = \"\"\n cheminFic = FF.getOuEnregistrerFichier()\n if cheminFic != \"\":\n Prog.CreerFichierTravail(cheminFic)\n FF.messageInfo(\"Succès\", \"L'opération s'est déroulée avec succès.\")\n except :\n FF.messageWarning(\"Erreur\", \"Une erreur est survenue lors de la création du fichier modèle...\")\n\ndef creerFichiersCLS():\n try:\n if (varNomFicTravail.get() == \"\"):\n FF.messageWarning(\"Renseignements manquants\", \"Choisissez le fichier source.\")\n choixFicDeTravail()\n else :\n if FF.verifieExistanceFichier(varNomFicTravail.get()):\n if (varNomRep.get() == \"\"):\n FF.messageWarning(\"Renseignements manquants\", \"Choisissez un répertoire où placer le(s) fichier(s) à importer dans IBM Lotus.\")\n choixRepFinal()\n else:\n if FF.verifieExistanceRepertoire(varNomRep.get()):\n Prog.LanceCreationFichierCLS(varNomFicTravail.get(), varNomRep.get())\n #FF.messageInfo(\"Succès\", \"L'opération s'est déroulée avec succès.\")\n else:\n choixRepFinal()\n else:\n choixFicDeTravail()\n except :\n FF.messageWarning(\"Erreur\", \"Une erreur est survenue lors de la création du ou des fichier(s) à importer.... Vérifiez qu'il n'y ait pas un Alt+Tab dans un des fichiers.\")\n\ndef creerFichierSupprimeCaisse():\n try:\n if (varNomFicTravail.get() == \"\"):\n FF.messageWarning(\"Renseignements manquants\", \"Choisissez le fichier de travail.\")\n choixFicDeTravail()\n else :\n if FF.verifieExistanceFichier(varNomFicTravail.get()):\n if (varNomRep.get() == \"\"):\n FF.messageWarning(\"Renseignements manquants\", \"Choisissez un répertoire où placer le(s) fichier(s) à importer dans IBM Lotus.\")\n choixRepFinal()\n else:\n if FF.verifieExistanceRepertoire(varNomRep.get()):\n \n if (varNomFicCaisses.get() == \"\"):\n FF.messageWarning(\"Renseignements manquants\", \"Choisissez le fichier des caisses à rendre inactives.\")\n choixFicCaisse()\n else :\n if FF.verifieExistanceFichier(varNomFicCaisses.get()):\n Prog.LanceCreationFichierSupprimeCaisses(varNomFicCaisses.get(), varNomFicTravail.get(), varNomRep.get())\n else:\n choixFicCaisse()\n else:\n choixRepFinal()\n else:\n choixFicDeTravail()\n except :\n FF.messageWarning(\"Erreur\", \"Une erreur est survenue lors de la création du fichier pour rendre des caisses inactives... Vérifiez qu'il n'y ait pas un Alt+Tab dans un des fichiers.\")\n\n\ndef afficheInfos():\n global fenPrincipale\n texte = \"Penser à ouvrir le(s) fichier(s) résultat(s) avec OpenOffice puis enregistrez les au format '.ods' avant de les importer.\\nLe code source de cette application est disponible sur: https://github.com/edlingerpm/DeploiementCLS\\n(copié dans le presse papier).\"\n try :\n fenPrincipale.clipboard_clear()\n fenPrincipale.clipboard_append(\"https://github.com/edlingerpm/DeploiementCLS\")\n FF.messageInfo(\"Information importante\", texte)\n except :\n print(\"Erreur!!!!\")\n None\n\ndef testModif():\n global tableau\n \n if FF.verifieExistanceFichier(varNomFicTravail.get()):\n # try :\n maMatrice = FF.getRensDansFichierExportComplet(varNomFicTravail.get())\n # print(len(maMatrice))\n for i in range(0, len(maMatrice)) :\n # print(maMatrice[i][0])\n tableau.insert('', 'end', iid=maMatrice[i][0], values=(maMatrice[i][1], maMatrice[i][2], maMatrice[i][3]))\n tableau.update\n # except :\n # print(\"Erreur testModif!!!!\")\n # None\n else:\n choixFicDeTravail()\n\n# def pointeur(event):\n# print( \"Clic détecté en X =\" + str(event.x) +\\\n# \", Y =\" + str(event.y))\n \n#========== Programme principal =============\n\n# Création du widget principal (\"parent\") :\nfenPrincipale = Tk()\nfenPrincipale.title(\"Création du fichier d'importation dans IBM Lotus\")\nfenPrincipale.geometry(\"650x130\")\n\n# fenPrincipale.geometry(\"650x200\")\n\n# fenPrincipale.bind(\"\", pointeur) # Button-1 --> clic gauche; Button-2 --> clic molette; Button-3 --> clic droit\n# fenPrincipale.resizable(False, False)\n\ntry: #sert à éviter un message d'erreur si le fichier icone n'existe pas\n fenPrincipale.iconbitmap('icone.ico')\nexcept : None\n\nGAUCHE = 10\nLARGEURBOUTONS = 15\nLIGNEDUBAS = 100\n\n# création des widgets \"enfants\" :\n# can1 = Canvas(fen1,bg='dark grey',height=250, width=250)\n# can1.pack(side=LEFT, padx =5, pady =5)\n#chaine.configure(text = \"test\") # pour changer le texte d'un label\n\n# ---- Gestion de la zone \"où enregistrer les fichiers\"\n# ---- Label\nlblRep1 = Label(fenPrincipale, text = 'Choix du répertoire où enregistrer les fichiers de travail :')\nlblRep1.place(x=GAUCHE, y = 5)\n\n# ---- zone de texte \nvarNomRep = StringVar()\nentr2 = Entry(fenPrincipale, textvariable = varNomRep, width =100)\nvarNomRep.set(\"\")\nentr2.place(x=GAUCHE, y= 25)\n\n# ---- Bouton ------------------\nbtnChoixRep = Button(fenPrincipale, text='...', width =2, command=choixRepFinal)\nbtnChoixRep.place(x=620, y= 23)\n#*********************************************************\n\n# ---- Gestion de la zone \"fichier de travail\"\n# ---- Label\nlblFic2 = Label(fenPrincipale, text = 'Choix du fichier de travail :')\nlblFic2.place(x=GAUCHE, y=50)\n\n# ---- zone de texte\nvarNomFicTravail = StringVar()\nentr1 = Entry(fenPrincipale, textvariable = varNomFicTravail, width =45) # varTC.set(\"\")\nvarNomFicTravail.set(\"\")\nentr1.place(x=GAUCHE, y= 70)\n\n# ---- Bouton ------------------\nbtnFicTravail = Button(fenPrincipale, text='...', width =2, command=choixFicDeTravail)\nbtnFicTravail.place(x=289, y= 68)\n#*********************************************************\n\n# ---- Gestion de la zone \"fichier des caisses\"\n# ---- Label\nlblFic3 = Label(fenPrincipale, text = 'Choix du fichier des caisses à rendre inactives :')\nlblFic3.place(x=GAUCHE +330, y=50)\n\n# ---- zone de texte\nvarNomFicCaisses = StringVar()\nentr2 = Entry(fenPrincipale, textvariable = varNomFicCaisses, width =45) # varTC.set(\"\")\nvarNomFicCaisses.set(\"\")\nentr2.place(x=GAUCHE+330, y= 70)\n\n# ---- Bouton ------------------\nbtnFicCaisse = Button(fenPrincipale, text='...', width =2, command=choixFicCaisse)\nbtnFicCaisse.place(x=620, y= 68)\n#*********************************************************\n\nbtnCreerFicTravail = Button(fenPrincipale, text='Créer un modèle', width =LARGEURBOUTONS, command=creerFichierModele)\nbtnCreerFicTravail.place(x=GAUCHE, y= LIGNEDUBAS)\n\nbtnCreerFichierCLS = Button(fenPrincipale, \n text='Créer le(s) fichier(s) à importer', \n width =LARGEURBOUTONS + 15, \n command=creerFichiersCLS)\nbtnCreerFichierCLS.place(x=115, y= LIGNEDUBAS)\n\nbtnSupprimerCaisses = Button(fenPrincipale, \n text='Créer le fichier pour supprimer caisse(s)', \n width =LARGEURBOUTONS + 20, \n command=creerFichierSupprimeCaisse)\nbtnSupprimerCaisses.place(x=310, y= LIGNEDUBAS)\n\nbtnQuit = Button(fenPrincipale,text='Quitter', width =LARGEURBOUTONS -5, command=fermeTout)\nbtnQuit.place(x=535, y= LIGNEDUBAS)\n\nbtnInfo = Button(fenPrincipale,text='?', width =3, command=afficheInfos)\nbtnInfo.place(x=615, y= LIGNEDUBAS)\n\n\n# btnModif = Button(fenPrincipale,text='Test', width =5, command=testModif)\n# btnModif.place(x=GAUCHE, y= LIGNEDUBAS+30)\n\n\n# lststrMaListe = ListStore(str, str)\n\n# tableau = Treeview(fenPrincipale, columns=('nomfamille', 'prenom', 'da'))\n# tableau.heading('nomfamille', text='Nom de famille')\n# tableau.heading('prenom', text='Prénom')\n# tableau.heading('da', text='DA')\n# tableau['show'] = 'headings' # sans ceci, il y avait une colonne vide à gauche qui a pour rôle d'afficher le paramètre \"text\" qui peut être spécifié lors du insert\n# tableau.place(x=GAUCHE + 50, y= LIGNEDUBAS+30)\n# tableau.insert('', 'end', iid=\"45\", values=(\"1\", \"2\", \"3\"))\n# tableau.insert('', 'end', iid=\"48\", values=(\"4\", \"5\", \"6\"))\n# tableau.set_property(\"editable\", True)\n# tableau.editable = True\n\n\n# démarrage du réceptionnaire d'évènements (boucle principale) :\nfenPrincipale.mainloop()\n\ntry:\n fenPrincipale.destroy()\nexcept:\n None","sub_path":"IHM.py","file_name":"IHM.py","file_ext":"py","file_size_in_byte":9437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"53996377","text":"from HelperLibrary.StorageFunctions import StorageFunctions\n\n\nclass Information:\n def __init__(self, username):\n self.username = username\n\n def execute(self):\n user_data = StorageFunctions(\"users\").retrieve([\"username\"], [self.username])\n user_id = (user_data[0])[0]\n drones_data = StorageFunctions(\"drones\").retrieve([\"user_id\"], [user_id])\n if not drones_data:\n print(\"You have not booked any drones\")\n else:\n print(\"You have booked:\")\n counter = 1\n for booked_data in drones_data:\n origin_data = StorageFunctions(\"locations\").retrieve([\"id\"], [booked_data[8]])\n origin = (origin_data[0])[1]\n destination_data = StorageFunctions(\"locations\").retrieve([\"id\"], [booked_data[9]])\n destination = (destination_data[0])[1]\n print(counter, \": Drone number - \", booked_data[0], \", from \", origin, \" to \", destination, sep='')\n counter += 1\n","sub_path":"BookingSystem/Information.py","file_name":"Information.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"428154970","text":"#!/usr/bin/python\n\n\"\"\"Update an existing highscore in the database.\n\nThis code updates a player's existing highscore in the database,\nif the new score is higher.\n\"\"\"\n\nimport cgi\nimport cgitb\nimport json\n\nimport pymysql\n\nimport processing\n\n\ndef update_score(player_id, level_number, score):\n \"\"\"Update a score in the database.\n\n This function updates an existing score in the\n database for a particular player and level.\n \"\"\"\n\n connection, cursor = processing.connect_to_database()\n cursor.execute(\"UPDATE scores SET score=%s \"\n \"WHERE player_id=%s AND level_id=%s\", (score, player_id, level_number))\n connection.commit()\n\n\ndef is_best(player_id, level_number, score):\n \"\"\"Ensure that the score is the player's highest for that level.\n\n This function checks that the new score is actually better than\n the existing score. If the new score is higher, it returns True.\n If the new score is lower or an old score doesn't exist, it returns\n False.\n \"\"\"\n\n connection, cursor = processing.connect_to_database()\n cursor.execute(\"SELECT score FROM scores \"\n \"WHERE player_id=%s AND level_id=%s\", (player_id, level_number))\n current_best = [(row[0]) for row in cursor.fetchall()]\n\n # There isn't an existing score if length of list is 0\n if len(current_best) != 0 and int(score) > current_best[0]:\n return True\n else:\n return False\n\n\nif __name__ == \"__main__\":\n # Turn on debug mode\n cgitb.enable()\n # Print necessary headers\n print(\"Content-Type: text/html; charset=utf-8\\n\\n\")\n\n form = cgi.FieldStorage()\n player_name = processing.get_player_name(form)\n level_number = processing.get_level_number(form)\n score = processing.get_score(form)\n\n if player_name != None and level_number != None and score != None:\n player_id = processing.get_player_id(player_name)\n\n if player_id != None and is_best(player_id, level_number, score):\n update_score(player_id, level_number, score)\n print(json.dumps([player_name, level_number, score]))\n else:\n # If player doesn't exist of score isn't best\n print(json.dumps(None))\n\n else:\n # If player/level/score not provided\n print(json.dumps(None))","sub_path":"Client-Server Database/updatescore.py","file_name":"updatescore.py","file_ext":"py","file_size_in_byte":2285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"576220832","text":"'''\n44. Wildcard Matching\n\nGiven an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'.\n\n'?' Matches any single character.\n'*' Matches any sequence of characters (including the empty sequence).\nThe matching should cover the entire input string (not partial).\n\nNote:\n\ns could be empty and contains only lowercase letters a-z.\np could be empty and contains only lowercase letters a-z, and characters like ? or *.\nExample 1:\n\nInput:\ns = \"aa\"\np = \"a\"\nOutput: false\nExplanation: \"a\" does not match the entire string \"aa\".\nExample 2:\n\nInput:\ns = \"aa\"\np = \"*\"\nOutput: true\nExplanation: '*' matches any sequence.\nExample 3:\n\nInput:\ns = \"cb\"\np = \"?a\"\nOutput: false\nExplanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.\nExample 4:\n\nInput:\ns = \"adceb\"\np = \"*a*b\"\nOutput: true\nExplanation: The first '*' matches the empty sequence, while the second '*' matches the substring \"dce\".\nExample 5:\n\nInput:\ns = \"acdcb\"\np = \"a*c?b\"\nOutput: false\nAccepted\n228,395\nSubmissions\n943,459\n\n'''\n\n# 2020/04/15, memoization, too hard\n\n'''\nRuntime: 832 ms, faster than 51.16% of Python3 online submissions for Wildcard Matching.\nMemory Usage: 93.4 MB, less than 41.67% of Python3 online submissions for Wildcard Matching.\n'''\n\n\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n memo = {}\n self.dfs(s, 0, p, 0, memo)\n return memo[(0, 0)]\n\n def dfs(self, string, i, pattern, j, memo):\n if (i, j) in memo: return memo[(i, j)]\n if i >= len(string):\n for k in range(j, len(pattern)):\n if pattern[k] != '*':\n memo[(i, j)] = False\n return False\n memo[(i, j)] = True\n return memo[(i, j)]\n if j >= len(pattern):\n memo[(i, j)] = False\n return memo[(i, j)]\n if pattern[j] != '*':\n memo[(i, j)] = self.is_valid(string[i], pattern[j]) \\\n and self.dfs(string, i + 1, pattern, j + 1, memo)\n else:\n memo[(i, j)] = self.dfs(string, i + 1, pattern, j, memo) \\\n or self.dfs(string, i, pattern, j + 1, memo)\n return memo[(i, j)]\n\n def is_valid(self, s, p):\n return s == p or p == '?'\n","sub_path":"0044. Wildcard Matching.py","file_name":"0044. Wildcard Matching.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"42523843","text":"from bs4 import BeautifulSoup\nimport urllib.request\n\n\ntowns={1:'Zagreb+Gl.+Kol.',2:'OGULIN',}\n\n#default is Zagreb if no data is entered\ni_key=1\n\ndef stripped(data,sub=''):\n if data==None:\n data=sub\n else:\n data=data.strip()\n \n return data\n \n\ndef get_data(url):\n response=urllib.request.urlopen(url)\n html=response.read()\n b=BeautifulSoup(html)\n \n b=b.find_all('tr')\n \n print('TRAIN ID - ARRIVAL TIME - LATE - DESTINATION')\n \n for i in b:\n x=i.find_all('td')\n train_id=x[0].a.string.strip()\n \n arrival=x[1].string.strip()\n \n late=stripped(x[2].string,'On Time')\n \n \n from_town=stripped(x[6].string)\n print(train_id+' - '+arrival+' - '+late+' - '+from_town)\n \n\n\ninpt=input('Select number for city: \\n1-Zagreb\\n2-Ogulin\\n:')\n\n\nif inpt.strip()!='':\n i_key=int(inpt)\n\n\n\nif (inpt.strip()!='') and (i_key in towns):\n url='http://vred.hzinfra.hr/hzinfo/Default.asp?KO='+towns[i_key]+'&Category=hzinfo&Service=PANO&LANG=HR&OD1=D&SCREEN=2'\n print('Selected city: '+towns[i_key])\nelse:\n print('You have provided wrong input. Showing trains for Zagreb')\n url='http://vred.hzinfra.hr/hzinfo/Default.asp?KO='+towns[i_key]+'&Category=hzinfo&Service=PANO&LANG=HR&OD1=D&SCREEN=2'\n\n\n\n\nget_data(url)\n\n\n\n\n\n\n\n","sub_path":"hz_get_simple_data_for_2_cities.py","file_name":"hz_get_simple_data_for_2_cities.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"27520230","text":"\"\"\"Wrapper of the Keras model for training without batches\"\"\"\nimport tensorflow as tf\nimport numpy as np\nimport os\n\nfrom copy import deepcopy\nfrom typing import List, Optional, Callable\nfrom tqdm import tqdm\n\nfrom icscreator.kernel.layers import Model\nfrom icscreator.kernel.visualization import BaseVisualizer, EmptyVisualizer\n\n\nclass Trainer(object):\n \"\"\"Class for training models\"\"\"\n\n def __init__(self,\n model: Model,\n optimizer: tf.optimizers.Optimizer,\n loss: tf.losses.Loss,\n model_path: Optional[str] = None,\n metrics: Optional[List[Callable]] = None,\n target_metric: str = \"loss\",\n metric_comparator: Callable = min,\n epochs: int = 1000,\n early_stopping: int = 50,\n visualizer: BaseVisualizer = EmptyVisualizer()):\n self._model = model\n self._optimizer = optimizer\n self._loss = loss\n self._model_path = model_path\n self._metrics = metrics if metrics is not None else []\n self._target_metric = target_metric\n self._metric_comparator = metric_comparator\n self._epochs = epochs\n self._early_stopping = early_stopping\n self._visualizer = visualizer\n self._best_metric_value = None\n self._best_model = None\n self._best_epoch = 0\n\n @property\n def best_model(self) -> Model:\n return self._best_model\n\n def _train_step(self, data: tf.Tensor, target: tf.Tensor) -> (dict, np.ndarray):\n with tf.GradientTape() as tape:\n prediction = self._model(data, sequence=True)\n loss = self._loss(target, prediction)\n gradients = tape.gradient(loss, self._model.trainable_variables)\n self._optimizer.apply_gradients(zip(gradients, self._model.trainable_variables))\n\n prediction = prediction.numpy()\n results = {m.__name__: m(target.numpy(), prediction) for m in self._metrics}\n results[\"loss\"] = loss.numpy()\n return results, prediction\n\n def _prediction_step(self, data: tf.Tensor, target: tf.Tensor) -> (dict, np.ndarray):\n prediction = self._model(data, sequence=True)\n loss = self._loss(target, prediction)\n prediction = prediction.numpy()\n results = {m.__name__: m(target.numpy(), prediction) for m in self._metrics}\n results[\"loss\"] = loss.numpy()\n return results, prediction\n\n @staticmethod\n def _metrics_to_text(epoch: int, results: dict) -> str:\n text = f\"Epoch {epoch}: \" + \", \".join([f\"{k} = {v:.6f}\" for k, v in results.items()])\n return text\n\n def _is_metric_best(self, metric: float) -> bool:\n result = False\n if self._best_metric_value is None or metric == self._metric_comparator(metric, self._best_metric_value):\n self._best_metric_value = metric\n result = True\n return result\n\n def fit(self, train_x: np.ndarray, train_y: np.ndarray, test_x: np.ndarray, test_y: np.ndarray) -> Model:\n desc = self._metrics_to_text(0, {m.__name__: None for m in self._metrics})\n pbar = tqdm(total=self._epochs, desc=desc, ncols=100)\n\n train_x = tf.convert_to_tensor(value=train_x, dtype=self._model.dtype)\n train_y = tf.convert_to_tensor(value=train_y, dtype=self._model.dtype)\n test_x = tf.convert_to_tensor(value=test_x, dtype=self._model.dtype)\n test_y = tf.convert_to_tensor(value=test_y, dtype=self._model.dtype)\n\n for e in range(self._epochs):\n if e - self._best_epoch > self._early_stopping:\n break\n\n train_metrics, _ = self._train_step(train_x, train_y)\n test_metrics, test_prediction = self._prediction_step(test_x, test_y)\n pbar.set_description(self._metrics_to_text(e, test_metrics))\n pbar.update(1)\n\n self._visualizer.draw([test_prediction, test_y],\n train=[train_metrics[self._target_metric]],\n test=[test_metrics[self._target_metric]])\n\n if self._is_metric_best(test_metrics[self._target_metric]):\n self._model.save(self._model_path)\n self._best_epoch = e\n self._best_model = deepcopy(self._model)\n self._visualizer.save_fig(os.path.join(self._model_path, \"figure.jpg\"))\n\n return self._best_model\n","sub_path":"icscreator/kernel/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":4439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"268214888","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/mautrix/util/signed_token.py\n# Compiled at: 2019-11-21 01:01:47\n# Size of source mod 2**32: 1335 bytes\nfrom typing import Dict, Optional\nfrom hashlib import sha256\nimport hmac, json, base64\n\ndef _get_checksum(key: str, payload: bytes) -> str:\n hasher = hmac.new((key.encode('utf-8')), msg=payload, digestmod=sha256)\n checksum = base64.urlsafe_b64encode(hasher.digest())\n return checksum.decode('utf-8').rstrip('=')\n\n\ndef sign_token(key: str, payload: Dict) -> str:\n payload_b64 = base64.urlsafe_b64encode(json.dumps(payload).encode('utf-8'))\n checksum = _get_checksum(key, payload_b64)\n payload_str = payload_b64.decode('utf-8').rstrip('=')\n return f\"{checksum}:{payload_str}\"\n\n\ndef verify_token(key: str, data: str) -> Optional[Dict]:\n if not data:\n return\n try:\n checksum, payload = data.split(':', 1)\n except ValueError:\n return\n else:\n payload += (3 - (len(payload) + 3) % 4) * '='\n if checksum != _get_checksum(key, payload.encode('utf-8')):\n return\n payload = base64.urlsafe_b64decode(payload).decode('utf-8')\n try:\n return json.loads(payload)\n except json.JSONDecodeError:\n return","sub_path":"pycfiles/blkmautrix-0.0.18-py3.6/signed_token.cpython-36.py","file_name":"signed_token.cpython-36.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"461873043","text":"import sys\n\nentry = {}\nentry_rev = {}\n\n\ndef definition(vari, num):\n\n if vari in entry:\n del entry_rev[entry[vari]]\n entry[vari] = num\n entry_rev[num] = vari\n\n\ndef calc(alist):\n\n if len(list(filter(lambda z: z in entry.keys(), alist[1:][::2]))) != len(alist[1:][::2]):\n print(\" \".join(alist[1:]) + ' unknown')\n\n else:\n sum = eval(\n \" \".join(map(lambda z: entry[z] if z in entry.keys() else z, alist[1:-1])))\n\n if str(sum) in entry_rev:\n print(\" \".join(alist[1:]) + \" \" + entry_rev[str(sum)])\n\n else:\n print(\" \".join(alist[1:]) + ' unknown ')\n\n\nfor line in sys.stdin:\n func = line.split()[0]\n if func == 'def':\n definition(line.split()[1], line.split()[2])\n\n elif func == 'calc':\n calc(line.split())\n\n elif func == 'clear':\n entry.clear()\n entry_rev.clear()\n else:\n break\n\n# # 변수 3개 이상은?\n# # calc에 value만 넣어서 entry에서 확인\n\n# #calculation function 알고리즈 어디가 틀린지 찾아야함\n\n# #entry_rev를 만듬으로서 dictionary를 list로 접근하는 것에서 (O(n))\n# #O(1)로 바꿈\n\n# # for statement 보다 map(lambda), filter(lambda)가 더 빠르다.\n\n\ndef solution(p):\n next = True\n while(next):\n p += 1\n a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n first = p // 1000\n second = (p % 1000) // 100\n third = (p % 100) // 10\n fourth = p % 10\n count = 0\n number = [first, second, third, fourth]\n for i in number:\n if i in a:\n count += 1\n a.remove(i)\n if count == 4:\n next = False\n return p\n\n\nprint(solution(1987))\n","sub_path":"addingwords.py","file_name":"addingwords.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"197506808","text":"\"\"\"\nScript used for patching settings in\nNUnit assembly configuration files (xml format)\n\"\"\"\nimport xml.etree.ElementTree as ET\n\ndef get_setting_value_element(element_tree, setting_name):\n \"\"\" Get setting value element by name in a config element tree \"\"\"\n try:\n value = element_tree.find(\".//setting[@name='{}']\".format(setting_name)).find(\"value\")\n except:\n raise Exception(\"Setting with name=<{}> could not be found\".format(setting_name))\n return value\n\ndef peek_setting(element_tree, setting_name):\n \"\"\" Get setting text value by name in a config element tree \"\"\"\n value = get_setting_value_element(element_tree, setting_name)\n return value.text\n\ndef poke_setting(element_tree, setting_name, new_text_value):\n \"\"\" Set new setting text value by name in a config element tree \"\"\"\n value = get_setting_value_element(element_tree, setting_name)\n value.text = new_text_value\n\ndef do_replace(config_files, replace_settings):\n \"\"\" \n Set multiple settings in multiple config files\n \\nconfig_files - a list of files to patch\n \\nreplace_settings - a dictionary with settings names \n and new setting values\n \\nExample: do_replace([\"FileA.config\", \"FileB.config\"], {\"Setting1\" : \"Value1\", \"Setting2\" : \"Value2\"})\n \"\"\"\n for config_file in config_files:\n # Open configuration settings file as an element tree\n config_tree_root = ET.parse(config_file)\n print(\"*** Opened file <{}>\".format(config_file))\n\n # Replace all settings\n for setting_name, replace_value in replace_settings.items():\n old_value = peek_setting(config_tree_root, setting_name)\n poke_setting(config_tree_root, setting_name, replace_value)\n new_value = peek_setting(config_tree_root, setting_name)\n print(\"Changed setting <{}> from <{}> to <{}>\".format(setting_name, old_value, new_value))\n\n # Save modified tree to file\n modified_file = \"{}\".format(config_file)\n config_tree_root.write(modified_file)\n print(\"**** Saved changes to file <{}>\".format(modified_file))\n\n\ndef test_do_replace():\n do_replace(\n [\n r\"C:\\wa\\Sally\\trunk\\WIN32\\Output\\x86\\Debug\\CcbDeviceTests.dll.config\", \n r\"C:\\wa\\Sally\\trunk\\WIN32\\Output\\x86\\Debug\\DeflectionDeviceTests.dll.config\"\n ], \n {\n \"RemoteIp\" : \"171.0.14.254\",\n \"PowerBoxRelayIndexPower\" : \"0\"\n }\n )\n","sub_path":"xml_config/patchconfig.py","file_name":"patchconfig.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"480586508","text":"import datetime\nimport random\nfrom typing import Text, Tuple\n\nfrom currency_providers.driver import BaseProviderDriver\n\n\nclass Driver(BaseProviderDriver):\n base_url = \"http://data.fixer.io/api/\"\n access_key = \"1d3ef12f7d656b3e63cbee7e6874702f\"\n\n def __init__(self, base):\n super().__init__(base=base)\n self._mock_data = {}\n for currency in [\"EUR\", \"CHF\", \"USD\", \"GBP\"]:\n currency = self._format_currency(currency)\n self._mock_data[currency] = {}\n for i in range(0, 1400): # 4 años\n date = datetime.datetime.now() - datetime.timedelta(days=i)\n self._mock_data[currency][self._parse_date(date)] = random.random()\n\n @staticmethod\n def _format_currency(currency):\n return currency.upper()\n\n @staticmethod\n def _parse_date(date):\n return date.strftime(\"%Y-%m-%d\")\n\n def rates(self, currency: Text, date: datetime = None) -> Tuple[bool, float, datetime.datetime]:\n currency = self._format_currency(currency)\n if not date:\n date = datetime.datetime.now()\n date_str = self._parse_date(date)\n return True, self._mock_data[currency][date_str], date\n\n def exchanges(self, currency_origin: Text, currency_destination: Text, amount: int) -> Tuple[\n bool, float, datetime.datetime]:\n currency_origin = self._format_currency(currency_origin)\n currency_destination = self._format_currency(currency_destination)\n first_key = next(i for i in self._mock_data[currency_origin])\n amount_origin = self._mock_data[currency_origin][first_key]\n amount_destination = self._mock_data[currency_destination][first_key]\n return True, (amount * (amount_origin / amount_destination)), datetime.datetime.strptime(first_key, \"%Y-%m-%d\")\n\n def time_weighted_rate(self) -> Tuple[bool, float]:\n response, content = self.request.request(url=\"latest\", method=\"get\", data={\"access_key\": \"\"})\n return content\n","sub_path":"currency_providers/providers/mock/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"378671984","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport json\nimport time\nimport paho.mqtt.client as mqtt\nimport traceback\nimport os.path\n######## r3 ZMQ ############\n\nmyclientid_ = \"smallkiosk\"\ndht_sensordata_file_ = \"/tmp/dht11data.txt\"\nquery_sensor_intervall_ = 60\n\ndef sendR3Message(client, topic, datadict, qos=0, retain=False):\n client.publish(topic, json.dumps(datadict), qos, retain)\n\n\ndef decodeR3Payload(payload):\n try:\n return json.loads(payload.decode(\"utf-8\"))\n except Exception as e:\n print(\"Error decodeR3Payload:\" + str(e))\n return {}\n\n# reads data from dht_sensordata_file_\n# which is generated by cron every minute\n# crontab:\n# * * * * * /root/Adafruit_Python_DHT/examples/AdafruitDHT.py 11 30 > /tmp/dht11data.txt.new && mv /tmp/dht11data.txt.new /tmp/dht11data.txt\n\n\ndef getAndPublishDHT11SensorValues(client):\n data = \"\"\n ts = 0\n try:\n ts = int(os.path.getmtime(dht_sensordata_file_))\n with open(dht_sensordata_file_, \"r\") as dhtf:\n data = dhtf.read()\n except:\n return\n\n if data[:0 + 5] == \"Temp=\":\n temp = float(data[5:5 + 4])\n sendR3Message(client, \"realraum/\" + myclientid_ + \"/temperature\",\n {\"Location\": \"LoTHR\", \"Value\": temp, \"Ts\": ts}, retain=True)\n if data[12:12 + 9] == \"Humidity=\":\n humidity = float(data[21:21 + 4])\n sendR3Message(client,\n \"realraum/\" + myclientid_ + \"/relhumidity\",\n {\"Location\": \"LoTHR\",\n \"Percent\": humidity,\n \"Ts\": ts},\n retain=True)\n\ndef onMQTTDisconnect(mqttc, userdata, rc):\n if rc != 0:\n print(\"Unexpected disconnection.\")\n while True:\n time.sleep(5)\n print(\"Attempting reconnect\")\n try:\n mqttc.reconnect()\n break\n except ConnectionRefusedError:\n continue\n else:\n print(\"Clean disconnect.\")\n sys.exit()\n\n# Start zmq connection to publish / forward sensor data\ndef initMQTT():\n client = mqtt.Client(client_id=myclientid_)\n client.connect(\"mqtt.realraum.at\", 1883, keepalive=31)\n client.on_disconnect = onMQTTDisconnect\n return client\n\n\nif __name__ == '__main__':\n client = None\n last_get_sensor_data_ts = time.time()\n try:\n client = initMQTT()\n while True:\n if time.time() - last_get_sensor_data_ts > query_sensor_intervall_:\n getAndPublishDHT11SensorValues(client)\n last_get_sensor_data_ts = time.time()\n client.loop()\n\n except Exception as e:\n traceback.print_exc()\n finally:\n if isinstance(client, mqtt.Client):\n # client_stop_loop()\n client.disconnect()\n","sub_path":"scripts/dht11sensor.py","file_name":"dht11sensor.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"314651743","text":"# imports\nimport numpy as np\nimport emcee as em\nimport corner\nfrom diag_depr import *\nfrom matplotlib import pyplot as plt\nfrom methods import *\nfrom problem_config import *\n\n'''\n'''\n'''\nemcee test case\n'''\n'''\n'''\n# %%\n\n\ndiag = Diagnostic(x, y, e, true_coeffs, total_samples, Post.posterior)\n\n# %%\ndiag.run(walker_list, show_error = False, export_results = True, plt_filename = 'diagnostics/walker_comp.png')\ndiag.export_df('walker_comparison')\n\n# %%\nprint(diag.df)\n\n# %%\nwalker_list = [250]\ndiag.run(walker_list, show_error = True, export_results = True, plt_filename = 'diagnostics/250_error_bands.png')\n# %%\ndiag.show_corner(export_results = True, path = 'diagnostics/250_walker_corner.png')\n\n# %%\ndiag.compare_model_vs_real()\n\n# %%\n\n\na = 0.2\nfor i in range(100):\n plt.plot(diag.fc[[i, i+1], 0], diag.fc[[i, i+1], 2], alpha = a, color = 'teal')\n # plt.scatter(diag.fc[i, 0], diag.fc[i, 2], alpha = a, color = 'black', s = 10)\n if a <= .98:\n a = a + .005\nplt.ylabel('a2')\nplt.xlabel('a0')\nplt.savefig('diagnostics/walker_example.png', dpi = 600)\nplt.show()\n\n\n# # metrop\n# s = Sampler(Post, metropolis, {'scale':1./20., 'iterations':1000000})\n# a_0 = np.array([1, 1, 1])\n# s.sample(a_0)\n# print(s.theta)\n#\n# corner.corner(s.theta)\n","sub_path":"Setup/Deprecated/testing_grounds.py","file_name":"testing_grounds.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"240072522","text":"from ctypes import *\nfrom ctypes.wintypes import *\nimport logging\nimport time\nfrom .Enum import *\nfrom .Constants import *\n\nLOGGER = logging.getLogger(__name__)\n\nSIMCONNECT_OBJECT_ID = DWORD\n\n\ndef IsHR(hr, value):\n _hr = ctypes.HRESULT(hr)\n return ctypes.c_ulong(_hr.value).value == value\n\n\ndef millis():\n return int(round(time.time() * 1000))\n\n\nclass sData(dict):\n __getattr__ = dict.__getitem__\n __setattr__ = dict.__setitem__\n __delattr__ = dict.__delitem__\n\n\nclass Request:\n def __init__(\n self,\n _name,\n _time=None,\n _DATA_DEFINITION_ID=SIMCONNECT_DATA_DEFINITION_ID,\n _DATA_REQUEST_ID=SIMCONNECT_DATA_REQUEST_ID,\n _psc=None,\n ):\n self.DATA_DEFINITION_ID = _DATA_DEFINITION_ID\n self.DATA_REQUEST_ID = _DATA_REQUEST_ID\n self.definitions = []\n self.time = _time\n self.timeout = millis()\n self.name = _name\n self.outData = {}\n self.psc = _psc\n self.psc.out_data[self.DATA_REQUEST_ID] = None\n\n def add(self, name, deff):\n self.definitions.append(deff)\n self.outData[name] = len(self.outData)\n self.psc.AddToDataDefinition(\n self.psc.hSimConnect,\n self.DATA_DEFINITION_ID.value,\n deff[0],\n deff[1],\n SIMCONNECT_DATATYPE.SIMCONNECT_DATATYPE_FLOAT64,\n 0,\n SIMCONNECT_UNUSED,\n )\n\n\nclass SimConnect:\n\n # TODO: update callbackfunction to expand functions.\n def my_dispatch_proc(self, pData, cbData, pContext):\n dwID = pData.contents.dwID\n self.pS = None\n if dwID == SIMCONNECT_RECV_ID.SIMCONNECT_RECV_ID_EVENT:\n evt = cast(pData, POINTER(SIMCONNECT_RECV_EVENT))\n uEventID = evt.contents.uEventID\n if uEventID == self.EventID.EVENT_SIM_START:\n LOGGER.info(\"SIM START\")\n\n elif dwID == SIMCONNECT_RECV_ID.SIMCONNECT_RECV_ID_SIMOBJECT_DATA_BYTYPE:\n pObjData = cast(\n pData, POINTER(SIMCONNECT_RECV_SIMOBJECT_DATA_BYTYPE)\n ).contents\n dwRequestID = pObjData.dwRequestID\n for _request in self.Requests:\n if dwRequestID == _request.DATA_REQUEST_ID.value:\n self.out_data[_request.DATA_REQUEST_ID] = cast(\n pObjData.dwData, POINTER(c_double * 200)\n ).contents\n elif dwID == SIMCONNECT_RECV_ID.SIMCONNECT_RECV_ID_OPEN:\n LOGGER.info(\"SIM OPEN\")\n\n elif dwID == SIMCONNECT_RECV_ID.SIMCONNECT_RECV_ID_QUIT:\n self.quit = 1\n else:\n LOGGER.debug(\"Received: {}\".format(dwID))\n return\n\n def __init__(self, auto_connect=True, library_path=\"./SimConnect.dll\"):\n\n self.EventID = SIMCONNECT_CLIENT_EVENT_ID\n self.DATA_DEFINITION_ID = SIMCONNECT_DATA_DEFINITION_ID\n self.DATA_REQUEST_ID = SIMCONNECT_DATA_REQUEST_ID\n self.GROUP_ID = SIMCONNECT_NOTIFICATION_GROUP_ID\n self.INPUT_GROUP_ID = SIMCONNECT_INPUT_GROUP_ID\n self.CLIENT_DATA_ID = SIMCONNECT_CLIENT_DATA_ID\n self.CLIENT_DATA_DEFINITION_ID = SIMCONNECT_CLIENT_DATA_DEFINITION_ID\n\n self.Requests = []\n self.out_data = {}\n\n self.SimConnect = cdll.LoadLibrary(library_path)\n self.set_attributes()\n\n if auto_connect:\n self.connect()\n\n def set_attributes(self):\n # SIMCONNECTAPI SimConnect_Open(\n # \tHANDLE * phSimConnect,\n # \tLPCSTR szName,\n # \tHWND hWnd,\n # \tDWORD UserEventWin32,\n # \tHANDLE hEventHandle,\n # \tDWORD ConfigIndex)\n\n self.__Open = self.SimConnect.SimConnect_Open\n self.__Open.restype = HRESULT\n self.__Open.argtypes = [POINTER(HANDLE), LPCSTR, HWND, DWORD, HANDLE, DWORD]\n\n # SIMCONNECTAPI SimConnect_Close(\n # \tHANDLE hSimConnect);\n\n self.__Close = self.SimConnect.SimConnect_Close\n self.__Close.restype = HRESULT\n self.__Close.argtypes = [HANDLE]\n\n # SIMCONNECTAPI SimConnect_AddToDataDefinition(\n # \tHANDLE hSimConnect,\n # \tSIMCONNECT_DATA_DEFINITION_ID DefineID,\n # \tconst char * DatumName,\n # \tconst char * UnitsName,\n # \tSIMCONNECT_DATATYPE DatumType = SIMCONNECT_DATATYPE_FLOAT64,\n # \tfloat fEpsilon = 0,\n # \tDWORD DatumID = SIMCONNECT_UNUSED);\n\n self.AddToDataDefinition = self.SimConnect.SimConnect_AddToDataDefinition\n self.AddToDataDefinition.restype = HRESULT\n self.AddToDataDefinition.argtypes = [\n HANDLE,\n self.DATA_DEFINITION_ID,\n c_char_p,\n c_char_p,\n SIMCONNECT_DATATYPE,\n c_float,\n DWORD,\n ]\n\n # SIMCONNECTAPI SimConnect_SubscribeToSystemEvent(\n # \tHANDLE hSimConnect,\n # \tSIMCONNECT_CLIENT_EVENT_ID EventID,\n # \tconst char * SystemEventName);\n\n self.__SubscribeToSystemEvent = (\n self.SimConnect.SimConnect_SubscribeToSystemEvent\n )\n self.__SubscribeToSystemEvent.restype = HRESULT\n self.__SubscribeToSystemEvent.argtypes = [HANDLE, self.EventID, c_char_p]\n\n # SIMCONNECTAPI SimConnect_CallDispatch(\n # \tHANDLE hSimConnect,\n # \tDispatchProc pfcnDispatch,\n # \tvoid * pContext);\n\n DispatchProc = CFUNCTYPE(c_void_p, POINTER(SIMCONNECT_RECV), DWORD, c_void_p)\n\n self.__CallDispatch = self.SimConnect.SimConnect_CallDispatch\n self.__CallDispatch.restype = HRESULT\n self.__CallDispatch.argtypes = [HANDLE, DispatchProc, c_void_p]\n\n # SIMCONNECTAPI SimConnect_RequestDataOnSimObjectType(\n # \tHANDLE hSimConnect,\n # \tSIMCONNECT_DATA_REQUEST_ID RequestID,\n # \tSIMCONNECT_DATA_DEFINITION_ID DefineID,\n # \tDWORD dwRadiusMeters,\n # \tSIMCONNECT_SIMOBJECT_TYPE type);\n\n self.__RequestDataOnSimObjectType = (\n self.SimConnect.SimConnect_RequestDataOnSimObjectType\n )\n self.__RequestDataOnSimObjectType.restype = HRESULT\n self.__RequestDataOnSimObjectType.argtypes = [\n HANDLE,\n self.DATA_REQUEST_ID,\n self.DATA_DEFINITION_ID,\n DWORD,\n SIMCONNECT_SIMOBJECT_TYPE,\n ]\n\n # SIMCONNECTAPI SimConnect_SetDataOnSimObject(\n # \tHANDLE hSimConnect,\n # \tSIMCONNECT_DATA_DEFINITION_ID DefineID,\n # \tSIMCONNECT_OBJECT_ID ObjectID,\n # \tSIMCONNECT_DATA_SET_FLAG Flags,\n # \tDWORD ArrayCount,\n # \tDWORD cbUnitSize,\n # \tvoid * pDataSet);\n\n # self.SetDataOnSimObject = self.SimConnect.SimConnect_SetDataOnSimObject\n # self.SetDataOnSimObject.restype = HRESULT\n # self.SetDataOnSimObject.argtypes = [HANDLE, DATA_DEFINE_ID, SIMCONNECT_OBJECT_ID, SIMCONNECT_DATA_SET_FLAG, DWORD, DWORD, ibbuf]\n\n # SIMCONNECTAPI SimConnect_TransmitClientEvent(\n # \tHANDLE hSimConnect,\n # \tSIMCONNECT_OBJECT_ID ObjectID,\n # \tSIMCONNECT_CLIENT_EVENT_ID EventID,\n # \tDWORD dwData,\n # \tSIMCONNECT_NOTIFICATION_GROUP_ID GroupID,\n # \tSIMCONNECT_EVENT_FLAG Flags);\n\n self.__TransmitClientEvent = self.SimConnect.SimConnect_TransmitClientEvent\n self.__TransmitClientEvent.restype = HRESULT\n self.__TransmitClientEvent.argtypes = [\n HANDLE,\n SIMCONNECT_OBJECT_ID,\n self.EventID,\n DWORD,\n DWORD,\n DWORD,\n ]\n\n # SIMCONNECTAPI SimConnect_MapClientEventToSimEvent(\n # \tHANDLE hSimConnect,\n # \tSIMCONNECT_CLIENT_EVENT_ID EventID,\n # \tconst char * EventName = \"\");\n\n self.__MapClientEventToSimEvent = (\n self.SimConnect.SimConnect_MapClientEventToSimEvent\n )\n self.__MapClientEventToSimEvent.restype = HRESULT\n self.__MapClientEventToSimEvent.argtypes = [HANDLE, self.EventID, c_char_p]\n\n # SIMCONNECTAPI SimConnect_AddClientEventToNotificationGroup(\n # \tHANDLE hSimConnect,\n # \tSIMCONNECT_NOTIFICATION_GROUP_ID GroupID,\n # \tSIMCONNECT_CLIENT_EVENT_ID EventID,\n # \tBOOL bMaskable = FALSE);\n\n self.__AddClientEventToNotificationGroup = (\n self.SimConnect.SimConnect_AddClientEventToNotificationGroup\n )\n self.__AddClientEventToNotificationGroup.restype = HRESULT\n self.__AddClientEventToNotificationGroup.argtypes = [\n HANDLE,\n self.GROUP_ID,\n self.EventID,\n c_bool,\n ]\n\n # SIMCONNECTAPI SimConnect_SetSystemEventState(\n # HANDLE hSimConnect,\n # SIMCONNECT_CLIENT_EVENT_ID EventID\n # SIMCONNECT_STATE dwState);\n self.__SetSystemEventState = self.SimConnect.SimConnect_SetSystemEventState\n self.__SetSystemEventState.restype = HRESULT\n self.__SetSystemEventState.argtypes = [HANDLE, self.EventID, SIMCONNECT_STATE]\n\n # SIMCONNECTAPI SimConnect_AddClientEventToNotificationGroup(\n # HANDLE hSimConnect,\n # SIMCONNECT_NOTIFICATION_GROUP_ID GroupID\n # SIMCONNECT_CLIENT_EVENT_ID EventID\n # BOOL bMaskable = FALSE);\n self.__AddClientEventToNotificationGroup = (\n self.SimConnect.SimConnect_AddClientEventToNotificationGroup\n )\n self.__AddClientEventToNotificationGroup.restype = HRESULT\n self.__AddClientEventToNotificationGroup.argtypes = [\n HANDLE,\n self.GROUP_ID,\n self.EventID,\n c_bool,\n ]\n\n # SIMCONNECTAPI SimConnect_RemoveClientEvent(\n # HANDLE hSimConnect,\n # SIMCONNECT_NOTIFICATION_GROUP_ID GroupID\n # SIMCONNECT_CLIENT_EVENT_ID EventID);\n self.__RemoveClientEvent = self.SimConnect.SimConnect_RemoveClientEvent\n self.__RemoveClientEvent.restype = HRESULT\n self.__RemoveClientEvent.argtypes = [HANDLE, self.GROUP_ID, self.EventID]\n\n # SIMCONNECTAPI SimConnect_SetNotificationGroupPriority(\n # HANDLE hSimConnect,\n # SIMCONNECT_NOTIFICATION_GROUP_ID GroupID\n # DWORD uPriority);\n self.__SetNotificationGroupPriority = (\n self.SimConnect.SimConnect_SetNotificationGroupPriority\n )\n self.__SetNotificationGroupPriority.restype = HRESULT\n self.__SetNotificationGroupPriority.argtypes = [HANDLE, self.GROUP_ID, DWORD]\n\n # SIMCONNECTAPI SimConnect_ClearNotificationGroup(\n # HANDLE hSimConnect,\n # SIMCONNECT_NOTIFICATION_GROUP_ID GroupID);\n self.__ClearNotificationGroup = (\n self.SimConnect.SimConnect_ClearNotificationGroup\n )\n self.__ClearNotificationGroup.restype = HRESULT\n self.__ClearNotificationGroup.argtypes = [HANDLE, self.GROUP_ID]\n\n # SIMCONNECTAPI SimConnect_RequestNotificationGroup(\n # HANDLE hSimConnect,\n # SIMCONNECT_NOTIFICATION_GROUP_ID GroupID\n # DWORD dwReserved = 0\n # DWORD Flags = 0);\n self.__RequestNotificationGroup = (\n self.SimConnect.SimConnect_RequestNotificationGroup\n )\n self.__RequestNotificationGroup.restype = HRESULT\n self.__RequestNotificationGroup.argtypes = [HANDLE, self.GROUP_ID, DWORD, DWORD]\n\n # SIMCONNECTAPI SimConnect_ClearDataDefinition(\n # HANDLE hSimConnect,\n # SIMCONNECT_DATA_DEFINITION_ID DefineID);\n self.__ClearDataDefinition = self.SimConnect.SimConnect_ClearDataDefinition\n self.__ClearDataDefinition.restype = HRESULT\n self.__ClearDataDefinition.argtypes = [HANDLE, self.DATA_DEFINITION_ID]\n\n # SIMCONNECTAPI SimConnect_RequestDataOnSimObject(\n # HANDLE hSimConnect,\n # SIMCONNECT_DATA_REQUEST_ID RequestID\n # SIMCONNECT_DATA_DEFINITION_ID DefineID\n # SIMCONNECT_OBJECT_ID ObjectID\n # SIMCONNECT_PERIOD Period\n # SIMCONNECT_DATA_REQUEST_FLAG Flags = 0\n # DWORD origin = 0\n # DWORD interval = 0\n # DWORD limit = 0);\n self.__RequestDataOnSimObject = (\n self.SimConnect.SimConnect_RequestDataOnSimObject\n )\n self.__RequestDataOnSimObject.restype = HRESULT\n self.__RequestDataOnSimObject.argtypes = [\n HANDLE,\n self.DATA_REQUEST_ID,\n self.DATA_DEFINITION_ID,\n SIMCONNECT_OBJECT_ID,\n SIMCONNECT_PERIOD,\n SIMCONNECT_DATA_REQUEST_FLAG,\n DWORD,\n DWORD,\n DWORD,\n ]\n\n # SIMCONNECTAPI SimConnect_SetDataOnSimObject(\n # HANDLE hSimConnect,\n # SIMCONNECT_DATA_DEFINITION_ID DefineID\n # SIMCONNECT_OBJECT_ID ObjectID\n # SIMCONNECT_DATA_SET_FLAG Flags\n # DWORD ArrayCount\n # DWORD cbUnitSize\n # void * pDataSet);\n self.__SetDataOnSimObject = self.SimConnect.SimConnect_SetDataOnSimObject\n self.__SetDataOnSimObject.restype = HRESULT\n self.__SetDataOnSimObject.argtypes = [\n HANDLE,\n self.DATA_DEFINITION_ID,\n SIMCONNECT_OBJECT_ID,\n SIMCONNECT_DATA_SET_FLAG,\n DWORD,\n DWORD,\n c_void_p,\n ]\n\n # SIMCONNECTAPI SimConnect_MapInputEventToClientEvent(\n # HANDLE hSimConnect,\n # SIMCONNECT_INPUT_GROUP_ID GroupID\n # const char * szInputDefinition\n # SIMCONNECT_CLIENT_EVENT_ID DownEventID\n # DWORD DownValue = 0\n # SIMCONNECT_CLIENT_EVENT_ID UpEventID = (SIMCONNECT_CLIENT_EVENT_ID)SIMCONNECT_UNUSED\n # DWORD UpValue = 0\n # BOOL bMaskable = FALSE);\n self.__MapInputEventToClientEvent = (\n self.SimConnect.SimConnect_MapInputEventToClientEvent\n )\n self.__MapInputEventToClientEvent.restype = HRESULT\n self.__MapInputEventToClientEvent.argtypes = [\n HANDLE,\n self.INPUT_GROUP_ID,\n c_char_p,\n self.EventID,\n DWORD,\n self.EventID,\n DWORD,\n c_bool,\n ]\n\n # SIMCONNECTAPI SimConnect_SetInputGroupPriority(\n # HANDLE hSimConnect,\n # SIMCONNECT_INPUT_GROUP_ID GroupID\n # DWORD uPriority);\n self.__SetInputGroupPriority = self.SimConnect.SimConnect_SetInputGroupPriority\n self.__SetInputGroupPriority.restype = HRESULT\n self.__SetInputGroupPriority.argtypes = [HANDLE, self.INPUT_GROUP_ID, DWORD]\n\n # SIMCONNECTAPI SimConnect_RemoveInputEvent(\n # HANDLE hSimConnect,\n # SIMCONNECT_INPUT_GROUP_ID GroupID\n # const char * szInputDefinition);\n self.__RemoveInputEvent = self.SimConnect.SimConnect_RemoveInputEvent\n self.__RemoveInputEvent.restype = HRESULT\n self.__RemoveInputEvent.argtypes = [HANDLE, self.INPUT_GROUP_ID, c_char_p]\n\n # SIMCONNECTAPI SimConnect_ClearInputGroup(\n # HANDLE hSimConnect,\n # SIMCONNECT_INPUT_GROUP_ID GroupID);\n self.__ClearInputGroup = self.SimConnect.SimConnect_ClearInputGroup\n self.__ClearInputGroup.restype = HRESULT\n self.__ClearInputGroup.argtypes = [HANDLE, self.INPUT_GROUP_ID]\n\n # SIMCONNECTAPI SimConnect_SetInputGroupState(\n # HANDLE hSimConnect,\n # SIMCONNECT_INPUT_GROUP_ID GroupID\n # DWORD dwState);\n self.__SetInputGroupState = self.SimConnect.SimConnect_SetInputGroupState\n self.__SetInputGroupState.restype = HRESULT\n self.__SetInputGroupState.argtypes = [HANDLE, self.INPUT_GROUP_ID, DWORD]\n\n # SIMCONNECTAPI SimConnect_RequestReservedKey(\n # HANDLE hSimConnect,\n # SIMCONNECT_CLIENT_EVENT_ID EventID\n # const char * szKeyChoice1 = \"\"\n # const char * szKeyChoice2 = \"\"\n # const char * szKeyChoice3 = \"\");\n self.__RequestReservedKey = self.SimConnect.SimConnect_RequestReservedKey\n self.__RequestReservedKey.restype = HRESULT\n self.__RequestReservedKey.argtypes = [\n HANDLE,\n self.EventID,\n c_char_p,\n c_char_p,\n c_char_p,\n ]\n\n # SIMCONNECTAPI SimConnect_UnsubscribeFromSystemEvent(\n # HANDLE hSimConnect,\n # SIMCONNECT_CLIENT_EVENT_ID EventID);\n self.__UnsubscribeFromSystemEvent = (\n self.SimConnect.SimConnect_UnsubscribeFromSystemEvent\n )\n self.__UnsubscribeFromSystemEvent.restype = HRESULT\n self.__UnsubscribeFromSystemEvent.argtypes = [HANDLE, self.EventID]\n\n # SIMCONNECTAPI SimConnect_WeatherRequestInterpolatedObservation(\n # HANDLE hSimConnect,\n # SIMCONNECT_DATA_REQUEST_ID RequestID\n # float lat\n # float lon\n # float alt);\n self.__WeatherRequestInterpolatedObservation = (\n self.SimConnect.SimConnect_WeatherRequestInterpolatedObservation\n )\n self.__WeatherRequestInterpolatedObservation.restype = HRESULT\n self.__WeatherRequestInterpolatedObservation.argtypes = [\n HANDLE,\n self.DATA_REQUEST_ID,\n c_float,\n c_float,\n c_float,\n ]\n\n # SIMCONNECTAPI SimConnect_WeatherRequestObservationAtStation(\n # HANDLE hSimConnect,\n # SIMCONNECT_DATA_REQUEST_ID RequestID\n # const char * szICAO);\n self.__WeatherRequestObservationAtStation = (\n self.SimConnect.SimConnect_WeatherRequestObservationAtStation\n )\n self.__WeatherRequestObservationAtStation.restype = HRESULT\n self.__WeatherRequestObservationAtStation.argtypes = [\n HANDLE,\n self.DATA_REQUEST_ID,\n c_char_p,\n ]\n\n # SIMCONNECTAPI SimConnect_WeatherRequestObservationAtNearestStation(\n # HANDLE hSimConnect,\n # SIMCONNECT_DATA_REQUEST_ID RequestID\n # float lat\n # float lon);\n self.__WeatherRequestObservationAtNearestStation = (\n self.SimConnect.SimConnect_WeatherRequestObservationAtNearestStation\n )\n self.__WeatherRequestObservationAtNearestStation.restype = HRESULT\n self.__WeatherRequestObservationAtNearestStation.argtypes = [\n HANDLE,\n self.DATA_REQUEST_ID,\n c_float,\n c_float,\n ]\n\n # SIMCONNECTAPI SimConnect_WeatherCreateStation(\n # HANDLE hSimConnect,\n # SIMCONNECT_DATA_REQUEST_ID RequestID\n # const char * szICAO\n # const char * szName\n # float lat\n # float lon\n # float alt);\n self.__WeatherCreateStation = self.SimConnect.SimConnect_WeatherCreateStation\n self.__WeatherCreateStation.restype = HRESULT\n self.__WeatherCreateStation.argtypes = [\n HANDLE,\n self.DATA_REQUEST_ID,\n c_char_p,\n c_char_p,\n c_float,\n c_float,\n c_float,\n ]\n\n # SIMCONNECTAPI SimConnect_WeatherRemoveStation(\n # HANDLE hSimConnect,\n # SIMCONNECT_DATA_REQUEST_ID RequestID\n # const char * szICAO);\n self.__WeatherRemoveStation = self.SimConnect.SimConnect_WeatherRemoveStation\n self.__WeatherRemoveStation.restype = HRESULT\n self.__WeatherRemoveStation.argtypes = [HANDLE, self.DATA_REQUEST_ID, c_char_p]\n\n # SIMCONNECTAPI SimConnect_WeatherSetObservation(\n # HANDLE hSimConnect,\n # DWORD Seconds\n # const char * szMETAR);\n self.__WeatherSetObservation = self.SimConnect.SimConnect_WeatherSetObservation\n self.__WeatherSetObservation.restype = HRESULT\n self.__WeatherSetObservation.argtypes = [HANDLE, DWORD, c_char_p]\n\n # SIMCONNECTAPI SimConnect_WeatherSetModeServer(\n # HANDLE hSimConnect,\n # DWORD dwPort\n # DWORD dwSeconds);\n self.__WeatherSetModeServer = self.SimConnect.SimConnect_WeatherSetModeServer\n self.__WeatherSetModeServer.restype = HRESULT\n self.__WeatherSetModeServer.argtypes = [HANDLE, DWORD, DWORD]\n\n # SIMCONNECTAPI SimConnect_WeatherSetModeTheme(\n # HANDLE hSimConnect,\n # const char * szThemeName);\n self.__WeatherSetModeTheme = self.SimConnect.SimConnect_WeatherSetModeTheme\n self.__WeatherSetModeTheme.restype = HRESULT\n self.__WeatherSetModeTheme.argtypes = [HANDLE, c_char_p]\n\n # SIMCONNECTAPI SimConnect_WeatherSetModeGlobal(\n # HANDLE hSimConnect);\n self.__WeatherSetModeGlobal = self.SimConnect.SimConnect_WeatherSetModeGlobal\n self.__WeatherSetModeGlobal.restype = HRESULT\n self.__WeatherSetModeGlobal.argtypes = [HANDLE]\n\n # SIMCONNECTAPI SimConnect_WeatherSetModeCustom(\n # HANDLE hSimConnect);\n self.__WeatherSetModeCustom = self.SimConnect.SimConnect_WeatherSetModeCustom\n self.__WeatherSetModeCustom.restype = HRESULT\n self.__WeatherSetModeCustom.argtypes = [HANDLE]\n\n # SIMCONNECTAPI SimConnect_WeatherSetDynamicUpdateRate(\n # HANDLE hSimConnect,\n # DWORD dwRate);\n self.__WeatherSetDynamicUpdateRate = (\n self.SimConnect.SimConnect_WeatherSetDynamicUpdateRate\n )\n self.__WeatherSetDynamicUpdateRate.restype = HRESULT\n self.__WeatherSetDynamicUpdateRate.argtypes = [HANDLE, DWORD]\n\n # SIMCONNECTAPI SimConnect_WeatherRequestCloudState(\n # HANDLE hSimConnect,\n # SIMCONNECT_DATA_REQUEST_ID RequestID\n # float minLat\n # float minLon\n # float minAlt\n # float maxLat\n # float maxLon\n # float maxAlt\n # DWORD dwFlags = 0);\n self.__WeatherRequestCloudState = (\n self.SimConnect.SimConnect_WeatherRequestCloudState\n )\n self.__WeatherRequestCloudState.restype = HRESULT\n self.__WeatherRequestCloudState.argtypes = [\n HANDLE,\n self.DATA_REQUEST_ID,\n c_float,\n c_float,\n c_float,\n c_float,\n c_float,\n c_float,\n DWORD,\n ]\n\n # SIMCONNECTAPI SimConnect_WeatherCreateThermal(\n # HANDLE hSimConnect,\n # SIMCONNECT_DATA_REQUEST_ID RequestID\n # float lat\n # float lon\n # float alt\n # float radius\n # float height\n # float coreRate = 3.0f\n # float coreTurbulence = 0.05f\n # float sinkRate = 3.0f\n # float sinkTurbulence = 0.2f\n # float coreSize = 0.4f\n # float coreTransitionSize = 0.1f\n # float sinkLayerSize = 0.4f\n # float sinkTransitionSize = 0.1f);\n self.__WeatherCreateThermal = self.SimConnect.SimConnect_WeatherCreateThermal\n self.__WeatherCreateThermal.restype = HRESULT\n self.__WeatherCreateThermal.argtypes = [\n HANDLE,\n self.DATA_REQUEST_ID,\n c_float,\n c_float,\n c_float,\n c_float,\n c_float,\n c_float,\n c_float,\n c_float,\n c_float,\n c_float,\n c_float,\n c_float,\n c_float,\n ]\n\n # SIMCONNECTAPI SimConnect_WeatherRemoveThermal(\n # HANDLE hSimConnect,\n # SIMCONNECT_OBJECT_ID ObjectID);\n self.__WeatherRemoveThermal = self.SimConnect.SimConnect_WeatherRemoveThermal\n self.__WeatherRemoveThermal.restype = HRESULT\n self.__WeatherRemoveThermal.argtypes = [HANDLE, SIMCONNECT_OBJECT_ID]\n\n # SIMCONNECTAPI SimConnect_AICreateParkedATCAircraft(\n # HANDLE hSimConnect,\n # const char * szContainerTitle\n # const char * szTailNumber\n # const char * szAirportID\n # SIMCONNECT_DATA_REQUEST_ID RequestID);\n self.__AICreateParkedATCAircraft = (\n self.SimConnect.SimConnect_AICreateParkedATCAircraft\n )\n self.__AICreateParkedATCAircraft.restype = HRESULT\n self.__AICreateParkedATCAircraft.argtypes = [\n HANDLE,\n c_char_p,\n c_char_p,\n c_char_p,\n self.DATA_REQUEST_ID,\n ]\n\n # SIMCONNECTAPI SimConnect_AICreateEnrouteATCAircraft(\n # HANDLE hSimConnect,\n # const char * szContainerTitle\n # const char * szTailNumber\n # int iFlightNumber\n # const char * szFlightPlanPath\n # double dFlightPlanPosition\n # BOOL bTouchAndGo\n # SIMCONNECT_DATA_REQUEST_ID RequestID);\n self.__AICreateEnrouteATCAircraft = (\n self.SimConnect.SimConnect_AICreateEnrouteATCAircraft\n )\n self.__AICreateEnrouteATCAircraft.restype = HRESULT\n self.__AICreateEnrouteATCAircraft.argtypes = [\n HANDLE,\n c_char_p,\n c_char_p,\n c_int,\n c_char_p,\n c_double,\n c_bool,\n self.DATA_REQUEST_ID,\n ]\n\n # SIMCONNECTAPI SimConnect_AICreateNonATCAircraft(\n # HANDLE hSimConnect,\n # const char * szContainerTitle\n # const char * szTailNumber\n # SIMCONNECT_DATA_INITPOSITION InitPos\n # SIMCONNECT_DATA_REQUEST_ID RequestID);\n self.__AICreateNonATCAircraft = (\n self.SimConnect.SimConnect_AICreateNonATCAircraft\n )\n self.__AICreateNonATCAircraft.restype = HRESULT\n self.__AICreateNonATCAircraft.argtypes = [\n HANDLE,\n c_double,\n c_double,\n SIMCONNECT_DATA_INITPOSITION,\n self.DATA_REQUEST_ID,\n ]\n\n # SIMCONNECTAPI SimConnect_AICreateSimulatedObject(\n # HANDLE hSimConnect,\n # const char * szContainerTitle\n # SIMCONNECT_DATA_INITPOSITION InitPos\n # SIMCONNECT_DATA_REQUEST_ID RequestID);\n self.__AICreateSimulatedObject = (\n self.SimConnect.SimConnect_AICreateSimulatedObject\n )\n self.__AICreateSimulatedObject.restype = HRESULT\n self.__AICreateSimulatedObject.argtypes = [\n HANDLE,\n c_char_p,\n SIMCONNECT_DATA_INITPOSITION,\n self.DATA_REQUEST_ID,\n ]\n\n # SIMCONNECTAPI SimConnect_AIReleaseControl(\n # HANDLE hSimConnect,\n # SIMCONNECT_OBJECT_ID ObjectID\n # SIMCONNECT_DATA_REQUEST_ID RequestID);\n self.__AIReleaseControl = self.SimConnect.SimConnect_AIReleaseControl\n self.__AIReleaseControl.restype = HRESULT\n self.__AIReleaseControl.argtypes = [\n HANDLE,\n SIMCONNECT_OBJECT_ID,\n self.DATA_REQUEST_ID,\n ]\n\n # SIMCONNECTAPI SimConnect_AIRemoveObject(\n # HANDLE hSimConnect,\n # SIMCONNECT_OBJECT_ID ObjectID\n # SIMCONNECT_DATA_REQUEST_ID RequestID);\n self.__AIRemoveObject = self.SimConnect.SimConnect_AIRemoveObject\n self.__AIRemoveObject.restype = HRESULT\n self.__AIRemoveObject.argtypes = [\n HANDLE,\n SIMCONNECT_OBJECT_ID,\n self.DATA_REQUEST_ID,\n ]\n\n # SIMCONNECTAPI SimConnect_AISetAircraftFlightPlan(\n # HANDLE hSimConnect,\n # SIMCONNECT_OBJECT_ID ObjectID\n # const char * szFlightPlanPath\n # SIMCONNECT_DATA_REQUEST_ID RequestID);\n self.__AISetAircraftFlightPlan = (\n self.SimConnect.SimConnect_AISetAircraftFlightPlan\n )\n self.__AISetAircraftFlightPlan.restype = HRESULT\n self.__AISetAircraftFlightPlan.argtypes = [\n HANDLE,\n SIMCONNECT_OBJECT_ID,\n c_char_p,\n self.DATA_REQUEST_ID,\n ]\n\n # SIMCONNECTAPI SimConnect_ExecuteMissionAction(\n # HANDLE hSimConnect,\n # const GUID guidInstanceId);\n self.__ExecuteMissionAction = self.SimConnect.SimConnect_ExecuteMissionAction\n self.__ExecuteMissionAction.restype = HRESULT\n self.__ExecuteMissionAction.argtypes = []\n\n # SIMCONNECTAPI SimConnect_CompleteCustomMissionAction(\n # HANDLE hSimConnect,\n # const GUID guidInstanceId);\n self.__CompleteCustomMissionAction = (\n self.SimConnect.SimConnect_CompleteCustomMissionAction\n )\n self.__CompleteCustomMissionAction.restype = HRESULT\n self.__CompleteCustomMissionAction.argtypes = []\n\n # SIMCONNECTAPI SimConnect_RetrieveString(\n # SIMCONNECT_RECV * pData,\n # DWORD cbData\n # void * pStringV\n # char ** pszString\n # DWORD * pcbString);\n self.__RetrieveString = self.SimConnect.SimConnect_RetrieveString\n self.__RetrieveString.restype = HRESULT\n self.__RetrieveString.argtypes = []\n\n # SIMCONNECTAPI SimConnect_GetLastSentPacketID(\n # HANDLE hSimConnect,\n # DWORD * pdwError);\n self.__GetLastSentPacketID = self.SimConnect.SimConnect_GetLastSentPacketID\n self.__GetLastSentPacketID.restype = HRESULT\n self.__GetLastSentPacketID.argtypes = [HANDLE, DWORD]\n\n # SIMCONNECTAPI SimConnect_GetNextDispatch(\n # HANDLE hSimConnect,\n # SIMCONNECT_RECV ** ppData\n # DWORD * pcbData);\n self.__GetNextDispatch = self.SimConnect.SimConnect_GetNextDispatch\n self.__GetNextDispatch.restype = HRESULT\n self.__GetNextDispatch.argtypes = []\n\n # SIMCONNECTAPI SimConnect_RequestResponseTimes(\n # HANDLE hSimConnect,\n # DWORD nCount\n # float * fElapsedSeconds);\n self.__RequestResponseTimes = self.SimConnect.SimConnect_RequestResponseTimes\n self.__RequestResponseTimes.restype = HRESULT\n self.__RequestResponseTimes.argtypes = [HANDLE, DWORD, c_float]\n\n # SIMCONNECTAPI SimConnect_InsertString(\n # char * pDest,\n # DWORD cbDest\n # void ** ppEnd\n # DWORD * pcbStringV\n # const char * pSource);\n self.__InsertString = self.SimConnect.SimConnect_InsertString\n self.__InsertString.restype = HRESULT\n self.__InsertString.argtypes = []\n\n # SIMCONNECTAPI SimConnect_CameraSetRelative6DOF(\n # HANDLE hSimConnect,\n # float fDeltaX\n # float fDeltaY\n # float fDeltaZ\n # float fPitchDeg\n # float fBankDeg\n # float fHeadingDeg);\n self.__CameraSetRelative6DOF = self.SimConnect.SimConnect_CameraSetRelative6DOF\n self.__CameraSetRelative6DOF.restype = HRESULT\n self.__CameraSetRelative6DOF.argtypes = []\n\n # SIMCONNECTAPI SimConnect_MenuAddItem(\n # HANDLE hSimConnect,\n # const char * szMenuItem\n # SIMCONNECT_CLIENT_EVENT_ID MenuEventID\n # DWORD dwData);\n self.__MenuAddItem = self.SimConnect.SimConnect_MenuAddItem\n self.__MenuAddItem.restype = HRESULT\n self.__MenuAddItem.argtypes = []\n\n # SIMCONNECTAPI SimConnect_MenuDeleteItem(\n # HANDLE hSimConnect,\n # SIMCONNECT_CLIENT_EVENT_ID MenuEventID);\n self.__MenuDeleteItem = self.SimConnect.SimConnect_MenuDeleteItem\n self.__MenuDeleteItem.restype = HRESULT\n self.__MenuDeleteItem.argtypes = []\n\n # SIMCONNECTAPI SimConnect_MenuAddSubItem(\n # HANDLE hSimConnect,\n # SIMCONNECT_CLIENT_EVENT_ID MenuEventID\n # const char * szMenuItem\n # SIMCONNECT_CLIENT_EVENT_ID SubMenuEventID\n # DWORD dwData);\n self.__MenuAddSubItem = self.SimConnect.SimConnect_MenuAddSubItem\n self.__MenuAddSubItem.restype = HRESULT\n self.__MenuAddSubItem.argtypes = []\n\n # SIMCONNECTAPI SimConnect_MenuDeleteSubItem(\n # HANDLE hSimConnect,\n # SIMCONNECT_CLIENT_EVENT_ID MenuEventID\n # const SIMCONNECT_CLIENT_EVENT_ID SubMenuEventID);\n self.__MenuDeleteSubItem = self.SimConnect.SimConnect_MenuDeleteSubItem\n self.__MenuDeleteSubItem.restype = HRESULT\n self.__MenuDeleteSubItem.argtypes = []\n\n # SIMCONNECTAPI SimConnect_RequestSystemState(\n # HANDLE hSimConnect,\n # SIMCONNECT_DATA_REQUEST_ID RequestID\n # const char * szState);\n self.__RequestSystemState = self.SimConnect.SimConnect_RequestSystemState\n self.__RequestSystemState.restype = HRESULT\n self.__RequestSystemState.argtypes = []\n\n # SIMCONNECTAPI SimConnect_SetSystemState(\n # HANDLE hSimConnect,\n # const char * szState\n # DWORD dwInteger\n # float fFloat\n # const char * szString);\n self.__SetSystemState = self.SimConnect.SimConnect_SetSystemState\n self.__SetSystemState.restype = HRESULT\n self.__SetSystemState.argtypes = []\n\n # SIMCONNECTAPI SimConnect_MapClientDataNameToID(\n # HANDLE hSimConnect,\n # const char * szClientDataName\n # SIMCONNECT_CLIENT_DATA_ID ClientDataID);\n self.__MapClientDataNameToID = self.SimConnect.SimConnect_MapClientDataNameToID\n self.__MapClientDataNameToID.restype = HRESULT\n self.__MapClientDataNameToID.argtypes = []\n\n # SIMCONNECTAPI SimConnect_CreateClientData(\n # HANDLE hSimConnect,\n # SIMCONNECT_CLIENT_DATA_ID ClientDataID\n # DWORD dwSize\n # SIMCONNECT_CREATE_CLIENT_DATA_FLAG Flags);\n self.__CreateClientData = self.SimConnect.SimConnect_CreateClientData\n self.__CreateClientData.restype = HRESULT\n self.__CreateClientData.argtypes = [\n HANDLE,\n self.CLIENT_DATA_ID,\n DWORD,\n SIMCONNECT_CREATE_CLIENT_DATA_FLAG,\n ]\n\n # SIMCONNECTAPI SimConnect_AddToClientDataDefinition(\n # HANDLE hSimConnect,\n # SIMCONNECT_CLIENT_DATA_DEFINITION_ID DefineID\n # DWORD dwOffset\n # DWORD dwSizeOrType\n # float fEpsilon = 0\n # DWORD DatumID = SIMCONNECT_UNUSED);\n self.__AddToClientDataDefinition = (\n self.SimConnect.SimConnect_AddToClientDataDefinition\n )\n self.__AddToClientDataDefinition.restype = HRESULT\n self.__AddToClientDataDefinition.argtypes = [\n HANDLE,\n self.CLIENT_DATA_DEFINITION_ID,\n DWORD,\n DWORD,\n c_float,\n DWORD,\n ]\n\n # SIMCONNECTAPI SimConnect_ClearClientDataDefinition(\n # HANDLE hSimConnect,\n # SIMCONNECT_CLIENT_DATA_DEFINITION_ID DefineID);\n self.__ClearClientDataDefinition = (\n self.SimConnect.SimConnect_ClearClientDataDefinition\n )\n self.__ClearClientDataDefinition.restype = HRESULT\n self.__ClearClientDataDefinition.argtypes = [\n HANDLE,\n self.CLIENT_DATA_DEFINITION_ID,\n ]\n\n # SIMCONNECTAPI SimConnect_RequestClientData(\n # HANDLE hSimConnect,\n # SIMCONNECT_CLIENT_DATA_ID ClientDataID\n # SIMCONNECT_DATA_REQUEST_ID RequestID\n # SIMCONNECT_CLIENT_DATA_DEFINITION_ID DefineID\n # SIMCONNECT_CLIENT_DATA_PERIOD Period = SIMCONNECT_CLIENT_DATA_PERIOD_ONCE\n # SIMCONNECT_CLIENT_DATA_REQUEST_FLAG Flags = 0\n # DWORD origin = 0\n # DWORD interval = 0\n # DWORD limit = 0);\n self.__RequestClientData = self.SimConnect.SimConnect_RequestClientData\n self.__RequestClientData.restype = HRESULT\n self.__RequestClientData.argtypes = [\n HANDLE,\n self.CLIENT_DATA_ID,\n self.DATA_REQUEST_ID,\n self.CLIENT_DATA_DEFINITION_ID,\n SIMCONNECT_CLIENT_DATA_PERIOD,\n SIMCONNECT_CLIENT_DATA_REQUEST_FLAG,\n DWORD,\n DWORD,\n DWORD,\n ]\n\n # SIMCONNECTAPI SimConnect_SetClientData(\n # HANDLE hSimConnect,\n # SIMCONNECT_CLIENT_DATA_ID ClientDataID\n # SIMCONNECT_CLIENT_DATA_DEFINITION_ID DefineID\n # SIMCONNECT_CLIENT_DATA_SET_FLAG Flags\n # DWORD dwReserved\n # DWORD cbUnitSize\n # void * pDataSet);\n self.__SetClientData = self.SimConnect.SimConnect_SetClientData\n self.__SetClientData.restype = HRESULT\n self.__SetClientData.argtypes = [\n HANDLE,\n self.CLIENT_DATA_ID,\n self.CLIENT_DATA_DEFINITION_ID,\n SIMCONNECT_CLIENT_DATA_SET_FLAG,\n DWORD,\n DWORD,\n c_void_p,\n ]\n\n # SIMCONNECTAPI SimConnect_FlightLoad(\n # HANDLE hSimConnect,\n # const char * szFileName);\n self.__FlightLoad = self.SimConnect.SimConnect_FlightLoad\n self.__FlightLoad.restype = HRESULT\n self.__FlightLoad.argtypes = [HANDLE, c_char_p]\n\n # SIMCONNECTAPI SimConnect_FlightSave(\n # HANDLE hSimConnect,\n # const char * szFileName\n # const char * szTitle\n # const char * szDescription\n # DWORD Flags);\n self.__FlightSave = self.SimConnect.SimConnect_FlightSave\n self.__FlightSave.restype = HRESULT\n self.__FlightSave.argtypes = [HANDLE, c_char_p, c_char_p, c_char_p, DWORD]\n\n # SIMCONNECTAPI SimConnect_FlightPlanLoad(\n # HANDLE hSimConnect,\n # const char * szFileName);\n self.__FlightPlanLoad = self.SimConnect.SimConnect_FlightPlanLoad\n self.__FlightPlanLoad.restype = HRESULT\n self.__FlightPlanLoad.argtypes = [HANDLE, c_char_p]\n\n # SIMCONNECTAPI SimConnect_Text(\n # HANDLE hSimConnect,\n # SIMCONNECT_TEXT_TYPE type\n # float fTimeSeconds\n # SIMCONNECT_CLIENT_EVENT_ID EventID\n # DWORD cbUnitSize\n # void * pDataSet);\n self.__Text = self.SimConnect.SimConnect_Text\n self.__Text.restype = HRESULT\n self.__Text.argtypes = [\n HANDLE,\n SIMCONNECT_TEXT_TYPE,\n c_float,\n self.EventID,\n DWORD,\n c_void_p,\n ]\n\n # SIMCONNECTAPI SimConnect_SubscribeToFacilities(\n # HANDLE hSimConnect,\n # SIMCONNECT_FACILITY_LIST_TYPE type\n # SIMCONNECT_DATA_REQUEST_ID RequestID);\n self.__SubscribeToFacilities = self.SimConnect.SimConnect_SubscribeToFacilities\n self.__SubscribeToFacilities.restype = HRESULT\n self.__SubscribeToFacilities.argtypes = [\n HANDLE,\n SIMCONNECT_FACILITY_LIST_TYPE,\n self.DATA_REQUEST_ID,\n ]\n\n # SIMCONNECTAPI SimConnect_UnsubscribeToFacilities(\n # HANDLE hSimConnect,\n # SIMCONNECT_FACILITY_LIST_TYPE type);\n self.__UnsubscribeToFacilities = (\n self.SimConnect.SimConnect_UnsubscribeToFacilities\n )\n self.__UnsubscribeToFacilities.restype = HRESULT\n self.__UnsubscribeToFacilities.argtypes = [\n HANDLE,\n SIMCONNECT_FACILITY_LIST_TYPE,\n ]\n\n # SIMCONNECTAPI SimConnect_RequestFacilitiesList(\n # HANDLE hSimConnect,\n # SIMCONNECT_FACILITY_LIST_TYPE type\n # SIMCONNECT_DATA_REQUEST_ID RequestID);\n self.____RequestFacilitiesList = (\n self.SimConnect.SimConnect_RequestFacilitiesList\n )\n self.____RequestFacilitiesList.restype = HRESULT\n self.____RequestFacilitiesList.argtypes = [\n HANDLE,\n SIMCONNECT_FACILITY_LIST_TYPE,\n self.DATA_REQUEST_ID,\n ]\n\n self.hSimConnect = HANDLE()\n self.quit = 0\n self.my_dispatch_proc_rd = DispatchProc(self.my_dispatch_proc)\n # self.haveData = False\n\n def connect(self):\n try:\n err = self.__Open(\n byref(self.hSimConnect), LPCSTR(b\"Request Data\"), None, 0, 0, 0\n )\n if IsHR(err, 0):\n LOGGER.debug(\"Connected to Flight Simulator!\")\n # Set up the data definition, but do not yet do anything with itd\n # Request an event when the simulation starts\n self.__SubscribeToSystemEvent(\n self.hSimConnect, self.EventID.EVENT_SIM_START, b\"SimStart\"\n )\n except OSError:\n LOGGER.debug(\"Did not find Flight Simulator running.\")\n exit(0)\n\n def run(self):\n for _request in self.Requests:\n self.out_data[_request.DATA_REQUEST_ID] = None\n if _request.time is not None:\n if (_request.timeout + _request.time) < millis():\n self.request_data(_request)\n _request.timeout = millis()\n\n self.__CallDispatch(self.hSimConnect, self.my_dispatch_proc_rd, None)\n\n def exit(self):\n self.__Close(self.hSimConnect)\n\n def map_to_sim_event(self, name):\n for m in self.EventID:\n if name.decode() == m.name:\n LOGGER.debug(\"Already have event: {}\".format(m))\n return m\n\n names = [m.name for m in self.EventID] + [name.decode()]\n self.EventID = Enum(self.EventID.__name__, names)\n evnt = list(self.EventID)[-1]\n err = self.__MapClientEventToSimEvent(self.hSimConnect, evnt.value, name)\n if IsHR(err, 0):\n return evnt\n else:\n LOGGER.error(\"Error: MapToSimEvent\")\n return None\n\n def add_to_notification_group(self, group, evnt, bMaskable=False):\n self.__AddClientEventToNotificationGroup(\n self.hSimConnect, group, evnt, bMaskable\n )\n\n def request_data(self, _Request):\n self.out_data[_Request.DATA_REQUEST_ID] = None\n self.__RequestDataOnSimObjectType(\n self.hSimConnect,\n _Request.DATA_REQUEST_ID.value,\n _Request.DATA_DEFINITION_ID.value,\n 0,\n SIMCONNECT_SIMOBJECT_TYPE.SIMCONNECT_SIMOBJECT_TYPE_USER,\n )\n\n def get_data(self, _Request, _format=False):\n LOGGER.debug(\"try to get data\")\n\n if self.out_data[_Request.DATA_REQUEST_ID] is None:\n LOGGER.debug(\"no data found\")\n return None\n\n if _format:\n map = {}\n else:\n map = sData\n\n for od in _Request.outData:\n data = self.out_data[_Request.DATA_REQUEST_ID][_Request.outData[od]]\n LOGGER.debug(\"got key {}, value {}\".format(od, data))\n if _format:\n map[od] = data\n else:\n setattr(map, od, data)\n\n return map\n\n def send_data(self, evnt, data=DWORD(0)):\n err = self.__TransmitClientEvent(\n self.hSimConnect,\n SIMCONNECT_OBJECT_ID_USER,\n evnt.value,\n data,\n SIMCONNECT_GROUP_PRIORITY_HIGHEST,\n DWORD(16),\n )\n if IsHR(err, 0):\n LOGGER.debug(\"Event Sent\")\n return True\n else:\n return False\n\n def new_request(self, time=None):\n name = \"Request\" + str(len(self.Requests))\n names = [m.name for m in self.DATA_DEFINITION_ID] + [name]\n self.DATA_DEFINITION_ID = Enum(self.DATA_DEFINITION_ID.__name__, names)\n DEFINITION_ID = list(self.DATA_DEFINITION_ID)[-1]\n\n names = [m.name for m in self.DATA_REQUEST_ID] + [name]\n self.DATA_REQUEST_ID = Enum(self.DATA_REQUEST_ID.__name__, names)\n REQUEST_ID = list(self.DATA_REQUEST_ID)[-1]\n\n _Request = Request(\n _DATA_DEFINITION_ID=DEFINITION_ID,\n _DATA_REQUEST_ID=REQUEST_ID,\n _time=time,\n _name=name,\n _psc=self,\n )\n self.Requests.append(_Request)\n return _Request\n","sub_path":"SimConnect/SimConnect.py","file_name":"SimConnect.py","file_ext":"py","file_size_in_byte":43537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"594356714","text":"#!/usr/bin/env python2\n\nimport random\nfrom sys import argv\n\nif __name__ == '__main__':\n\tcols = int(argv[1])\n\tout = open('./data.csv', 'w')\n\tfor i in range(60000):\n\t\tfor i in range(cols-1):\n\t\t\tout.write(str(random.random()) + \",\")\n\t\tout.write(str(random.random()) + '\\n')\n\tout.close()\n","sub_path":"docker/host/gen_data.py","file_name":"gen_data.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"209516689","text":"import pandas as pd\nimport numpy as np\nimport dateandtime\n\ndef preprocess(data):\n data['MTS'] = data.apply((lambda x: pd.Series({'MTS':dateandtime.convert_dates(x['MTS'])})), axis = 1)\n date = [str(x) for x in data['MTS']]\n date_new = [x.split() for x in date]\n data['date'] = pd.Series([x[0] for x in date_new])\n data['time'] = pd.Series([x[1] for x in date_new])\n time_new = [x.split(':') for x in data['time']]\n data['hours'] = pd.Series([x[0] for x in time_new])\n data['minutes'] = pd.Series([x[1] for x in time_new])\n data['seconds'] = pd.Series([x[2] for x in time_new])\n data['hour_minute'] = pd.Series([(x[0] + ':' + x[1]) for x in time_new])\n return data\n\n","sub_path":"new_process.py","file_name":"new_process.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"284047233","text":"\n'''\nDefine custom losses here and add them to the global_loss_list dict (important!)\nKeep this file to functions with a few lines adding loss components\nDo the actual implementation of the loss components in Loss_implementations.py\n\n'''\nglobal_loss_list = {}\n\nimport tensorflow as tf\n\n##### prototype for merging loss function\nfrom betaLosses import min_beta_loss_rowsplits , min_beta_loss_truth , pre_training_loss, null_loss\nglobal_loss_list['min_beta_loss_rowsplits'] = min_beta_loss_rowsplits\nglobal_loss_list['min_beta_loss_truth'] = min_beta_loss_truth\nglobal_loss_list['pre_training_loss'] = pre_training_loss\nglobal_loss_list['null_loss'] = null_loss\n\n\n\n\n######\n\ndef fraction_loss_with_penalties(truth, pred):\n from Loss_implementations import frac_loss, good_frac_sum_loss, good_frac_range_loss\n fracloss = frac_loss(truth, pred) \n fracsumloss = good_frac_sum_loss(truth,pred) \n fracrangeloss = good_frac_range_loss(truth, pred)\n \n loss = fracloss + fracsumloss + 100.* fracrangeloss\n \n loss = tf.Print(loss, [tf.reduce_mean(loss), \n tf.reduce_mean(fracloss), \n tf.reduce_mean(fracsumloss), \n tf.reduce_mean(fracrangeloss)],\n 'loss, fracloss, fracsumloss, fracrangeloss ')\n return loss\nglobal_loss_list['fraction_loss_with_penalties']=fraction_loss_with_penalties\n\ndef fraction_loss_with_penalties_sort_pred(truth, pred):\n from Loss_implementations import frac_loss_sort_pred, good_frac_sum_loss, good_frac_range_loss\n fraclosssortpred = frac_loss_sort_pred(truth, pred) \n fracsumloss = good_frac_sum_loss(truth,pred) \n fracrangeloss = good_frac_range_loss(truth, pred)\n \n loss = fraclosssortpred + fracsumloss + 100.* fracrangeloss\n \n loss = tf.Print(loss, [tf.reduce_mean(loss), \n tf.reduce_mean(fraclosssortpred), \n tf.reduce_mean(fracsumloss), \n tf.reduce_mean(fracrangeloss)],\n 'loss, fracloss (sort pred), fracsumloss, fracrangeloss ')\n return loss\nglobal_loss_list['fraction_loss_with_penalties_sort_pred']=fraction_loss_with_penalties_sort_pred\n\n\n\n\n\n\n####### for the 'pre'clustering tests\n","sub_path":"modules/Losses.py","file_name":"Losses.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"111605604","text":"from gpiozero import MotionSensor\nimport os\nimport time\nimport tweepy\npir=MotionSensor(4)\ntime.sleep(4)\nif pir.motion_detected:\n print(\"motion detected\")\nelse:\n print(\"no detection of motion\")\n \na=0\nwhile a<=2:\n img=\"/home/cs2017a106/im.jpg\"\n cmd=\"fswebcam -r 1280x720 -S 3 --jpeg 100 \"+img\n os.system(cmd)\n print(\"pic taken\")\n time.sleep(5)\n a+=1\n\ndef get_api(cfg):\n auth = tweepy.OAuthHandler(cfg['consumer_key'], cfg['consumer_secret'])\n auth.set_access_token(cfg['access_token'], cfg['access_token_secret'])\n return tweepy.API(auth)\n\ndef main():\n # Fill in the values noted in previous step here\n cfg = { \n \"consumer_key\" : \"JS7bbVBAo0j5ZDDMq5nJMVJV1\",\n \"consumer_secret\" : \"7bTkI1c06sf8j2uDtRehCAkSQLuhUWACCLuG1FgKgrmImQODxM\",\n \"access_token\" : \"967252071517970433-IsKl2YTxcjtUhE8LkFpXRXzcF6SNl3B\",\n \"access_token_secret\" : \"F3BAuVQfciu7EaSncW7T68WLXSIVROM78Y4G8lsVKg7xK\" \n }\n api = get_api(cfg)\n tweet = \"Nice!!! one\"\n status = api.update_status(status=tweet)\n # Yes, tweet is called 'status' rather confusing\nif __name__ == \"__main__\":\n main()\n print(\"success\")\n","sub_path":"md.py","file_name":"md.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"37584762","text":"# metaDatsetGen imports\nfrom core.config import cfg, createFilenameID\n\n# misc imports\nfrom utils.base import *\nimport pprint\npp = pprint.PrettyPrinter(indent=4)\nimport pickle,cv2,uuid,os,sys\nimport os.path as osp\nimport numpy as np\nfrom numpy import transpose as npt\n\ndef load_mixture_set_single(setID,repetition,size):\n pklName = createFilenameID(setID,str(repetition),str(size)) + \".pkl\"\n # write pickle file of the roidb\n if osp.exists(pklName) is True:\n fid = open(pklName,\"rb\")\n loaded = pickle.load(fid)\n fid.close()\n\n trainData = loaded['train']\n print_each_size(trainData[0])\n testData = loaded['test']\n print_each_size(testData[0])\n else:\n raise ValueError(\"{} does not exists\".format(pklName))\n return trainData,testData\n\n \ndef load_mixture_set(setID,repetition,final_size):\n\n roidbTr = {}\n roidbTe = {}\n l_roidbTr = {}\n l_roidbTe = {}\n annoCountsTr = {}\n annoCountsTe = {}\n\n datasetSizes = cfg.MIXED_DATASET_SIZES\n if final_size not in datasetSizes:\n print(\"invalid dataset size\")\n print(\"valid option sizes include:\")\n print(datasetSizes)\n raise ValueError(\"size {} is not in cfg.MIXED_DATASET_SIZES\".format(final_size))\n sizeIndex = datasetSizes.index(final_size)\n \n for size in datasetSizes[:sizeIndex+1]:\n print(size)\n # create a file for each dataset size\n pklName = createFilenameID(setID,str(repetition),str(size)) + \".pkl\"\n # write pickle file of the roidb\n if osp.exists(pklName) is True:\n fid = open(pklName,\"rb\")\n loaded = pickle.load(fid)\n fid.close()\n\n train = loaded['train']\n test = loaded['test']\n print(pklName)\n # todo: what depends on the old version?\n # old version: returns only one list of sizes from \"final_size\"\n annoCountsTr[size] = train[1]\n annoCountsTe[size] = test[1]\n # if size == final_size: # only save the last count\n # annoCountsTr = train[1]\n # annoCountsTe = test[1]\n for dsID,roidb in train[0].items():\n print(dsID,type(roidb),len(roidb))\n l_roidb = list(roidb)\n if dsID not in roidbTr.keys():\n # sometimes read in as tuple\n # cause unknown\n roidbTr[dsID] = list(l_roidb)\n if size < 5000: print(\"less than 5k @ {}\".format(size))\n if size < 5000: l_roidbTr[dsID] = list(l_roidb)\n else:\n print(\"(a)@ {} roidbTr v.s. l_roidbTr: {} v.s. {}\".format(dsID,len(roidbTr[dsID]),len(l_roidbTr[dsID])))\n roidbTr[dsID].extend(l_roidb)\n print(\"(b)@ {} roidbTr v.s. l_roidbTr: {} v.s. {}\".format(dsID,len(roidbTr[dsID]),len(l_roidbTr[dsID])))\n if size < 5000: print(\"less than 5k @ {}\".format(size))\n if size < 5000: l_roidbTr[dsID].extend(l_roidb)\n print(\"(c)@ {} roidbTr v.s. l_roidbTr: {} v.s. {}\".format(dsID,len(roidbTr[dsID]),len(l_roidbTr[dsID])))\n\n for dsID,roidb in test[0].items():\n print(dsID,type(roidb),len(roidb))\n l_roidb = list(roidb)\n if dsID not in roidbTe.keys():\n roidbTe[dsID] = list(l_roidb)\n if size < 5000: l_roidbTe[dsID] = list(l_roidb)\n else:\n roidbTe[dsID].extend(l_roidb)\n if size < 5000: l_roidbTe[dsID].extend(l_roidb)\n else:\n raise ValueError(\"{} does not exists\".format(pklName))\n # KNOWN ISSUE: the annoCounts* ordering is incorrect.\n # see ymlConfig/default_dataset_index.yml v.s. config DATASET_ORDER \n for ds in roidbTr.keys():\n print(\"@ {} roidbTr v.s. l_roidbTr: {} v.s. {}\".format(ds,len(roidbTr[ds]),len(l_roidbTr[ds])))\n for ds in roidbTe.keys():\n print(\"@ {} roidbTe v.s. l_roidbTe: {} v.s. {}\".format(ds,len(roidbTe[ds]),len(l_roidbTe[ds])))\n return {\"train\":[roidbTr,annoCountsTr,l_roidbTr],\"test\":[roidbTe,annoCountsTe,l_roidbTe]}\n\ndef save_mixture_set_single(roidb,annoCount,setID,repetition,size):\n pklName = createFilenameID(setID,str(repetition),str(size)) + \".pkl\"\n saveInfo = {\"allRoidb\":roidb,\"annoCounts\":annoCount}\n with open(pklName,\"wb\") as f:\n pickle.dump(saveInfo,f)\n \nclass PreviousCounts():\n\n def __init__(self,size,initVal):\n self._prevCounts = [initVal for _ in range(size)]\n\n def __getitem__(self,idx):\n return self._prevCounts[idx]\n\n def __str__(self):\n return str(self._prevCounts)\n\n def update(self,roidbs):\n for idx,roidb in enumerate(roidbs):\n if roidb is None: continue\n self._prevCounts[idx] = len(roidb)\n\n def zero(self):\n self.setAllTo(0)\n\n def setAllTo(self,val):\n for idx in range(8):\n self._prevCounts[idx] = val\n\n\n","sub_path":"lib/utils/mixture_utils.py","file_name":"mixture_utils.py","file_ext":"py","file_size_in_byte":5039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"135875877","text":"import json\n# import logging\n# import sys\nfrom .models import *\n\n\ndef read_json_file():\n movies_data = []\n with open('imdb.json') as f:\n movies_data = json.loads(f.read())\n\n for data in movies_data:\n j = []\n for i in data['genre']:\n j.append(str(i))\n data['genre'] = j\n\n return movies_data\n\n\ndef store_movie_in_db():\n \"\"\"\n Function to store question in database\n :return:\n \"\"\"\n logging.info(\"Inside \" + str(__name__))\n try:\n movies_data = read_json_file()\n # m = Movies()\n for movie_data in movies_data:\n m = Movies()\n m.m_title = movie_data['name']\n m.m_director = movie_data['director']\n m.m_genre = movie_data['genre']\n m.m_imdb_score = movie_data['imdb_score']\n m.m_99popularity = movie_data['99popularity']\n m.save()\n return \"DONE\"\n except Exception:\n # exc_type, exc_obj, tb = sys.exc_info()\n # logging.critical(\"EXCEPTION - \" + str(e) + \" in \" + str(__name__) + \" on line number: \" + str(tb.tb_lineno))\n return None\n\n\n# if __name__ == '__main__':\n# store_question_in_db()\n","sub_path":"movies/add_movies_data_json_to_db.py","file_name":"add_movies_data_json_to_db.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"20267702","text":"import os\nimport unittest\nfrom aibolit.patterns.method_siblings.method_siblings import MethodSiblings\nfrom pathlib import Path\n\n\nclass TestMethodSiblingsSiblings(unittest.TestCase):\n dir_path = Path(os.path.realpath(__file__)).parent\n\n @unittest.skip(\"Not implemented\")\n def test_find_simple_method_siblings(self):\n self.assertEqual(\n [2], MethodSiblings(Path(self.dir_path, 'SimpleMethodSiblings.java')).value()\n )\n\n @unittest.skip(\"Not implemented\")\n def test_find_alternate_method_siblings(self):\n self.assertEqual(\n [2], MethodSiblings(Path(self.dir_path, 'AlternateMethodSiblings.java')).value()\n )\n","sub_path":"test/patterns/method_siblings/test_method_siblings.py","file_name":"test_method_siblings.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"858798","text":"# -*- coding: utf-8 -*-\n\n\nimport requests\nimport time\nimport random\nimport string\nfrom apisms import _5sim, onlinesim\nfrom . import ProxyManager\nfrom python3_anticaptcha import ImageToTextTask\nfrom lxml import html, etree\n\n\ndef rsleep(left = 2, right = 5):\n time.sleep(random.triangular(left, right))\n\ndef prepare():\n pm = ProxyManager.ProxyMN()\n proxy = {'https': 'http://' + pm.GetProxyList(Limit = 1, Type = 'https')[0] + '/'}\n http = requests.Session()\n http.headers.update({\n 'User-agent': 'Mozilla/5.0 (Linux; U; Android 4.4.4; en-US; XT1022 Build/KXC21.5-40) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 UCBrowser/10.7.0.636 U3/0.8.0 Mobile Safari/534.30'\n })\n http.proxies = proxy\n resp = http.get('https://m.vk.com/')\n return http, resp\n\ndef start(session, name, surname, year, month, day, sex, captcha_sid = None, captcha_key = None):\n url = \"https://m.vk.com/join.php?act=start\"\n values = {'act': 'start',\n 'first_name': name,\n 'last_name': surname,\n 'bday': day,\n 'bmonth': month,\n 'byear': year,\n 'sex': sex,\n '_nlm': '1',\n '_ref': 'join'\n }\n if captcha_sid is not None:\n values['captcha_sid'] = captcha_sid\n values['captcha_key'] = captcha_key\n \n response = session.post(url, values)\n return session, response\n\n\ndef get_sms(session, phone_number, _hash):\n values = {'act': 'phone',\n 'hash': _hash,\n '_nlm': '1',\n '_ref': 'join'\n }\n if phone_number.startswith('+77'):\n values['phone_prefix'] = '+77'\n values['phone_number'] = phone_number.split('+77')[1]\n elif phone_number.startswith('+7'):\n values['phone_prefix'] = '+7'\n values['phone_number'] = phone_number.split('+7')[1]\n \n url = \"https://m.vk.com/join?act=phone&hash=\" + _hash\n response = session.post(url, values)\n return session, response\n \n\ndef check_code(session, phone_number, code, _hash):\n url = \"https://m.vk.com/join?act=check_code&hash=\" + _hash\n values = {'act': 'check_code',\n 'hash': _hash,\n 'phone': phone_number,\n 'code': code,\n '_nlm': '1',\n '_ref': 'join'\n }\n response = session.post(url, values)\n return session, response\n\ndef finish(session, key_url, phone_number, password):#session, phone_number, password, key_url):\n \"\"\"a = key_url.split('?')[1]\n values = {}\n for i in a.split('&'):\n b = i.split('=')\n values[b[0]] = b[1]\n for i, j in values.items():\n print(i, j)\n \n values = {\n \n 'expire': '',\n 'recaptcha': '',\n 'captcha_sid': '',\n 'captcha_key': '',\n 'email': phone_number,\n 'pass': password,\n 'join_to_already': 0\n }\"\"\"\n values = {'email': phone_number,\n 'pass': password\n }\n key_url = key_url[:4] + key_url[5:]\n response = session.post(key_url, values)\n return session, response\n \n \n \n#finish(\"https://login.vk.com/?act=login&_origin=https://m.vk.com&ip_h=338750eb054fc82b33&lg_h=bb495da8821fd6e060&role=pda&join_code=12654&join_hash=724ec96c1c2412ec10b45c0be0cb644c&to=am9pbj9hY3Q9ZG9uZQ--&pass=dima_bog_debaga\")\n\n\ndef registration(name = 'Лада', surname = 'Беленова', sex = '1', birthday = None, country = 'kazakhstan', service = '5sim'):\n try:\n session, response = prepare()\n \n rsleep()\n \n if birthday is None:\n byear = str(random.randint(1980, 1998))\n bmonth = str(random.randint(1, 12))\n bday = str(random.randint(1, 28))\n else:\n bday, bmonth, byear = birthday.split('.')\n \n session, response = start(session, name, surname, byear, bmonth, bday, sex)\n while 'captcha' in response.text:\n print('we need captcha')\n pm = ProxyManager.ProxyMN()\n prxlst = pm.GetProxyList(Limit = 5, Type = 'https')\n for i in range(5):\n try:\n proxy = {'https': 'http://' + prxlst[i] + '/'}\n session.proxies = proxy\n session, response = start(session, name, surname, byear, bmonth, bday, sex)\n if 'captcha' not in response.text:\n break\n except Exception:\n print('problems')\n \n print(response.text)\n _hash = response.text.split('action=\"/join?act=phone&hash=')[1].split('\"')[0]\n print('gonna get phone')\n \n \n \n \n \n if service == '5sim':\n ss = _5sim._5simApi()\n \n elif service == 'onlinesim':\n ss = onlinesim.onlinesimApi()\n \n phone_number = ss.get_number(country = country) \n print('number has been got', phone_number) \n session, response = get_sms(session, phone_number, _hash)\n print(response.text)\n sms_code = None\n i = 0\n while sms_code is None:\n time.sleep(1)\n i += 1\n sms_code = ss.check()\n print(sms_code)\n if i >= 60:\n print('no sms')\n ss.ban()\n return registration(name, surname, sex, birthday, country, service)\n session, response = check_code(session, phone_number, sms_code, _hash)\n print(response.text)\n key_url = response.text.split('
0:\n x1 = (-b - sqrt(d)) / (2 * a)\n x2 = (-b + sqrt(d)) / (2 * a)\n if x1 > x2:\n print(2, x2, x1)\n else:\n print(2, x1, x2)\n else:\n print(0)\n","sub_path":"doneTask_03/Task11_equation_02.py","file_name":"Task11_equation_02.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"158334896","text":"from django.shortcuts import render\nfrom django.template import loader\nfrom django.http import Http404, HttpResponse, HttpResponseRedirect\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.contrib.auth.decorators import login_required, permission_required\nfrom .models import Pago\n#from .forms import PagoFormFactory\nfrom .forms import PagoForm\nfrom Apps.GestionDeFacturas.models import Factura\nfrom VeterinariaPatagonica import tools\nfrom django.utils import timezone\n\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom VeterinariaPatagonica.tools import GestorListadoQueryset\n\n\n\ndef pago(request):\n\n context = {}#Defino el contexto.\n template = loader.get_template('GestionDePagos/GestionDePagos.html')#Cargo el template desde la carpeta templates/GestionDePagos.\n return HttpResponse(template.render(context, request))#Devuelvo la url con el template armado.\n\n\n@login_required(redirect_field_name='proxima')\n@permission_required('GestionDePagos.add_Pago', raise_exception=True)\ndef crear(request, idFactura = None): #, factura_id=None\n\n factura = Factura.objects.get(id=idFactura)\n context = {'usuario': request.user}\n\n pagos= len(Pago.objects.filter(factura=idFactura))\n\n if not pagos:\n\n pago=Pago(importeTotal=factura.sumar_total_adelanto, factura=factura)\n\n if request.method == 'POST':\n formulario = PagoForm(request.POST, instance=pago)\n if formulario.is_valid():\n pago = formulario.save()\n return HttpResponseRedirect(\"/GestionDePagos/ver/{}\".format(pago.id))\n else:\n context['formulario'] = formulario\n else:\n context['formulario'] = PagoForm(instance=pago)\n else:\n print(\"Error, ya hay Pagos\")\n template = loader.get_template('GestionDePagos/formulario.html')\n return HttpResponse(template.render(context, request))\n\n '''factura = None\n if factura_id:\n factura = Factura.objects.get(pk=factura_id)\n PagoForm = PagoFormFactory(pago, factura)'''\n\n\n\n\n\n@login_required(redirect_field_name='proxima')\n@permission_required('GestionDePagos.delete_Pago', raise_exception=True)\ndef eliminar(request, id):\n\n try:\n pago = Pago.objects.get(id=id)\n except ObjectDoesNotExist:\n raise Http404()\n\n if request.method == 'POST':\n\n pago.delete()\n return HttpResponseRedirect( \"/GestionDePagos/\" )\n\n else:\n\n template = loader.get_template('GestionDePagos/eliminar.html')\n context = {\n 'usuario' : request.user,\n 'id' : id\n }\n\n return HttpResponse( template.render( context, request) )\n\ndef ver(request, id):\n\n try:\n pago = Pago.objects.get(id=id)\n except ObjectDoesNotExist:\n raise Http404(\"No encontrado\", \"El pago con id={} no existe.\".format(id))\n\n template = loader.get_template('GestionDePagos/ver.html')\n contexto = {\n 'pago': pago,\n 'usuario': request.user\n }\n\n return HttpResponse(template.render(contexto, request))\n\ndef listar(request):\n\n gestor = GestorListadoQueryset(\n orden=[\n [\"orden_fecha\", \"Fecha\"],\n [\"orden_importeTotal\", \"Importe Total\"],\n [\"orden_factura\", \"Factura\"],\n\n [\"orden_baja\", \"Baja\"],\n ]\n )\n\n pagosQuery = Pago.objects.all()\n pagos = pagosQuery.filter(tools.paramsToFilter(request.GET, Pago))\n\n gestor.cargar(request, pagos)\n gestor.ordenar()#[TODO] NO ANDA ESTE METODO.\n\n template = loader.get_template('GestionDePagos/listar.html')\n paginator = Paginator(pagosQuery, 1)\n page = request.GET.get('page')\n\n\n\n try:\n pagos = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer, deliver first page.\n pagos = paginator.page(1)\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n pagos = paginator.page(paginator.num_pages)\n\n contexto = {\n 'pagosQuery' : pagosQuery,\n 'usuario' : request.user,\n 'pagos': pagos,\n 'gestor' : gestor,\n }\n return HttpResponse(template.render(contexto, request))\n","sub_path":"VeterinariaPatagonica/Apps/GestionDePagos/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"85200926","text":"#!/usr/bin/env python\n# | Copyright 2009-2016 Karlsruhe Institute of Technology\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 os, sys\nfrom gcSupport import Options, getConfig, scriptOptions, utils\nfrom grid_control.datasets import DataProvider, DatasetError\nfrom grid_control.utils import thread_tools\nfrom hpfwk import clear_current_exception\nfrom python_compat import imap, itemgetter, izip, lmap, lzip, set, sort_inplace, sorted\n\nusage = '%s [OPTIONS] | ' % sys.argv[0]\nparser = Options(usage)\nparser.addBool(None, 'l', 'list-datasets', default = False, help = 'Show list of all datasets in query / file')\nparser.addBool(None, 'b', 'list-blocks', default = False, help = 'Show list of blocks of the dataset(s)')\nparser.addBool(None, 'f', 'list-files', default = False, help = 'Show list of all files grouped according to blocks')\nparser.addBool(None, 's', 'list-storage', default = False, help = 'Show list of locations where data is stored')\nparser.addBool(None, 'm', 'metadata', default = False, help = 'Get metadata infomation of dataset files')\nparser.addBool(None, 'M', 'block-metadata', default = False, help = 'Get common metadata infomation of dataset blocks')\nparser.addBool(None, 'O', 'ordered', default = False, help = 'Sort dataset blocks and files')\nparser.addText(None, 'p', 'provider', default = '', help = 'Default dataset provider')\nparser.addText(None, 'C', 'settings', default = '', help = 'Specify config file as source of detailed dataset settings')\nparser.addText(None, 'S', 'save', default = '', help = 'Saves dataset information to specified file')\nparser.addBool(None, 'i', 'info', default = False, help = 'Gives machine readable info of given dataset(s)')\nparser.addBool(None, 'c', 'config-entry', default = False, help = 'Gives config file entries to run over given dataset(s)')\nparser.addBool(None, 'n', 'config-nick', default = False, help = 'Use dataset path to derive nickname in case it it undefined')\nparser.addText(None, 'L', 'location', default = 'hostname', help = 'Format of location information')\noptions = scriptOptions(parser)\n\n# we need exactly one positional argument (dataset path)\nif len(options.args) != 1:\n\tutils.exitWithUsage(usage)\n\n# Disable threaded queries\ndef noThread(desc, fun, *args, **kargs):\n\tfun(*args, **kargs)\n\treturn type('DummyThread', (), {'join': lambda self: None})()\nthread_tools.start_thread = noThread\n\ndef get_dataset_config(opts, args):\n\tdataset = args[0].strip()\n\tif os.path.exists(dataset):\n\t\topts.provider = 'ListProvider'\n\telse:\n\t\topts.provider = 'DBS3Provider'\n\tcfgSettings = {'dbs blacklist T1 *': 'False', 'remove empty blocks *': 'False',\n\t\t'remove empty files *': 'False', 'location format *': opts.location,\n\t\t'nickname check collision *': 'False',\n\t\t'dataset *': dataset, 'dataset provider *': opts.provider}\n\tif opts.metadata or opts.block_metadata:\n\t\tcfgSettings['lumi filter *'] = '-'\n\t\tcfgSettings['keep lumi metadata *'] = 'True'\n\treturn getConfig(configFile = opts.settings, configDict = {'dataset': cfgSettings})\n\ndef list_datasets(blocks):\n\t# Add some enums for consistent access to info dicts\n\tDataProvider.NFiles = -1\n\tDataProvider.NBlocks = -2\n\n\tprint('')\n\tinfos = {}\n\torder = []\n\tinfosum = {DataProvider.Dataset : 'Sum'}\n\tfor block in blocks:\n\t\tdsName = block.get(DataProvider.Dataset, '')\n\t\tif not infos.get(dsName, None):\n\t\t\torder.append(dsName)\n\t\t\tinfos[dsName] = {DataProvider.Dataset: block[DataProvider.Dataset]}\n\t\tdef updateInfos(target):\n\t\t\ttarget[DataProvider.NBlocks] = target.get(DataProvider.NBlocks, 0) + 1\n\t\t\ttarget[DataProvider.NFiles] = target.get(DataProvider.NFiles, 0) + len(block[DataProvider.FileList])\n\t\t\ttarget[DataProvider.NEntries] = target.get(DataProvider.NEntries, 0) + block[DataProvider.NEntries]\n\t\tupdateInfos(infos[dsName])\n\t\tupdateInfos(infosum)\n\thead = [(DataProvider.Dataset, 'Dataset'), (DataProvider.NEntries, '#Events'),\n\t\t(DataProvider.NBlocks, '#Blocks'), (DataProvider.NFiles, '#Files')]\n\tutils.printTabular(head, lmap(lambda x: infos[x], order) + ['=', infosum])\n\ndef list_blocks(blocks, headerbase):\n\tprint('')\n\tutils.printTabular(headerbase + [(DataProvider.BlockName, 'Block'), (DataProvider.NEntries, 'Events')], blocks)\n\ndef list_files(datasets, blocks):\n\tprint('')\n\tfor block in blocks:\n\t\tif len(datasets) > 1:\n\t\t\tprint('Dataset: %s' % block[DataProvider.Dataset])\n\t\tprint('Blockname: %s' % block[DataProvider.BlockName])\n\t\tutils.printTabular([(DataProvider.URL, 'Filename'), (DataProvider.NEntries, 'Events')], block[DataProvider.FileList])\n\t\tprint('')\n\ndef print_metadata(src, maxlen):\n\tfor (mk, mv) in src:\n\t\tif len(str(mv)) > 200:\n\t\t\tmv = ' %s...' % (len(str(mv)), repr(mv)[:200])\n\t\tprint('\\t%s: %s' % (mk.rjust(maxlen), mv))\n\tif src:\n\t\tprint('')\n\ndef list_metadata(datasets, blocks):\n\tprint('')\n\tfor block in blocks:\n\t\tif len(datasets) > 1:\n\t\t\tprint('Dataset: %s' % block[DataProvider.Dataset])\n\t\tprint('Blockname: %s' % block[DataProvider.BlockName])\n\t\tmk_len = max(imap(len, block.get(DataProvider.Metadata, [''])))\n\t\tfor f in block[DataProvider.FileList]:\n\t\t\tprint('%s [%d events]' % (f[DataProvider.URL], f[DataProvider.NEntries]))\n\t\t\tprint_metadata(lzip(block.get(DataProvider.Metadata, []), f.get(DataProvider.Metadata, [])), mk_len)\n\t\tprint('')\n\ndef list_block_metadata(datasets, blocks):\n\tfor block in blocks:\n\t\tif len(datasets) > 1:\n\t\t\tprint('Dataset: %s' % block[DataProvider.Dataset])\n\t\tprint('Blockname: %s' % block[DataProvider.BlockName])\n\t\tmkdict = lambda x: dict(izip(block[DataProvider.Metadata], x[DataProvider.Metadata]))\n\t\tmetadata = utils.QM(block[DataProvider.FileList], mkdict(block[DataProvider.FileList][0]), {})\n\t\tfor fileInfo in block[DataProvider.FileList]:\n\t\t\tutils.intersectDict(metadata, mkdict(fileInfo))\n\t\tprint_metadata(metadata.items(), max([0] + lmap(len, metadata.keys())))\n\ndef list_storage(blocks, headerbase):\n\tprint('')\n\tprint('Storage elements:')\n\tfor block in blocks:\n\t\tdsName = block[DataProvider.Dataset]\n\t\tif len(headerbase) > 0:\n\t\t\tprint('Dataset: %s' % dsName)\n\t\tif block.get(DataProvider.BlockName, None):\n\t\t\tprint('Blockname: %s' % block[DataProvider.BlockName])\n\t\tif block[DataProvider.Locations] is None:\n\t\t\tprint('\\tNo location contraint specified')\n\t\telif block[DataProvider.Locations] == []:\n\t\t\tprint('\\tNot located at anywhere')\n\t\telse:\n\t\t\tfor se in block[DataProvider.Locations]:\n\t\t\t\tprint('\\t%s' % se)\n\t\tprint('')\n\ndef list_config_entries(opts, blocks, provider):\n\tprint('')\n\tprint('dataset =')\n\tinfos = {}\n\torder = []\n\tmaxnick = 5\n\tfor block in blocks:\n\t\tdsName = block[DataProvider.Dataset]\n\t\tif not infos.get(dsName, None):\n\t\t\torder.append(dsName)\n\t\t\tinfos[dsName] = dict([(DataProvider.Dataset, dsName)])\n\t\t\tif DataProvider.Nickname not in block and opts.confignick:\n\t\t\t\ttry:\n\t\t\t\t\tif '/' in dsName:\n\t\t\t\t\t\tblock[DataProvider.Nickname] = dsName.lstrip('/').split('/')[1]\n\t\t\t\t\telse:\n\t\t\t\t\t\tblock[DataProvider.Nickname] = dsName\n\t\t\t\texcept Exception:\n\t\t\t\t\tclear_current_exception()\n\t\t\tif DataProvider.Nickname in block:\n\t\t\t\tnick = block[DataProvider.Nickname]\n\t\t\t\tinfos[dsName][DataProvider.Nickname] = nick\n\t\t\t\tmaxnick = max(maxnick, len(nick))\n\t\t\tif len(block[DataProvider.FileList]):\n\t\t\t\tinfos[dsName][DataProvider.URL] = block[DataProvider.FileList][0][DataProvider.URL]\n\tfor dsID, dsName in enumerate(order):\n\t\tinfo = infos[dsName]\n\t\tproviderName = sorted(provider.getClassNames(), key = len)[0]\n\t\tnickname = info.get(DataProvider.Nickname, 'nick%d' % dsID).rjust(maxnick)\n\t\tfilterExpr = utils.QM(providerName == 'list', ' %% %s' % info[DataProvider.Dataset], '')\n\t\tprint('\\t%s : %s : %s%s' % (nickname, providerName, provider.getDatasetExpr(), filterExpr))\n\ndef list_infos(blocks):\n\tevSum = 0\n\tfor block in blocks:\n\t\tblockId = '%s %s' % (block.get(DataProvider.Dataset, '-'), block.get(DataProvider.BlockName, '-'))\n\t\tblockStorage = '-'\n\t\tif block.get(DataProvider.Locations, None):\n\t\t\tblockStorage = str.join(',', block.get(DataProvider.Locations, '-'))\n\t\tevSum += block.get(DataProvider.NEntries, 0)\n\t\tprint('%s %s %d %d' % (blockId, blockStorage, block.get(DataProvider.NEntries, 0), evSum))\n\ndef save_dataset(opts, provider):\n\tprint('')\n\tblocks = provider.getBlocks(show_stats = False)\n\tif opts.ordered:\n\t\tsort_inplace(blocks, key = itemgetter(DataProvider.Dataset, DataProvider.BlockName))\n\t\tfor b in blocks:\n\t\t\tsort_inplace(b[DataProvider.FileList], key = itemgetter(DataProvider.URL))\n\tDataProvider.saveToFile(opts.save, blocks)\n\tprint('Dataset information saved to ./%s' % opts.save)\n\ndef main(opts, args):\n\tconfig = get_dataset_config(opts, args)\n\n\tprovider = config.getPlugin('dataset', cls = DataProvider)\n\tblocks = provider.getBlocks(show_stats = False)\n\tif len(blocks) == 0:\n\t\traise DatasetError('No blocks!')\n\n\tdatasets = set(imap(itemgetter(DataProvider.Dataset), blocks))\n\tif len(datasets) > 1 or opts.info:\n\t\theaderbase = [(DataProvider.Dataset, 'Dataset')]\n\telse:\n\t\tprint('Dataset: %s' % blocks[0][DataProvider.Dataset])\n\t\theaderbase = []\n\n\tif opts.list_datasets:\n\t\tlist_datasets(blocks)\n\tif opts.list_blocks:\n\t\tlist_blocks(blocks, headerbase)\n\tif opts.list_files:\n\t\tlist_files(datasets, blocks)\n\tif opts.list_storage:\n\t\tlist_storage(blocks, headerbase)\n\tif opts.metadata and not opts.save:\n\t\tlist_metadata(datasets, blocks)\n\tif opts.block_metadata and not opts.save:\n\t\tlist_block_metadata(datasets, blocks)\n\tif opts.config_entry:\n\t\tlist_config_entries(opts, blocks, provider)\n\tif opts.info:\n\t\tlist_infos(blocks)\n\tif opts.save:\n\t\tsave_dataset(opts, provider)\n\nif __name__ == '__main__':\n\tsys.exit(main(options.opts, options.args))\n","sub_path":"scripts/datasetInfo.py","file_name":"datasetInfo.py","file_ext":"py","file_size_in_byte":10130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"511731164","text":"import biovec\n\nimport numpy as np\nfrom json_tricks import dumps\nfrom scripts.sklearn.ml_sample_code import train_and_optimize\n\n\nclass Model(object):\n\n fasta = None\n trained_vectors = {}\n\n def __init__(self, fasta_path, trained_vectors):\n self.fasta = self.read_fasta(fasta_path)\n\n for key, vectors in trained_vectors.items():\n self.trained_vectors.update({key: vectors})\n\n @staticmethod\n def read_fasta(path):\n \"\"\"\n Reads amino sequences and properties from fasta-formatted file\n\n :param path: path to fasta file\n :return: list of dicts fo fasta sequences and binding properties {'seq':, 'bind':}\n \"\"\"\n fasta = []\n\n with open(path, 'r') as f:\n # Intermediary variables for the current header and sequence\n header = ''\n amino_sequence = ''\n binding = ''\n # Start reading the input file line by line\n while True:\n # Read the line\n line = f.readline()\n\n # If the header is not empty,\n if header:\n # Check if the current line is empty or contains no whitespace chars\n # If so, reached the end of sequence - add the header and sequence tuple to the list\n # and reset the intermediary variables\n if line.strip():\n if not (line.startswith('>') or line.startswith(';')):\n if not (line.startswith('-') or line.startswith('+')):\n # If the line is not empty and is not a set of non-printing chars, read the sequence\n amino_sequence = line.strip()\n else:\n binding = line.strip()\n else:\n fasta.append({'seq': amino_sequence, 'bind': binding})\n header = ''\n amino_sequence = ''\n binding = ''\n\n # If the header variable is empty, check if the current line is the header\n # In the case, initialise the header with the line and begin a new loop iteration\n if line.startswith('>') or line.startswith(';'):\n if not amino_sequence:\n header = line.strip()\n\n # End Of File reached - break the loop\n if line == '':\n fasta.append({'seq': amino_sequence, 'bind': binding})\n break\n return fasta\n\n def compute_vector(self, vectors, word):\n \"\"\"\n Compute word vector by sum over triples\n\n :param vectors:\n :param word: string of amino residues\n :return: element-wise sum of vectors as ndarray(model.wv.vector_size)\n \"\"\"\n return sum([vectors.wv.get_vector(x) for x in [word[i:i + 3] for i in range(len(word) - 2)]])\n\n def compose_data(self, vectors):\n \"\"\"\n Put the inputs (word vectors) and targets together\n\n :param path: path to fasta file\n :return: ndarray(n_samples, n_features), ndarray(n_samples,)\n \"\"\"\n vecs = []\n bindings = []\n\n for entry in self.fasta:\n seq = entry.get('seq')\n vecs.extend([self.compute_vector(vectors, seq[i - 3:i + 4]) for i in range(3, len(seq) - 3)])\n bindings.append(np.array([1 if entry.get('bind')[i] == '+' else 0 for i in range(3, len(seq) - 3)]))\n\n return np.stack(vecs, axis=0), np.hstack(bindings)\n\n def train(self):\n print('Training started')\n print('Vector sizes: ' + ', '.join(self.trained_vectors.keys()))\n for key, vectors in self.trained_vectors.items():\n print('Training for vector size: ' + key)\n # Get the data\n X, y = self.compose_data(vectors)\n\n cv_results, refined_result = train_and_optimize(X, y)\n\n for i in range(len(cv_results)):\n with open('cv_result_' + key + '_outer_split_' + str(i) + '.json', 'w') as f:\n f.write(dumps(cv_results[i]))\n\n with open('refined_result_' + key + '.txt', 'w') as f:\n f.write(refined_result)\n\n\ntr_vecs = {}\n#for i in ['25', '50', '75', '100', '125', '150', '200']:\nfor i in ['25']:\n model = biovec.models.load_protvec(\"../../trained_models/trained.model\")\n tr_vecs.update({i: model.wv.load_word2vec_format(fname=\"../../output/trained.vectors\")})\n#model = biovec.models.load_protvec(\"../trained_models/trained.model\")\n#model.wv.load_word2vec_format(fname=\"../output/trained.vectors\")\n\nmodel = Model('../../data/ppi_data.fasta', tr_vecs)\nmodel.train()\n","sub_path":"scripts/sklearn/model_scikit.py","file_name":"model_scikit.py","file_ext":"py","file_size_in_byte":4754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"634213028","text":"import requests\nfrom bs4 import BeautifulSoup\n\nbase_url = \"https://tocka.com.mk/\"\nr = requests.get(base_url)\nsoup = BeautifulSoup(r.text, \"html.parser\")\nfor title in soup.find_all(class_=\"item\") and soup.find_all(class_=\"caption\"):\n if title.a:\n print(title.a.text)\n else: \n print(title.contents[0])\n\n\n","sub_path":"17_decodewebpage.py","file_name":"17_decodewebpage.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"26924994","text":"import unittest\nfrom SI507project5_code import *\n\n\nclass TestGetData(unittest.TestCase):\n def setUp(self):\n self.ident1 = create_request_identifier(\"https://api.tumblr.com/v2/blog/\", {'blog-identifier': 'hayoubi.tumblr.com', 'method':'posts', 'type': None, 'limit':'20'})\n self.ident2 = create_request_identifier(\"https://api.tumblr.com/v2/blog/\", {'blog-identifier': 'medbutt.tumblr.com', 'method':'posts', 'type': None, 'limit':'20'})\n self.tumblr_data1 = get_data_from_api(\"https://api.tumblr.com/v2/blog/\", \"Tumblr\", {'blog-identifier': 'hayoubi.tumblr.com', 'method':'posts', 'type': None, 'limit':'20'})\n\n def test_create_request_identifier(self):\n self.assertEqual(\n self.ident1,\n \"https://api.tumblr.com/v2/blog/hayoubi.tumblr.com/posts?api_key=O1kHF4BtrMdtWuFi9CGPwGXiIlR4xFcR6kluaeskPII8eE3j1Q&limit=20\",\n \"Testing the request identifier is formatted correctly.\")\n self.assertEqual(\n self.ident2,\n \"https://api.tumblr.com/v2/blog/medbutt.tumblr.com/posts?api_key=O1kHF4BtrMdtWuFi9CGPwGXiIlR4xFcR6kluaeskPII8eE3j1Q&limit=20\",\n \"Testing the request identifier is formatted correctly.\")\n\n def test_get_data_from_api(self):\n self.assertEqual(len(self.tumblr_data1['response']['posts']), 20, \"Testing if the length of retrived data meets the limit params\")\n self.assertEqual(self.tumblr_data1['response']['posts'][0]['blog_name'], \"hayoubi\", \"Testing the blog identifier.\")\n self.assertEqual(self.tumblr_data1['response']['posts'][0]['type'], \"photo\", \"Testing if the post type is right.\")\n self.assertEqual(len(self.tumblr_data1['response']['posts'][0]['tags']), 8, \"Testing the number of tags.\")\n\nclass TestCaching(unittest.TestCase):\n def setUp(self):\n self.data = get_from_cache(\"https://api.tumblr.com/v2/blog/hayoubi.tumblr.com/posts?api_key=O1kHF4BtrMdtWuFi9CGPwGXiIlR4xFcR6kluaeskPII8eE3j1Q&limit=20\", CACHE_DICTION)\n self.data_null = get_from_cache(\"https://hello.world\", CACHE_DICTION)\n def test_get_from_cache(self):\n self.assertEqual(self.data['response']['blog']['name'], \"hayoubi\", \"Test if previous data is in the cache diction.\")\n self.assertEqual(self.data['response']['posts'][0]['id'], 165771558644, \"Test if previous data is in the cache diction.\")\n self.assertIsNone(self.data_null, \"Testing if new data is not in the cache diction.\")\n\nclass TestTumblrPost(unittest.TestCase):\n def setUp(self):\n tumblr_data1 = get_data_from_api(\"https://api.tumblr.com/v2/blog/\", \"Tumblr\", {'blog-identifier': 'hayoubi.tumblr.com', 'method':'posts', 'type': None, 'limit':'20'})\n self.post_inst = TumblrPost(tumblr_data1['response']['posts'][0])\n\n def test_constructor(self):\n self.assertEqual(self.post_inst.url, \"http://hayoubi.tumblr.com/post/165771558644/hello-sorry-i-dont-post-here-much-anymore-i\", \"Testing the post instance's url.\")\n self.assertEqual(self.post_inst.type, \"photo\", \"Testing the post instance's type.\")\n self.assertEqual(self.post_inst.num_tags, 8, \"Testing the post instance's num of tags.\")\n self.assertEqual(self.post_inst.slug.title(), \"Hello Sorry I Dont Post Here Much Anymore I\", \"Testing the post instance's title.\")\n\n def test_str_method(self):\n self.assertEqual(self.post_inst.__str__(), \"hayoubi | photo | http://hayoubi.tumblr.com/post/165771558644/hello-sorry-i-dont-post-here-much-anymore-i\")\n\n\n\n\nif __name__ == \"__main__\":\n unittest.main(verbosity=2)\n","sub_path":"SI507project5_tests.py","file_name":"SI507project5_tests.py","file_ext":"py","file_size_in_byte":3539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"43419634","text":"class ListNode:\n\tdef __init__(self, x):\n\t\tself.val = x\n\t\tself.next = None\n\nclass Solution:\n def reverseList(self, A):\n curr = A\n prev = None\n nxt = None\n\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n\n if nxt:\n A.next = self.reverseList(nxt)\n\n return prev\n\n def lPalin(self, A):\n slow = A\n fast = A.next\n\n while slow and fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n\n head1 = A\n head2 = self.reverseList(slow.next)\n while head1 and head2:\n if head1.val != head2.val:\n return 0\n head1 = head1.next\n head2 = head2.next\n\n return 1\n","sub_path":"Stacks/Stacks I/5. Palindrome List.py","file_name":"5. Palindrome List.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"306334486","text":"import paho.mqtt.client as mqtt #import the client1\nimport time\n\nthe_instance = 'k5izbpn65slp'\nthe_node = \"counter\"\nusername = \"sadiq.a.ahmad@gmail.com\"\npassword = \"aB01@\"\n\ndef on_message(client, userdata, message):\n global count\n print(\"message received \" ,str(message.payload.decode(\"utf-8\")))\n print(\"message topic=\",message.topic)\n if message.topic == f'{the_instance}/{the_node}/reset/set': # receive new value for input port\n count = int(message.payload.decode(\"utf-8\"))\n print(count)\n client.publish(f\"{the_instance}/{the_node}/count\", message.payload)\n\ndef on_connect(mqttc, obj, flags, rc):\n print(\"connected: \" + str(rc))\n # client.publish(\"nodewire/instances\", the_instance) # the instance\n # client.publish(f\"{the_instance}/nodes\", the_node) # the node name\n client.publish(f\"{the_instance}/{the_node}/count\", \"0\") # output port\n client.subscribe(f\"{the_instance}/{the_node}/reset/set\") # input port\n client.publish(f\"{the_instance}/{the_node}/reset\", 0) # input port\n\ndef on_disconnect(client, obj, rc):\n print('disconnected')\n client.user_data_set(obj + 1)\n #if obj == 0:\n time.sleep(5)\n print('reconnecting')\n client.reconnect()\n\nbroker_address = \"s2.nodewire.org\" # our broker address\nprint(\"creating new instance\")\nclient = mqtt.Client('counter') # create new instance\nclient.on_message=on_message # attach function to callback\nclient.on_connect = on_connect\nclient.on_disconnect = on_disconnect\nclient.user_data_set(0)\nprint(\"connecting to broker\")\nclient.username_pw_set(username, password=password)\nclient.connect(broker_address) # connect to broker\n# you can publish and subscribe to topics here but better to do that under the on_connect event\n\nlast_time = time.time()\ncount = 0\nwhile True:\n client.loop()\n if time.time()-last_time>1:\n last_time = time.time()\n count = count + 1\n # print(count)\n client.publish(f\"{the_instance}/{the_node}/count\", count)\n if count == 10: client.publish(f\"{the_instance}/mynode/reset/set\", 1)\n","sub_path":"samples/testd.py","file_name":"testd.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"143181968","text":"from django.urls import path\nfrom . import views\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(\"add\", views.add, name=\"add\"),\n path(\"request\", views.req, name=\"request\"),\n path(\"dashboard\", views.dashboard, name=\"dashboard\"),\n path(\"requests\", views.reqs, name=\"reqs\"),\n path(\"patient/\", views.indipatient, name=\"indipatient\"),\n path(\"update/\", views.update, name=\"update\"),\n path(\"request/\", views.indirequest, name=\"indirequest\"),\n path(\"addrequest/\", views.addrequest, name=\"addrequest\"),\n path(\"donors\", views.donor, name=\"donor\"),\n path(\"services\", views.services, name=\"service\")\n]","sub_path":"WebApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"503566298","text":"from django.contrib import admin\nfrom django.urls import path\nfrom django.conf.urls import url,include\nfrom . import views\n\n \napp_name ='Pharmacy'\n\nurlpatterns = [\n url(r'^$',views.index, name='index'),\n url(r'^s$',views.signup, name='signup'),\n url(r'^a$',views.admin, name='admin'),\n url(r'^d$',views.drugdetail, name='drugdetail'),\n url(r'^l$',views.locationdetail, name='locationdetails'),\n url(r'^m$',views.medbook, name='medbook'),\n url(r'^p$',views.postmedicaldata, name='postmedicaldata'),\n url(r'^n$',views.nurse, name='nurse'),\n url(r'^u$',views.userreq, name='userreq'),\n url(r'^pl$',views.pharmalogin, name='pharmalogin'),\n] \n","sub_path":"Pharmacy/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"211457705","text":"import os\nimport json\n\n## Arguments\nNOTEBOOK_DIR = \"\"\nDIR_STATIC = \"files\"\nMODULE_ID = 93300\nTAGS = \"DB\"\nCOMMON_CODE_URL = \"\"\nAUTHOR = \"Aravind Sankaran\"\n\n# setting this to false will over-write code_urls.txt and your changes will be lost\nCODE_URLS_REUSE = True\n\nMODULE_NAME = os.getcwd().split('/')[-1]\n# Relative path. leave it blank if notebook files are in current dir\nNOTEBOOK_DIR = os.path.join(os.getcwd(),NOTEBOOK_DIR)\n\nconfigs = {}\n\nconfigs[\"dir_path\"] = NOTEBOOK_DIR\nconfigs[\"dir_static\"] = DIR_STATIC\nconfigs[\"module_name\"] = MODULE_NAME\nconfigs[\"module_id\"] = MODULE_ID\nconfigs[\"author\"] = AUTHOR\nconfigs[\"tags\"] = TAGS\n\ndef get_list_all_files_name(dir_path):\n all_files_path = []\n dnt = []\n if os.path.exists(os.path.join(dir_path, \"DoNotTrack\")):\n dnt = open(os.path.join(dir_path, \"DoNotTrack\"), 'r').read().split()\n # print(dnt)\n for f in os.listdir(dir_path):\n if os.path.isfile(os.path.join(dir_path, f)):\n if f.endswith('.ipynb') or f.endswith('.pdf'):\n if f not in dnt:\n all_files_path.append(os.path.join(f))\n\n return all_files_path\n\n\ndef parse_code_urls():\n with open('code_urls.txt', 'r') as f:\n while(True):\n x = f.readline().strip()\n if x is \"\":\n return\n y = f.readline().strip()\n configs[x]['code_url'] = y\n f.readline()\n\nfile_list = get_list_all_files_name(NOTEBOOK_DIR)\nfile_list.sort()\n\n\nconfigs['file_list'] = file_list\n\nfor f in file_list:\n configs[f] = {}\n\n\npage_id = 1\ncode_urls_txt = \"\"\nfor f in file_list:\n page_name = f.split('.ipynb')[0]\n pdf = False\n if \".pdf\" in page_name:\n pdf = True\n page_name = page_name.split(\".pdf\")[0]\n code_url = \"\"\n if os.path.exists(os.path.join(os.getcwd(),page_name)):\n code_url = \"https://github.com/as641651/\" + MODULE_NAME + \"/tree/master/\" + page_name\n\n if COMMON_CODE_URL != \"\":\n code_url = COMMON_CODE_URL\n\n configs[f][\"code_url\"] = code_url\n configs[f][\"page_name\"] = page_name\n configs[f][\"pdf\"] = pdf\n configs[f][\"page_id\"] = MODULE_ID + page_id\n \n page_id = page_id+1\n code_urls_txt += f + \"\\n\" + code_url + \"\\n\\n\"\n\n# overwrite code urls from cache\nif CODE_URLS_REUSE:\n parse_code_urls()\nelse:\n with open('code_urls.txt', 'w') as f:\n f.write(code_urls_txt)\n \nwith open('configs.json', 'w') as outfile:\n json.dump(configs, outfile, indent=4, sort_keys=True)\n\nprint(configs)\n","sub_path":"generate_meta_data.py","file_name":"generate_meta_data.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"376361019","text":"import os\nimport sys\n\nimport asyncio\nfrom datetime import datetime\n\nimport requests\nfrom requests.exceptions import ConnectionError, Timeout, TooManyRedirects\nimport json\n\nfrom discord.ext import commands\n\nfrom sqlalchemy import create_engine, func, MetaData, Table, Column, BigInteger, String, TIMESTAMP\n\nif not os.path.isfile('config.py'):\n sys.exit(\"'config.py' not found.\")\nelse:\n import config\n\nclass Prices(commands.Cog, name='prices'):\n # Initializes background collection of crypto data from CMC\n def __init__(self, bot):\n self.bot = bot\n self.prices = {}\n # Establishes connection with database\n self.engine = create_engine('sqlite:///db/coinsDB.db', echo = True)\n self.conn = self.engine.connect()\n # Adds class functions to loop background tasks\n self.bg_task1 = self.bot.loop.create_task(self.check_prices())\n self.bg_task2 = self.bot.loop.create_task(self.send_prices())\n \n async def check_prices(self):\n # REST query, parse, and stores data about crypto coins all in one go\n await self.bot.wait_until_ready()\n while not self.bot.is_closed():\n # API request to CMC\n url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'\n \n headers = {\n 'Accepts': 'application/json',\n 'X-CMC_PRO_API_KEY': '1bc59ff0-44db-417a-818d-9f93408f36fc'\n }\n \n try:\n response = requests.get(url, headers=headers)\n response.raise_for_status()\n data = json.loads(response.text)\n except (ConnectionError, Timeout, TooManyRedirects) as e:\n data = json.loads(response.text)\n code = data['status']['error_code']\n message = data['status']['error_message']\n print(f'{code}: {message}')\n print(e)\n \n # Parse info from request\n for i in data['data']:\n coin = i['symbol']\n # Creates table for coin if it doesn't exist in database\n if not self.engine.dialect.has_table(self.engine, coin):\n meta = MetaData(self.engine)\n # Create table with columns\n Table(coin, meta,\n Column('timestamp', TIMESTAMP, nullable=False, server_default=func.now(), onupdate=func.now()),\n Column('supply', BigInteger),\n Column('price', String),\n Column('volume_24h', BigInteger),\n Column('percent_1h', String),\n Column('percent_24h', String)\n )\n meta.create_all()\n # Fill respective table with data\n meta = MetaData(bind=None)\n table = Table(coin, meta, autoload=True, autoload_with=self.engine)\n ins = table.insert().values(\n supply=i['circulating_supply'],\n price = '%.2f'%i['quote']['USD']['price'],\n volume_24h = i['quote']['USD']['volume_24h'],\n percent_1h = '%.2f'%i['quote']['USD']['percent_change_1h'],\n percent_24h = '%.2f'%i['quote']['USD']['percent_change_24h']\n )\n self.conn.execute(ins)\n \n # Save coin, price, and 1h percent to dict\n price = i['quote']['USD']['price']\n price = '%.2f'%price\n percent_1h = i['quote']['USD']['percent_change_1h']\n percent_1h = '%.2f'%percent_1h\n self.prices[coin] = {\n 'price': price,\n 'percent_1h': percent_1h\n }\n \n await asyncio.sleep(60*10)\n \n async def send_prices(self):\n # Spits message to Discord channel\n await self.bot.wait_until_ready()\n channel = self.bot.get_channel(config.CHANNELS[0])\n while not self.bot.is_closed():\n now = datetime.now().strftime(\"%H:%M\")\n if (now in ['06:00', '12:00', '18:00']):\n message = 'Current prices:\\n'\n for k, v in self.prices.items():\n if k in ['BTC', 'ETH', 'LINK', 'AAVE', 'DOGE']:\n message += f'{k} -- ${v[\"price\"]} ({v[\"percent_1h\"]}%)\\n'\n await channel.send(message)\n await asyncio.sleep(60)\n await asyncio.sleep(1)\n \n @commands.command(name='getprice')\n async def get_price(self, ctx, coin='ALL'):\n coin = coin.upper()\n if coin == 'ALL':\n message = 'Last updated prices:\\n'\n for k, v in self.prices.items():\n if k in ['BTC', 'ETH', 'LINK', 'AAVE', 'DOGE']:\n message += f'{k} -- ${v[\"price\"]} ({v[\"percent_1h\"]}%)\\n'\n await ctx.send(message)\n else:\n if coin in self.prices.keys():\n await ctx.send(f'Last updated price of {coin}: ${self.prices[coin][\"price\"]} ({self.prices[coin][\"percent_1h\"]}%)')\n else:\n await ctx.send('That coin doesn\\'t exist, and neither should you.')\n \ndef setup(bot):\n bot.add_cog(Prices(bot))\n","sub_path":"cogs/prices.py","file_name":"prices.py","file_ext":"py","file_size_in_byte":5340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"227162196","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nAdvent of code\nDay 23 - Part 1\n\"\"\"\n\nimport os \nos.chdir(\"/Users/em/Documents/git-projects/adventofcode/2017/d23\")\n\nwith open(\"input.txt\", \"r\") as f:\n input = f.read()\n \ncommands = input.split('\\n')\n\n\ndef process_command(reg, command):\n \"\"\"\n Process command.\n Return shift to find next command to be executed.\n \"\"\" \n c = command.split(' ')\n t = c[0]\n r = c[1]\n\n assert(t in ['set','sub','mul','jnz'])\n \n if t == 'set':\n reg[r] = get_value(reg, c[2])\n elif t == 'sub':\n reg[r] -= get_value(reg, c[2])\n elif t == 'mul':\n reg[r] *= get_value(reg, c[2])\n# elif t == 'mod':\n# reg[r] = reg[r] % get_value(reg, c[2])\n elif t == 'jnz':\n if get_value(reg, c[1]) != 0:\n return get_value(reg, c[2])\n \n return 1\n\n\ndef get_value(reg, s):\n try:\n value = int(s)\n except ValueError:\n value = reg[s]\n return value\n\n\n#d = {'a':7}\n#exec \"def f(x): return x + a\" in d\n#exec \"def f2(x): return x - 2\" in d\n\n\n\n# Part 1\nreg = dict(zip([chr(ord('a')+i) for i in range(8)],[0]*8))\n\ncnt = 0\np = 0\nwhile (0 <= p < len(commands)):\n if 'mul' in commands[p]:\n cnt += 1\n p += process_command(reg, commands[p])\nprint('Solution of part 1: {0}'.format(cnt))\n\n\n# Part 2\nreg = dict(zip([chr(ord('a')+i) for i in range(8)],[0]*8))\nreg['a'] = 1\np = 0\nwhile (0 <= p < len(commands)):\n# command = commands[p]\n# print p\n# print reg\n# print command \n p += process_command(reg, commands[p])\n\nprint('Solution of part 1: {0}'.format(reg['h']))\n\n\n\n\n","sub_path":"2017/d23/d23.py","file_name":"d23.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"522264459","text":"# ProductOfArray --> Write a recursive function that takes an array of numbers and returns a product of all the elements\n\ndef productOfArray(arr):\n if(len(arr) == 1):\n return arr[0]\n else: \n return arr[0] * productOfArray(arr[1: len(arr)])\n\n\nsample1 = [1,2,3]\nsample2 = [1,2,3,4]\nsample3 = [1,2,3,10]\n\nprint(productOfArray(sample1)) #ans --> 6\nprint(productOfArray(sample2)) #ans --> 24\nprint(productOfArray(sample3)) #ans --> 60","sub_path":"src/interview_questions/recursionAndDynamicProgramming/easy/productOfArray.py","file_name":"productOfArray.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"150147577","text":"from xml.etree import ElementTree\nimport pymysql\n\n#XML reading configuration options\nFILE_NAME = \"game_trailers.xml\"\nXML_SUBDATA_TAG = \"Game\" \n#XML_TAG = \"Youtube\" \nXML_TAG = \"genre\" \nXML_ID = \"GameTitle\"\n\n\n#SQL writing configuration options\nSQL_UNIQUE_TABLE = \"games\"\nSQL_OTHER_TABLE = \"genres\"\nSQL_OTHER_COLUMN= \"genre\"\nSQL_RELATION_TABLE = \"genres_of_games\"\nSQL_UNIQUE_COLUMN = \"name\"\nNEW_COLUMN = \"url\"\nNEW_COLUMN_TYPE=NEW_COLUMN+\" VARCHAR(511)\"\n#SQL_NEW_COLUMN = \"name\"\n\ntree = ElementTree.parse(FILE_NAME)\nroot = tree.getroot()\n\nconn = pymysql.Connect(host=\"127.0.0.1\",user=\"atlas\",database=\"gamedb\")\ncurs = conn.cursor()\ncurs.execute(\"SELECT DISTINCT \"+SQL_UNIQUE_COLUMN+\", id FROM \"+SQL_UNIQUE_TABLE)\ntags = {}\nids = {}\nvalues = {}\nfor row in curs:\n ids[row[0]] = row[1]\n values[row[1]] = row[0]\n tags[row[0]] = []\n\ncurs = conn.cursor()\ncurs.execute(\"SELECT DISTINCT \"+SQL_OTHER_COLUMN+\", id FROM \"+SQL_OTHER_TABLE)\nother_ids = {}\nother_values = {}\nfor row in curs:\n other_ids[row[0]] = row[1] \n other_values[row[1]] = row[0]\n\ncurs = conn.cursor()\ncurs.execute(\"SELECT DISTINCT * FROM \"+SQL_RELATION_TABLE)\nrelations = {}\nfor row in curs:\n relations[(values[row[0]],other_values[row[1]])]=True\nconn.close()\n\nfor piece in root.iter(XML_SUBDATA_TAG):\n if piece.iter(XML_ID) != None:\n for xmlId in piece.iter(XML_ID):\n for xmlTag in piece.iter(XML_TAG):\n xmlTag.text=xmlTag.text.strip()\n #if xmlTag.text.startswith(\"http://\"):\n #xmlTag.text=xmlTag.text.replace(\"http://\",\"\",1)\n if xmlId.text in tags and xmlTag.text not in tags[xmlId.text]:\n tags[xmlId.text].append(xmlTag.text)\n\nprint (tags)\n\n#Entity table update\n#with open(FILE_NAME+\".sql\",\"w\") as sql:\n# sql.write(\"ALTER TABLE \"+SQL_UNIQUE_TABLE+\"\\n ADD \"+NEW_COLUMN_TYPE+\";\\n\")\n# for key, tag in tags.items():\n# for url in tag:\n# sql.write(\"UPDATE \"+SQL_UNIQUE_TABLE+\"\\n SET \"+NEW_COLUMN+\" = '\"\n# +url+\"'\\n WHERE \"+SQL_UNIQUE_COLUMN+\" = '\"\n# +key.replace(\"'\",\"\\\\'\")+\"';\\n\")\n\n#Entity table insert\n#with open(FILE_NAME+\".sql\",\"w\") as sql:\n# visited = {}\n# for key, value in tags.items():\n# for v in value:\n# if v not in other_ids and v not in visited:\n# visited[v]=True\n# sql.write(\"INSERT INTO \"+SQL_OTHER_TABLE+\"\\n (\"\n# +SQL_OTHER_COLUMN+\") VALUES\\n \"\n# +\"('\"+v.replace(\"'\",\"\\\\'\")+\"');\\n\")\n\n\n#Relationship tables\nwith open(FILE_NAME+\".sql\",\"w\") as sql:\n for key, value in tags.items():\n for v in value:\n if (key,v) not in relations:\n sql.write(\"INSERT INTO \"+SQL_RELATION_TABLE+\"\\n (game_id, genre_id)\"\n +\" VALUES\\n (\"+str(ids[key])+\", \"+str(other_ids[v])+\");\\n\")\n","sub_path":"data/xmlToSql.py","file_name":"xmlToSql.py","file_ext":"py","file_size_in_byte":2870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"302313254","text":"import argparse\nfrom wav2letter_trainer import Wav2LetterTrainer\nfrom wav2letter_model import Wav2LetterModel\n\nparser = argparse.ArgumentParser(description='Wav2Letter training')\nparser.add_argument('--train-manifest', metavar='DIR',\n help='path to train manifest csv',\n default='__data__/csv/manifests/JSUT/jsut-2_5-train.csv')\nparser.add_argument('--val-manifest', metavar='DIR',\n help='path to validation manifest csv',\n default='__data__/csv/manifests/JSUT/jsut-2_5-dev.csv')\nparser.add_argument('--sample-rate', default=16000, type=int, help='Sample rate')\nparser.add_argument('--batch-size', default=76, type=int, help='Batch size for training')\nparser.add_argument('--num-workers', default=0, type=int, help='Number of workers used in data-loading')\nparser.add_argument('--labels-path', default='__data__/json/jp_labels.json', help='Contains all characters for transcription')\nparser.add_argument('--window-size', default=.02, type=float, help='Window size for spectrogram in seconds')\nparser.add_argument('--peak-normalization',dest='peak_normalization', default=False, action='store_true', help='Apply peak normalization while training and validation')\nparser.add_argument('--window-stride', default=.01, type=float, help='Window stride for spectrogram in seconds')\nparser.add_argument('--window', default='hamming', help='Window type for spectrogram generation')\nparser.add_argument('--epochs', default=200, type=int, help='Number of training epochs')\nparser.add_argument('--cuda', default=True,dest='cuda', action='store_true', help='Use cuda to train model')\nparser.add_argument('--usePcen', default=True,dest='pcen', action='store_true', help='Use pcen features')\nparser.add_argument('--lr', '--learning-rate', default=1e-5, type=float, help='initial learning rate')\nparser.add_argument('--mixPrec',dest='mixPrec',default=False,action='store_true', help='use mix precision for training')\nparser.add_argument('--reg-scale', dest='reg_scale', default=0.9, type=float, help='L2 regularizationScale')\nparser.add_argument('--momentum', default=0.90, type=float, help='momentum')\nparser.add_argument('--max-norm', default=400, type=int, help='Norm cutoff to prevent explosion of gradients')\nparser.add_argument('--learning-anneal', default=1.2, type=float, help='Annealing applied to learning rate every epoch')\nparser.add_argument('--silent', dest='silent', action='store_true', help='Turn off progress tracking per iteration')\nparser.add_argument('--checkpoint', default=False,dest='checkpoint', action='store_true', help='Enables checkpoint saving of model')\nparser.add_argument('--checkpoint-per-batch', default=0, type=int, help='Save checkpoint per batch. 0 means never save')\nparser.add_argument('--visdom', dest='visdom', action='store_true', help='Turn on visdom graphing')\nparser.add_argument('--tensorboard', default=True,dest='tensorboard', action='store_true', help='Turn on tensorboard graphing')\nparser.add_argument('--log-dir', default='visualize/w2lOnMozillaDataAftr118Epch', help='Location of tensorboard log')\nparser.add_argument('--log-params', dest='log_params', action='store_true', help='Log parameter values and gradients')\nparser.add_argument('--seed', default=1234 )\nparser.add_argument('--id', default='Wav2Letter training', help='Identifier for visdom/tensorboard run')\nparser.add_argument('--save-folder', default='models', help='Location to save epoch models')\nparser.add_argument('--model-path', default='models/wav2Letter_final.pth.tar',\n help='Location to save best validation model')\nparser.add_argument('--continue-from', default='', help='Continue from checkpoint model')\nparser.add_argument('--finetune', default=False,dest='finetune', action='store_true',\n help='Finetune the model from checkpoint \"continue_from\"')\nparser.add_argument('--augment', default=False ,dest='augment', action='store_true', help='Use random tempo and gain perturbations.')\nparser.add_argument('--noise-dir', default=None,\n help='Directory to inject noise into audio. If default, noise Inject not added')\nparser.add_argument('--noise-prob', default=0.9, help='Probability of noise being added per sample')\nparser.add_argument('--noise-min', default=0.1,\n help='Minimum noise level to sample from. (1.0 means all noise, not original signal)', type=float)\nparser.add_argument('--noise-max', default=0.7,\n help='Maximum noise levels to sample from. Maximum 1.0', type=float)\nparser.add_argument('--no-shuffle', dest='no_shuffle', action='store_true',\n help='Turn off shuffling and sample from dataset based on sequence length (smallest to largest)')\nparser.add_argument('--no-sortaGrad', dest='no_sorta_grad', action='store_true',\n help='Turn off ordering of dataset on sequence length for the first epoch.')\nparser.add_argument('--no-bidirectional', dest='bidirectional', action='store_false', default=True,\n help='Turn off bi-directional RNNs, introduces lookahead convolution')\nparser.add_argument('--dist-url', default='tcp://127.0.0.1:1550', type=str,\n help='url used to set up distributed training')\nparser.add_argument('--dist-backend', default='gloo', type=str, help='distributed backend')\nparser.add_argument('--world-size', default=1, type=int,\n help='number of distributed processes')\nparser.add_argument('--rank', default=0, type=int,\n help='The rank of this process')\nparser.add_argument('--gpu-rank', default=None,\n help='If using distributed parallel for multi-gpu, sets the GPU for the process')\n\nif __name__ == '__main__':\n args = parser.parse_args()\n model = Wav2LetterModel(continue_from=args.continue_from,\n sample_rate=args.sample_rate,\n window_size=args.window_size,\n window_stride=args.window_stride,\n window=args.window,\n noise_dir=args.noise_dir,\n noise_prob=args.noise_prob,\n noise_min=args.noise_min,\n noise_max=args.noise_max,\n labels_path=args.labels_path)\n\n trainer = Wav2LetterTrainer(model=model.get(),\n id=args.id,\n cuda=args.cuda,\n epochs=args.epochs,\n batch_size=args.batch_size,\n save_folder=args.save_folder,\n lr=args.lr,\n momentum=args.momentum,\n train_manifest=args.train_manifest,\n val_manifest=args.val_manifest,\n peak_normalization=args.peak_normalization,\n no_sorta_grad=args.no_sorta_grad,\n num_workers=args.num_workers,\n no_shuffle=args.no_shuffle,\n max_norm=args.max_norm,\n checkpoint_per_batch=args.checkpoint_per_batch,\n model_path=args.model_path,\n learning_anneal=args.learning_anneal,\n checkpoint=args.checkpoint,\n augment=args.augment,\n seed=args.seed,\n pcen=args.pcen)\n\n trainer.run(epochs=args.epochs,\n early_stop=15)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"482349458","text":"import logging\n\nfrom test.splunk_test_utils import splunk_single_search\n\nlogger = logging.getLogger(__name__)\n\n\ndef test_poller_integration_event(setup_splunk):\n logger.info(f\"Integration test for poller\")\n search_string = 'search index=\"em_logs\" sourcetype=\"sc4snmp:meta\" earliest=-1m'\n result_count, events_count = splunk_single_search(setup_splunk, search_string)\n assert result_count > 0\n assert events_count > 0\n\n\ndef test_poller_integration_metric(setup_splunk):\n logger.info(f\"Integration test for poller\")\n search_string = \"| mcatalog values(metric_name) where index=em_metrics AND metric_name=sc4snmp.*\"\n result_count, metric_count = splunk_single_search(setup_splunk, search_string)\n assert result_count > 0\n assert metric_count > 0\n","sub_path":"test/test_poller_integration.py","file_name":"test_poller_integration.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"360837110","text":"import re\na='Дана строка, содержащая русский текст. Если в тексте есть два одинаковых слова, то вывести слова текста в алфавитном поpядке, ' \\\n 'в противном случае удалить из слов текста гласные буквы.'\n\n\na=re.sub('[,.]','',a)\na=a.casefold()\na = a.split(\" \")\nprint(sorted(a)) if len(set(a))!=len(a) else print(re.sub('[уеаоэяию]','',str(a)))\n\n\n","sub_path":"Task1/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"587871955","text":"import json\nimport logging\n\nimport aiohttp\nfrom discord.ext import commands\n\nlog = logging.getLogger(__name__)\n\n\nclass BotsDiscord:\n \"\"\"Posting your bot information to bot listing sites\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n self.session = aiohttp.ClientSession(loop=self.bot.loop)\n\n def __unload(self):\n self.session.close()\n\n async def __local_check(self, ctx):\n return await self.bot.is_owner(ctx.author)\n\n @commands.command()\n async def botspwtoken(self, ctx, token: str):\n \"\"\"Token for bots.discord.pw\"\"\"\n await self.bot.database.set_cog_config(self, {\"dbotspw_token\": token})\n await ctx.send(\"Token set\")\n\n @commands.command()\n async def botsorgtoken(self, ctx, token: str):\n \"\"\"Token for discordbots.org\"\"\"\n await self.bot.database.set_cog_config(self, {\"dbotsorg_token\": token})\n await ctx.send(\"Token set\")\n\n async def post_payload(self, base_url, token):\n url = base_url + \"api/bots/{}/stats\".format(self.bot.user.id)\n payload = {\"server_count\": len(self.bot.guilds)}\n headers = {\"Authorization\": token, \"Content-Type\": \"application/json\"}\n async with self.session.post(\n url, data=json.dumps(payload), headers=headers) as r:\n log.info(\"Payload: {} Response: {}\".format(payload, r.status))\n\n async def post_dbotspw(self, doc):\n if not doc:\n return\n token = doc.get(\"dbotspw_token\")\n if not token:\n return\n url = \"https://bots.discord.pw/\"\n await self.post_payload(url, token)\n\n async def post_dbotsorg(self, doc):\n if not doc:\n return\n token = doc.get(\"dbotsorg_token\")\n if not token:\n return\n url = \"https://discordbots.org/\"\n await self.post_payload(url, token)\n\n async def post_stats(self):\n doc = await self.bot.database.get_cog_config(self)\n await self.post_dbotspw(doc)\n await self.post_dbotsorg(doc)\n\n async def on_ready(self):\n await self.post_stats()\n\n async def on_guild_remove(self, guild):\n await self.post_stats()\n\n async def on_guild_join(self, guild):\n await self.post_stats()\n\n\ndef setup(bot):\n cog = BotsDiscord(bot)\n bot.loop.create_task(\n bot.database.setup_cog(cog, {\n \"dbotsorg_token\": None,\n \"dbotspw_token\": None\n }))\n bot.add_cog(cog)\n","sub_path":"cogs/botsdiscord.py","file_name":"botsdiscord.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"191948516","text":"from datetime import datetime\n\nclass Spy:\n\n def __init__(self, name, salutation, age, rating):\n self.name = name\n self.salutation = salutation\n self.age = age\n self.rating = rating\n self.is_online = True\n self.chat = []\n self.current_status_message = None\n\nclass maintain: # class to maintain the words\n count = 1\n get = 0\n\n def __init__(self,text,):\n self.txt = text\n maintain.get = ( maintain.get + len(self.txt.split()) )/ maintain.count\n maintain.count += 1\n # print maintain.get\n\n\n\nclass ChatMessage:\n\n def __init__(self,message,sent_by_me):\n self.message = message\n self.time = datetime.now()\n self.sent_by_me = sent_by_me\n\n\nspy = Spy('Bond' , 'Mr.', 24, 4.7) # object of Spy class\n\nfriend_one = Spy('Jeff ', 'Mr.', 35, 7.9)\nfriend_two = Spy('Larry', 'Mr.', 20, 6.1)\nfriend_three = Spy('Steve', 'Mr.', 45, 8.7)\n\n\nfriends = [friend_one, friend_two, friend_three]","sub_path":"spy_details.py","file_name":"spy_details.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"622050418","text":"import os\nimport re\nimport time\nimport yaml\nimport requests\nimport shutil\nfrom .templates import expand_template, get_template_path\nfrom github import Github, GithubException\n\nGITHUB_TOKEN_PATTERN = re.compile('https://([^@]*)@?github.com/([^/]+)/.*git')\nGITLAB_TOKEN_PATTERN = re.compile('http://gitlab-ci-token:([^@]+)@(.*)\\.git')\n\n\ndef _download_yaml(url, headers={}):\n r = requests.get(url, headers=headers)\n try:\n return yaml.load(r.text)\n except:\n print('Error', url)\n return {}\n\n\ndef _get_distro_info(distros=None):\n info = {}\n main_url = os.environ['ROSDISTRO_INDEX_URL']\n folder = os.path.split(main_url)[0]\n D = _download_yaml(main_url)\n for distro_name, distro_info in D['distributions'].items():\n if distros is not None and distro_name not in distros:\n continue\n url_part = distro_info['distribution'][0]\n new_url = os.path.join(folder, url_part)\n info[distro_name] = _download_yaml(new_url)\n if distros is not None:\n remaining = set(distros) - set(info.keys())\n for distro in remaining:\n print('Warning! Distro \"{}\" not found.'.format(distro))\n return info\n\n\ndef _extract_token(distro_info):\n for distro, distro_data in distro_info.items():\n for name, d in distro_data['repositories'].items():\n if 'source' not in d:\n continue\n m = GITHUB_TOKEN_PATTERN.match(d['source'].get('url', ''))\n if m:\n if len(m.group(1)):\n return m.group(1)\n\n\ndef _get_package_info(g, distro_info, filter_packages=None):\n packages = {}\n cached_tracks = {}\n\n for distro, distro_data in distro_info.items():\n for name, d in distro_data['repositories'].items():\n if filter_packages and name not in filter_packages:\n continue\n if name not in packages:\n pkg = {}\n packages[name] = pkg\n else:\n pkg = packages[name]\n pkg[distro] = {}\n distro_d = pkg[distro]\n\n url = d.get('release', {}).get('url')\n if url and url[-4:] == '.git':\n if url in cached_tracks:\n tracks = cached_tracks[url]\n else:\n m = GITLAB_TOKEN_PATTERN.match(url)\n if m:\n headers = {'PRIVATE-TOKEN': m.group(1)}\n tracks_url = 'http://' + m.group(2) + '/raw/master/tracks.yaml'\n else:\n tracks_url = url[:-4] + '/raw/master/tracks.yaml'\n headers = {}\n tracks = _download_yaml(tracks_url, headers).get('tracks', {})\n cached_tracks[url] = tracks\n dtracks = tracks.get(distro, {})\n m = GITHUB_TOKEN_PATTERN.match(dtracks.get('vcs_uri', ''))\n if m:\n distro_d['org'] = m.group(2)\n upstream = dtracks.get('devel_branch')\n if upstream:\n distro_d['upstream'] = upstream\n release_tag = dtracks.get('release_tag')\n if release_tag == ':{ask}' and 'last_release' in dtracks:\n distro_d['last_release'] = dtracks['last_release']\n\n if 'source' in d:\n upstream = d['source'].get('version')\n if upstream:\n if 'upstream' in distro_d:\n if upstream != distro_d['upstream']:\n print('Package {} does not have matching upstream branches for {}. ({} vs. {})'\n .format(name, distro, upstream, distro_d['upstream']))\n else:\n distro_d['upstream'] = upstream\n\n if 'org' not in distro_d:\n m = GITHUB_TOKEN_PATTERN.match(d['source'].get('url', ''))\n if m:\n pkg[distro]['org'] = m.group(2)\n\n release = d.get('release', {}).get('version')\n if release:\n if '-' in release:\n release = release.partition('-')[0]\n distro_d['release'] = release\n return packages\n\n\ndef _get_package_status(g, name, branch_info):\n if 'org' not in branch_info:\n return ''\n elif 'upstream' not in branch_info:\n return 'NO SOURCE'\n elif 'release' not in branch_info:\n return 'NO RELEASE'\n repo = g.get_repo(branch_info['org'] + '/' + name)\n branch = branch_info.get('last_release', branch_info['release'])\n try:\n the_diff = repo.compare(branch, branch_info['upstream'])\n if len(the_diff.commits) > 0:\n return 'CHANGED'\n else:\n return 'BLOOMED'\n except GithubException as e:\n print('Error getting diff with repo {} between {}, {}'.format(name, branch, branch_info['upstream']))\n return 'BROKEN'\n\n\ndef _query_package_statuses(g, package_info):\n for pkg_name, info in package_info.items():\n for distro, d_info in info.items():\n status = _get_package_status(g, pkg_name, d_info)\n d_info['status'] = status\n\n\ndef build_bloom_status_page(packages=None, distros=None, output_dir='.'):\n start_time = time.time()\n print('Retrieving list of distros from ROSDISTRO_INDEX_URL')\n distro_info = _get_distro_info(distros)\n token = _extract_token(distro_info)\n if token:\n g = Github(token)\n else:\n g = Github()\n print('Retrieving package info')\n package_info = _get_package_info(g, distro_info, packages)\n print('Retrieving package statuses')\n _query_package_statuses(g, package_info)\n\n data = {\n 'start_time': start_time,\n 'start_time_local_str': time.strftime('%Y-%m-%d %H:%M:%S %z', time.localtime(start_time)),\n 'packages': package_info,\n 'distros': list(distro_info.keys())\n }\n\n output_filename = os.path.join(output_dir, 'bloom_status.html')\n print(\"Generating bloom status page '%s':\" % output_filename)\n template_name = 'status/bloom_status_page.html.em'\n html = expand_template(template_name, data)\n with open(output_filename, 'w') as h:\n h.write(html)\n for subfolder in ['css', 'js']:\n dst = os.path.join(output_dir, subfolder)\n if not os.path.exists(dst):\n src = get_template_path(os.path.join('status', subfolder))\n shutil.copytree(src, dst)\n","sub_path":"ros_buildfarm/bloom_status.py","file_name":"bloom_status.py","file_ext":"py","file_size_in_byte":6489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"552754923","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Dec 11 13:55:47 2018\r\n\r\n@author: 612383423\r\n\"\"\"\r\n### Mobile Data Bundle purchase program (from Module 2 chapter 8) with exceptions and validations\r\n\r\ndef DataBundlePurchase(truePasscode, balance):\r\n counter = 0\r\n if passwordCheck(truePasscode):\r\n while counter < 3:\r\n if counter == 0:\r\n answer=input('''\r\n Login successful. What do you want to do today? \r\n Press 1 to view your credit balance\r\n Press 2 to purchase data\r\n Press 3 to top up your account.\r\n \r\n ''')\r\n else: \r\n answer = input(\"Please, try again: \")\r\n if answer == '1': \r\n return checkBalance(balance)\r\n elif answer =='2': \r\n if checkNumber():\r\n return buyData(balance)\r\n else:\r\n return 'Sorry, your phone number is not valid.'\r\n elif answer == '3':\r\n return topupBalance(balance)\r\n elif checkType(answer, \"1, 2 or 3\") or checkLength(answer, 1):\r\n counter += 1\r\n else:\r\n counter += 1 \r\n return('locked out after 3 attempts') \r\n else: \r\n return 'locked out after 3 attempts'\r\n \r\n \r\ndef passwordCheck(truePasscode): \r\n counter = 0\r\n while counter < 3:\r\n try:\r\n attempt = (input('Please enter your 4-digit password: '))\r\n if attempt == truePasscode:\r\n return True\r\n elif checkType(attempt, \"numbers\") or checkLength(attempt, 4):\r\n counter += 1\r\n else:\r\n counter += 1\r\n raise EOFError\r\n except EOFError:\r\n print(\"Sorry, that doesn't match our records.\")\r\n continue # This causes it to continue\r\n return False\r\n\r\ndef checkLength(answer, length):\r\n try:\r\n if len(answer)!= length:\r\n raise ValueError\r\n except ValueError:\r\n print(\"Required number of digits: {}.\".format(length))\r\n return True \r\n return False\r\n\r\ndef checkType(answer, requirement):\r\n try:\r\n if not answer.isdigit():\r\n raise TypeError\r\n except TypeError:\r\n print(\"Type {} only please.\".format(requirement))\r\n return True \r\n return False\r\n\r\ndef checkBalance(balance):\r\n if balance > 0:\r\n return ( 'Your balance is £{}'.format(balance))\r\n else: \r\n return ('Your balance is insufficient: £{}'.format(balance))\r\n \r\n \r\ndef checkNumber(): \r\n counter = 0\r\n while counter < 3:\r\n try:\r\n phone_number = input('Please enter your phone number: ')\r\n if checkType(phone_number, \"numbers\") or checkLength(phone_number, 2):\r\n counter += 1\r\n else:\r\n confirm_number = input ('Thanks. Please enter your number again to confirm: ')\r\n if phone_number == confirm_number:\r\n return True\r\n else: \r\n counter2 = 0\r\n while counter2 < 3:\r\n reconfirm_number = input('The number is not matching. Please, try again.')\r\n if reconfirm_number == phone_number:\r\n return True\r\n else:\r\n counter2 += 1\r\n return False\r\n except EOFError:\r\n print(\"Sorry, that doesn't match our records.\")\r\n continue # This causes it to continue\r\n return False\r\n \r\ndef buyData(balance):\r\n print('\\nThanks for confirming your number. Your current balance is £{}'.format(balance))\r\n print('\\nAs you can only purchase in multiples of £5, the max you can spend is...')\r\n highest_price(balance)\r\n user_pays = (input('How much do you want to spend on data? multiples of £5 only, please: '))\r\n counter = 1\r\n while counter < 3:\r\n try:\r\n if checkType(user_pays, 'amount'):\r\n counter += 1\r\n elif float(user_pays) > float(balance):\r\n counter += 1\r\n raise Exception\r\n elif (int(user_pays)%5)!=0:\r\n counter += 1\r\n raise ArithmeticError\r\n else: \r\n new_balance = float(balance)-float(user_pays)\r\n new_balance_2dp = round(new_balance, 2)\r\n return ('Purchase successful! Your new balance is £{}'.format(new_balance_2dp))\r\n except ArithmeticError:\r\n print('Sorry, the amount you requested is not a multiple of £5.')\r\n except Exception:\r\n print('Sorry, you don\\'t have enough money to purchase. The max you can spend is:')\r\n highest_price(balance)\r\n user_pays = (input('How much do you want to spend on data? multiples of £5 only, please: '))\r\n return 'locked out after 3 attempts'\r\n \r\ndef highest_price(balance):\r\n int_balance = int(balance)\r\n for i in range (int_balance-5,int_balance):\r\n if(i%5==0):\r\n max = i\r\n print ('£',max)\r\n return\r\n \r\ndef topupBalance (balance):\r\n user_topup = (input('Your current balance is £{}. How much do you want to top up? multiples of £5 only, please: '.format(balance)))\r\n counter = 1\r\n while counter < 3:\r\n try:\r\n if checkType(user_topup, 'amount'):\r\n counter += 1\r\n elif (int(user_topup)%5)!=0:\r\n counter += 1\r\n raise ArithmeticError\r\n else: \r\n new_topup_balance = float(balance)+float(user_topup)\r\n new_topup_balance_2dp = round(new_topup_balance, 2)\r\n return ('Purchase successful! Your new balance is £{}'.format(new_topup_balance_2dp))\r\n except ArithmeticError:\r\n print('Sorry, the amount you requested is not a multiple of £5.')\r\n user_topup = (input('Your current balance is £{}. How much do you want to top up? multiples of £5 only, please: '.format(balance)))\r\n return 'locked out after 3 attempts'\r\n","sub_path":"ch02_validation/data_bundle_functions.py","file_name":"data_bundle_functions.py","file_ext":"py","file_size_in_byte":6155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"101150062","text":"# task1-------------------------------------------------------------------------\r\n\"\"\"\r\n\r\nУмова: Дано два цілих числа. Вивести найменше з них.\r\n\r\nВхідні дані: користувач вводить ціле число\r\n\r\nВихідні дані: вивести ціле число\r\n\"\"\"\r\n# Програма для виводу меншого числа\r\n# a,b - цілі числа для порівняня\r\na = int(input())\r\nb = int(input())\r\n# Порівняня чисел\r\nif a < b:\r\n print(a)\r\nelse:\r\n print(b)\r\n# ------------------------------------------------------------------------------\r\n\r\n\r\n# task2-------------------------------------------------------------------------\r\n\"\"\"\r\n\r\nУмова: Вивести результат функції sign(x), що визначається наступним чином: \r\nsign(x) = 1, if x > 0, \r\nsign(x) = -1, if x < 0, \r\nsign(x) = 0, if x = 0..\r\n\r\nВхідні дані: користувач вводить дійсне число.\r\n\r\nВихідні дані: вивести результат sign.\r\n\"\"\"\r\n# Програма для визначення мат. функції sign\r\n# sign - число для перевірки\r\nsign = int(input())\r\n# перевірка на число додатнє\r\nif sign > 0:\r\n print(1)\r\n# перевірка на чило відємне\r\nelif sign < 0:\r\n print(-1)\r\n# перевірка чи дорівнює 0\r\nelse:\r\n print(0)\r\n# ------------------------------------------------------------------------------\r\n\r\n\r\n# task3-------------------------------------------------------------------------\r\n\"\"\"\r\n\r\nУмова: Дано три цілих числа. Вивести найменше з них.\r\n\r\nВхідні дані: 3 цілих числа. Кожне число користувач вводить в окремому рядку.\r\n\r\nВихідні дані: вивести ціле число\r\n\"\"\"\r\n# Програма для знаходження меншого числа\r\n# number1,number2,number3 - цілі числа\r\nnumber1 = int(input())\r\nnumber2 = int(input())\r\nnumber3 = int(input())\r\n# перевірка\r\nif (number1 < number2) and (number2 < number3):\r\n print(number1)\r\nelif (number1 < number3) and (number3 < number2):\r\n print(number1)\r\nelif (number2 < number1) and (number1 < number3):\r\n print(number2)\r\nelif (number2 < number3) and (number3 < number1):\r\n print(number2)\r\nelif (number3 < number1) and (number1 < number2):\r\n print(number3)\r\nelif (number3 < number2) and (number2 < number1):\r\n print(number3)\r\nelif (number1 == number2) and (number1 < number3):\r\n print(number1)\r\nelif (number1 == number3) and (number1 < number2):\r\n print(number1)\r\nelif (number3 == number2) and (number3 < number1):\r\n print(number2)\r\nelse:\r\n print(number1)\r\n\r\n# ------------------------------------------------------------------------------\r\n\r\n\r\n# task4-------------------------------------------------------------------------\r\n\"\"\"\r\n\r\nЗадача №4 \r\n\r\nУмова: Дано ціле число, що визначає рік. Визначити, чи є вказаний рік \r\nвисокосним. Якщо так, то вивести користувачу \"LEAP\", в іншому випадку – \r\n\"СOMMON\".\r\n\r\nРік високосний, якщо виконується хоча б одна з умов:\r\n\r\nрік завжди високосним, якщо його номер ділиться на 4 без остачі і не ділиться \r\nбез остачі на 100\r\nрік завжди високосним, якщо його номер ділиться на 400 без остачі\r\n\r\nВхідні дані: ціле число, що вводить користувач\r\n\r\nВихідні дані: вивести текстовий рядок.\r\n\"\"\"\r\n# Програма для визначення чи високосний рік\r\n# year - заданий рік\r\nyear = int(input())\r\n# перевірка на високосність\r\nif year % 400 == 0:\r\n print(\"LEAP\")\r\nelif (year % 4 == 0) and (year % 100 != 0):\r\n print(\"LEAP\")\r\nelse:\r\n print(\"COMMON\")\r\n\r\n# ------------------------------------------------------------------------------\r\n\r\n\r\n# task5-------------------------------------------------------------------------\r\n\"\"\"\r\n\r\nУмова: Дано три цілих числа. Визначте, скільки з них дорівнюють один одному. \r\nПрограма повинна виводити одне з чисел: 3 (якщо всі числа однакові), 2 (якщо \r\nдва з них дорівнюють один одному, а третє відрізняється) або 0 (якщо всі числа \r\nрізні).\r\n\r\nВхідні дані: 3 цілих числа. Кожне число користувач вводить в окремому рядку.\r\n\r\nВихідні дані: вивести ціле число\r\n\"\"\"\r\n# прогрма для визначеня кількості однакових чисел\r\n# number1,number2,nember3 - цілі числа\r\nnumber1 = int(input())\r\nnumber2 = int(input())\r\nnumber3 = int(input())\r\n# визначеня кількості однакових чисел\r\nif (number1 == number2) and (number2 == number3):\r\n print(3)\r\nelif (number1 == number2) or (number2 == number3) or (number1 == number3):\r\n print(2)\r\nelse:\r\n print(0)\r\n\r\n# ------------------------------------------------------------------------------\r\n\r\n\r\n# task6-------------------------------------------------------------------------\r\n\"\"\"\r\n\r\nУмова: Шахова тура переміщається по горизонталі або по вертикалі. Дано координа \r\nти двох клітин шахової дошки. Визначити, чи може тура перейти з першої клітини \r\nу другу за один хід. Користувач вводить чотири цілих числа від 1 до 8, кожне з \r\nяких визначає номер рядку та стовпчика клітини. Перші два числа - для першої \r\nклітини, останні два числа – для другої. Програма має вивести \"YES\", якщо тура \r\nможе виконати переміщення, або \"NO\" в іншому випадку.\r\n\r\nВхідні дані: 4 цілих числа. Кожне число користувач вводить в окремому рядку.\r\n\r\nВихідні дані: вивести текстовий рядок.\r\n\"\"\"\r\n# Програма для визначеня можливости ходу тури\r\n# Ввід координат початкової точки\r\nx1 = int(input())\r\ny1 = int(input())\r\n# Ввід координат кінцевої точки\r\nx2 = int(input())\r\ny2 = int(input())\r\n# Перевірка на можливість ходу\r\nif (x1 == x2) or (y1 == y2):\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\r\n# ------------------------------------------------------------------------------\r\n\r\n\r\n# task7-------------------------------------------------------------------------\r\n\"\"\"\r\nУмова: Дано координати двох клітин шахової дошки. Визначити, чи однакового вони\r\nкольору. Користувач вводить чотири цілих числа від 1 до 8, кожне з яких \r\nвизначає номер рядку та стовпчика клітини. Перші два числа - для першої \r\nклітини, останні два числа – ��ля другої. Програма має вивести \"YES\", якщо \r\nколір однаковий, або \"NO\" в іншому випадку.\r\n\r\nВхідні дані: 4 цілих числа. Кожне число користувач вводить в окремому рядку.\r\n\r\nВихідні дані: вивести текстовий рядок.\r\n\"\"\"\r\n# Програма для визначення однаковості кольору клітинок\r\n# Запис перших координат\r\nx1 = int(input())\r\ny1 = int(input())\r\n# Запис других координат\r\nx2 = int(input())\r\ny2 = int(input())\r\n# Якщо остача від ділення однакова то клітинки одного кольору\r\nif ((x1 - x2) % 2 == (y1 - y2) % 2):\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\r\n# ------------------------------------------------------------------------------\r\n\r\n\r\n# task8-------------------------------------------------------------------------\r\n\"\"\"\r\n\r\nУмова: Шаховий король переміщується по горизонталі, по вертикалі або по \r\nдіагоналі на будь-яку сусідню клітинку. Дано координати двох клітин шахової \r\nдошки. Визначити, чи може король перейти з першої клітини у другу за один хід. \r\nКористувач вводить чотири цілих числа від 1 до 8, кожне з яких визначає номер \r\nрядку та стовпчика клітини. Перші два числа - для першої клітини, останні два \r\nчисла – для другої. Програма має вивести \"YES\", якщо хід можливий, або \"NO\" в \r\nіншому випадку.\r\n\r\nВхідні дані: 4 цілих числа. Кожне число користувач вводить в окремому рядку.\r\n\r\nВихідні дані: вивести текстовий рядок.\r\n\"\"\"\r\n# Програма на можливість ходу короля\r\n# координата початку\r\nx1 = int(input())\r\ny1 = int(input())\r\n# Координата закінчення\r\nx2 = int(input())\r\ny2 = int(input())\r\n# Перевірка можливості\r\nif (x1 == x2 + 1) and ((y1 == y2 + 1) or (y1 == y2 - 1) or (y1 == y2)):\r\n print(\"YES\")\r\nelif (x1 == x2 - 1) and ((y1 == y2 - 1) or (y1 == y2 + 1) or (y1 == y2)):\r\n print(\"YES\")\r\nelif (x1 == x2) and ((y1 == y2 - 1) or (y1 == y2 + 1)):\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\r\n\r\n# ------------------------------------------------------------------------------\r\n\r\n\r\n# task9-------------------------------------------------------------------------\r\n\"\"\"\r\nУмова: Шаховий слон рухається по діагоналі на будь-яку кількість клітин. Дано \r\nкоординати двох клітин шахової дошки. Визначити, чи може слон перейти з першої \r\nклітини у другу за один хід. Користувач вводить чотири цілих числа від 1 до 8, \r\nкожне з яких визначає номер рядку та стовпчика клітини. Перші два числа - для \r\nпершої клітини, останні два числа – для другої. Програма має вивести \"YES\", \r\nякщо хід можливий, або \"NO\" в іншому випадку.\r\n\r\nВхідні дані: 4 цілих числа. Кожне число користувач вводить в окремому рядку.\r\n\r\nВихідні дані: вивести текстовий рядок.\r\n\"\"\"\r\n# Програма для перевірки можливості можливості ходу слона\r\n# Координати почадку ходу\r\nx1 = int(input())\r\ny1 = int(input())\r\n# Координати закінчення ходу\r\nx2 = int(input())\r\ny2 = int(input())\r\n# Перевірка можливості\r\nif abs(x2 - x1) == abs(y2 - y1):\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\r\n\r\n# ------------------------------------------------------------------------------\r\n\r\n\r\n# task10------------------------------------------------------------------------\r\n\"\"\"\r\n\r\nУмова: Шахова королева рухається по горизонталі, по вертикалі або по діагоналі \r\nна будь-яку кількість клітин. Дано координати двох клітин шахової дошки. \r\nВизначити, чи може королева перейти з першої клітини у другу за один хід. \r\nКористувач вводить чотири цілих числа від 1 до 8, кожне з яких визначає номер \r\nрядку та стовпчика клітини. Перші два числа - для першої клітини, останні два \r\nчисла – для другої. Програма має вивести \"YES\", якщо хід можливий, або \"NO\" в \r\nіншому випадку.\r\n\r\nВхідні дані: 4 цілих числа. Кожне число користувач вводить в окремому рядку.\r\n\r\nВихідні дані: вивести текстовий рядок.\r\n\"\"\"\r\nx1 = int(input())\r\n\r\ny1 = int(input())\r\n\r\nx2 = int(input())\r\n\r\ny2 = int(input())\r\n\r\nif x2 - x1 == y2 - y1:\r\n\r\n print(\"YES\")\r\n\r\nelif x2 - x1 == y1 - y2:\r\n\r\n print(\"YES\")\r\n\r\nelif (x1 == x2) or (y1 == y2):\r\n\r\n print(\"YES\")\r\n\r\nelse:\r\n\r\n print(\"NO\")\r\n\r\n# ------------------------------------------------------------------------------\r\n\r\n\r\n# task11------------------------------------------------------------------------\r\n\"\"\"\r\n\r\nУмова: Шаховий кінь рухається як літера L. Він може переміщатись на дві \r\nклітинки по горизонталі і одну клітинку по вертикалі або на дві клітинки по \r\nвертикалі і одну по горизонталі. Дано координати двох клітин шахової дошки. \r\nВизначити, чи може кінь перейти з першої клітини у другу за один хід. \r\nКористувач вводить чотири цілих числа від 1 до 8, кожне з яких визначає номер \r\nрядку та стовпчика клітини. Перші два числа - для першої клітини, останні два \r\nчисла – для другої. Програма має вивести \"YES\", якщо хід можливий, або \"NO\" в \r\nіншому випадку.\r\n\r\nВхідні дані: 4 цілих числа. Кожне число користувач вводить в окремому рядку.\r\n\r\nВихідні дані: вивести текстовий рядок.\r\n\"\"\"\r\n# Програма для перевірки можливості ходу коня\r\n# Координати початку ходу\r\nx1 = int(input())\r\ny1 = int(input())\r\n# Координати початку ходу\r\nx2 = int(input())\r\ny2 = int(input())\r\n# Перевірка ходу\r\nif ((x1 == x2 + 2) or (x1 == x2 - 2)) and ((y1 == y2 + 1) or (y1 == y2 - 1)):\r\n print(\"YES\")\r\nelif ((x1 == x2 + 1) or (x1 == x2 - 1)) and ((y1 == y2 + 2) or (y1 == y2 - 2)):\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\r\n\r\n# ------------------------------------------------------------------------------\r\n\r\n\r\n# task12------------------------------------------------------------------------\r\n\"\"\"\r\n\r\nУмова: Шоколад має форму прямокутника, розділеного на n?m клітин. Шоколад може \r\nбути розділений на дві частини тільки по горизонталі або по вертикалі, при \r\nцьому клітини мають бути цілими. Визначити, чи можна розділити шоколад за один \r\nкрок таким чином, щоб одна з частин матиме точно k клітин. Програма має \r\nвивести \"YES\", якщо шоколад можна поділити, або \"NO\" в іншому випадку.\r\n\r\nВхідні дані: 3 цілих числа: n,m, k. Кожне число користувач вводить в окремому \r\nрядку.\r\n\r\nВихідні дані: вивести текстовий рядок.\r\n\"\"\"\r\n# Програма на можливість поділу шоколадки на 2 частини\r\n# Шоколадка розміром n на m\r\nn = int(input())\r\nm = int(input())\r\n# Площу неохыдної частини\r\nk = int(input())\r\n# Перевірка\r\nif (k % n == 0) and (k < n * m):\r\n print(\"YES\")\r\nelif (k % m == 0) and (k < n * m):\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\r\n\r\n # ------------------------------------------------------------------------------\r\n","sub_path":"students/km61/Xarchenko_Kateryna/homework_2.py","file_name":"homework_2.py","file_ext":"py","file_size_in_byte":16957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"602366778","text":"\"\"\"Utilities for testing Lux applications\n\"\"\"\nimport os\nimport unittest\nimport string\nimport logging\nimport json\nfrom unittest import mock\nfrom urllib.parse import urlparse, urlunparse\nfrom io import StringIO\n\nfrom pulsar import get_event_loop\nfrom pulsar.utils.httpurl import (Headers, encode_multipart_formdata,\n ENCODE_BODY_METHODS)\nfrom pulsar.utils.string import random_string\nfrom pulsar.utils.websocket import (SUPPORTED_VERSIONS, websocket_key,\n frame_parser)\nfrom pulsar.apps.wsgi import WsgiResponse\nfrom pulsar.apps.test import test_timeout, sequential # noqa\n\nimport lux\nfrom lux.extensions.rest.client import LocalClient, Response\nfrom lux.core.commands.generate_secret_key import generate_secret\nlogger = logging.getLogger('lux.test')\n\n\ndef randomname(prefix=None, len=8):\n \"\"\"Generate a random name with a prefix (default to ``luxtest-``)\n \"\"\"\n prefix = prefix if prefix is not None else 'luxtest-'\n name = random_string(min_len=len, max_len=len,\n characters=string.ascii_letters)\n return ('%s%s' % (prefix, name)).lower()\n\n\ndef green(test_fun):\n \"\"\"Decorator to run a test function in the lux application green_pool\n if available, otherwise in the event loop executor.\n\n In both cases it returns a :class:`~asyncio.Future`.\n\n This decorator should not be used for functions returning a coroutine\n or a :class:`~asyncio.Future`.\n \"\"\"\n def _(o):\n try:\n pool = o.app.green_pool\n except AttributeError:\n pool = None\n if pool:\n return pool.submit(test_fun, o)\n else:\n loop = get_event_loop()\n return loop.run_in_executor(None, test_fun, o)\n\n return _\n\n\ndef test_app(test, config_file=None, config_params=True, argv=None, **params):\n \"\"\"Return an application for testing. Override if needed.\n \"\"\"\n if config_params:\n kwargs = test.config_params.copy()\n kwargs.update(params)\n if 'SECRET_KEY' not in kwargs:\n kwargs['SECRET_KEY'] = generate_secret()\n if 'PASSWORD_SECRET_KEY' not in kwargs:\n kwargs['PASSWORD_SECRET_KEY'] = generate_secret()\n else:\n kwargs = params\n config_file = config_file or test.config_file\n if argv is None:\n argv = []\n if '--log-level' not in argv:\n argv.append('--log-level')\n levels = test.cfg.loglevel if hasattr(test, 'cfg') else ['none']\n argv.extend(levels)\n app = lux.App(config_file, argv=argv, **kwargs).setup()\n app.stdout = StringIO()\n app.stderr = StringIO()\n return app\n\n\ndef get_params(*names):\n cfg = {}\n for name in names:\n value = os.environ.get(name)\n if value:\n cfg[name] = value\n else:\n return\n return cfg\n\n\nclass TestClient:\n \"\"\"An utility for simulating lux clients\n \"\"\"\n def __init__(self, app, headers=None):\n self.app = app\n self.headers = headers or []\n\n def run_command(self, command, argv=None, **kwargs):\n argv = argv or []\n cmd = self.app.get_command(command)\n return cmd(argv, **kwargs)\n\n def request_start_response(self, method, path, HTTP_ACCEPT=None,\n headers=None, body=None, content_type=None,\n token=None, cookie=None, **extra):\n method = method.upper()\n extra['REQUEST_METHOD'] = method.upper()\n path = path or '/'\n extra['HTTP_ACCEPT'] = HTTP_ACCEPT or '*/*'\n extra['pulsar.connection'] = mock.MagicMock()\n heads = self.headers[:]\n if headers:\n heads.extend(headers)\n if content_type:\n heads.append(('content-type', content_type))\n if token:\n heads.append(('Authorization', 'Bearer %s' % token))\n if cookie:\n heads.append(('Cookie', cookie))\n\n # Encode body\n if (method in ENCODE_BODY_METHODS and body is not None and\n not isinstance(body, bytes)):\n content_type = Headers(heads).get('content-type')\n if content_type is None:\n body, content_type = encode_multipart_formdata(body)\n heads.append(('content-type', content_type))\n elif content_type == 'application/json':\n body = json.dumps(body).encode('utf-8')\n\n request = self.app.wsgi_request(path=path, headers=heads, body=body,\n extra=extra)\n start_response = mock.MagicMock()\n return request, start_response\n\n def request(self, method, path, **params):\n request, sr = self.request_start_response(method, path, **params)\n yield from self.app(request.environ, sr)\n return request\n\n def get(self, path=None, **extra):\n return self.request('get', path, **extra)\n\n def post(self, path=None, **extra):\n return self.request('post', path, **extra)\n\n def put(self, path=None, **extra):\n return self.request('put', path, **extra)\n\n def delete(self, path=None, **extra):\n return self.request('delete', path, **extra)\n\n def options(self, path=None, **extra):\n return self.request('options', path, **extra)\n\n def head(self, path=None, **extra):\n return self.request('head', path, **extra)\n\n def wsget(self, path):\n \"\"\"make a websocket request\"\"\"\n headers = [('Connection', 'Upgrade'),\n ('Upgrade', 'websocket'),\n ('Sec-WebSocket-Version', str(max(SUPPORTED_VERSIONS))),\n ('Sec-WebSocket-Key', websocket_key())]\n return self.get(path, headers=headers)\n\n\nclass TestMixin:\n config_file = 'tests.config'\n \"\"\"The config file to use when building an :meth:`application`\"\"\"\n config_params = {}\n \"\"\"Dictionary of parameters to override the parameters from\n :attr:`config_file`\"\"\"\n prefixdb = 'luxtest_'\n\n def authenticity_token(self, doc):\n name = doc.find('meta', attrs={'name': 'csrf-param'})\n value = doc.find('meta', attrs={'name': 'csrf-token'})\n if name and value:\n name = name.attrs['content']\n value = value.attrs['content']\n return {name: value}\n\n def cookie(self, response):\n \"\"\"Extract a cookie from the response if available\n \"\"\"\n headers = response.get_headers()\n return dict(headers).get('Set-Cookie')\n\n def bs(self, response, status_code=None, mode=None):\n \"\"\"Return a BeautifulSoup object from the ``response``\n \"\"\"\n from bs4 import BeautifulSoup\n return BeautifulSoup(self.html(response, status_code),\n 'html.parser')\n\n def html(self, response, status_code=None):\n \"\"\"Get html/text content from response\n \"\"\"\n if status_code:\n self.assertEqual(response.status_code, status_code)\n self.assertEqual(response.content_type,\n 'text/html; charset=utf-8')\n return self._content(response).decode('utf-8')\n\n def text(self, response, status_code=None):\n \"\"\"Get JSON object from response\n \"\"\"\n if status_code:\n self.assertEqual(response.status_code, status_code)\n self.assertEqual(response.content_type,\n 'text/plain; charset=utf-8')\n return self._content(response).decode('utf-8')\n\n def json(self, response, status_code=None):\n \"\"\"Get JSON object from response\n \"\"\"\n if status_code:\n self.assertEqual(response.status_code, status_code)\n self.assertEqual(response.content_type,\n 'application/json; charset=utf-8')\n return json.loads(self._content(response).decode('utf-8'))\n\n def ws_upgrade(self, response):\n from lux.extensions.sockjs import LuxWs\n self.assertEqual(response.status_code, 101)\n #\n connection = response.connection\n upgrade = connection.upgrade\n self.assertTrue(upgrade.called)\n websocket = upgrade.call_args[0][0](get_event_loop())\n connection.reset_mock()\n #\n self.assertIsInstance(websocket.handler, LuxWs)\n websocket._connection = response.connection\n websocket.connection_made(response.connection)\n self.assertTrue(websocket.cache.wsclient)\n websocket.cache.wsclient.logger = mock.MagicMock()\n return websocket\n\n def ws_message(self, **params):\n msg = json.dumps(params)\n return json.dumps([msg])\n\n def get_ws_message(self, websocket):\n mock = websocket.connection.write\n self.assertTrue(mock.called)\n frame = mock.call_args[0][0]\n return self.parse_frame(websocket, frame)\n\n def parse_frame(self, websocket, frame):\n parser = frame_parser(kind=1)\n frame = parser.decode(frame)\n wsclient = websocket.cache.wsclient\n websocket.connection.reset_mock()\n msg = json.loads(frame.body[1:])[0]\n return wsclient.protocol.decode(msg)\n\n def assertValidationError(self, response, field=None, text=None):\n \"\"\"Assert a Form validation error\n \"\"\"\n if isinstance(response, WsgiResponse):\n self.assertEqual(response.status_code, 422)\n data = self.json(response)\n else:\n data = response\n if field is not None:\n errors = data['errors']\n self.assertTrue(errors)\n data = dict(((d.get('field', ''), d['message']) for d in errors))\n self.assertTrue(field in data)\n if text:\n self.assertEqual(data[field], text)\n elif text:\n self.assertEqual(data['message'], text)\n self.assertTrue(data['error'])\n\n def check_og_meta(self, bs, type=None, image=None):\n meta = bs.find('meta', property='og:type')\n self.assertEqual(meta['content'], type or 'website')\n #\n if image:\n meta = bs.find('meta', property='og:image')\n self.assertEqual(meta['content'], image)\n\n def _content(self, response):\n return b''.join(response.content)\n\n\nclass TestCase(unittest.TestCase, TestMixin):\n \"\"\"TestCase class for lux tests.\n\n It provides several utilities methods.\n \"\"\"\n apps = None\n\n def application(self, **params):\n \"\"\"Return an application for testing. Override if needed.\n \"\"\"\n app = test_app(self, **params)\n if self.apps is None:\n self.apps = []\n self.apps.append(app)\n return app\n\n def fetch_command(self, command, app=None):\n \"\"\"Fetch a command.\"\"\"\n if not app:\n app = self.application()\n cmd = app.get_command(command)\n self.assertTrue(cmd.logger)\n self.assertEqual(cmd.name, command)\n return cmd\n\n\nclass AppTestCase(unittest.TestCase, TestMixin):\n \"\"\"Test class for testing a single aaplication\n \"\"\"\n odm = None\n \"\"\"Original odm handler\"\"\"\n app = None\n\n @classmethod\n def setUpClass(cls):\n # Create the application\n cls.dbs = {}\n cls.app = cls.create_test_application()\n cls.client = TestClient(cls.app)\n if hasattr(cls.app, 'odm'):\n # Store the original odm for removing the new databases\n cls.odm = cls.app.odm\n return cls.setupdb()\n\n @classmethod\n def tearDownClass(cls):\n if cls.odm:\n return cls.dropdb()\n\n @classmethod\n def create_test_application(cls):\n \"\"\"Return the lux application\"\"\"\n return test_app(cls)\n\n @classmethod\n def dbname(cls, engine):\n if engine not in cls.dbs:\n cls.dbs[engine] = randomname(cls.prefixdb)\n return cls.dbs[engine]\n\n @classmethod\n @green\n def setupdb(cls):\n cls.app.odm = cls.odm.database_create(database=cls.dbname)\n odm = cls.app.odm()\n DATASTORE = cls.app.config['DATASTORE']\n if not isinstance(DATASTORE, dict):\n DATASTORE = {'default': DATASTORE}\n # Replace datastores\n datastore = {}\n for original_engine, database in cls.dbs.items():\n orig_url = str(original_engine.url)\n for engine in odm.engines():\n if engine.url.database == database:\n new_url = str(engine.url)\n for key, url in DATASTORE.items():\n if url == orig_url:\n datastore[key] = new_url\n cls.app.config['DATASTORE'] = datastore\n odm.table_create()\n cls.populatedb()\n\n @classmethod\n @green\n def dropdb(cls):\n cls.app.odm().close()\n cls.odm().database_drop(database=cls.dbname)\n\n @classmethod\n def populatedb(cls):\n pass\n\n def create_superuser(self, username, email, password):\n \"\"\"A shortcut for the create_superuser command\n \"\"\"\n return self.client.run_command('create_superuser',\n ['--username', username,\n '--email', email,\n '--password', password])\n\n\nclass TestApiClient(TestClient):\n \"\"\"Api client test handler\n \"\"\"\n def request(self, method, path, data=None, **params):\n \"\"\"Override :meth:`TestClient.request` for testing Api clients\n inside a lux application\n \"\"\"\n path = urlunparse(('', '') + tuple(urlparse(path))[2:])\n params['body'] = data\n request, sr = self.request_start_response(method, path, **params)\n response = self.app(request.environ, sr)\n green_pool = self.app.green_pool\n response = green_pool.wait(response, True) if green_pool else response\n return Response(response)\n\n\nclass WebApiTestCase(AppTestCase):\n \"\"\"Test case for an api-web application pair\n \"\"\"\n web_config_file = None\n\n @classmethod\n def setUpClass(cls):\n assert cls.web_config_file, \"no web_config_file specified\"\n yield from super().setUpClass()\n cls.web = test_app(cls, config_file=cls.web_config_file,\n config_params=False)\n api = cls.web.api\n http = api.http(cls.web)\n assert not isinstance(http, LocalClient), \"API_URL not an absolute url\"\n http = TestApiClient(cls.app, list(http.headers))\n api._http = http\n assert api.http(cls.web) == http\n cls.webclient = TestClient(cls.web)\n\n def check_html_token(self, doc, token):\n value = doc.find('meta', attrs={'name': 'user-token'})\n if value:\n self.assertEqual(value.attrs['content'], token)\n else:\n raise ValueError('user-token meta tag not available')\n","sub_path":"lux/utils/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":14762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"650702916","text":"# coding=utf-8\r\n\r\n\r\nclass Joueur():\r\n \"\"\"Classe Joueur\r\n\r\n Deux joueurs sont créés et positionnés aux extrémités du plateau de jeu.\r\n \"\"\"\r\n\r\n def __init__(self, name, pawn, finishline, phasenumber, y, x):\r\n \"\"\"Constructeur de la classe Joueur\r\n\r\n Un joueur possède:\r\n - un nom permettant de le distinguer,\r\n - un pion permettant de suivre ses déplacements,\r\n - une ligne d'arrivee à franchir pour gagner,\r\n - une position x (colonne),\r\n - une position y (ligne),\r\n - un nombre de mur à poser.\r\n \"\"\"\r\n\r\n self.nom = name\r\n self.pion = pawn\r\n self.arrivee = finishline\r\n self.posY = y\r\n self.posX = x\r\n self.nbMurs = 10\r\n\r\n # Compteur de phases\r\n self.numerophase = phasenumber\r\n\r\n def retraitMur(self):\r\n \"\"\"Méthode retraitMur\r\n\r\n Décrémente le stock des murs à poser du joueur.\r\n \"\"\"\r\n\r\n self.nbMurs -= 1\r\n print(\"Joueur \", self.pion, \", il vous reste \", self.nbMurs, \" murs.\")\r\n","sub_path":"projet/games/Quoridor/Joueur.py","file_name":"Joueur.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"187643302","text":"import pygame\nimport random\nimport math\nfrom pygame import mixer\n\n\ndef game_loop():\n pygame.init()\n\n screen = pygame.display.set_mode((800, 600))\n\n background = pygame.image.load('./res/city_background.png')\n\n mixer.music.load(\"./res/background_game_music.wav\")\n\n mixer.music.play(-1)\n\n person = pygame.image.load('./res/person.png')\n personX = 336\n personY = 480\n personX_change = 0\n\n missile = []\n missileX = []\n missileY = []\n missileY_change = []\n num_of_missiles = 15\n\n for i in range(num_of_missiles):\n missile.append(pygame.image.load('./res/missile.png'))\n missileX.append(random.randint(0, 700))\n missileY.append(-10)\n missileY_change.append(2)\n\n def print_person():\n screen.blit(person, (personX, personY))\n\n def print_missile(x, y, i):\n screen.blit(missile[i], (x, y))\n\n def collision_cheak(missileX, missileY, personX, personY):\n distance = math.sqrt((math.pow(missileX - personX, 2) + (math.pow(missileY - personY, 2))))\n\n if distance <= 27:\n return True\n else:\n return False\n\n game_over = pygame.font.Font('freesansbold.ttf', 45)\n fontX = 5\n fontY = 270\n\n def print_game_over():\n game_over_ = game_over.render(\"GAME OVER! Press Enter to restart\", True, (0, 0, 0))\n screen.blit(game_over_, (fontX, fontY))\n\n score = 0\n score_font = pygame.font.Font('./res/font.ttf', 32)\n score_fontX = 10\n score_fontY = 10\n\n def print_score():\n score_render = score_font.render(\"Score: \" + str(score), True, (0, 0, 0))\n screen.blit(score_render, (score_fontX, score_fontY))\n\n hiscore_font = pygame.font.Font('./res/font.ttf', 32)\n hiscore_fontX = 610\n hiscore_fontY = 10\n\n def print_hiscore():\n hiscore_render = hiscore_font.render(\"Hiscore: \" + str(hiscore), True, (0, 0, 0))\n screen.blit(hiscore_render, (hiscore_fontX, hiscore_fontY))\n\n with open(\"./res/Hiscore_Manager_Tackle_Missile.txt\", \"r\") as f:\n hiscore = f.read()\n\n game__over = False\n running = True\n\n while running:\n if game__over:\n with open(\"./res/Hiscore_Manager_Tackle_Missile.txt\", \"w\") as f:\n f.write(str(hiscore))\n screen.blit(background, (0, 0))\n print_game_over()\n print_hiscore()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RETURN:\n game_loop()\n else:\n screen.blit(background, (0, 0))\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RIGHT:\n personX_change = 3\n elif event.key == pygame.K_LEFT:\n personX_change = -3\n\n if personX >= 736:\n game__over = True\n\n elif personX <= 0:\n game__over = True\n\n elif score > int(hiscore):\n hiscore = score\n for i in range(num_of_missiles):\n if missileY[i] >= 536:\n score += 1\n missileY[i] = -10\n missileX[i] = random.randint(0, 700)\n collision = collision_cheak(missileX[i], missileY[i], personX, personY)\n if collision:\n for j in range(num_of_missiles):\n game__over = True\n\n missileY[i] += missileY_change[i]\n print_missile(missileX[i], missileY[i], i)\n print_hiscore()\n print_score()\n personX += personX_change\n print_person()\n pygame.display.update()\n\n\npygame.init()\n\nscreen = pygame.display.set_mode((800, 600))\n\nbackground = pygame.image.load('./res/city_background.png')\n\nmixer.music.load(\"./res/background_game_music.wav\")\n\nmixer.music.play(-1)\n\ngame_start = pygame.font.Font('freesansbold.ttf', 64)\nfontX = 100\nfontY = 270\n\n\ndef print_game_start():\n game_start_ = game_start.render(\"Press Enter to start\", True, (0, 0, 0))\n screen.blit(game_start_, (fontX, fontY))\n\n\ngame_name = pygame.font.Font('./res/font.ttf', 45)\ngame_name_fontY = 100\n\ngame_name_fontX = 250\n\n\ndef print_game_name():\n game_name_ = game_name.render(\"Tackle Missiles\", True, (0, 0, 0))\n screen.blit(game_name_, (game_name_fontX, game_name_fontY))\n\n\nrunning = True\n\nwhile running:\n screen.blit(background, (0, 0))\n print_game_start()\n print_game_name()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RETURN:\n game_loop()\n pygame.display.update()\n","sub_path":"Tackle_Missiles.py","file_name":"Tackle_Missiles.py","file_ext":"py","file_size_in_byte":4984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"506125137","text":"#!/usr/bin/env python\n\nimport sys\nimport voikko.voikkoinfl as infl\n\nnoun_types = infl.readInflectionTypes('subst.aff')\n\nif len(sys.argv) == 3:\n inflected = infl.inflectWord(sys.argv[1], sys.argv[2], noun_types)\n\n for w in inflected:\n print(w.formName + ': ' + w.inflectedWord)\nelse:\n print('Usage: [app] word infl-class, e.g.')\n print(' app talo valo ')\n\n","sub_path":"voikkoinfl/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"474442442","text":"\"\"\"\nUniversity of California, Irvine\nMSWE - 248P\nSherlin Mary Koshy (smkoshy)\n\"\"\"\n#Reference URL :https://github.com/fchollet/deep-learning-with-python-notebooks/blob/master/5.3-using-a-pretrained-convnet.ipynb\n\n#import necessary libraries\nimport os,sys\nimport tensorflow.keras\nfrom tensorflow.keras.applications import VGG16\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras import models\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import optimizers\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef extract_features(directory, sample_count):\n #Import VGG16 network pretrained on imagenet, not including the top-most dense layer\n #this convbase is used to extract features from our dataset\n conv_base = VGG16(weights='imagenet', include_top=False, input_shape=(150, 150, 3))\n \n datagen = ImageDataGenerator(rescale=1./255)\n batch_size = 20\n \n features = np.zeros(shape=(sample_count, 4, 4, 512))\n labels = np.zeros(shape=(sample_count))\n generator = datagen.flow_from_directory(directory, target_size=(150, 150),\n batch_size=batch_size, class_mode='binary')\n i = 0\n for inputs_batch, labels_batch in generator:\n features_batch = conv_base.predict(inputs_batch)\n features[i * batch_size : (i + 1) * batch_size] = features_batch\n labels[i * batch_size : (i + 1) * batch_size] = labels_batch\n i += 1\n if i * batch_size >= sample_count:\n break\n return features, labels\n\ndef build_model():\n #build model for classification 1 hidden layer 256 neurons activation-relu\n #dropout layer to reduce overfit output layer of 1 neuron with sigmoid activation for cat/dog classification\n #optimizer-rmsprop loss function-binary_crossentropy evaluation metric accuracy\n model = models.Sequential()\n model.add(layers.Dense(256, activation='relu', input_dim=4 * 4 * 512))\n model.add(layers.Dropout(0.5))\n model.add(layers.Dense(1, activation='sigmoid'))\n\n model.compile(optimizer=optimizers.RMSprop(lr=2e-5), loss='binary_crossentropy', metrics=['acc'])\n return model\n \ndef plot_graphs(history):\n acc = history.history['acc']\n val_acc = history.history['val_acc']\n loss = history.history['loss']\n val_loss = history.history['val_loss']\n \n epochs = range(len(acc))\n\n plt.plot(epochs, acc, 'bo', label='Training acc')\n plt.plot(epochs, val_acc, 'b', label='Validation acc')\n plt.title('Training and validation accuracy')\n plt.legend()\n\n plt.figure()\n\n plt.plot(epochs, loss, 'bo', label='Training loss')\n plt.plot(epochs, val_loss, 'b', label='Validation loss')\n plt.title('Training and validation loss')\n plt.legend()\n\n plt.show()\n\ndef main():\n # The directory where smaller dataset is stored\n base_dir = sys.argv[1]\n print(\"Path to dataset: {}\".format(base_dir))\n \n #specify path to dataset\n train_dir = os.path.join(base_dir, 'train')\n validation_dir = os.path.join(base_dir, 'validation')\n test_dir = os.path.join(base_dir, 'test')\n\n #obtain features from dataset using convbase - Fast feature extraction method \n train_features, train_labels = extract_features(train_dir, 2000)\n validation_features, validation_labels = extract_features(validation_dir, 1000)\n test_features, test_labels = extract_features(test_dir, 1000)\n \n #reshape features to make them suitable for densely connected layer\n train_features = np.reshape(train_features, (2000, 4 * 4 * 512))\n validation_features = np.reshape(validation_features, (1000, 4 * 4 * 512))\n test_features = np.reshape(test_features, (1000, 4 * 4 * 512)) \n \n #build classifier\n model=build_model()\n #fit obtained training features to classifier\n history = model.fit(train_features, train_labels, epochs=30,\n batch_size=20, validation_data=(validation_features, validation_labels))\n \n #save trained model \n model.save('cats_and_dogs_pretrained_1.h5')\n #plot graphs of training vs validation accuracy and loss \n plot_graphs(history) \n \n score = model.evaluate(test_features, test_labels, verbose = 0) \n\n print(\"***Test Accuracy***\") \n print(\"Test accuracy:{}\".format(score[1]))\n \n \n \n \nif __name__==\"__main__\":\n main()","sub_path":"248P_M5/248P_M5_Cats_Dogs_Pretrained/CatsDogsPretrained.py","file_name":"CatsDogsPretrained.py","file_ext":"py","file_size_in_byte":4383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"193875262","text":"from zoundry.appframework.global_services import getApplicationModel\r\nimport wx #@UnusedImport\r\nimport wx.lib.throbber #@Reimport @UnusedImport\r\n\r\n\r\n# ------------------------------------------------------------------------------\r\n# Progress throbber. This widget is often used instead of a progress meter\r\n# when we don't know how long an operation will take. Instead, we simply show\r\n# this little spinning throbber widget and, hopefully, some text that changes\r\n# as work is done.\r\n# ------------------------------------------------------------------------------\r\nclass ZProgressIconCtrl(wx.PyControl):\r\n\r\n def __init__(self, parent, useSmallIcons = False):\r\n self.useSmallIcons = useSmallIcons\r\n self.bitmaps = self._loadBitmaps()\r\n self.backgroundColor = None\r\n self.currIdx = 0\r\n self.timerId = wx.NewId()\r\n self.timer = None\r\n\r\n size = wx.Size(self.bitmaps[0].GetWidth(), self.bitmaps[0].GetHeight())\r\n wx.Control.__init__(self, parent, wx.ID_ANY, style = wx.NO_BORDER, size = size)\r\n self.SetSizeHintsSz(size)\r\n self.SetMinSize(size)\r\n\r\n self.Bind(wx.EVT_PAINT, self.onPaint, self)\r\n self.Bind(wx.EVT_ERASE_BACKGROUND, self.onEraseBackground, self)\r\n self.Bind(wx.EVT_WINDOW_DESTROY, self.onDestroy, self)\r\n wx.EVT_TIMER(self, self.timerId, self.onTimer)\r\n # end __init__()\r\n\r\n def isRunning(self):\r\n return self.timer is not None and self.timer.IsRunning()\r\n # end isRunning()\r\n\r\n def _loadBitmaps(self):\r\n bitmaps = []\r\n prefix = u\"\" #$NON-NLS-1$\r\n if self.useSmallIcons:\r\n prefix = u\"sm-\" #$NON-NLS-1$\r\n for i in range(1, 9):\r\n bitmaps.append( getApplicationModel().getResourceRegistry().getBitmap(u\"images/common/progress/%sprogress-icon-%d.png\" % (prefix, i)) ) #$NON-NLS-1$\r\n return bitmaps\r\n # end _loadBitmaps()\r\n\r\n def setBackgroundColor(self, backgroundColor):\r\n self.backgroundColor = backgroundColor\r\n # end setBackgroundColor()\r\n\r\n def onEraseBackground(self, event): #@UnusedVariable\r\n pass\r\n # end onEraseBackground()\r\n\r\n def onPaint(self, event):\r\n paintDC = wx.BufferedPaintDC(self)\r\n if self.backgroundColor is None:\r\n paintDC.SetBackground(wx.Brush(self.GetParent().GetBackgroundColour(), wx.SOLID))\r\n else:\r\n paintDC.SetBackground(wx.Brush(self.backgroundColor, wx.SOLID))\r\n paintDC.Clear()\r\n\r\n paintDC.DrawBitmap(self.bitmaps[self.currIdx], 0, 0)\r\n\r\n del paintDC\r\n event.Skip()\r\n # end onPaint()\r\n\r\n def onDestroy(self, event):\r\n if self.timer is not None and self.timer.IsRunning():\r\n self.timer.Stop()\r\n event.Skip()\r\n # end onDestroy()\r\n\r\n def onTimer(self, event):\r\n self.currIdx = (self.currIdx + 1) % 8\r\n self.Refresh()\r\n event.Skip()\r\n # end onTimer()\r\n\r\n def start(self):\r\n if self.timer is None:\r\n self.timer = wx.Timer(self, self.timerId)\r\n if not self.timer.IsRunning():\r\n self.timer.Start(85)\r\n # end start()\r\n\r\n def stop(self):\r\n if self.timer is not None and self.timer.IsRunning():\r\n self.timer.Stop()\r\n # end stop()\r\n\r\n# end ZProgressIconCtrl\r\n\r\n\r\n# ------------------------------------------------------------------------------------------\r\n# Composite for a progress animation control with a text lable\r\n# ------------------------------------------------------------------------------------------\r\nclass ZProgressLabelCtrl(wx.Panel):\r\n\r\n def __init__(self, parent, text = None, useSmallIcons = False):\r\n if text is None:\r\n text = u\"\" #$NON-NLS-1$\r\n\r\n wx.Panel.__init__(self, parent, wx.ID_ANY)\r\n\r\n self.label = wx.StaticText(self, wx.ID_ANY, text)\r\n self.animateControl = ZProgressIconCtrl(self, useSmallIcons)\r\n self.animateControl.Show(False)\r\n\r\n box = wx.BoxSizer(wx.HORIZONTAL)\r\n box.Add(self.animateControl, 0, wx.ALIGN_RIGHT | wx.RIGHT, 5)\r\n box.Add(self.label, 1, wx.EXPAND | wx.ALIGN_LEFT )\r\n\r\n self.SetSizeHints(-1, self.animateControl.GetSizeTuple()[1])\r\n self.SetAutoLayout(True)\r\n self.SetSizer(box)\r\n self.Layout()\r\n # end __init__()\r\n\r\n def isRunning(self):\r\n return self.animateControl.isRunning()\r\n # end isRunning()\r\n\r\n def setLabel(self, text):\r\n self.label.SetLabel(text)\r\n # end setLabel()\r\n\r\n def start(self):\r\n self.animateControl.Show(True)\r\n if not self.IsShown():\r\n self.Show(True)\r\n self.animateControl.start()\r\n self.Layout()\r\n # end __init__()\r\n\r\n def stop(self):\r\n self.animateControl.Show(False)\r\n self.Layout()\r\n self.animateControl.stop()\r\n # end start()\r\n\r\n def Show(self, bShow):\r\n wx.Panel.Show(self, bShow)\r\n if bShow:\r\n self.start()\r\n else:\r\n self.stop()\r\n if self.GetParent():\r\n self.GetParent().Layout()\r\n # end Show()\r\n\r\n# end ZProgressLabelCtrl\r\n","sub_path":"src/python/zoundry/appframework/ui/widgets/controls/progress.py","file_name":"progress.py","file_ext":"py","file_size_in_byte":5109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"283466328","text":"from django.shortcuts import render,HttpResponse\nfrom leave_mngt.models import shift_rota as sr\n#from django.db.models import Count\n#from datetime import datetime as dt\nimport datetime as dt\n#import openpyxl\nimport pandas as pd\nimport json\n\n# Create your views here.\n\ndef home(request):\n today_date=dt.datetime.now()\n month=today_date.strftime('%B')\n year=today_date.strftime('%Y')\n date=today_date.strftime('%d')\n return render(request,'leave_mngt/homepage.html',{'month':month,'year':year,'date':date})\n\ndef shiftrota_view(request):\n# grouped=[day['shift_date'] for day in sr.objects.values('shift_date').annotate(unique_names=Count('shift_date',distinct=True))]\n# day=[i for i in grouped]\n# resource_grouped=[i['Resource_Analyst'] for i in sr.objects.values('Resource_Analyst').annotate(unique_names=Count('Resource_Analyst',distinct=True))]\n# resource=[i for i in resource_grouped]\n# #application_grouped=[i['application'] for i in sr.objects.values('application','Resource_Analyst').annotate(unique_names=Count('Resource_Analyst',distinct=True))]\n# #application=[i for i in application_grouped]\n# application_grouped = [i for i in sr.objects.values('application', 'Resource_Analyst').annotate(unique_names=Count('Resource_Analyst', distinct=True))]\n# application = [i for i in application_grouped]\n# location_groupped=[i for i in sr.objects.values('location','Resource_Analyst').annotate(unique_name=Count('Resource_Analyst',distinct=True))]\n# location=[i for i in location_groupped]\n\n #obj=sr.objects.all().order_by('-location')\n #return render(request,'leave_mngt/shift.html',{'obj':obj,'day':day,'resource':resource,'application':application,'location':location})\n # wb=openpyxl.load_workbook(\"leave_data_v2.xlsx\")\n # worksheet=wb[\"Sheet1\"]\n # print(worksheet)\n # excel_data=list()\n # for row in worksheet.iter_rows():\n # row_data=list()\n # for cell in row:\n # row_data.append(str(cell.value))\n # excel_data.append(row_data)\n #return render(request,'leave_mngt/shift.html',{'obj':obj})\n excel_data=pd.read_excel(\"leave_data_v2.xlsx\")\n dt_list=['location','application','Resource_Analyst']\n excel_data=excel_data.rename(columns=lambda x:x.strftime('%d-%b') if x not in dt_list else x)\n today = dt.date.today()\n day1 = today - dt.timedelta(days=today.weekday())\n day2 = day1 + dt.timedelta(days=1)\n day2 = day2.strftime('%d-%b')\n day3 = day1 + dt.timedelta(days=2)\n day3 = day3.strftime('%d-%b')\n day4 = day1 + dt.timedelta(days=3)\n day4 = day4.strftime('%d-%b')\n day5 = day1 + dt.timedelta(days=4)\n day5 = day5.strftime('%d-%b')\n day1 = day1.strftime('%d-%b')\n filtered_columns=['location','application','Resource_Analyst',day1,day2,day3,day4,day5]\n excel_data=excel_data.reindex(columns=filtered_columns)\n #excel_data=excel_data.loc[:,['location','application','Resource_Analyst',day1,day2,day3,day4,day5]]\n #date1=pd.DataFrame(excel_data.columns[3:])\n #date_json_records=date1.reset_index().to_json(orient='records')\n #date=json.loads(date_json_records)\n #day1=[str(row['0']) for row in date]\n day=[i for i in excel_data.columns[3:]]\n json_records=excel_data.reset_index().to_json(orient='records')\n #data=[]\n data=json.loads(json_records)\n #my_list=zip(data,day1)\n context={'df':data,'day':day,'day1':day1}\n #context={'mylist':my_list}\n #df=excel_data.to_html()\n #return HttpResponse(df)\n return render(request, 'leave_mngt/shift_v1.html', context)","sub_path":"leave_mngt/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"156465638","text":"import sys\r\n\r\nsys.path.insert(0,'C:/Users/admin/Desktop/PythonSDK_V20190905/Python_SDK_Demo')\r\nsys.path.insert(0,\"E:/envs/IOT_LIGHT/Lib/site-packages/PythonSDK_V20190905\")\r\n\r\n\r\nfrom PythonSDK_V20190905.com.huawei.iotplatform.client.invokeapi.Authentication import Authentication\r\nfrom Python_SDK_Demo.com.huawei.iotplatform.constant.Constant import Constant\r\nfrom Python_SDK_Demo.com.huawei.iotplatform.client.dto.PostDeviceCommandInDTO import PostDeviceCommandInDTO\r\nfrom Python_SDK_Demo.com.huawei.iotplatform.client.dto.CommandDTOV4 import CommandDTOV4\r\nfrom PythonSDK_V20190905.com.huawei.iotplatform.client.invokeapi.SignalDelivery import SignalDelivery\r\n\r\ndef classtodict(obj):\r\n dict={}\r\n for key in dir(obj):\r\n value=getattr(obj,key)\r\n if not key.startswith(\"__\") and not callable(value):\r\n dict[key]=value\r\n return dict\r\n\r\nif __name__==\"__main__\":\r\n authentication = Authentication()\r\n ag = authentication.getAuthToken(Constant().clientInfo())\r\n accesstoken = ag.split(\",\")[0].split(\":\")[1]\r\n\r\n #设置命令body格式\r\n commanddtov4 = CommandDTOV4()\r\n commanddtov4.serviceId = \"streetlight\"\r\n commanddtov4.method = \"SWITCH_LIGHT\"\r\n commanddtov4.paras = {\"SWITCH_LIGHT\":\"OFF\"}\r\n commanddtov4=classtodict(commanddtov4)\r\n\r\n\r\n #设置命令类\r\n postdevicecommandindto=PostDeviceCommandInDTO()\r\n postdevicecommandindto.setDeviceId(\"8e1a7c4a-31ee-4621-bf2e-f5a6a81c1b18\")\r\n postdevicecommandindto.command=commanddtov4\r\n\r\n\r\n signaldelivery=SignalDelivery()\r\n print(type(postdevicecommandindto))\r\n print(signaldelivery.postDeviceCommand(postdevicecommandindto,appId=None,accessToken=accesstoken[1:-1]))\r\n\r\n\r\n\r\n\r\n","sub_path":"PythonSDKDemo_V20190905/Python_SDK_Demo/com/huawei/iotplatform/client/invokeapiTest/postcommandtest.py","file_name":"postcommandtest.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"172122906","text":"from ethereumetl.jobs.composite_item_exporter import CompositeItemExporter\n\nRECEIPT_FIELDS_TO_EXPORT = [\n 'receipt_transaction_hash',\n 'receipt_transaction_index',\n 'receipt_block_hash',\n 'receipt_block_number',\n 'receipt_cumulative_gas_used',\n 'receipt_gas_used',\n 'receipt_contract_address',\n 'receipt_root',\n 'receipt_status'\n]\n\nLOG_FIELDS_TO_EXPORT = [\n 'log_index',\n 'log_transaction_hash',\n 'log_transaction_index',\n 'log_block_hash',\n 'log_block_number',\n 'log_address',\n 'log_data',\n 'log_topics'\n]\n\n\ndef export_receipts_job_item_exporter(receipts_output=None, logs_output=None):\n return CompositeItemExporter(\n filename_mapping={\n 'receipt': receipts_output,\n 'log': logs_output\n },\n field_mapping={\n 'receipt': RECEIPT_FIELDS_TO_EXPORT,\n 'log': LOG_FIELDS_TO_EXPORT\n }\n )\n","sub_path":"ethereumetl/jobs/export_receipts_job_item_exporter.py","file_name":"export_receipts_job_item_exporter.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"532902887","text":"from __future__ import print_function\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport time\r\nimport random\r\nimport math\r\n\r\nclass Skipgram:\r\n def __init__(self, config, N, dims):\r\n self.config = config\r\n self.N = N\r\n self.dims = dims\r\n\r\n self.labels = tf.placeholder(tf.int32, shape=[None, 1])\r\n self.inputs = tf.placeholder(tf.int32, shape=[None])\r\n\r\n self.embedding = tf.get_variable('embedding', [self.N, self.dims], initializer=tf.contrib.layers.xavier_initializer())\r\n\r\n # Lookup the corresponding embedding vectors for each sample in X\r\n self.Y = tf.nn.embedding_lookup(self.embedding, self.inputs)\r\n\r\n # for test\r\n # self.test = tf.reduce_sum(tf.add_n([self.Y]))\r\n\r\n ############ define variables for skipgram ####################\r\n # construct variables for nce loss\r\n self.nce_weights = tf.get_variable('nce_weights', [self.N, self.dims],\r\n initializer=tf.contrib.layers.xavier_initializer())\r\n self.nce_biases = tf.get_variable('nce_biases', [self.N], initializer=tf.zeros_initializer())\r\n\r\n self.loss_sg = self.make_skipgram_loss()\r\n\r\n # compute gradients for skipgram\r\n self.train_opt_sg = tf.train.AdamOptimizer(self.config.sg_learning_rate).minimize(self.loss_sg)\r\n\r\n def make_skipgram_loss(self):\r\n loss = tf.reduce_sum(tf.nn.sampled_softmax_loss(\r\n weights=self.nce_weights,\r\n biases=self.nce_biases,\r\n labels=self.labels,\r\n inputs=self.Y,\r\n num_sampled=self.config.num_sampled,\r\n num_classes=self.N))\r\n return loss\r\n","sub_path":"skipgram.py","file_name":"skipgram.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"150033934","text":"\nimport cv2 as cv\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Constants\nMIN_IMAGE_NUMBER = 1\nMAX_IMAGE_NUMBER = 300\nFILE_FORMAT = '.bmp'\n\n# Objects\nclass image_obj:\n def __init__(self, number, diameter, perimeter, anatomy, \n area, compacity, momentum, solidity):\n self.number = number\n self.diameter = diameter\n self.perimeter = perimeter\n self.anatomy = anatomy\n self.area = area\n self.compacity = compacity\n self.momentum = momentum\n self.solidity = solidity\n\n# Variables\nimages_list = []\nimages_list.append([\"#\",\"DIAMETRO\",\"PERIMETRO\",\"ESQUELETO\",\"AREA\",\n \"COMPACIDADE\",\"MOMENTO\",\"SOLIDEZ\"])\n\nfor i in range(MIN_IMAGE_NUMBER, MAX_IMAGE_NUMBER + 1):\n image = image_obj\n\n img1 = cv.imread(f'{i}{FILE_FORMAT}')\n print(\"Processando imagem {0}{1} ...\".format(i, FILE_FORMAT))\n\n img1 = cv.cvtColor(img1, cv.COLOR_BGR2RGB)\n\n img2 = img1.copy()\n img2 = cv.cvtColor(img2,cv.COLOR_BGR2GRAY)\n _,img2 = cv.threshold(img2, 127, 255, cv.THRESH_BINARY)\n\n contorno, ordem = cv.findContours(img2, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)\n diametro = np.sqrt(4 * cv.contourArea(contorno[0]) / np.pi)\n\n perimetro = cv.countNonZero(cv.Canny(img2, 50, 100))\n\n img3 = np.zeros(img2.shape, np.uint8)\n kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (3, 3))\n\n end = False\n img4 = img2.copy()\n while (not end):\n erosao = cv.erode(img4, kernel)\n dilatacao = cv.dilate(erosao, kernel)\n subt = cv.subtract(img4, dilatacao)\n img3 = cv.bitwise_or(img3, subt)\n img4 = erosao.copy()\n\n zeros = np.size(img4) - cv.countNonZero(img4)\n if (zeros == np.size(img4)):\n end = True\n\n esqueleto = cv.countNonZero(img3)\n\n area = cv.countNonZero(img2)\n\n compacidade = np.square(perimetro) / area\n\n momentos = cv.moments(contorno[0])\n momento = int(momentos['m10']/momentos['m00'])\n\n area_obj = cv.contourArea(contorno[0])\n area_convex = cv.contourArea( cv.convexHull(contorno[0]))\n solidez = area_obj / area_convex\n\n image.number = i\n image.diameter = round(diametro, 2)\n image.perimeter = round(perimetro, 2)\n image.anatomy = round(esqueleto, 2)\n image.area = round(area, 2)\n image.compacity = round(compacidade, 2)\n image.momentum = round(momento, 2)\n image.solidity = round(solidez, 2)\n\n images_list.append([image.number,\n image.diameter,\n image.perimeter,\n image.anatomy,\n image.area,\n image.compacity,\n image.momentum,\n image.solidity,\n ])\n\nnp.savetxt(\"result.csv\", images_list, delimiter=\";\", fmt=\"%s\")\nprint(\"\\nAnalise finalizada e salva no arquivo result.csv\")\n","sub_path":"shape-classifier/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":2721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"150174266","text":"import plotly.graph_objects as go\nimport pandas as pd\nimport os\n\nif not os.path.exists(\"images\"):\n os.mkdir(\"images\")\n\ndata=pd.read_csv('top_5_users_data.csv')\n\n# ['e8610bbf-b03e-43f7-a6d3-f9e6c6348d01', '60a5e187cfb72611e06f5d2d',\n# '9c2a93d4-70a2-4e0f-a328-9db4d52c54a7', '60a5798e0da2c6793191dca1','60a5daf60da2c6793191eac5']\n# '4d96a0ca-262d-4f0f-b699-30817466a9f0'\ndata.timestamp=pd.to_datetime(data.timestamp)\n\nuser_data=data[data['useridentifier']=='9c2a93d4-70a2-4e0f-a328-9db4d52c54a7'].sort_values('timestamp')\n\nuser_graph=user_data[~(user_data.event.isna())]\n\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=user_graph['timestamp'], y=user_graph['event'], mode='lines+markers',name='lines+markers'))\n\nfig.write_image(\"images/user1.svg\")","sub_path":"sankey_diagram.py","file_name":"sankey_diagram.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"351173620","text":"####Please do not remove lines below####\nfrom lmfit import Parameters\nimport numpy as np\nimport sys\nimport os\nsys.path.append(os.path.abspath('.'))\nsys.path.append(os.path.abspath('./Functions'))\nsys.path.append(os.path.abspath('./Fortran_routines'))\n####Please do not remove lines above####\n\n####Import your modules below if needed####\nfrom ff_cylinder import ff_cylinder, ff_cylinder_dist\nfrom PeakFunctions import Gaussian, LogNormal\nfrom utils import find_minmax\n\n\n\nclass Cylinder: #Please put the class name same as the function name\n def __init__(self,x=0, R=1.0, Rsig=0.0, H=1.0, Hsig=0.0, Nsample=41, dist='Gaussian', norm=1.0,bkg=0.0, mpar={}):\n \"\"\"\n Form factor of a poly-dispersed cylinder\n x : Independent variable in the form of a scalar or an array of Q-values\n R : Radius of the cylinder in the same inverse unit as Q\n Rsig : Width of the distribution in R\n H : Length/Height of the cylinder in the same inverse unit as Q\n Hsig : Width of the distribution in H\n Nsample : No. of points for doing the averging\n dist : The type of distribution: \"Gaussian\" or \"LogNormal\"\n norm : Normalization constant\n bkg : Additive constant background\n \"\"\"\n if type(x)==list:\n self.x=np.array(x)\n else:\n self.x=x\n self.R=R\n self.Rsig=Rsig\n self.H=H\n self.Hsig=Hsig\n self.dist=dist\n self.norm=norm\n self.bkg=bkg\n self.Nsample=Nsample\n self.__mpar__=mpar #If there is any multivalued parameter\n self.choices={'dist':['Gaussian','LogNormal']} #If there are choices available for any fixed parameters\n self.init_params()\n self.output_params={'scaler_parameters':{}}\n\n def init_params(self):\n \"\"\"\n Define all the fitting parameters like\n self.param.add('sig',value = 0, vary = 0, min = -np.inf, max = np.inf, expr = None, brute_step = None)\n \"\"\"\n self.params=Parameters()\n self.params.add('R',value=self.R,vary=0,min=-np.inf,max=np.inf,expr=None,brute_step=0.1)\n self.params.add('Rsig',value=self.Rsig,vary=0,min=-np.inf,max=np.inf,expr=None,brute_step=0.1)\n self.params.add('H',value=self.H,vary=0,min=-np.inf,max=np.inf,expr=None,brute_step=0.1)\n self.params.add('Hsig',value=self.Hsig,vary=0,min=-np.inf,max=np.inf,expr=None,brute_step=0.1)\n self.params.add('R',value=self.R,vary=0,min=-np.inf,max=np.inf,expr=None,brute_step=0.1)\n self.params.add('norm',value=self.norm,vary=0,min=-np.inf,max=np.inf,expr=None,brute_step=0.1)\n self.params.add('bkg', value=self.bkg,vary=0,min=-np.inf, max=np.inf, expr=None, brute_step=0.1)\n\n def y(self):\n \"\"\"\n Define the function in terms of x to return some value\n \"\"\"\n q=self.x\n if self.dist=='Gaussian':\n if self.Rsig>1e-3:\n rdist=Gaussian.Gaussian(x=0.0,pos=self.R, wid=self.Rsig)\n rmin, rmax = max(0.001, self.R-5*self.Rsig),self.R+5*self.Rsig\n r = np.linspace(rmin, rmax, self.Nsample)\n rdist.x = r\n distr = rdist.y()\n self.output_params['R_distribution']={'x':r,'y':distr}\n else:\n r = np.array([self.R])\n distr=np.ones_like(r)\n if self.Hsig>1e-3:\n hdist=Gaussian.Gaussian(x=0.0,pos=self.H, wid=self.Hsig)\n hmin, hmax = max(0.001, self.H-5*self.Hsig),self.H+5*self.Hsig\n h = np.linspace(hmin, hmax, self.Nsample)\n hdist.x = h\n disth = hdist.y()\n self.output_params['H_distribution'] = {'x': h, 'y': disth}\n if self.Rsig < 1e-3:\n r = np.ones_like(h) * self.R\n distr=np.ones_like(r)\n else:\n h = np.ones_like(r) * self.H\n disth = np.ones_like(h)\n elif self.dist=='LogNormal':\n if self.Rsig > 1e-3:\n rdist = LogNormal.LogNormal(x=0.0, pos=self.R, wid=self.Rsig)\n rmin, rmax = max(0.001, self.R*(1 - np.exp(self.Rsig))), self.R*(1 + 2*np.exp(self.Rsig))\n r = np.linspace(rmin, rmax, self.Nsample)\n rdist.x = r\n distr = rdist.y()\n self.output_params['R_distribution'] = {'x': r, 'y': distr}\n else:\n r = np.array([self.R])\n distr = np.ones_like(r)\n if self.Hsig > 1e-3:\n hdist = LogNormal.LogNormal(x=0.0, pos=self.H,wid=self.Hsig)\n hmin, hmax = max(0.001, self.H*(1 - np.exp(self.Hsig))), self.H*(1 + 2*np.exp(self.Hsig))\n h = np.linspace(hmin, hmax, self.Nsample)\n hdist.x = h\n disth = hdist.y()\n self.output_params['H_distribution'] = {'x': h, 'y': disth}\n if self.Rsig < 1e-3:\n r = np.ones_like(h) * self.R\n distr=np.ones_like(r)\n else:\n h = np.ones_like(r) * self.H\n disth = np.ones_like(h)\n\n result = ff_cylinder_dist(q,r,distr,h,disth)\n return self.norm*result+self.bkg\n\n\nif __name__=='__main__':\n x=np.arange(0.001,1.0,0.1)\n fun=Cylinder(x=x)\n print(fun.y())\n","sub_path":"Functions/FormFactors/Cylinder.py","file_name":"Cylinder.py","file_ext":"py","file_size_in_byte":5405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"175018350","text":"from django.shortcuts import render, get_object_or_404\nfrom django.conf import settings\nfrom django.urls import reverse\nfrom django.http import *\nfrom django.contrib.auth import models as django_models\nfrom django.contrib.auth import decorators as django_decorators;\nfrom datetime import date\nfrom ..forms import site as forms\nfrom .. import models\n\nfrom .common import *\n\n\ndef index(request): \n return render(request, \"photoadmin/index.html\", {}, \"text/html\");\n# End index function\n\ndef registration(request):\n form = None\n \n if request.method == \"POST\":\n # process request\n form = forms.RegistrationForm(request.POST)\n \n #validate the form\n sucess = form.process_form() # bool(request.POST['agree_terms'])\n \n if sucess:\n return HttpResponseRedirect(reverse(APP_NAME+\":registration_confirm\"))\n \n else:\n form = forms.RegistrationForm()\n \n return render(request, \"photoadmin/site/register.html\", create_context({\"form\": form}), \"text/html\")\n# End registration view\n\ndef registration_cofirm(request):\n return render(request, \"photoadmin/site/register_cofirm.html\", DEFAULT_CONTEXT) \n\ndef account_activation(request, hashed_email):\n ''' View function for activation account page\n '''\n form = None\n data_context = create_context()\n data_context[\"start_at_step\"] = 0 \n \n wizard_step_one_failed = False\n wizard_step_two_failed = False\n wizard_step_three_failed = False\n \n if request.method == \"GET\":\n \n initial_form_data = None\n \n # Todo: decode hashed_email to email address\n \n try:\n user = django_models.User.objects.get(email=hashed_email) \n \n if user:\n # Initialize the dictionary\n initial_form_data = {\n \"name\": user.first_name,\n \"last_name\": user.last_name,\n \"email\": user.email\n }\n \n # End if\n \n except(django_models.User.DoesNotExist):\n raise Http404(\"Does not exist user with this email: \"+hashed_email)\n \n # End try-except\n \n form = forms.ActivationAccountForm(initial_form_data)\n \n else:\n form = forms.ActivationAccountForm(request.POST)\n \n # If everything was ok then redirect user to confirmation page\n if form.process_form():\n return HttpResponseRedirect(reverse(APP_NAME+':activate_account_confirmation', args=(hashed_email,)));\n \n else:\n data_context[\"gender\"] = form.data['gender']\n data_context[\"country\"] = form.data['country']\n \n # if some error occurre while procesing the form then display errors to user \n general_errors = form.non_field_errors()\n print(general_errors)\n \n if general_errors:\n data_context[\"error\"] = general_errors[0]\n \n else: \n data_context[\"validation_fail\"] = True\n \n # add to data_context failed fields dict\n for key in form.errors.keys():\n \n # Determing which wizard step must be displayed based\n # on failed fields validation\n if not wizard_step_one_failed and key in (\"name\", \"last_name\", \"birthday\", \"email\"):\n wizard_step_one_failed = True \n \n elif not wizard_step_two_failed and key in (\"address\", \"city\", \"state\", \"zip_code\", \"country\"):\n wizard_step_two_failed = True \n \n elif not wizard_step_three_failed and key == \"aggrement_acceptance\":\n wizard_step_three_failed = True\n \n data_context[key+\"_valid\"] = False\n\n print(\"wizard_step_one_failed = \", wizard_step_one_failed)\n print(\"wizard_step_two_failed = \", wizard_step_two_failed)\n print(\"wizard_step_three_failed = \", wizard_step_three_failed)\n \n if wizard_step_two_failed and not wizard_step_one_failed:\n data_context[\"start_at_step\"] = 1\n \n elif wizard_step_three_failed and not wizard_step_two_failed:\n data_context[\"start_at_step\"] = 2\n \n \n # End proces_form if-else \n \n \n # End main if \n \n data_context[\"form\"] = form \n \n print(data_context)\n \n return render(request, \"photoadmin/site/activate_account.html\", data_context)\n\n# End account_activation\n\ndef account_activation_confirm(request, hashed_email):\n print(\"account_activation_confirm() Enter\");\n person = get_object_or_404(models.Person, email=hashed_email)\n return render(request, \"photoadmin/site/activate_account_confirm.html\", create_context({\"name\": person.name, \"last_name\": person.last_name, \"gender\": person.gender }))\n \n# End account_activation_confirm function","sub_path":"photoadmin/views/site.py","file_name":"site.py","file_ext":"py","file_size_in_byte":5254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"486026430","text":"from .models import UserWithCryptoKey\nimport logging\n\nclass AuthBackendWithCryptoKey(object):\n def authenticate(self, email, private_key): \n try:\n user = UserWithCryptoKey.objects.get(private_key=private_key)\n except UserWithCryptoKey.DoesNotExist:\n logging.getLogger(\"error_logger\").error(\"user with login %s does not exists \" % login)\n return None\n\n def get_user(self, private_key):\n try:\n user = UserWithCryptoKey.objects.get(private_key=private_key)\n if user.is_active:\n return user\n return None\n except UserWithCryptoKey.DoesNotExist:\n logging.getLogger(\"error_logger\").error(\"user with %(user_id)d not found\")\n return None","sub_path":"store/crypto_auth/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"636367866","text":"from maneuvers.kit import *\r\n\r\nfrom maneuvers.dribbling.catch import Catch\r\nfrom maneuvers.dribbling.carry import Carry\r\n\r\nclass Dribble(Maneuver):\r\n\r\n def __init__(self, car: Car, info: GameInfo, target: vec3):\r\n super().__init__(car)\r\n\r\n self.target = target\r\n self.info = info\r\n\r\n #self.catch = Catch(car, info, target)\r\n self.carry = Carry(car, info.ball, target)\r\n self.flick = AirDodge(car, 0.15, info.ball.pos)\r\n self.flicking = False\r\n\r\n def step(self, dt):\r\n #if not self.catch.finished:\r\n # self.catch.step(dt)\r\n # self.controls = self.catch.controls\r\n if not self.flicking:\r\n self.carry.step(dt)\r\n self.controls = self.carry.controls\r\n self.finished = self.carry.finished\r\n car = self.car\r\n \r\n dir_to_target = direction(ground(car.pos), ground(self.target))\r\n if (\r\n distance(car.pos, self.info.ball.pos) < 150\r\n and distance(ground(car.pos), ground(self.info.ball.pos)) < 80\r\n and dot(car.forward(), dir_to_target) > 0.9\r\n and norm(car.vel) > distance(car, self.target) / 3\r\n and norm(car.vel) > 1500\r\n and dot(dir_to_target, direction(ground(car.pos), ground(self.info.ball.pos))) > 0.95\r\n ):\r\n self.flicking = True\r\n \r\n for opponent in self.info.opponents:\r\n if distance(opponent, car) < max(800, norm(opponent.vel)) and distance(car.pos, self.info.ball.pos) < 250:\r\n self.flicking = True\r\n else:\r\n self.flick.step(dt)\r\n self.controls = self.flick.controls\r\n self.finished = self.flick.finished\r\n\r\n\r\n\r\n def render(self, draw: DrawingTool):\r\n if not self.flicking:\r\n self.carry.render(draw)\r\n ","sub_path":"RLBotPack/BotimusPrime/source/maneuvers/dribbling/dribble.py","file_name":"dribble.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"442799639","text":"#!/usr/bin/python\nimport csv\nimport re\n\nDEBUG = True\n\ndef to_int(s):\n try:\n return int(round(float(s)))\n except ValueError:\n return s\n\n\n\nclass Transistor(object):\n def __init__(self, doc, part, manufacturer, polarity, pin_count, ce_v_max, ce_v_unit, cb_v_max, cb_v_unit, eb_v_max, eb_v_unit, c_current_max, c_current_unit, dev_dissipation, dev_dissipation_unit, stg_temp_min, stg_temp_max, stg_temp_unit, dc_gain_min):\n self.doc = doc\n self.part = part\n self.manufacturer = manufacturer\n self.polarity = polarity\n self.pin_count = pin_count\n self.ce_v_max = ce_v_max\n self.ce_v_unit = ce_v_unit\n self.cb_v_max = cb_v_max\n self.cb_v_unit = cb_v_unit\n self.eb_v_max = eb_v_max\n self.eb_v_unit = eb_v_unit\n self.c_current_max = c_current_max\n self.c_current_unit = c_current_unit\n self.dev_dissipation = dev_dissipation\n self.dev_dissipation_unit = dev_dissipation_unit\n self.stg_temp_min = stg_temp_min\n self.stg_temp_max = stg_temp_max\n self.stg_temp_unit = stg_temp_unit\n self.dc_gain_min = dc_gain_min\n\n def __str__(self):\n return str(self.__dict__)\n\n def __eq__(self, other):\n # Check for equality based on these attributes ONLY:\n if (self.doc == other.doc and\n self.part == other.part and\n # self.manufacturer == other.manufacturer and\n # self.polarity == other.polarity and\n self.pin_count == other.pin_count and\n self.ce_v_max == other.ce_v_max and\n self.cb_v_max == other.cb_v_max and\n self.eb_v_max == other.eb_v_max and\n self.c_current_max == other.c_current_max and\n self.dev_dissipation == other.dev_dissipation and\n self.stg_temp_min == other.stg_temp_min and\n self.stg_temp_max == other.stg_temp_max and\n set(self.dc_gain_min) == set(other.dc_gain_min)):\n return True\n else:\n return False\n\n def isFull(self):\n # Check for equality based on these attributes ONLY:\n if (self.doc != \"\" and\n self.part != \"\" and\n # self.manufacturer != \"\" and\n self.polarity != \"\" and\n self.pin_count != \"\" and\n self.ce_v_max != \"\" and\n self.cb_v_max != \"\" and\n self.eb_v_max != \"\" and\n self.c_current_max != \"\" and\n self.dev_dissipation != \"\" and\n self.stg_temp_min != \"\" and\n self.stg_temp_max != \"\" and\n self.dc_gain_min != \"\"):\n return True\n else:\n return False\n\ndef load_extracted():\n # Index Values in the extracted data\n DOC_ID = 0\n PART_NUM = 1\n MANUFACTURER = 2\n POLARITY = 3\n CE_V_MAX = 4\n CB_V_MAX = 5\n EB_V_MAX = 6\n C_CURRENT_MAX = 7\n DEV_DISSIPATION = 8\n STG_TEMP_MIN = 9\n STG_TEMP_MAX = 10\n DC_GAIN_MIN = 11\n\n # doc,part,manufacturer,polarity,ce_v_max,cb_v_max,eb_v_max,c_current_max,dev_dissipation,stg_temp_min,stg_temp_max,dc_gain_min\n transistor_list = []\n with open('export.csv', 'rb') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n\n # Build a dictionary of all gold data\n for row in reader:\n # Remove \".pdf\" from filename\n if row[DOC_ID].lower().endswith('.pdf'):\n row[DOC_ID] = row[DOC_ID][:-4]\n doc = row[DOC_ID]\n part = row[PART_NUM]\n manufacturer = row[MANUFACTURER]\n polarity = row[POLARITY].lower()\n pin_count = \"3\"\n ce_v_max = to_int(row[CE_V_MAX])\n ce_v_unit = \"\"\n cb_v_max = to_int(row[CB_V_MAX])\n cb_v_unit = \"\"\n eb_v_max = to_int(row[EB_V_MAX])\n eb_v_unit = \"\"\n c_current_max = row[C_CURRENT_MAX]\n c_current_unit = \"\"\n dev_dissipation = row[DEV_DISSIPATION]\n dev_dissipation_unit = \"\"\n stg_temp_min = row[STG_TEMP_MIN]\n stg_temp_max = row[STG_TEMP_MAX]\n stg_temp_unit = \"\"\n dc_gain_min = re.findall(r'\\d+', row[DC_GAIN_MIN])\n\n transistor = Transistor(doc, part, manufacturer, polarity, pin_count, ce_v_max, ce_v_unit, cb_v_max, cb_v_unit, eb_v_max, eb_v_unit, c_current_max, c_current_unit, dev_dissipation, dev_dissipation_unit, stg_temp_min, stg_temp_max, stg_temp_unit, dc_gain_min)\n transistor_list.append(transistor)\n\n return transistor_list\n\ndef load_gold():\n # Index Values in the gold data\n PART_NUM = 0\n MANUFACTURER = 1\n POLARITY = 2\n PIN_COUNT = 3\n CE_V_MAX = 4\n CB_V_MAX = 5\n EB_V_MAX = 6\n C_CURRENT_MAX = 7\n DEV_DISSIPATION = 8\n STG_TEMP_MIN = 9\n STG_TEMP_MAX = 10\n STG_TEMP_UNIT = 11\n DC_GAIN_MIN = 12 # can be multiple\n DOC_ID = 13\n transistor_list = []\n with open('../input/gold_data.csv', 'rb') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n\n # Build a dictionary of all gold data\n for row in reader:\n # Remove \".pdf\" from filename\n if row[DOC_ID].lower().endswith('.pdf'):\n row[DOC_ID] = row[DOC_ID][:-4]\n doc = row[DOC_ID]\n part = row[PART_NUM]\n manufacturer = row[MANUFACTURER]\n polarity = row[POLARITY].lower()\n pin_count = row[PIN_COUNT]\n try:\n ce_v_max = to_int(row[CE_V_MAX].split()[0])\n ce_v_unit = row[CE_V_MAX].split()[1]\n except IndexError:\n ce_v_max = \"\"\n ce_v_unit = \"\"\n try:\n cb_v_max = to_int(row[CB_V_MAX].split()[0])\n cb_v_unit = row[CB_V_MAX].split()[1]\n except IndexError:\n cb_v_max = \"\"\n cb_v_unit = \"\"\n try:\n eb_v_max = to_int(row[EB_V_MAX].split()[0])\n eb_v_unit = row[EB_V_MAX].split()[1]\n except IndexError:\n eb_v_max = \"\"\n eb_v_unit = \"\"\n try:\n c_current_max = row[C_CURRENT_MAX].split()[0]\n c_current_unit = row[C_CURRENT_MAX].split()[1]\n except IndexError:\n c_current_max = \"\"\n c_current_unit = \"\"\n try:\n dev_dissipation = row[DEV_DISSIPATION].split()[0]\n dev_dissipation_unit = row[DEV_DISSIPATION].split()[1]\n except IndexError:\n dev_dissipation = \"\"\n dev_dissipation_unit = \"\"\n\n stg_temp_min = row[STG_TEMP_MIN]\n stg_temp_max = row[STG_TEMP_MAX]\n stg_temp_unit = row[STG_TEMP_UNIT]\n\n # Multiple valid DC Gains, separated by spaces. Output each in array.\n dc_gain_min = row[DC_GAIN_MIN].split();\n transistor = Transistor(doc, part, manufacturer, polarity, pin_count, ce_v_max, ce_v_unit, cb_v_max, cb_v_unit, eb_v_max, eb_v_unit, c_current_max, c_current_unit, dev_dissipation, dev_dissipation_unit, stg_temp_min, stg_temp_max, stg_temp_unit, dc_gain_min)\n transistor_list.append(transistor)\n\n return transistor_list\n\n# Load all gold data into a dictionary\ngold_transistors = load_gold()\ntotal_gold = len(gold_transistors)\ngold_docs = set()\n\nextracted_transistors = load_extracted()\ntotal_extracted = 0\nextracted_docs = set()\n\nmismatched = []\ncount_correct = 0\n# NOTE: Yeah, this is not ideal as we're iterating over a lot of transistors.\n# In future perhaps implement HASH and use set intersection\nfor extracted in extracted_transistors:\n # Check to see if the extracted transistor has a full schema\n if extracted.isFull():\n total_extracted += 1\n extracted_docs.add(extracted.doc)\n for gold in gold_transistors:\n gold_docs.add(gold.doc)\n if gold.doc == extracted.doc and gold.part==extracted.part:\n if gold == extracted:\n # print(\"Correct: \" + str(gold))\n count_correct += 1\n else:\n mismatched.append((gold, extracted))\n\nif DEBUG:\n print(\"=======================================================================\")\n print(\" Total Gold: \" + str(total_gold))\n print(\" Total Extracted: \" + str(total_extracted))\n print(\" Total True: \" + str(count_correct))\n print(\" Total Documents in Extracted: \" + str(len(extracted_docs)))\n print(\" Total Documents in Gold: \" + str(len(gold_docs)))\n print(\"=======================================================================\")\n","sub_path":"test/final_accuracy.py","file_name":"final_accuracy.py","file_ext":"py","file_size_in_byte":8603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"552128240","text":"from server import api, db\nfrom server.models import Other\nfrom flask import request, g\nfrom flask_restful import Resource\n\nimport datetime\n\n\nclass Advice(Resource):\n\n def __init__(self):\n self.current_time = datetime.datetime.now().strftime('%Y-%m-%d')\n\n def option(self):\n return {\n 'code': 20000\n }\n\n def get(self):\n advice = Other.query.filter_by(\n ownerId = g.userId,\n time = str(self.current_time)\n ).first()\n if advice:\n data = advice.advice\n else:\n data = ''\n return {\n 'code': 20000,\n 'data': data\n }\n\n def post(self):\n data = request.get_json(force = True)\n advice = data.get('advice')\n check_advice = Other.query.filter_by(\n ownerId = g.userId,\n time = str(self.current_time)\n ).first()\n if check_advice:\n check_advice.advice = advice\n else:\n new_advice = Other(\n advice = advice,\n ownerId = g.userId\n )\n db.session.add(new_advice)\n db.session.commit()\n return {\n 'code': 20000\n }\n\n\napi.add_resource(Advice, '/advice')\n","sub_path":"server/views/Task/advice.py","file_name":"advice.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"390690657","text":"from django.urls import path\nfrom .views import UserRecordView, BloodRecordView, RegisterRecordView, DonationRecordView, EventRecordView,BloodValidatorRecordView, ListDonorRecord, SetAvailabilityRecordView, SetLatitudeLongitudeRecordView, SetLastDonatedDateRecordView, SetPictureRecordView\napp_name = 'api'\nurlpatterns = [\n path('user/', UserRecordView.as_view(), name='users'),\n path('register/', RegisterRecordView.as_view(), name='register'),\n path('blood/', BloodRecordView.as_view(), name='blood'),\n path('donation/', DonationRecordView.as_view(), name='donation'),\n path('event/', EventRecordView.as_view(), name='event'),\n path('BloodValidator/', EventRecordView.as_view(), name='BloodValidator'),\n path('list-of-donors/', ListDonorRecord.as_view(), name='ListOfDonors'),\n path('available-status/', SetAvailabilityRecordView.as_view(), name='AvailabilityStatus'),\n path('set-lat-long/', SetLatitudeLongitudeRecordView.as_view(), name='LatitudeLongitude'),\n path('set-last-donated-date/', SetLastDonatedDateRecordView.as_view(), name='LastDonatedDate'),\n path('set-picture/', SetPictureRecordView.as_view(), name='LastDonatedDate'), \n]","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"619410693","text":"import krakenex\nfrom stock.fees_provider import *\nfrom stock.currency_exchanger import *\n\nkraken = krakenex.API()\nbitbay = \"https://bitbay.net/API/Public\"\nNUMBER_OF_OFFERS = 10\n\n\nclass DataParser:\n currency = \"\"\n cryptocurrency = \"\"\n\n def __init__(self, currency, cryptocurrency):\n self.currency = currency\n self.cryptocurrency = cryptocurrency\n\n def bitbay_deposit(self, type, currency):\n trades = self.bitbay_trades(type)\n trades_with_fees = self.trades_after_fees(trades, bitbay_fees, currency, \"EUR\", type)\n return sorted_by_exchange_rate(trades_with_fees, True)\n\n def bitbay_withdraw(self, type, currency):\n trades = self.bitbay_deposit(type, currency)\n withdrawn_trades = self.trades_after_withdrawal(trades, bitbay_withdrawal)\n return sorted_by_exchange_rate(withdrawn_trades, False)\n\n def kraken_deposit(self, type, currency):\n trades = self.kraken_trades(type)\n trades_with_fees = self.trades_after_fees(trades, kraken_fees, currency, \"USD\", type)\n return sorted_by_exchange_rate(trades_with_fees, True)\n\n def kraken_withdraw(self, type, currency):\n trades = self.kraken_deposit(type, currency)\n withdrawn_trades = self.trades_after_withdrawal(trades, kraken_withdrawal)\n return sorted_by_exchange_rate(withdrawn_trades, False)\n\n def bitbay_trades(self, type):\n data = connect(\"{}/{}{}/orderbook.json\".format(bitbay, self.cryptocurrency, self.currency))\n trades = []\n for trade in data[type][0:min(NUMBER_OF_OFFERS, len(data[type]))]:\n cost = float(trade[0]) * float(trade[1])\n trades.append([cost, float(trade[1])])\n return trades\n\n def kraken_trades(self, type):\n data = kraken.query_public('Depth', {'pair': self.cryptocurrency + self.currency, 'count': NUMBER_OF_OFFERS})\n trades = []\n for trade in data['result'][next(iter(data['result']))][type]:\n cost = float(trade[0]) * float(trade[1])\n trades.append([cost, float(trade[1])])\n return trades\n\n @staticmethod\n def common_pairs():\n kraken_pairs = DataParser.kraken_pairs()\n bitbay_pairs = DataParser.bitbay_pairs()\n common_keys = kraken_pairs.keys() & bitbay_pairs.keys()\n\n return {key: set(kraken_pairs[key]) & set(bitbay_pairs[key]) for key in common_keys}\n\n\n @staticmethod\n def kraken_pairs():\n dataRetrieved = kraken.query_public(\"AssetPairs\")\n pairs = {}\n\n for valuePair in dataRetrieved['result']:\n if dataRetrieved['result'][valuePair].get('wsname') is not None:\n splitted = re.split('/', dataRetrieved['result'][valuePair]['wsname'])\n\n if splitted[0] == 'XBT':\n splitted[0] = 'BTC'\n\n if splitted[1] == 'XBT':\n splitted[1] = 'BTC'\n\n if pairs.get(splitted[1]) is None:\n pairs[splitted[1]] = []\n\n pairs[splitted[1]].append(splitted[0])\n\n return pairs\n\n @staticmethod\n def bitbay_pairs():\n data = connect(\"https://api.bitbay.net/rest/trading/stats\".format(bitbay))\n pairs = {}\n\n for entry in data['items']:\n splitted = re.split('-', entry)\n\n if pairs.get(splitted[1]) is None:\n pairs[splitted[1]] = []\n\n pairs[splitted[1]].append(splitted[0])\n\n return pairs\n\n def trades_after_fees(self, trades, fees, base_currency, target_currency, type):\n trades_after_fees = []\n for trade in trades:\n fee = FeesProvider.get_fee(fees, CurrencyExchanger.convert(base_currency, target_currency, float(trade[0])))\n value = trade[0] * ((1 + fee / 100) if type == 'asks' else (1 - fee / 100))\n trades_after_fees.append([value, float(trade[1])])\n return trades_after_fees\n\n def trades_after_withdrawal(self, trades, withdrawal_costs):\n trades_after_withdrawal = []\n for trade in trades:\n quantity = trade[1] - FeesProvider.get_withdrawal_cost(withdrawal_costs, self.cryptocurrency)\n trades_after_withdrawal.append([trade[0], quantity])\n return trades_after_withdrawal\n","sub_path":"3/stock/data_parser.py","file_name":"data_parser.py","file_ext":"py","file_size_in_byte":4238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"396685741","text":"\"\"\"\nCommand function to schema-validate a HXL dataset.\nDavid Megginson\nNovember 2014\n\nLicense: Public Domain\nDocumentation: http://hxlstandard.org\n\"\"\"\n\nimport sys\nimport os\nimport argparse\nfrom copy import copy\nfrom hxl.model import HXLDataProvider, HXLColumn\nfrom hxl.parser import HXLReader, writeHXL\nfrom hxl.schema import readHXLSchema\n\nclass HXLValidateFilter(HXLDataProvider):\n \"\"\"Composable filter class to validate a HXL dataset against a schema.\n\n This is the class supporting the hxlvalidate command-line utility.\n\n Because this class is a {@link hxl.model.HXLDataProvider}, you can use\n it as the source to an instance of another filter class to build a\n dynamic, singled-threaded processing pipeline.\n\n Usage:\n\n
\n    source = HXLReader(sys.stdin)\n    schema = readHXLSchema(readHXL(open('my-schema.csv', 'r')))\n    filter = HXLValidateFilter(source, schema)\n    writeHXL(sys.stdout, filter)\n    
\n \"\"\"\n\n def __init__(self, source, schema, show_all=False):\n \"\"\"\n @param source a HXL data source\n @param schema a HXLSchema object\n @param show_all boolean flag to report all lines (including those without errors).\n \"\"\"\n self.source = source\n self.schema = schema\n self.show_all = show_all\n self._saved_columns = None\n\n @property\n def columns(self):\n \"\"\"\n Add columns for the error reporting.\n \"\"\"\n if self._saved_columns is None:\n # append error columns\n err_col = HXLColumn(hxlTag='#x_errors', headerText='Error messages')\n tag_col = HXLColumn(hxlTag='#x_tags', headerText='Error tag')\n row_col = HXLColumn(hxlTag='#x_rows', headerText='Error row number (source)')\n col_col = HXLColumn(hxlTag='#x_cols', headerText='Error column number (source)')\n self._saved_columns = self.source.columns + [err_col, tag_col, row_col, col_col]\n return self._saved_columns\n\n def __next__(self):\n \"\"\"\n Report rows with error information.\n \"\"\"\n validation_errors = []\n def callback(error):\n \"\"\"\n Collect validation errors\n \"\"\"\n validation_errors.append(error)\n self.schema.callback = callback\n\n \"\"\"\n Read rows until we find an error (unless we're printing all rows)\n \"\"\"\n row = next(self.source)\n while row:\n if self.show_all or not self.schema.validateRow(row):\n # append error data to row\n error_row = copy(row)\n messages = \"\\n\".join(map(lambda e: e.message, validation_errors))\n tags = \"\\n\".join(map(lambda e: e.rule.hxlTag if e.rule else '', validation_errors))\n rows = \"\\n\".join(map(lambda e: str(e.row.sourceRowNumber) if e.row else '', validation_errors))\n columns = \"\\n\".join(map(lambda e: str(e.column.sourceColumnNumber) if e.column else '', validation_errors))\n error_row.values = error_row.values + [messages, tags, rows, columns]\n return error_row\n else:\n row = next(self.source)\n\n next = __next__\n\n\ndef run(args, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr):\n \"\"\"\n Run hxlvalidate with command-line arguments.\n @param args A list of arguments, excluding the script name\n @param stdin Standard input for the script\n @param stdout Standard output for the script\n @param stderr Standard error for the script\n \"\"\"\n\n parser = argparse.ArgumentParser(description = 'Validate a HXL dataset.')\n parser.add_argument(\n 'infile',\n help='HXL file to read (if omitted, use standard input).',\n nargs='?',\n type=argparse.FileType('r'),\n default=stdin\n )\n parser.add_argument(\n 'outfile',\n help='HXL file to write (if omitted, use standard output).',\n nargs='?',\n type=argparse.FileType('w'),\n default=stdout\n )\n parser.add_argument(\n '-s',\n '--schema',\n help='Schema file for validating the HXL dataset (if omitted, use the default core schema).',\n metavar='schema',\n type=argparse.FileType('r'),\n default=None\n )\n parser.add_argument(\n '-a',\n '--all',\n help='Include all rows in the output, including those without errors',\n action='store_const',\n const=True,\n default=False\n )\n args = parser.parse_args(args)\n\n source = HXLReader(args.infile)\n if args.schema:\n schema = readHXLSchema(HXLReader(args.schema), baseDir=os.path.dirname(args.schema.name))\n else:\n schema = readHXLSchema()\n filter = HXLValidateFilter(source, schema, args.all)\n writeHXL(args.outfile, filter)\n\n# end\n","sub_path":"hxl/filters/validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":4822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"407626555","text":"\n\"\"\"\nThis code finds the axis-ratio of a specified host halo and\nalso tests the accuracy of this code by plotting the\nfractional error between a known axis-ratio and the calculated\none, as a function of N number of samples (i.e. subhaloes).\n\"\"\"\n\n### for boundary tests: check halo 18, 30 ###\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport numpy.random as random\n\ninfile = 'halo_data.txt'\nmass = 1\nL = 125\n\n\ndef main():\n all_ids, radius, x_coords, y_coords, z_coords = get_file_data()\n chosen_host_id = get_host_halo(all_ids)\n sub_x, sub_y, sub_z, host_radius = get_subhalo_coords(chosen_host_id,\n all_ids, x_coords, y_coords, z_coords, radius)\n check_boundary(sub_x, sub_y, sub_z)\n a_len, b_len, c_len = get_axes(sub_x, sub_y, sub_z)\n c_a_ratio = c_len / a_len\n b_a_ratio = b_len / a_len\n print('Axis ratio c:a is '+str(c_a_ratio))\n print('Axis ratio b:a is '+str(b_a_ratio))\n correlation()\n\n\ndef random_sphere(N):\n \"\"\" random_sphere returns the azimuthal angle, phi, and polar angle, theta\n of N points generated uniformly at random over the surface of a sphere.\n \"\"\"\n # See https://mathworld.wolfram.com/SpherePointPicking.html for the\n # algorithm. (Basically just the Inverse Transfer Method.)\n phi = 2 * np.pi * random.random(N)\n theta = np.arccos(2 * random.random(N) - 1)\n return phi, theta\n\n\ndef spherical_to_cartesian(phi, theta, r):\n \"\"\" spherical_to_cartesian converts spherical coordiantes to cartesian\n coordinates. Here, phi is the azimuthal angle, theta is the polar angle, and\n r is the radius.\n \"\"\"\n # See https://mathworld.wolfram.com/SphericalCoordinates.html, but note the\n # difference in convention.\n x = r * np.cos(phi) * np.sin(theta)\n y = r * np.sin(phi) * np.sin(theta)\n z = r * np.cos(theta)\n return x, y, z\n\n\ndef random_ball(N, R):\n \"\"\" random_ball returns a N points (x, y, z) generated uniformly at\n random from within a ball of radius r.\n \"\"\"\n phi, theta = random_sphere(N)\n # Inverse Transform Method, See\n # http://www.columbia.edu/~ks20/4404-Sigman/4404-Notes-ITM.pdf\n r = random.random(N) ** (1.0 / 3) * R\n return spherical_to_cartesian(phi, theta, r)\n\n\ndef random_ellipsoid(N, a, b, c):\n \"\"\" random_ellipsoid returns N points generated uniformly at random inside\n an ellipsoid. The axes of the ellipsoid are given by (a, b, c) which\n are aligned with the x, y, and z axes, respectively.\n \"\"\"\n x, y, z = random_ball(N, 1.0)\n return x * a, y * b, z * c\n\n\ndef get_file_data():\n \"\"\"\n self-explanatory\n \"\"\"\n array = np.loadtxt(infile, usecols=(0, 4, 8, 9, 10)).T\n all_ids = array[0]\n radius = array[1]\n x_coords = array[2]\n y_coords = array[3]\n z_coords = array[4]\n return all_ids, radius, x_coords, y_coords, z_coords\n\n\ndef get_host_halo(all_ids):\n \"\"\"\n Parces through the data file and saves the host-halo\n ids into a list, from here the user can pick which\n one they want to receive the axis-ratio for.\n \"\"\"\n total_haloes = len(all_ids)\n host_halo_ids = [] # stores first instance of new id in a list\n for i in range(total_haloes):\n previous_halo = all_ids[i - 1]\n current_halo = all_ids[i]\n if previous_halo != current_halo and i < total_haloes - 1:\n host_halo_ids.append(current_halo)\n total_hosts = len(host_halo_ids)\n pick_host = int(input('Choose a number between 0 and ' +\n str(total_hosts - 1) + ': '))\n chosen_host_id = host_halo_ids[pick_host]\n return chosen_host_id\n\n\ndef get_subhalo_coords(chosen_host_id, all_ids, x, y, z, radii):\n host_and_sub_indices = np.where(chosen_host_id == all_ids)\n all_x, all_y, all_z = x[host_and_sub_indices], y[host_and_sub_indices], \\\n z[host_and_sub_indices]\n all_radii = radii[host_and_sub_indices]\n host_radius = all_radii[0]\n host_x, host_y, host_z = all_x[0], all_y[0], all_z[0]\n sub_x, sub_y, sub_z = all_x[1:], all_y[1:], all_z[1:]\n\n \"\"\"\n Adjust subhalo positions so they're relative to center of host.\n Coordinate will be negative if subhalo center is positioned to \n the left of the host center.\n \"\"\"\n sub_x -= host_x\n sub_y -= host_y\n sub_z -= host_z\n return sub_x, sub_y, sub_z, host_radius\n\n\n# TEST\ndef check_boundary(sub_x, sub_y, sub_z):\n \"\"\"\n Using the subhalo \"difference\" matrices for x,y,z\n check if the each subhalo position for x,y,z is a\n sensible distance from its host. If it's not, the subhalo\n has been \"split\" to the other side of the simulation box,\n and this must be corrected for.\n \"\"\"\n list = [sub_x, sub_y, sub_z]\n for position in list:\n # subhalo split and on right side, host left\n too_big = np.where(position > (L/2))\n # subhalo split and on left side, host right\n too_small = np.where(position < (-L/2))\n position[too_big] -= L\n position[too_small] += L\n\n\ndef make_inertia_tensor():\n \"\"\"\n Create an empty 3x3 matrix to store our inertia tensor\n values.\n \"\"\"\n empty_inertia_tensor = np.zeros((3, 3))\n return empty_inertia_tensor\n\n\ndef populate_inertia_tensor(inertia_tensor, sub_x, sub_y, sub_z):\n \"\"\"\n Moments and Products of Inertia about various axes:\n Ixx = sum[(y^2 + z^2) * mass]\n Iyy = sum[(x^2 + z^2) * mass]\n Izz = sum[(x^2 + y^2) * mass]\n Ixy = Iyx = -sum[x * y * mass]\n Iyz = Izy = -sum[y * z * mass]\n Ixz = Izx = -sum[x * z * mass]\n\n We use this matrix to determine the moment of inertia for an\n arbitrarily shaped object, characterizing its shape.\n \"\"\"\n inertia_tensor[0][0] = np.sum(((sub_y**2) + (sub_z**2)) * mass)\n inertia_tensor[0][1] = -np.sum((sub_x * sub_y * mass))\n inertia_tensor[0][2] = -np.sum((sub_x * sub_z * mass))\n inertia_tensor[1][0] = -np.sum((sub_x * sub_y * mass))\n inertia_tensor[1][1] = np.sum(((sub_x ** 2) + (sub_z ** 2)) * mass)\n inertia_tensor[1][2] = -np.sum((sub_y * sub_z * mass))\n inertia_tensor[2][0] = -np.sum((sub_x * sub_z * mass))\n inertia_tensor[2][1] = -np.sum((sub_y * sub_z * mass))\n inertia_tensor[2][2] = np.sum(((sub_x ** 2) + (sub_y ** 2)) * mass)\n return inertia_tensor\n\n\ndef compute_e_values(inertia_tensor):\n \"\"\"\n Function computes the eigenvalues and right eigenvectors\n of a the inertia tensor. It returns an array of the eigenvalues,\n and an array of unit \"length\" eigenvectors.\n\n This inertia tensor matrix transforms a rotation vector into\n an angular momentum vector. The eigenvectors of the inertia\n tensor are the axes about which we can rotate the object\n without wobbling/procession. The eigenvalues are the moment(s)\n of inertia, which when multiplied by the angular frequency,\n characterizes the angular momentum.\n \"\"\"\n evalues, evectors = np.linalg.eig(inertia_tensor)\n return evalues\n\n\ndef convert_to_length(evalues):\n \"\"\"\n This function converts the eigenvalues into physical lengths\n for our host halo axes, and thus our axis ratios.\n\n Ellipsoid equations:\n Ia = (1/5)* mass * (b^2 + c^2)\n Ib = (1/5)* mass * (a^2 + c^2)\n Ic = (1/5)* mass * (a^2 + b^2)\n\n Solve a system of equations for a,b,c and reorder\n so a is the largest axis, and so on.\n \"\"\"\n Ia = evalues[0]\n Ib = evalues[1]\n Ic = evalues[2]\n c = math.sqrt((1/2) * 5 * (1/mass) * (Ib - Ic + Ia))\n b = math.sqrt((5 * (1/mass) * Ia) - c**2)\n a = math.sqrt((5 * (1/mass) * (Ic - Ia)) + c**2)\n # shortcut!\n return np.flip(np.sort([a, b, c]))\n\n\ndef get_axes(x_arr, y_arr, z_arr):\n \"\"\"\n Returns the axis lengths largest to smallest of the halo\n delineated as a,b,c.\n \"\"\"\n empty_inertia_tensor = make_inertia_tensor()\n inertia_tensor = populate_inertia_tensor(empty_inertia_tensor,\n x_arr, y_arr, z_arr)\n evalues = compute_e_values(inertia_tensor)\n axis_a_length, axis_b_length, axis_c_length = convert_to_length(\n evalues)\n return axis_a_length, axis_b_length, axis_c_length\n\n\ndef correlation():\n \"\"\"\n This function is a test of this code above. It takes in some arbitrary\n axis lengths and a randomly generated number of N points, representative\n of N subhaloes. An ellipsoid is therefore generated for my code to\n determine the axis ratios of. The expected ratio vs. my code's calculated\n ratio is compared and plotted against different N. This fractional error is\n taken for many iterations, of this N amount of sample points for each N value,\n and averaged.\n\n It is expected that the error at large N will be smaller than at small N.\n \"\"\"\n a = 1\n b = 0.5\n c = 0.25\n expected_ca = c / a\n expected_ba = b / a\n fig, (ax1, ax2) = plt.subplots(2, 1, dpi=100)\n fig.suptitle('Axis Ratio Correlations with Subhalo Abundance')\n ax1.set_title('c:a Axis Ratio')\n ax2.set_title('b:a Axis Ratio')\n ax2.set_xlabel(r'$log(N_{sh})$')\n ax1.set_ylabel('Mean Fractional Error')\n ax2.set_ylabel('Mean Fractional Error')\n N_list = np.logspace(1, 4, num=50, endpoint=True, base=10.0,\n dtype=int, axis=0).tolist()\n num_N = int(input('How many N iterations? '))\n error_ca_arr = np.zeros(len(N_list))\n error_ba_arr = np.zeros(len(N_list))\n for i in range(num_N):\n error_ca_list = []\n error_ba_list = []\n for N in N_list:\n x, y, z = random_ellipsoid(N, a, b, c)\n a_len, b_len, c_len = get_axes(x, y, z)\n measured_ca = c_len / a_len\n measured_ba = b_len / a_len\n error_ca_list.append(np.absolute((measured_ca - expected_ca))\n / expected_ca)\n error_ba_list.append(np.absolute((measured_ba - expected_ba))\n / expected_ba)\n error_ca_arr += np.asarray(error_ca_list)\n error_ba_arr += np.asarray(error_ba_list)\n error_ca_arr /= num_N\n error_ba_arr /= num_N\n ax1.plot(N_list, error_ca_arr, '.r-', markersize=1.5, linewidth=0.5)\n ax2.plot(N_list, error_ba_arr, '.b-', markersize=1.5, linewidth=0.5)\n ax1.set_xscale('log')\n ax1.set_yscale('log')\n ax2.set_xscale('log')\n ax2.set_yscale('log')\n plt.tight_layout()\n plt.show()\n\n\nif __name__ == '__main__':\n main()","sub_path":"axis_ratios.py","file_name":"axis_ratios.py","file_ext":"py","file_size_in_byte":10395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"573982694","text":"#!/usr/bin/python\n# coding=utf-8\n\n#Implementation of radix sort algorithmn on GPU\n#STEP 1\n\nimport numpy\nimport numbapro\nimport time\nimport math\nfrom numbapro import cuda\nfrom numba import *\n\nTPB_MAX = 1024\nATTR_CARD_MAX = int(math.pow(2,32))-1\n\n\ndef bin(s):\n\t#transform the integer to the type of binary code\n\t#return value is a string\n\treturn str(s) if s<=1 else bin(s>>1) + str(s&1)\n\nmin\n\n@cuda.jit('void(int64[:], int64[:], int64, int64)',target='gpu')\ndef reduce_phase(zero_list, one_list, hop, thread_num):\n i = cuda.grid(1)\n if i%(2*hop) == (2*hop-1):\n zero_list[i] += zero_list[i-hop]\n one_list[i] += one_list[i-hop]\n if hop == thread_num/2:\n if i == thread_num-1:\n one_list[i] = 0\n zero_list[i] = 0\n\n\n@cuda.jit('void(int64[:], int64[:], int64, int64)',target='gpu')\ndef downsweep_phase(zero_list, one_list, hop, base):\n i = cuda.grid(1)\n if i%(2*hop) == (2*hop-1):\n zero_list[i-hop], zero_list[i] = zero_list[i], zero_list[i-hop]+zero_list[i]\n one_list[i-hop], one_list[i] = one_list[i], one_list[i-hop]+one_list[i]\n cuda.syncthreads()\n if hop==1:\n one_list[i] += base\n\ndef Blelloch_scan_caller(d_zero_list, d_one_list, base):#zero_list uses 1 to represent 0, 0 to represent 1; one_list on the contrary\n thread_num = d_zero_list.shape[0]\n block_num = thread_num/TPB_MAX\n #step1. reduce\n hop = 1\n while hop < thread_num:\n reduce_phase[block_num,TPB_MAX](d_zero_list, d_one_list, hop, thread_num)\n hop *= 2\n\t\n #step2. downsweep\n hop/= 2\n while hop > 0:\n downsweep_phase[block_num,TPB_MAX](d_zero_list, d_one_list, hop, base)\n hop /= 2\n\n\n@cuda.jit('void(int64[:], int64[:])',target='gpu')\ndef sum_reduction(zero_list, tmp_out):\n bw = cuda.blockDim.x\n bx = cuda.blockIdx.x\n tid = cuda.threadIdx.x\n shared_list = cuda.shared.array(shape = (TPB_MAX), dtype = int64)\n \n i = bx*bw + tid\n shared_list[tid] = zero_list[i]\n cuda.syncthreads()\n\n hop = bw/2\n while hop > 0:\n if tid < hop:\n shared_list[tid] = shared_list[tid] + shared_list[tid+hop]\n cuda.syncthreads()\n hop /= 2\n if tid == 0:\n tmp_out[bx] = shared_list[0]\n\n@cuda.jit('void(int32[:], int64, int32, int64[:], int64[:])', target='gpu')\ndef get_list(arr, length, iter_order, zero_list, one_list):\n i = cuda.grid(1)\n if i < length:\n one_list[i] = (arr[i]>>iter_order)%2\n zero_list[i] = 1-one_list[i]\n else:\n one_list[i] = 0\n zero_list[i] = 0\n\n@cuda.jit('void(int32[:], int32[:], int64[:], int64[:], int64[:], int64[:], int64[:], int64[:], int64)', target='gpu')\ndef array_adjust(arr, d_arr,rid, d_rid, zero_list, one_list, d_zero_list, d_one_list, length):\n i = cuda.grid(1)\n if i 1]\n\n errors = []\n if len(duplicate_entries) > 0:\n content = json.dumps({'success': False, 'errors': errors, 'duplicate_entries': duplicate_entries})\n\n dbm = get_database_manager_for_org(Organization.objects.get(org_id=org_id))\n existent_email_addresses = User.objects.filter(email__in=reporter_details.values()).values('email')\n\n if len(existent_email_addresses) > 0:\n for duplicate_email in existent_email_addresses:\n errors.append(\"User with email %s already exists\" % duplicate_email['email'])\n content = json.dumps({'success': False, 'errors': errors, 'duplicate_entries': duplicate_entries})\n if errors.__len__() == 0 and duplicate_entries.keys().__len__() == 0:\n for reporter_id, email in reporter_details.iteritems():\n reporter_entity = get_by_short_code(dbm, reporter_id, [REPORTER])\n reporter_email = email.lower()\n put_email_information_to_entity(dbm, reporter_entity, email=reporter_email)\n user = User.objects.create_user(reporter_email, reporter_email, 'test123')\n group = Group.objects.filter(name=\"Data Senders\")[0]\n user.groups.add(group)\n user.first_name = reporter_entity.value(NAME_FIELD)\n user.save()\n profile = NGOUserProfile(user=user, org_id=org_id, title=\"Mr\",\n reporter_id=reporter_id.lower())\n profile.save()\n\n send_email_to_data_sender(user, language_code)\n\n content = json.dumps({'success': True, 'message': \"Users has been created\"})\n return content\n\n\ndef create_single_web_user(org_id, email_address, reporter_id, language_code):\n \"\"\"Create single web user from My Data Senders page\"\"\"\n return HttpResponse(\n __create_web_users(org_id, {reporter_id: email_address}, language_code))\n\n\n@login_required(login_url='/login')\n@csrf_view_exempt\n@is_not_expired\ndef create_multiple_web_users(request):\n \"\"\"Create multiple web users from All Data Senders page\"\"\"\n org_id = request.user.get_profile().org_id\n post_data = {}\n if request.method == 'POST':\n [post_data.update({item['reporter_id']: item['email']}) for item in json.loads(request.POST['post_data'])]\n content = __create_web_users(org_id, post_data, request.LANGUAGE_CODE)\n return HttpResponse(content)\n\n\n@csrf_view_exempt\n@csrf_response_exempt\n@require_http_methods(['POST'])\n@valid_web_user\n#todo remove form_code from here, use entity_type instead\ndef import_subjects_from_project_wizard(request, form_code):\n manager = get_database_manager(request.user)\n error_message, failure_imports, success_message, imported_entities, successful_imports = import_module.import_data(\n request, manager,\n default_parser=XlsOrderedParser,\n form_code=form_code)\n if len(imported_entities) != 0:\n detail_dict = dict()\n for short_code, entity_type in imported_entities.items():\n entity_type = entity_type.capitalize()\n if detail_dict.get(entity_type) is not None:\n detail_dict.get(entity_type).append(short_code)\n else:\n detail_dict.update({entity_type: [short_code]})\n for key, detail in detail_dict.items():\n detail_dict.update({key: \"[%s]\" % \", \".join(detail)})\n UserActivityLog().log(request, action=IMPORTED_SUBJECTS, detail=json.dumps(detail_dict))\n\n subjects_data = import_module.load_all_subjects(manager)\n\n return HttpResponse(json.dumps(\n {'success': error_message is None and is_empty(failure_imports),\n 'message': success_message,\n 'error_message': error_message,\n 'failure_imports': failure_imports,\n 'all_data': subjects_data,\n 'imported': imported_entities.keys()\n }))\n\n\ndef _make_form_context(questionnaire_form, entity_type, disable_link_class, hide_link_class, form_code, org_number,\n form_model_fields, is_update=False, back_link=None, web_view=False):\n return {'questionnaire_form': questionnaire_form,\n 'questions': form_model_fields,\n 'entity_type': entity_type,\n \"disable_link_class\": disable_link_class,\n \"hide_link_class\": hide_link_class,\n 'back_to_project_link': reverse(\"alldata_index\"),\n 'smart_phone_instruction_link': reverse(\"smart_phone_instruction\"),\n 'is_update': is_update,\n 'back_link': back_link,\n 'form_code': form_code,\n 'example_sms': get_example_sms_message(form_model_fields, form_code),\n 'org_number': org_number,\n \"web_view\": web_view,\n 'extension_template': \"entity/web_questionnaire.html\",\n \"register_subjects_link\": reverse(\"create_subject\", args=[entity_type]) + \"?web_view=True\",\n \"edit_subject_questionnaire_link\": reverse(\"edit_subject_questionnaire\", args=[entity_type])\n }\n\n\ndef get_template(user):\n return 'entity/register_subject.html' if user.get_profile().reporter else 'entity/subject/registration.html'\n\n\ndef initialize_values(form_model, subject):\n for field in form_model.fields:\n if field.name == LOCATION_TYPE_FIELD_NAME:\n field.value = ','.join(subject.location_path)\n elif field.name == GEO_CODE_FIELD_NAME:\n field.value = ','.join(map(str, subject.geometry['coordinates']))\n elif field.name == SHORT_CODE_FIELD:\n field.value = subject.short_code\n else:\n field.value = subject.data[field.name]['value'] if field.name in subject.data.keys() else None\n\n if field.value:\n field.value = field.convert_to_unicode()\n\n\n@valid_web_user\ndef edit_subject(request, entity_type, entity_id, project_id=None):\n manager = get_database_manager(request.user)\n form_model = get_form_model_by_entity_type(manager, [entity_type.lower()])\n subject = get_by_short_code(manager, entity_id, [entity_type.lower()])\n back_link = reverse(all_subjects, args=[entity_type])\n\n web_questionnaire_template = get_template(request.user)\n disable_link_class, hide_link_class = get_visibility_settings_for(request.user)\n if request.method == 'GET':\n initialize_values(form_model, subject)\n questionnaire_form = SubjectRegistrationForm(form_model)\n form_context = _make_form_context(questionnaire_form, entity_type, disable_link_class, hide_link_class,\n form_model.form_code, get_organization_telephone_number(request),\n form_model.fields, is_update=True,\n back_link=back_link)\n return render_to_response(web_questionnaire_template,\n form_context,\n context_instance=RequestContext(request))\n if request.method == 'POST':\n questionnaire_form = SubjectRegistrationForm(form_model, data=request.POST,\n country=get_organization_country(request))\n if not questionnaire_form.is_valid():\n form_context = _make_form_context(questionnaire_form, entity_type, disable_link_class, hide_link_class,\n form_model.form_code, get_organization_telephone_number(request),\n form_model.fields, is_update=True, back_link=back_link)\n return render_to_response(web_questionnaire_template,\n form_context,\n context_instance=RequestContext(request))\n\n success_message = None\n error_message = None\n try:\n response = WebPlayer(manager,\n LocationBridge(location_tree=get_location_tree(),\n get_loc_hierarchy=get_location_hierarchy)).accept(\n create_request(questionnaire_form, request.user.username, is_update=True))\n\n if response.success:\n success_message = _(\"Your changes have been saved.\")\n questionnaire_form = SubjectRegistrationForm(form_model, data=request.POST,\n country=get_organization_country(request))\n else:\n from datawinners.project.helper import errors_to_list\n\n questionnaire_form._errors = errors_to_list(response.errors, form_model.fields)\n form_context = _make_form_context(questionnaire_form, entity_type, disable_link_class, hide_link_class,\n form_model.form_code, get_organization_telephone_number(request),\n form_model.fields, is_update=True, back_link=back_link)\n return render_to_response(web_questionnaire_template,\n form_context,\n context_instance=RequestContext(request))\n\n except DataObjectNotFound:\n message = exception_messages.get(DataObjectNotFound).get(WEB)\n error_message = _(message) % (form_model.entity_type[0], form_model.entity_type[0])\n except Exception as exception:\n error_message = _(get_exception_message_for(exception=exception, channel=Channel.WEB))\n subject_context = _make_form_context(questionnaire_form, entity_type, disable_link_class, hide_link_class,\n form_model.form_code, get_organization_telephone_number(request),\n form_model.fields, is_update=True, back_link=back_link)\n subject_context.update({'success_message': success_message, 'error_message': error_message})\n\n return render_to_response(web_questionnaire_template, subject_context,\n context_instance=RequestContext(request))\n\n\n@valid_web_user\ndef create_subject(request, entity_type=None):\n manager = get_database_manager(request.user)\n form_model = get_form_model_by_entity_type(manager, [entity_type.lower()])\n web_questionnaire_template = get_template(request.user)\n disable_link_class, hide_link_class = get_visibility_settings_for(request.user)\n\n if request.method == 'GET':\n questionnaire_form = SubjectRegistrationForm(form_model)\n\n form_context = _make_form_context(questionnaire_form, entity_type, disable_link_class, hide_link_class,\n form_model.form_code, get_organization_telephone_number(request),\n form_model.fields, web_view=request.GET.get(\"web_view\", False))\n\n return render_to_response(web_questionnaire_template,\n form_context,\n context_instance=RequestContext(request))\n\n if request.method == 'POST':\n questionnaire_form = SubjectRegistrationForm(form_model, data=request.POST,\n country=get_organization_country(request))\n if not questionnaire_form.is_valid():\n form_context = _make_form_context(questionnaire_form, entity_type, disable_link_class, hide_link_class,\n form_model.form_code, get_organization_telephone_number(request),\n form_model.fields, web_view=True)\n return render_to_response(web_questionnaire_template,\n form_context,\n context_instance=RequestContext(request))\n\n success_message = None\n error_message = None\n try:\n from datawinners.project.helper import create_request\n\n response = WebPlayer(manager,\n LocationBridge(location_tree=get_location_tree(),\n get_loc_hierarchy=get_location_hierarchy)).accept(\n create_request(questionnaire_form, request.user.username), logger=websubmission_logger)\n if response.success:\n ReportRouter().route(get_organization(request).org_id, response)\n success_message = (_(\"Successfully submitted. Unique identification number(ID) is:\") + \" %s\") % (\n response.short_code,)\n detail_dict = dict({\"Subject Type\": entity_type.capitalize(), \"Unique ID\": response.short_code})\n UserActivityLog().log(request, action=REGISTERED_SUBJECT, detail=json.dumps(detail_dict))\n questionnaire_form = SubjectRegistrationForm(form_model)\n else:\n from datawinners.project.helper import errors_to_list\n\n questionnaire_form._errors = errors_to_list(response.errors, form_model.fields)\n form_context = _make_form_context(questionnaire_form, entity_type, disable_link_class, hide_link_class,\n form_model.form_code, get_organization_telephone_number(request),\n form_model.fields, web_view=True)\n return render_to_response(web_questionnaire_template,\n form_context,\n context_instance=RequestContext(request))\n\n except DataObjectNotFound:\n message = exception_messages.get(DataObjectNotFound).get(WEB)\n error_message = _(message) % (form_model.entity_type[0], form_model.entity_type[0])\n except DataObjectAlreadyExists as exception:\n error_message = _(\"Entity with Unique Identification Number (ID) = %s already exists.\") % exception.data[1]\n except Exception as exception:\n error_message = _(get_exception_message_for(exception=exception, channel=Channel.WEB))\n\n subject_context = _make_form_context(questionnaire_form, entity_type, disable_link_class, hide_link_class,\n form_model.form_code, get_organization_telephone_number(request),\n form_model.fields, web_view=True)\n subject_context.update({'success_message': success_message, 'error_message': error_message})\n\n return render_to_response(web_questionnaire_template, subject_context,\n context_instance=RequestContext(request))\n\n\n@valid_web_user\n@login_required(login_url='/login')\n@session_not_expired\n@is_not_expired\ndef edit_subject_questionnaire(request, entity_type=None):\n # edit subject type questionnaire view\n manager = get_database_manager(request.user)\n if entity_type is None:\n return HttpResponseRedirect(reverse(all_subject_types))\n\n form_model = get_form_model_by_entity_type(manager, [entity_type.lower()])\n if form_model is None:\n form_model = get_form_model_by_code(manager, REGISTRATION_FORM_CODE)\n fields = form_model.fields\n\n existing_questions = json.dumps(fields, default=field_to_json)\n return render_to_response('entity/questionnaire.html',\n {'existing_questions': repr(existing_questions),\n 'questionnaire_code': form_model.form_code,\n 'language': form_model.activeLanguages[0],\n 'entity_type': entity_type,\n 'post_url': reverse(save_questionnaire)},\n context_instance=RequestContext(request))\n\n\n@valid_web_user\ndef save_questionnaire(request):\n manager = get_database_manager(request.user)\n if request.method == 'POST':\n new_short_code = request.POST['questionnaire-code'].lower()\n saved_short_code = request.POST['saved-questionnaire-code'].lower()\n\n form_model = get_form_model_by_code(manager, saved_short_code)\n detail_dict = dict()\n if new_short_code != saved_short_code:\n try:\n form_model.form_code = new_short_code\n form_model.save()\n detail_dict.update({\"form_code\": new_short_code})\n except DataObjectAlreadyExists as e:\n if e.message.find(\"Form\") >= 0:\n return HttpResponse(json.dumps({'success': False,\n 'error_message': \"Questionnaire with this code already exists\"}))\n return HttpResponseServerError(e.message)\n\n json_string = request.POST['question-set']\n question_set = json.loads(json_string)\n try:\n saved_fields = form_model.fields\n QuestionnaireBuilder(form_model, manager).update_questionnaire_with_questions(question_set)\n form_model.save()\n changed = get_changed_questions(saved_fields, form_model.fields)\n changed.update(dict(entity_type=form_model.entity_type[0].capitalize()))\n detail_dict.update(changed)\n kwargs = dict()\n if request.POST.get(\"project-name\") is not None:\n kwargs.update(dict(project=request.POST.get(\"project-name\").capitalize()))\n UserActivityLog().log(request, action=EDITED_REGISTRATION_FORM, detail=json.dumps(detail_dict), **kwargs)\n return HttpResponse(json.dumps({'success': True, 'form_code': form_model.form_code}))\n except QuestionCodeAlreadyExistsException as e:\n return HttpResponse(json.dumps({'success': False, 'error_message': _(e.message)}))\n except QuestionAlreadyExistsException as e:\n return HttpResponse(json.dumps({'success': False, 'error_message': _(e.message)}))\n except EntityQuestionAlreadyExistsException as e:\n return HttpResponse(json.dumps({'success': False, 'error_message': _(e.message)}))\n\n\ndef subject_autocomplete(request, entity_type):\n search_text = lower(request.GET[\"term\"] or \"\")\n database_name = get_database_name(request.user)\n dbm = get_database_manager(request.user)\n form_model = get_form_model_by_entity_type(dbm, [entity_type.lower()])\n subject_name_field = get_field_by_attribute_value(form_model,'name','name')\n es_field_name_for_subject_name = es_field_name(subject_name_field.code, form_model.id)\n subject_short_code_field = get_field_by_attribute_value(form_model,'name','short_code')\n es_field_name_for_short_code = es_field_name(subject_short_code_field.code, form_model.id)\n query = elasticutils.S().es(urls=ELASTIC_SEARCH_URL).indexes(database_name).doctypes(lower(entity_type)) \\\n .query(or_={es_field_name_for_subject_name + '__match': search_text,\n es_field_name_for_subject_name + '_value': search_text,\n es_field_name_for_short_code + '__match': search_text,\n es_field_name_for_short_code + '_value': search_text}) \\\n .values_dict()\n resp = [{\"id\": r[es_field_name_for_short_code], \"label\": r[es_field_name_for_subject_name]} for r in\n query[:min(query.count(), 50)]]\n return HttpResponse(json.dumps(resp))\n\n\n@valid_web_user\ndef export_subject(request):\n manager = get_database_manager(request.user)\n query_text = request.POST.get('query_text', '')\n subject_type = request.POST.get('subject_type', '').lower()\n subject_list = SubjectQuery().query(request.user, subject_type, query_text)\n form_model = get_form_model_by_entity_type(manager, [subject_type.lower()])\n\n response = HttpResponse(mimetype='application/vnd.ms-excel')\n response['Content-Disposition'] = 'attachment; filename=\"%s.xls\"' % (subject_type,)\n field_codes = form_model.field_codes()\n labels = get_subject_headers(form_model.form_fields)\n raw_data = [labels]\n\n for subject in subject_list:\n raw_data.append(subject)\n\n wb = get_excel_sheet(raw_data, subject_type)\n add_codes_sheet(wb, form_model.form_code, field_codes)\n wb.save(response)\n return response\n\n\ndef add_codes_sheet(wb, form_code, field_codes):\n codes = [form_code]\n codes.extend(field_codes)\n ws = workbook_add_sheet(wb, [codes], \"codes\")\n ws.visibility = 1\n\n\ndef get_example_sms_message(fields, form_code):\n return \"%s %s\" % (form_code, get_example_sms(fields))\n\n\ndef get_example_sms(fields):\n example_sms = \"\"\n for field in fields:\n example_sms = example_sms + \" \" + unicode(_('answer')) + str(fields.index(field) + 1)\n return example_sms","sub_path":"datawinners/entity/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":31469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"83056094","text":"import importlib\nimport pkgutil\nimport json\nimport multiprocessing.queues\nimport sys\nimport traceback\n\nimport sentry_sdk\nfrom littleutils import DecentJSONEncoder\n\n\nclass SysStream:\n def __init__(self, output, color):\n self.output = output\n self.color = color\n\n def __getattr__(self, item):\n return getattr(sys.__stdout__, item)\n\n def write(self, s):\n if not s:\n return\n # TODO limit output length\n self.output.parts.append(\n dict(text=s, color=self.color)\n )\n\n\nclass OutputBuffer:\n def __init__(self):\n self.parts = []\n self.stdout = SysStream(self, \"white\")\n self.stderr = SysStream(self, \"red\")\n\n def pop(self):\n parts = self.parts.copy()\n self.parts.clear()\n return parts\n\n def string(self):\n return \"\".join(part[\"text\"] for part in self.parts)\n\n\noutput_buffer = OutputBuffer()\n\njson_encoder = DecentJSONEncoder()\n\n\ndef make_result(\n passed=False,\n messages=(),\n awaiting_input=False,\n output=None,\n output_parts=None,\n birdseye_objects=None,\n error=None,\n):\n if output is None:\n output = output_buffer.string()\n\n if output_parts is None:\n output_parts = output_buffer.pop()\n\n result = dict(\n passed=passed,\n messages=messages,\n awaiting_input=awaiting_input,\n output=output,\n output_parts=output_parts,\n birdseye_objects=birdseye_objects,\n error=error,\n )\n # Check that JSON encoding works here\n # because failures in the queue pickling are silent\n json_pickler.dumps(result)\n return result\n\n\n# Import eagerly\nsentry_sdk.Hub(sentry_sdk.Client(transport=lambda e: None))\n\n\ndef get_exception_event():\n event = {}\n\n def transport(e):\n nonlocal event\n event = e\n\n client = sentry_sdk.Client(transport=transport)\n hub = sentry_sdk.Hub(client)\n hub.capture_exception()\n\n assert event\n return event\n\n\ndef internal_error_result(sentry_offline=False):\n if sentry_offline:\n sentry_event = get_exception_event()\n else:\n sentry_event = None\n sentry_sdk.capture_exception()\n\n tb = traceback.format_exc()\n output = f\"\"\"\nINTERNAL ERROR IN COURSE:\n=========================\n\n{tb}\n\nThis is an error in our code, not yours.\n\"\"\"\n return make_result(\n output=output,\n output_parts=[dict(color=\"red\", text=output)],\n error=dict(traceback=tb, sentry_event=sentry_event),\n )\n\n\n# Queues don't communicate in pickle so that the worker\n# can't put something malicious for the master to unpickle\nclass JsonPickler:\n def loads(self, b):\n return json.loads(b.decode(\"utf8\"))\n\n def dumps(self, x):\n return json_encoder.encode(x).encode(\"utf8\")\n\n\nmultiprocessing.queues._ForkingPickler = json_pickler = JsonPickler()\n\n\ndef import_submodules(package, recursive=True):\n \"\"\"\n Import all submodules of a module, recursively, including subpackages\n\n https://stackoverflow.com/questions/3365740/how-to-import-all-submodules\n \"\"\"\n if isinstance(package, str):\n package = importlib.import_module(package)\n results = {}\n for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):\n full_name = package.__name__ + '.' + name\n results[full_name] = importlib.import_module(full_name)\n if recursive and is_pkg:\n results.update(import_submodules(full_name))\n return results\n","sub_path":"backend/main/workers/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"501631655","text":"# 129. 求根到叶子节点数字之和\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 Solution1:\n\n def rec(self, node, sum):\n if node == None:\n return 0\n if not node.left and not node.right:\n return sum * 10 + node.val\n return self.rec(node.left, sum * 10 + node.val) + self.rec(node.right, sum * 10 + node.val)\n\n def sumNumbers(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n return self.rec(root, 0)\n\n# 栈\nclass Solution: \n def sumNumbers(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n if root == None:\n return 0\n s = 0\n single_trace = root.val\n stack = []\n stack.append(root)\n if root.left == None and root.right == None:\n return single_trace\n fl = 1\n fr = 1\n while len(stack):\n temp = stack[-1]\n # if temp == None:\n # break\n if temp.left:\n stack.append(temp.left)\n single_trace = single_trace * 10 + temp.left.val\n temp.left = None\n fl = 0\n fr = 1\n elif temp.right:\n stack.append(temp.right)\n single_trace = single_trace * 10 + temp.right.val\n temp.right = None\n fl = 1\n fr = 0\n else:\n if not fl:\n s += single_trace\n single_trace //= 10\n fl = 1\n elif not fr:\n s += single_trace\n single_trace //= 10\n fr = 1\n else:\n single_trace //= 10\n stack.pop()\n \n return s","sub_path":"sumNumbers.py","file_name":"sumNumbers.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"312289320","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 11 10:24:31 2018\n\n@author: js-wxyu\n\"\"\"\n\ndef numerator(n):\n K=(n-2)//3\n remainder=(n-1)%3\n #by using Quadratic function,I can get the initial numerator and denominator without any if.\n den=int(2*K*abs(remainder-1)+2.5*remainder**2-5.5*remainder+4)\n num=int(2*K*abs(remainder-1)+1.5*remainder**2-3.5*remainder+3)\n while K>0:\n den,num=num+den,den\n den,num=num+den*2*K,den\n den,num=num+den,den\n K-=1\n num+=2*den\n return num\n\nimport time\nstart=time.time()\nn=100\n#n could be any natural number.\nprint(sum([int(i) for i in str(numerator(n))])) \nprint(time.time()-start)","sub_path":"Q65.py","file_name":"Q65.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"353178999","text":"import os\n\nimport django\n\nfrom datetime import datetime\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"museum.settings\")\ndjango.setup()\n\nfrom museum_site.wozzt_queue import WoZZT_Queue # noqa: E402\n\n\ndef main():\n now = datetime.now()\n\n if now.weekday() == 1: # Tuesday\n entry = WoZZT_Queue.objects.filter(category=\"tuesday\")\n else:\n entry = WoZZT_Queue.objects.filter(category=\"wozzt\")\n\n entry = entry.order_by(\"-priority\", \"id\")[0]\n entry.send_tweet()\n entry.delete_image()\n entry.delete()\n print(\"Done.\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tools/crons/newwoz.py","file_name":"newwoz.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"315925870","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n#pylint: disable=\n\"\"\"\nFile : reader.py\nAuthor : Valentin Kuznetsov \nDescription: Reader for uproot\nAccess file via xrootd\n xrdcp root://cms-xrd-global.cern.ch/\nfor example:\n xrdcp root://cms-xrd-global.cern.ch//store/data/Run2017F/Tau/NANOAOD/31Mar2018-v1/20000/6C6F7EAE-7880-E811-82C1-008CFA165F28.root\n\"\"\"\nfrom __future__ import print_function, division, absolute_import\n\n# system modules\nimport os\nimport sys\nimport time\nimport json\nimport random\nimport argparse\nimport traceback\n\n# numpy\nimport numpy as np\n\n# uproot\nimport uproot\ntry:\n # uproot verion 3.X\n from awkward import JaggedArray\nexcept:\n # uproot verion 2.X\n from uproot.interp.jagged import JaggedArray\n\n# numba\ntry:\n from numba import jit\nexcept:\n def jit(f):\n \"Simple decorator which calls underlying function\"\n def new_f():\n \"Action function\"\n f()\n return new_f\n\n# psutil\ntry:\n import psutil\nexcept:\n psutil = None\n\n# histogrammar\ntry:\n import histogrammar as hg\n import matplotlib\n matplotlib.use('Agg')\n from matplotlib.backends.backend_pdf import PdfPages\n import matplotlib.pyplot as plt\nexcept ImportError:\n hg = None\n\nclass OptionParser():\n def __init__(self):\n \"User based option parser\"\n self.parser = argparse.ArgumentParser(prog='PROG')\n self.parser.add_argument(\"--fin\", action=\"store\",\n dest=\"fin\", default=\"\", help=\"Input ROOT file\")\n self.parser.add_argument(\"--fout\", action=\"store\",\n dest=\"fout\", default=\"\", help=\"Output file name for ROOT specs\")\n self.parser.add_argument(\"--nan\", action=\"store\",\n dest=\"nan\", default=np.nan, help=\"NaN value for padding, default np.nan\")\n self.parser.add_argument(\"--branch\", action=\"store\",\n dest=\"branch\", default=\"Events\", help=\"Input ROOT file branch, default Events\")\n self.parser.add_argument(\"--identifier\", action=\"store\",\n dest=\"identifier\", default=\"run,event,luminosityBlock\", help=\"Event identifier, default run,event,luminosityBlock\")\n self.parser.add_argument(\"--branches\", action=\"store\",\n dest=\"branches\", default=\"\", help=\"Comma separated list of branches to read, default all\")\n self.parser.add_argument(\"--exclude-branches\", action=\"store\",\n dest=\"exclude_branches\", default=\"\", help=\"Comma separated list of branches to exclude, default None\")\n self.parser.add_argument(\"--nevts\", action=\"store\",\n dest=\"nevts\", default=5, help=\"number of events to parse, default 5, use -1 to read all events)\")\n self.parser.add_argument(\"--chunk-size\", action=\"store\",\n dest=\"chunk_size\", default=1000, help=\"Chunk size to use, default 1000\")\n self.parser.add_argument(\"--specs\", action=\"store\",\n dest=\"specs\", default=None, help=\"Input specs file\")\n self.parser.add_argument(\"--redirector\", action=\"store\",\n dest=\"redirector\", default='root://cms-xrd-global.cern.ch',\n help=\"XrootD redirector, default root://cms-xrd-global.cern.ch\")\n self.parser.add_argument(\"--info\", action=\"store_true\",\n dest=\"info\", default=False, help=\"Provide info about ROOT tree\")\n self.parser.add_argument(\"--hists\", action=\"store_true\",\n dest=\"hists\", default=False, help=\"Create historgams for ROOT tree\")\n self.parser.add_argument(\"--verbose\", action=\"store\",\n dest=\"verbose\", default=0, help=\"verbosity level\")\n\ndef dump_histograms(hdict, hgkeys):\n \"Helper function to dump histograms\"\n if not hg:\n return\n for key in hgkeys:\n make_plot(hdict['%s_orig' % key], '%s_orig' % key)\n make_plot(hdict['%s_norm' % key], '%s_norm' % key)\n\ndef make_plot(hist, name):\n \"Helper function to make histogram\"\n pdir = os.path.join(os.getcwd(), 'pdfs')\n try:\n os.makedirs(pdir)\n except OSError:\n pass\n fname = os.path.join(pdir, '%s.pdf' % name)\n pdf = PdfPages(fname)\n fig = plt.figure()\n hist.plot.matplotlib(name=name)\n pdf.savefig(fig)\n plt.close(fig)\n pdf.close()\n\ndef mem_usage(vmem0, swap0, vmem1, swap1, msg=None):\n \"helper function to show memory usage\"\n if msg:\n print(msg)\n mbyte = 10**6\n vmem_used = (vmem1.used-vmem0.used)/mbyte\n swap_used = (swap1.used-swap0.used)/mbyte\n print(\"VMEM used: %s (MB) SWAP used: %s (MB)\" % (vmem_used, swap_used))\n\ndef performance(nevts, tree, data, startTime, endTime, msg=\"\"):\n \"helper function to show performance metrics of data read from a given tree\"\n try:\n nbytes = sum(x.content.nbytes + x.stops.nbytes \\\n if isinstance(x, JaggedArray) \\\n else x.nbytes for x in data.values())\n print(\"# %s entries, %s %sbranches, %s MB, %s sec, %s MB/sec, %s kHz\" % \\\n (\n nevts,\n len(data),\n msg,\n nbytes / 1024**2,\n endTime - startTime,\n nbytes / 1024**2 / (endTime - startTime),\n tree.numentries / (endTime - startTime) / 1000))\n except Exception as exc:\n print(str(exc))\n\ndef steps(total, size):\n \"Return list of steps within total number given events\"\n step = int(float(total)/float(size))\n chunk = []\n for idx in range(total):\n if len(chunk) == size:\n yield chunk\n chunk = []\n chunk.append(idx)\n if len(chunk) > 0:\n yield chunk\n\ndef dim_jarr(arr):\n \"Return dimention (max length) of jagged array\"\n jdim = 0\n for item in arr:\n if jdim < len(item):\n jdim = len(item)\n return jdim\n\ndef min_max_arr(arr):\n \"\"\"\n Helper function to find out min/max values of given array.\n The array can be either jagged one or normal numpy.ndarray\n \"\"\"\n try:\n if isinstance(arr, JaggedArray):\n minv = 1e15\n maxv = -1e15\n for item in arr:\n if len(item) == 0:\n continue\n if np.min(item) < minv:\n minv = np.min(item)\n if np.max(item) > maxv:\n maxv = np.max(item)\n return float(minv), float(maxv)\n return float(np.min(arr)), float(np.max(arr))\n except ValueError:\n return 1e15, -1e15\n\nclass DataReader(object):\n \"\"\"\n DataReader class provide interface to read ROOT files\n and APIs to access its data. It uses two-pass procedure\n unless specs file is provided. The first pass parse entire\n file and identifies flat/jagged keys, their dimensionality\n and min/max values. All of them are stored in a file specs.\n The second pass uses specs to convert jagged structure of\n ROOT file into flat DataFrame format.\n \"\"\"\n def __init__(self, fin, branch='Events', selected_branches=None,\n exclude_branches=None, identifier=['run', 'event', 'luminosityBlock'],\n chunk_size=1000, nevts=-1, specs=None, nan=np.nan, histograms=False,\n redirector='root://cms-xrd-global.cern.ch', verbose=0):\n self.fin = xfile(fin, redirector)\n self.verbose = verbose\n if verbose:\n print(\"Reading {}\".format(self.fin))\n self.istream = uproot.open(self.fin)\n self.branches = {}\n self.gen = None\n self.out_branches = []\n self.identifier = identifier\n self.tree = self.istream[branch]\n self.nrows = self.tree.numentries\n self.nevts = nevts\n self.idx = -1\n self.chunk_idx = 0\n self.lastIdx = -1\n self.chunk_size = chunk_size if chunk_size < self.nrows else self.nrows\n self.nan = float(nan)\n self.attrs = []\n self.shape = None\n self.cache = {}\n self.hdict = {}\n self.hists = histograms\n if specs:\n self.load_specs(specs)\n else:\n self.jdim = {}\n self.minv = {}\n self.maxv = {}\n self.jkeys = []\n self.fkeys = []\n self.nans = {}\n\n # perform initialization\n time0 = time.time()\n self.init()\n if self.verbose:\n print(\"{} init is complete in {} sec\".format(self, time.time()-time0))\n\n if selected_branches:\n# self.out_branches = [a for b in selected_branches for a in self.attrs if a.startswith(b)]\n self.out_branches = []\n for attr in self.attrs:\n for name in selected_branches:\n if name.find('*') != -1:\n if attr.startswith(name):\n self.out_branches.append(attr)\n else:\n if attr == name:\n self.out_branches.append(attr)\n\n if self.out_branches:\n if self.verbose:\n print(\"Select branches ...\")\n for name in sorted(self.out_branches):\n print(name)\n if exclude_branches:\n out_branches = set()\n for attr in self.attrs:\n count = 0\n for name in exclude_branches:\n if name.find('*') != -1:\n if attr.startswith(name):\n count += 1\n else:\n if attr == name:\n count += 1\n if not count:\n out_branches.add(attr)\n self.out_branches = list(out_branches)\n if self.out_branches:\n if self.verbose:\n print(\"Select branches ...\")\n for name in sorted(self.out_branches):\n print(name)\n\n # declare histograms for original and normilized values\n if hg and self.hists:\n for key in self.attrs:\n low = self.minv[key]\n high = self.maxv[key]\n self.hdict['%s_orig' % key] = \\\n hg.Bin(num=100, low=low, high=high, quantity=lambda x: x, value=hg.Count())\n self.hdict['%s_norm' % key] = \\\n hg.Bin(num=100, low=0, high=1, quantity=lambda x: x, value=hg.Count())\n\n\n def load_specs(self, specs):\n \"load given specs\"\n if not isinstance(specs, dict):\n if self.verbose:\n print(\"load specs from {}\".format(specs))\n specs = json.load(open(specs))\n if self.verbose > 1:\n print(\"ROOT specs: {}\".format(json.dumps(specs)))\n self.jdim = specs['jdim']\n self.minv = specs['minv']\n self.maxv = specs['maxv']\n self.jkeys = specs['jkeys']\n self.fkeys = specs['fkeys']\n self.nans = specs['nans']\n\n def fetch_data(self, key):\n \"fetch data for given key from underlying ROOT tree\"\n if sys.version.startswith('3.') and isinstance(key, str):\n key = key.encode('ascii') # convert string to binary\n if key in self.branches:\n return self.branches[key]\n raise Exception('Unable to find \"%s\" key in ROOT branches' % key)\n\n def read_chunk(self, nevts, set_branches=False, set_min_max=False):\n \"Reach chunk of events and determine min/max values as well as load branch values\"\n # read some portion of the data to determine branches\n startTime = time.time()\n if not self.gen:\n if self.out_branches:\n self.gen = self.tree.iterate(branches=self.out_branches+self.identifier,\n entrysteps=nevts, keycache=self.cache)\n else:\n self.gen = self.tree.iterate(entrysteps=nevts, keycache=self.cache)\n self.branches = {} # start with fresh dict\n try:\n self.branches = next(self.gen) # python 3.X and 2.X\n except StopIteration:\n if self.out_branches:\n self.gen = self.tree.iterate(branches=self.out_branches+self.identifier,\n entrysteps=nevts, keycache=self.cache)\n else:\n self.gen = self.tree.iterate(entrysteps=nevts, keycache=self.cache)\n self.branches = next(self.gen) # python 3.X and 2.X\n endTime = time.time()\n self.idx += nevts\n if self.verbose:\n performance(nevts, self.tree, self.branches, startTime, endTime)\n if set_branches:\n for key, val in self.branches.items():\n self.minv[key], self.maxv[key] = min_max_arr(val)\n if isinstance(val, JaggedArray):\n self.jkeys.append(key)\n else:\n self.fkeys.append(key)\n if set_min_max:\n for key, val in self.branches.items():\n minv, maxv = min_max_arr(val)\n if minv < self.minv[key]:\n self.minv[key] = minv\n if maxv > self.maxv[key]:\n self.maxv[key] = maxv\n\n def columns(self):\n \"Return columns of produced output vector\"\n cols = self.flat_keys()\n for key in self.jagged_keys():\n for idx in range(self.jdim[key]):\n cols.append('%s_%s' % (key, idx))\n return cols\n\n def init(self):\n \"Initialize class data members by scaning ROOT tree\"\n if self.jdim and self.minv and self.maxv:\n self.attrs = sorted(self.flat_keys()) + sorted(self.jagged_keys())\n self.shape = len(self.flat_keys()) + sum(self.jdim.values())\n msg = \"+++ first pass: %s events, (%s-flat, %s-jagged) branches, %s attrs\" \\\n % (self.nrows, len(self.flat_keys()), len(self.jagged_keys()), self.shape)\n if self.verbose:\n print(msg)\n if self.verbose > 1:\n print(\"\\n### Flat attributes:\")\n for key in self.flat_keys():\n print(key)\n print(\"\\n### Jagged array attributes:\")\n for key in self.jagged_keys():\n print(key)\n self.idx = -1\n return\n\n if psutil and self.verbose:\n vmem0 = psutil.virtual_memory()\n swap0 = psutil.swap_memory()\n\n msg = ''\n time0 = time.time()\n\n # if self.nevnts=0 we'll use 2x self.chunk_size to determine\n # the dimensions otherwise job waits too long to possibly scan\n # all events in a file which can be too large.\n nrows = self.nrows\n if not self.nevts:\n nrows = 2*self.chunk_size\n if self.verbose:\n print(\"# will use {} events to obtain dimensionality\".format(nrows))\n\n # scan all rows to find out largest jagged array dimension\n tot = 0\n set_branches = True\n set_min_max = True\n for chunk in steps(nrows, self.chunk_size):\n nevts = len(chunk) # chunk here contains event indexes\n tot += nevts\n self.read_chunk(nevts, set_branches=set_branches, set_min_max=set_min_max)\n set_branches = False # we do it once\n for key in self.jkeys:\n if key not in self.jdim:\n self.jdim[key] = 0\n dim = dim_jarr(self.fetch_data(key))\n if dim > self.jdim.get(key, 0):\n self.jdim[key] = dim\n if self.nevts > 0 and tot > self.nevts:\n break\n\n # if we've been asked to read all or zero events we determine\n # number of events as all available rows in TTree which is set as\n # self.tree.numentries in __init__\n if self.nevts < 1:\n self.nevts = self.nrows\n\n # initialize all nan values (zeros) in normalize phase-space\n # this should be done after we get all min/max values\n for key in self.branches.keys():\n self.nans[key] = self.normalize(key, 0)\n\n # reset internal indexes since we done with first pass reading\n self.idx = -1\n self.gen = None\n\n # define final list of attributes\n self.attrs = sorted(self.flat_keys()) + sorted(self.jagged_keys())\n\n if self.verbose > 1:\n print(\"\\n### Dimensionality\")\n for key, val in self.jdim.items():\n print(key, val)\n print(\"\\n### min/max values\")\n for key, val in self.minv.items():\n print(key, val, self.maxv[key])\n self.shape = len(self.flat_keys()) + sum(self.jdim.values())\n msg = \"--- first pass: %s events, (%s-flat, %s-jagged) branches, %s attrs\" \\\n % (self.nrows, len(self.flat_keys()), len(self.jagged_keys()), self.shape)\n if self.verbose:\n print(msg)\n if self.verbose > 1:\n print(\"\\n### Flat attributes:\")\n for key in self.flat_keys():\n print(key)\n print(\"\\n### Jagged array attributes:\")\n for key in self.jagged_keys():\n print(key)\n if psutil and self.verbose:\n vmem1 = psutil.virtual_memory()\n swap1 = psutil.swap_memory()\n mem_usage(vmem0, swap0, vmem1, swap1)\n\n def write_specs(self, fout):\n \"Write specs about underlying file\"\n out = {'jdim': self.jdim, 'minv': self.minv, 'maxv': self.maxv}\n out['fkeys'] = self.flat_keys()\n out['jkeys'] = self.jagged_keys()\n out['nans'] = self.nans\n if self.verbose:\n print(\"write specs {}\".format(fout))\n with open(fout, 'w') as ostream:\n ostream.write(json.dumps(out))\n\n def next(self, verbose=0):\n \"Provides read interface for next event using vectorize approach\"\n self.idx = self.idx + 1\n # build output matrix\n time0 = time.time()\n shape = len(self.flat_keys())\n for key in sorted(self.jagged_keys()):\n shape += self.jdim[key]\n xdf = np.ndarray(shape=(shape,))\n mask = np.ndarray(shape=(shape,), dtype=np.int)\n\n # read new chunk of records if necessary\n if not self.idx % self.chunk_size:\n if self.idx + self.chunk_size > self.nrows:\n nevts = self.nrows - self.idx\n else:\n nevts = self.chunk_size\n self.read_chunk(nevts)\n self.chunk_idx = 0 # reset chunk index after we read the chunk of data\n self.idx = self.idx - nevts # reset index after chunk read by nevents offset\n if self.verbose > 1:\n print(\"idx\", self.idx, \"read\", nevts, \"events\")\n\n # read event info\n event = []\n for key in self.identifier:\n fdata = self.fetch_data(key)\n if len(fdata) <= self.chunk_idx:\n raise Exception(\"For key='%s' unable to find data at pos=%s while got %s\" \\\n % (key, self.chunk_idx, len(fdata)))\n event.append(fdata[self.chunk_idx])\n\n # form DataFrame record\n rec = {}\n for key in self.branches.keys():\n try:\n fdata = self.fetch_data(key)\n if len(fdata) <= self.chunk_idx:\n raise Exception(\"For key='%s' unable to find data at pos=%s while got %s\" \\\n % (key, self.chunk_idx, len(fdata)))\n rec[key] = fdata[self.chunk_idx]\n except:\n print(\"failed key\", key)\n print(\"failed idx\", self.chunk_idx)\n print(\"len(fdata)\", len(fdata))\n raise\n\n # advance chunk index since we read the record\n self.chunk_idx = self.chunk_idx + 1\n\n idx = 0\n for idx, key in enumerate(sorted(self.flat_keys())):\n if sys.version.startswith('3.') and isinstance(key, str):\n key = key.encode('ascii') # convert string to binary\n xdf[idx] = self.normalize(key, rec[key])\n if hg and self.hists:\n self.hdict['%s_orig' % key].fill(rec[key])\n if xdf[idx] != self.nan:\n self.hdict['%s_norm' % key].fill(xdf[idx])\n mask[idx] = 1\n if idx: # only advance position if we read something from flat_keys\n pos = idx + 1 # position in xdf for jagged branches\n else:\n pos = 0\n\n for key in sorted(self.jagged_keys()):\n # check if key in our record\n if key in rec.keys():\n vals = rec.get(key, [])\n else: # if not convert key to bytes key and use it to look-up a value\n vals = rec.get(key.encode('utf-8'), [])\n for jdx in range(self.jdim[key]):\n # assign np.nan in case if we get empty array\n val = vals[jdx] if len(vals) > jdx else np.nan\n idx = pos+jdx\n xdf[idx] = self.normalize(key, val)\n if hg and self.hists:\n self.hdict['%s_orig' % key].fill(val)\n if xdf[idx] != self.nan:\n self.hdict['%s_norm' % key].fill(xdf[idx])\n if np.isnan(val):\n mask[idx] = 0\n else:\n mask[idx] = 1\n pos = idx + 1\n\n if verbose > 1:\n print(\"# idx=%s event=%s shape=%s proc.time=%s\" % (\n self.idx, event, np.shape(xdf), (time.time()-time0)))\n if self.idx < 3:\n # pick-up 3 branches for cross checking\n if len(self.jagged_keys()):\n arrIdx = [random.randint(0, len(self.jagged_keys())-1) for _ in range(3)]\n try:\n keys = [self.jagged_keys()[i] for i in arrIdx]\n for key in keys:\n data = self.tree[key].array()\n idx = self.attrs.index(key)\n startIdx, endIdx = self.find_branch_idx(key)\n print(\"+ branch=%s, row %s, position %s:%s, min=%s max=%s\" \\\n % (key, self.idx, startIdx, endIdx, self.minv[key], self.maxv[key]))\n print(\"+ xdf\", xdf[startIdx:endIdx])\n print(data)\n except:\n print(\"arrIdx=%s, len(jagged_keys)=%s\" % (arrIdx, len(self.jagged_keys())))\n traceback.print_exc()\n return xdf, mask\n\n def find_branch_idx(self, attr):\n \"Find start and end indexes of given attribute\"\n idx = self.attrs.index(attr)\n if attr in self.flat_keys():\n return idx, idx+1\n start_idx = len(self.flat_keys())\n for key in sorted(self.jagged_keys()):\n if key == attr:\n return start_idx, start_idx + self.jdim[key]\n start_idx += self.jdim[key]\n raise Exception(\"Unable to find branch idx for %s\" % attr)\n\n def jagged_keys(self):\n \"helper function to return list of jagged branches\"\n jkeys = sorted(list(self.jkeys))\n if self.out_branches:\n return [k for k in jkeys if k in self.out_branches]\n return jkeys\n\n def flat_keys(self):\n \"helper function to return list of normal branches\"\n if self.out_branches:\n fkeys = [k for k in self.fkeys if k not in self.identifier and k in self.out_branches]\n return sorted(fkeys)\n fkeys = [k for k in self.fkeys if k not in self.identifier]\n return sorted(fkeys)\n\n def draw_value(self, key):\n \"Draw a random value from underlying chunk for a given key\"\n data = self.branches[key] # jagged array\n # get random index for accessing element of jagged array\n while True:\n idx = random.randint(0, len(data)-1)\n values = data[idx]\n if len(values):\n if len(values) == 1:\n val = values[0]\n else:\n jdx = random.randint(0, len(values)-1)\n val = values[jdx]\n if random.randint(0, 1):\n return val + val/10.\n return val - val/10.\n\n def normalize(self, key, val):\n \"Normalize given value to 0-1 range according to min/max values\"\n # in case if our value is np.nan we'll assign nan value given to class\n if np.isnan(val):\n return self.nan\n minv = float(self.minv.get(key, 0))\n maxv = float(self.maxv.get(key, 1))\n if maxv == minv:\n return val\n return (val-minv)/(maxv-minv)\n\n def denormalize(self, key, val):\n \"De-normalize given value to 0-1 range according to min/max values\"\n if val == 0:\n return self.nan\n minv = float(self.minv.get(key, 0))\n maxv = float(self.maxv.get(key, 1))\n return val*(maxv-minv)+minv\n\n def info(self):\n \"Provide human readable form of ROOT branches\"\n print(\"Number of events : %s\" % self.nrows)\n print(\"# flat branches : %s\" % len(self.flat_keys()))\n if self.verbose:\n for key in self.flat_keys():\n print(\"%s values in [%s, %s] range, dim=%s\" % (\n key,\n self.minv.get(key, 'N/A'),\n self.maxv.get(key, 'N/A'),\n self.jdim.get(key, 'N/A')))\n print(\"# jagged branches : %s\" % len(self.jagged_keys()))\n if self.verbose:\n for key in self.jagged_keys():\n print(\"%s values in [%s, %s] range, dim=%s\" % (\n key,\n self.minv.get(key, 'N/A'),\n self.maxv.get(key, 'N/A'),\n self.jdim.get(key, 'N/A')))\n\ndef object_size(data):\n \"Return size of the data\"\n return sys.getsizeof(data.tobytes())\n\ndef size_format(uinput):\n \"\"\"\n Format file size utility, it converts file size into KB, MB, GB, TB, PB units\n \"\"\"\n try:\n num = float(uinput)\n except Exception as exc:\n print_exc(exc)\n return \"N/A\"\n base = 1000. # CMS convention to use power of 10\n if base == 1000.: # power of 10\n xlist = ['', 'KB', 'MB', 'GB', 'TB', 'PB']\n elif base == 1024.: # power of 2\n xlist = ['', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']\n for xxx in xlist:\n if num < base:\n return \"%3.1f%s\" % (num, xxx)\n num /= base\n\ndef parse(reader, nevts, verbose, fout, hists):\n \"Parse given number of events from given reader\"\n time0 = time.time()\n count = 0\n if nevts == -1:\n nevts = reader.nrows\n farr = []\n jarr = []\n for _ in range(nevts):\n xdf, _mask = reader.next(verbose=verbose)\n fdx = len(reader.flat_keys())\n flat = xdf[:fdx]\n jagged = xdf[fdx:]\n fsize = object_size(flat)\n jsize = object_size(jagged)\n farr.append(fsize)\n jarr.append(jsize)\n count += 1\n print(\"avg(flat)=%s, avg(jagged)=%s, ratio=%s\" \\\n % (size_format(np.mean(farr)), size_format(np.mean(jarr)), np.mean(farr)/np.mean(jarr)))\n totTime = time.time()-time0\n print(\"Read %s evts, %s Hz, total time %s\" % (\n count, count/totTime, totTime))\n if fout:\n reader.write_specs(fout)\n if hg and hists:\n hgkeys = [k for k in reader.attrs]\n dump_histograms(reader.hdict, hgkeys)\n\ndef write(reader, nevts, verbose, fout):\n \"Write given number of events from given reader to NumPy\"\n time0 = time.time()\n count = 0\n with open(fout, 'wb+') as ostream:\n if nevts == -1:\n nevts = reader.nrows\n for _ in range(nevts):\n xdf = reader.next(verbose=verbose)\n ostream.write(xdf.tobytes())\n count += 1\n totTime = time.time()-time0\n print(\"Read %s evts, %s Hz, total time %s\" % (\n count, count/totTime, totTime))\n\ndef xfile(fin, redirector='root://cms-xrd-global.cern.ch'):\n \"Test if file is local or remote and setup proper prefix\"\n if fin.startswith(redirector):\n return fin\n if os.path.exists(fin):\n return fin\n return \"%s/%s\" % (redirector, fin)\n\ndef main():\n \"Main function\"\n optmgr = OptionParser()\n opts = optmgr.parser.parse_args()\n fin = opts.fin\n fout = opts.fout\n verbose = int(opts.verbose)\n nevts = int(opts.nevts)\n chunk_size = int(opts.chunk_size)\n nan = float(opts.nan)\n nevts = int(opts.nevts)\n specs = opts.specs\n branch = opts.branch\n branches = opts.branches.split(',') if opts.branches else []\n exclude_branches = []\n if opts.exclude_branches:\n if os.path.isfile(opts.exclude_branches):\n exclude_branches = \\\n [r.replace('\\n', '') for r in open(opts.exclude_branches).readlines()]\n else:\n exclude_branches = opts.exclude_branches.split(',')\n hists = opts.hists\n identifier = [k.strip() for k in opts.identifier.split(',')]\n reader = DataReader(fin, branch=branch, selected_branches=branches,\n identifier=identifier, exclude_branches=exclude_branches, histograms=hists,\n nan=nan, chunk_size=chunk_size,\n nevts=nevts, specs=specs, redirector=opts.redirector, verbose=verbose)\n if opts.info:\n reader.info()\n else:\n parse(reader, nevts, verbose, fout, hists)\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/python/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":29354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"36278529","text":"from subprocess import call\nfrom yuuki.dispatch import action\n\nCARRIERS = {\"AT&T\": \"txt.att.net\",\n \"T-Mobile\": \"tmomail.net\",\n \"Verizon\": \"vtext.com\",\n \"Sprint\": \"pm.sprint.com\",\n \"Virgin Mobile\": \"vmobl.com\",\n \"Tracfone\": \"mmst5.tracfone.com\",\n \"Metro PCS\": \"mymetropcs.com\",\n \"Boost Mobile\": \"myboostmobile.com\",\n \"Cricket\": \"sms.mycricket.com\",\n \"Ptel\": \"ptel.com\",\n \"Republic Wireless\": \"text.republicwireless.com\",\n \"Suncom\": \"tms.suncom.com\",\n \"Ting\": \"message.ting.com\",\n \"U.S. Cellular\": \"email.uscc.net\",\n \"Consumer Cellular\": \"cingularme.com\",\n \"C-Spire\": \"cspire1.com\",\n \"Page Plus\": \"vtext.com\"}\n\n\n@action(target='openc2:cellphone')\ndef notify(target, actuator, modifier):\n \"\"\"\n Send an alert to a cellphone.\n \n Required target specifiers:\n cellphone number - target['number']\n cell carrier - target['carrier']\n alert message - target['message']\n \"\"\"\n to = \"{}@{}\".format(target['number'], CARRIERS[target['carrier']])\n subject = \"OpenC2 Alert\"\n message = target['message']\n mailcmd = \"echo '{}' | mail -s '{}' {}\".format(message, subject, to)\n\n return call(mailcmd, shell=True)\n\n\n@action(target='openc2:domain')\ndef mitigate(target, actuator, modifier):\n \"\"\"Some documentation about mitigation\"\"\"\n return \"I can't do that, Dave\"\n\n\n","sub_path":"examples/simple_notify.py","file_name":"simple_notify.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"222927952","text":"import random\nimport time\n\nfrom prometheus_client import start_http_server, Summary, Counter, Histogram\n\n# Create a metric to track time spent and requests made.\nREQUEST_TIME = Summary('request_processing', 'Time spent processing request')\nSUCCESS_COUNTER = Counter('request_success', 'Success request')\nEXCEPTION_COUNTER = Counter('request_exception', 'Exceptions', [\"name\"])\nLATENCY_METRICS = Counter(\n \"request_latency_seconds\",\n \"Request latency in seconds\",\n)\n\n\n# Decorate function with metric.\n@REQUEST_TIME.time()\ndef process_request(t):\n # Summarize time\n time.sleep(t)\n\n # Increase counter\n if random.random() < 0.5:\n SUCCESS_COUNTER.inc()\n\n # Increase exception\n if random.random() < 0.4:\n try:\n exception = random.choice([KeyError, KeyboardInterrupt, InterruptedError])\n with EXCEPTION_COUNTER.labels(name=repr(exception)).count_exceptions(exception):\n raise exception\n except:\n pass\n\n # Histogram metric\n LATENCY_METRICS.observe(t * 10)\n\n\nif __name__ == '__main__':\n # Start up the server to expose the metrics.\n port = 8000\n addr = \"\"\n start_http_server(port, addr=addr)\n # Generate some requests.\n while True:\n process_request(random.random())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"310997596","text":"# -*- coding:utf8 -*-\n\nfrom plugins.plugin_base import PluginBase\nimport sqlite3\nimport random\nfrom datetime import datetime, timezone, timedelta\nimport re\n\n\nqueries = {\n 'new': \"insert into [accounts] (qq_id, balance, last_access) values(?, ?, strftime('%s','now'))\",\n 'get_acc': 'select * from [accounts] where qq_id=?',\n 'update': \"update [accounts] set balance=?, last_access=strftime('%s','now') where qq_id=?\",\n 'transfer': None\n}\n\nregexes = {\n 'transfer': re.compile(r'^\\.transfer \\[CQ:at,qq=\\d+] \\d+(\\.\\d{0,2})?$'),\n 'transfer_id': re.compile(r'(?<=qq=)\\d+')\n}\n\n\n\nclass AccountManager(PluginBase):\n def __init__(self):\n super().__init__()\n self.conn = sqlite3.connect('./plugins/data/account.db')\n\n def on_delete(self):\n self.conn.rollback()\n\n def on_group_message(self, group:str, sender:str, message:str):\n if regexes['transfer'].match(message):\n recipient = regexes['transfer_id'].search(message)[0]\n amount = float((message.split(' '))[2])\n self.transfer(sender, recipient, amount, group)\n # else: lottery\n\n\n def on_private_message(self, sender:str, message:str):\n if message != '.bal':\n return\n c = self.conn.cursor()\n acc = c.execute(queries['get_acc'], (sender,)).fetchone()\n # if has account, return bal\n if acc:\n timestr = datetime.fromtimestamp(acc[2], tz=timezone(timedelta(hours=8))).ctime()\n self.send_private(sender, f\"您的余额是{acc[1]}\\n最后更新于{timestr}\")\n # else create account\n else:\n self.create_account(sender)\n self.conn.commit()\n\n def create_account(self, qq_id:str):\n c = self.conn.cursor()\n new_bal = round(random.uniform(2000, 10000), 2)\n c.execute(queries['new'], (qq_id, new_bal))\n c.close()\n conn.commit()\n self.send_private(sender, f\"创建账户成功,您的余额是{new_bal}\")\n\n def transfer(self, sender:str, recipient:str, amount:float, group:str):\n c = self.conn.cursor()\n send_acc = c.execute(queries['get_acc'], (sender,)).fetchone()\n recv_acc = c.execute(queries['get_acc'], (recipient,)).fetchone()\n if not send_acc:\n self.send_group(group, f\"没有属于{sender}的账户,请私聊发送'.bal'创建\")\n elif not recv_acc:\n self.send_group(group, f\"没有属于{recipient}的账户,请私聊发送'.bal'创建\")\n elif send_acc[1] < amount:\n self.send_group(group, f\"余额不足\")\n else:\n c.execute(queries['update'], (send_acc[1] - amount, sender))\n c.execute(queries['update'], (recv_acc[1] + amount, recipient))\n self.conn.commit()\n self.send_group(group, f\"转账成功\")\n c.close()\n\n def lottery(self, sender:str, message:str):\n pass\n","sub_path":"plugins/cash/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":2894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"629823422","text":"from flask import url_for\n\n\nclass DeviceSerializer:\n def serialize(device):\n owner = None\n if device.owner_id:\n owner = {'id': device.owner_id,\n 'href': url_for('person', person_id=device.owner_id)}\n\n return {'device':\n {'id': device.id,\n 'href': device.url,\n 'name': device.name,\n 'mac': device.mac_address,\n 'owner': owner,\n 'last_seen': device.last_seen,\n 'connections': device.connections_url}}\n\n\nclass DevicesSerializer:\n def serialize(devices):\n return {'devices': [DeviceSerializer.serialize(d) for d in devices]}\n\n\nclass DeviceBasicSerializer:\n def serialize(device):\n url = url_for('device', device_id=device.id)\n return {'device':\n {'id': device.id,\n 'href': url,\n 'mac': device.mac_address}}\n","sub_path":"serializers/device.py","file_name":"device.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"281507266","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('invoices', '0014_billing_is_electronic'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='billing',\n options={'ordering': ['-register_at'], 'verbose_name': 'Factura', 'verbose_name_plural': 'Facturas', 'permissions': (('show_billing', 'Can Details Billing'), ('index_billing', 'Can List Billing'), ('cancel_billing', 'Can Canceled Billing'), ('pdf_billing', 'Can Pdf Billing'), ('copy_billing', 'Can Copy Billing'))},\n ),\n migrations.AddField(\n model_name='billing',\n name='register_at',\n field=models.DateTimeField(default=datetime.datetime.now, verbose_name=b'Fecha de Registro'),\n ),\n migrations.AlterField(\n model_name='reportsbilling',\n name='user',\n field=models.ForeignKey(verbose_name=b'Realizado por', to=settings.AUTH_USER_MODEL),\n ),\n ]\n","sub_path":"invoices/migrations/0015_auto_20151205_2027.py","file_name":"0015_auto_20151205_2027.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"607358378","text":"''' Demonstrates different ways to request financial data '''\r\nfrom datetime import datetime\r\nfrom threading import Thread\r\nimport time\r\n\r\nfrom ibapi.client import EClient, Contract\r\nfrom ibapi.wrapper import EWrapper\r\nfrom ibapi.utils import iswrapper\r\n\r\nclass MarketReader(EWrapper, EClient):\r\n ''' Serves as the client and the wrapper '''\r\n\r\n def __init__(self, addr, port, client_id):\r\n EClient. __init__(self, self)\r\n\r\n # Connect to TWS\r\n self.connect(addr, port, client_id)\r\n\r\n # Launch the client thread\r\n thread = Thread(target=self.run)\r\n thread.start()\r\n\r\n @iswrapper\r\n def tickByTickMidPoint(self, reqId, tick_time, midpoint):\r\n ''' Called in response to reqTickByTickData '''\r\n\r\n print('tickByTickMidPoint - Midpoint tick: {}'.format(midpoint))\r\n\r\n @iswrapper\r\n def tickPrice(self, reqId, field, price, attribs):\r\n ''' Called in response to reqMktData '''\r\n\r\n print('tickPrice - field: {}, price: {}'.format(field, price))\r\n\r\n @iswrapper\r\n def tickSize(self, reqId, field, size):\r\n ''' Called in response to reqMktData '''\r\n\r\n print('tickSize - field: {}, size: {}'.format(field, size))\r\n\r\n @iswrapper\r\n def realtimeBar(self, reqId, time, open, high, low, close, volume, WAP, count):\r\n ''' Called in response to reqRealTimeBars '''\r\n\r\n print('realtimeBar - Opening price: {}'.format(open))\r\n\r\n @iswrapper\r\n def historicalData(self, reqId, bar):\r\n ''' Called in response to reqHistoricalData '''\r\n\r\n print('historicalData - Close price: {}'.format(bar.close))\r\n\r\n @iswrapper\r\n def fundamentalData(self, reqId, data):\r\n ''' Called in response to reqFundamentalData '''\r\n\r\n print('Fundamental data: ' + data)\r\n\r\n def error(self, reqId, code, msg):\r\n ''' Called if an error occurs '''\r\n\r\n print('Error {}: {}'.format(code, msg))\r\n\r\ndef main():\r\n\r\n # Create the client and connect to TWS\r\n client = MarketReader('127.0.0.1', 7497, 0)\r\n\r\n # Request the current time\r\n con = Contract()\r\n con.symbol = 'IBM'\r\n con.secType = 'STK'\r\n con.exchange = 'SMART'\r\n con.currency = 'USD'\r\n\r\n # Request ten ticks containing midpoint data\r\n client.reqTickByTickData(0, con, 'MidPoint', 10, True)\r\n\r\n # Request market data\r\n client.reqMktData(1, con, '', False, False, [])\r\n\r\n # Request current bars\r\n client.reqRealTimeBars(2, con, 5, 'MIDPOINT', True, [])\r\n\r\n # Request historical bars\r\n now = datetime.now().strftime(\"%Y%m%d, %H:%M:%S\")\r\n client.reqHistoricalData(3, con, now, '2 w', '1 day',\r\n 'MIDPOINT', False, 1, False, [])\r\n\r\n # Request fundamental data\r\n client.reqFundamentalData(4, con, 'ReportSnapshot', [])\r\n\r\n # Sleep while the requests are processed\r\n time.sleep(5)\r\n\r\n # Disconnect from TWS\r\n client.disconnect()\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"algobook_python/algo-book/ch8/market_reader.py","file_name":"market_reader.py","file_ext":"py","file_size_in_byte":2922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"50615338","text":"#\n# Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.\n#\n# Example:\n#\n# Input:\n# [\n# 1->4->5,\n# 1->3->4,\n# 2->6\n# ]\n# Output: 1->1->2->3->4->4->5->6\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n # 前面做过两个链表融合的,直接用那道题的方法逐个融合\n def mergeKLists1(self, lists):\n \"\"\"\n :type lists: List[ListNode]\n :rtype: ListNode\n \"\"\"\n from functools import reduce\n return reduce(self.merge_two_lists, lists, None)\n # 交上去超时\n\n # 还是用两个链表融合的方法,但不是逐个融合,而是用分治\n def mergeKLists(self, lists):\n import sys\n sys.setrecursionlimit(100000) # 设置递归栈大小\n # leetcode上的python环境递归深度最多只能为1000,对于某些变态的test case,1000不够,所以设大点\n if not lists:\n return []\n if len(lists) == 1:\n return lists[0]\n else:\n return self.merge_two_lists(self.mergeKLists(lists[:len(lists) // 2]),\n self.mergeKLists(lists[len(lists) // 2:]))\n\n def merge_two_lists(self, l1, l2):\n if l1 and l2:\n if l1.val > l2.val:\n l1, l2 = l2, l1\n l1.next = self.merge_two_lists(l1.next, l2)\n return l1 or l2\n\n\nif __name__ == \"__main__\":\n l1, l1.next, l1.next.next = ListNode(1), ListNode(4), ListNode(5)\n l2, l2.next, l2.next.next = ListNode(1), ListNode(3), ListNode(4)\n l3, l3.next = ListNode(2), ListNode(6)\n lists = [l1, l2, l3]\n Solution().mergeKLists(lists)\n","sub_path":"023_merge_k_sorted_lists.py","file_name":"023_merge_k_sorted_lists.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"323686256","text":"# Write programs with loops that compute\n# a.  The sum of all even numbers between 2 and 100 (inclusive).\n# b.  The sum of all squares between 1 and 100 (inclusive).\n# c.  All powers of 2 from 2 0 up to 2 20 .\n# d.  The sum of all odd numbers between a and b (inclusive), where a and b are\n# inputs.\n# e.  The sum of all odd digits of an input. (For example, if the input is 32677, the\n# sum would be 3 + 7 + 7 = 17.)\n\nsum = 0.0\n\na = int(input(\"Enter a: \"))\nb = int(input(\"Enter b:\"))\n\nfor i in range(a, b):\n sum += i\n\nprint(sum)\n","sub_path":"Chapter4/P4.1D.py","file_name":"P4.1D.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"531914784","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport services.controlers.loggControler\nfrom services.controlers.loggControler import LoggControler\nfrom services.exceptions import *\nfrom services.controlers.controler import Controler\nimport services.querys.censusAssistanceQuery\nfrom services.querys.censusAssistanceQuery import CensusAssistanceQuery\nimport services.controlers.affectedPeopleControler\nimport os\nimport hashlib\nimport re\nimport cgi\nimport urllib\nfrom services.tools import *\n\nclass CensusAssistancesControler(Controler):\n\tdef __init__(self):\n\t\ttry:\n\t\t\tqueryPath=\"services.querys.censusAssistanceQuery.CensusAssistanceQuery()\"\n\t\t\tloggMsg=\"CensusAssistancesControler\"\n\t\t\tinfoMsg=\"CENSO_AYUDAS\"\n\t\t\tsuper(CensusAssistancesControler, self).__init__(queryPath, loggMsg, infoMsg)\n\t\texcept Exception as e:\n\t\t\tloggControler = LoggControler()\n\t\t\tloggControler.addLogg('Controler: CensusAssistancesControler/__init__()', ERROR_NO_DEFINIDO, e.message)\n\n\tdef getByEventId(self, eventId, sessionJson):\n\t\tlistObjs=[]\n\t\tstate = 300\n\t\ttry:\n\t\t\tsessionJson[\"userTypeId\"] = int(sessionJson[\"userTypeId\"])\n\t\t\tcompanyId = int(sessionJson[\"companyIdSession\"])\n\t\t\tobjs = self.queryObj.getByEventIdAndCompanyId(eventId, companyId)\n\t\t\tfor obj in objs:\n\t\t\t\tlistObjs.append(obj.toDictFront())\n\t\t\tstate = OK\n\t\texcept Exception as e:\n\t\t\tloggControler = services.controlers.loggControler.LoggControler()\n\t\t\tloggControler.addLogg('Controler: '+self.loggMsg+'-getByEventId()', ERROR_NO_DEFINIDO, e.message)\t\n\t\treturn listObjs, state\n\n\tdef getHeadsOfHousehold(self, eventId, sessionJson):\n\t\tlistObjs=[]\n\t\tstate = 300\n\t\ttry:\n\t\t\tsessionJson[\"userTypeId\"] = int(sessionJson[\"userTypeId\"])\n\t\t\tcompanyId = int(sessionJson[\"companyIdSession\"])\n\t\t\tobjs = self.queryObj.getByEventIdAndCompanyId(eventId, companyId)\n\t\t\tfor obj in objs:\n\t\t\t\tlistObjs.append(obj.getHeadOfHousehold())\n\t\t\tstate = OK\n\t\texcept Exception as e:\n\t\t\tloggControler = services.controlers.loggControler.LoggControler()\n\t\t\tloggControler.addLogg('Controler: '+self.loggMsg+'-getByEventId()', ERROR_NO_DEFINIDO, e.message)\t\n\t\treturn listObjs, state\n\n\tdef add(self, eventId, preparedBy, neighborhood, specificAreaCensus, sector, censusDate, \n\t\t\theadOfHousehold, householdHeadLastName, address, femaleUnder15years, maleUnder15years, femaleOver16years, \n\t\t\tmaleOver16years, total, ruralOrUrban, housingStatus, supplyKit, notSupplyKit, nightKit, groomingKit, \n\t\t\tothers, otherName, documentTypeId, documentNum, cellphone, municipality, beneficiarySignature,\n\t\t\tbeneficiaryfingerprint, censusSignature, deliveryDate, deliveryStatus, signature, fingerprint, sessionJson):\n\t\tmessage=self.infoMsg+\"_NO_REGISTRADO\"\n\t\tstate = 300\n\t\ttry:\n\t\t\t#sessionJson[\"userTypeId\"] = int(sessionJson[\"userTypeId\"])\n\t\t\tcompanyId = int(sessionJson[\"companyIdSession\"])\n\t\t\t# Validaciones\n\t\t\tdoRegister, validateMsg = self.getValidate()\n\t\t\tif total is None:\n\t\t\t\tfemUnd15=femaleUnder15years\n\t\t\t\tmalUnd15=maleUnder15years\n\t\t\t\tfemOve16=femaleOver16years\n\t\t\t\tmalOve16=maleOver16years\n\t\t\t\tif femaleUnder15years is None:\n\t\t\t\t\tfemUnd15=0\n\t\t\t\tif maleUnder15years is None:\n\t\t\t\t\tmalUnd15=0\n\t\t\t\tif femaleOver16years is None:\n\t\t\t\t\tfemOve16=0\n\t\t\t\tif maleOver16years is None:\n\t\t\t\t\tmalOve16=0\n\t\t\t\ttotal=femUnd15+malUnd15+femOve16+malOve16\n\t\t\t'''\n\t\t\texistsObj = self.queryObj.getByEventIdAndCompanyId(eventId, companyId)\n\t\t\tif existsObj:\n\t\t\t\tself.edit(eventId, preparedBy, neighborhood, specificAreaCensus, sector, censusDate, \n\t\t\t\t\theadOfHousehold, address, femaleUnder15years, maleUnder15years, femaleOver16years, \n\t\t\t\t\tmaleOver16years, total, ruralOrUrban, housingStatus, supplyKit, notSupplyKit, nightKit, groomingKit, \n\t\t\t\t\tothers, otherName, documentTypeId, documentNum, cellphone, existsObj.key().id())\n\t\t\t\tdeliveryStatus = \"Sin Entrega\"\n\t\t\t\tdeliveryOfAssistanceQuery.register(eventId, supplyKit, notSupplyKit, nightKit, groomingKit, \n\t\t\t\t\tothers, otherName, deliveryStatus, companyId)\n\t\t\t\tstate = OK\n\t\t\t\tmessage = self.infoMsg+\"_ACTUALIZADO\"\n\t\t\t\tdoRegister = False\n\t\t\t'''\n\t\t\t# Registro\n\t\t\tdeliveryOfAssistanceQuery = services.querys.deliveryOfAssistanceQuery.DeliveryOfAssistanceQuery()\n\t\t\tif doRegister == True:\n\t\t\t\tstate1, objId = self.queryObj.add(eventId, preparedBy, neighborhood, specificAreaCensus, sector, censusDate, \n\t\t\t\t\theadOfHousehold, householdHeadLastName, address, femaleUnder15years, maleUnder15years, femaleOver16years, \n\t\t\t\t\tmaleOver16years, total, ruralOrUrban, housingStatus, supplyKit, notSupplyKit, nightKit, groomingKit, \n\t\t\t\t\tothers, otherName, documentTypeId, documentNum, cellphone, municipality, beneficiarySignature,\n\t\t\t\t\tbeneficiaryfingerprint, censusSignature, deliveryDate, deliveryStatus, signature, fingerprint, companyId)\n\t\t\t\tdeliveryStatus = NO_DELIVERY\n\t\t\t\tstate, Obj2Id = deliveryOfAssistanceQuery.register(eventId, documentNum, supplyKit, notSupplyKit, nightKit, groomingKit, \n\t\t\t\t\tothers, otherName, deliveryStatus, companyId)\n\t\t\t\tif state == OK:\n\t\t\t\t\tmessage = self.infoMsg+\"_REGISTRADO\"\n\t\t\t\t\taffectedPeopleControler = services.controlers.affectedPeopleControler.AffectedPeopleControler()\n\t\t\t\t\t# Si ya existe lo edita:\n\t\t\t\t\texists, identifier = affectedPeopleControler.getExists(documentNum, eventId, sessionJson)\n\t\t\t\t\tif exists:\n\t\t\t\t\t\tmessage, state = affectedPeopleControler.edit(eventId, municipality, documentNum, documentTypeId, \n\t\t\t\t\t\t\theadOfHousehold, householdHeadLastName, None, ruralOrUrban, housingStatus, total, identifier)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# Si no existe, hace el registro\n\t\t\t\t\t\tmessage, state = affectedPeopleControler.add(eventId, municipality, documentNum, documentTypeId, \n\t\t\t\t\t\t\theadOfHousehold, householdHeadLastName, None, ruralOrUrban, housingStatus, total, sessionJson)\n\t\texcept Exception as e:\n\t\t\tloggControler = LoggControler()\n\t\t\tloggControler.addLogg('Controler: '+self.loggMsg+'-add()', ERROR_NO_DEFINIDO, e.message)\n\t\treturn message, state\n\n\tdef edit(self, eventId, preparedBy, neighborhood, specificAreaCensus, sector, censusDate, \n\t\t\theadOfHousehold, householdHeadLastName, address, femaleUnder15years, maleUnder15years, femaleOver16years, \n\t\t\tmaleOver16years, total, ruralOrUrban, housingStatus, supplyKit, notSupplyKit, nightKit, groomingKit, \n\t\t\tothers, otherName, documentTypeId, documentNum, cellphone, municipality, beneficiarySignature,\n\t\t\tbeneficiaryfingerprint, censusSignature, deliveryDate, deliveryStatus, signature, fingerprint, identifier):\n\t\tmessage=self.infoMsg+\"_NO_MODIFICADO\"\n\t\tstate = 300\n\t\ttry:\n\t\t\tif total==None:\n\t\t\t\ttotal=femaleUnder15years+maleUnder15years+femaleOver16years+maleOver16years\n\t\t\tobj = self.queryObj.getById(identifier)\n\t\t\tif eventId is not None:\n\t\t\t\tobj.eventId=eventId\n\t\t\tif preparedBy is not None:\n\t\t\t\tobj.preparedBy=preparedBy\n\t\t\tif neighborhood is not None:\n\t\t\t\tobj.neighborhood=neighborhood\n\t\t\tif specificAreaCensus is not None:\n\t\t\t\tobj.specificAreaCensus=specificAreaCensus\n\t\t\tif sector is not None:\n\t\t\t\tobj.sector=sector\n\t\t\tif censusDate is not None:\n\t\t\t\tobj.censusDate=censusDate\n\t\t\tif headOfHousehold is not None:\n\t\t\t\tobj.headOfHousehold=headOfHousehold\n\t\t\tif householdHeadLastName is not None:\n\t\t\t\tobj.householdHeadLastName=householdHeadLastName\n\t\t\tif address is not None:\n\t\t\t\tobj.address=address\n\t\t\tif femaleUnder15years is not None:\n\t\t\t\tobj.femaleUnder15years=femaleUnder15years\n\t\t\tif maleUnder15years is not None:\n\t\t\t\tobj.maleUnder15years=maleUnder15years\n\t\t\tif femaleOver16years is not None:\n\t\t\t\tobj.femaleOver16years=femaleOver16years\n\t\t\tif maleOver16years is not None:\n\t\t\t\tobj.maleOver16years=maleOver16years\n\t\t\tif total is not None:\n\t\t\t\tobj.total=total\n\t\t\tif ruralOrUrban is not None:\n\t\t\t\tobj.ruralOrUrban=ruralOrUrban\n\t\t\tif housingStatus is not None:\n\t\t\t\tobj.housingStatus=housingStatus\n\t\t\tif supplyKit is not None:\n\t\t\t\tobj.supplyKit=supplyKit\n\t\t\tif notSupplyKit is not None:\n\t\t\t\tobj.notSupplyKit=notSupplyKit\n\t\t\tif nightKit is not None:\n\t\t\t\tobj.nightKit=nightKit\n\t\t\tif groomingKit is not None:\n\t\t\t\tobj.groomingKit=groomingKit\n\t\t\tif others is not None:\n\t\t\t\tobj.others=others\n\t\t\tif otherName is not None:\n\t\t\t\tobj.otherName=otherName\n\t\t\tif documentTypeId is not None:\n\t\t\t\tobj.documentTypeId=documentTypeId\n\t\t\tif documentNum is not None:\n\t\t\t\tobj.documentNum=documentNum\n\t\t\tif cellphone is not None:\n\t\t\t\tobj.cellphone=cellphone\n\t\t\tif municipality is not None:\n\t\t\t\tobj.municipality=municipality\n\t\t\tif beneficiarySignature is not None:\n\t\t\t\tobj.beneficiarySignature=beneficiarySignature\n\t\t\tif beneficiaryfingerprint is not None:\n\t\t\t\tobj.beneficiaryfingerprint=beneficiaryfingerprint\n\t\t\tif censusSignature is not None:\n\t\t\t\tobj.censusSignature=censusSignature\n\t\t\tif deliveryDate is not None:\n\t\t\t\tobj.deliveryDate=deliveryDate\n\t\t\tif deliveryStatus is not None:\n\t\t\t\tobj.deliveryStatus=deliveryStatus\n\t\t\tif signature is not None:\n\t\t\t\tobj.signature=signature\n\t\t\tif fingerprint is not None:\n\t\t\t\tobj.fingerprint=fingerprint\n\t\t\tself.queryObj.edit(obj)\n\t\t\tmessage=self.infoMsg+\"_MODIFICADO\"\n\t\t\tstate = OK\n\t\texcept Exception as e:\n\t\t\tloggControler = LoggControler()\n\t\t\tloggControler.addLogg('Controler: '+self.loggMsg+'-edit()', ERROR_NO_DEFINIDO, e.message)\n\t\treturn message, state\n\n\tdef getValidate(self, **kwargs):\n\t\tvalidate = False\n\t\tvalidateMsg = \"ERROR_EN_VALIDACIÓN\"\n\t\ttry:\n\t\t\t# Aquí se incluyen las validaciones que se requieran\n\t\t\t# En dado caso se cumplan...\n\t\t\tvalidate = True\n\t\t\tvalidateMsg = \"VALIDACIÓN EXITOSA\"\n\t\texcept Exception as e:\n\t\t\tloggControler = LoggControler()\n\t\t\tloggControler.addLogg('Controler: '+self.loggMsg+'-getValidate()', ERROR_NO_DEFINIDO, e.message)\n\t\treturn validate, validateMsg","sub_path":"services/controlers/censusAssistancesControler.py","file_name":"censusAssistancesControler.py","file_ext":"py","file_size_in_byte":9433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"35894738","text":"#\n# Jacobi polynomials evaluated at a point or vector\n#\n# by Alberto Costa Nogueira Jr. (Matlab and Python versions)\n# Renato Cantao (Python version)\n#\nfrom numbers import Number\nimport numpy\n\ndef jacobi_p(x, m, alpha = 0.0, beta = 0.0):\n \"\"\"Jacobi polynomial.\"\"\"\n number_flag = False\n\n if isinstance(x, Number):\n x = numpy.array([x])\n number_flag = True\n\n aPb = alpha+beta # mnemonics: alpha plus beta\n aMb = alpha-beta # mnemonics: alpha minus beta\n\n Pn = numpy.ones(x.shape)\n Pn1 = 0.5*(aMb+(aPb+2.0)*x)\n\n if m == 0:\n Pm = Pn\n elif m == 1:\n Pm = Pn1\n else:\n for n in range(1, m+1):\n n1 = n+1.0\n n2 = 2.0*n\n\n a1n = 2.0*n1*( n1+aPb )*( n2+aPb )\n a2n = ( n2+aPb+1.0 )*aPb*aMb\n a3n = ( n2+aPb )*( n2+aPb+1.0 )*( n2+aPb+2.0 )\n a4n = 2.0*( n+alpha )*( n+beta )*( n2+aPb+2.0 )\n\n Pn2 = ( ( a2n+a3n*x )*Pn1-a4n*Pn )/a1n\n Pn = Pn1\n Pn1 = Pn2\n\n Pm = Pn\n\n if number_flag:\n return Pm[0]\n else:\n return Pm\n \n#-- jacobi_p.py ----------------------------------------------------------------\n","sub_path":"lessons/08_dg/jacobi_p.py","file_name":"jacobi_p.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"312776344","text":"import pickle\nimport sys\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom yw.env.env_manager import EnvManager\nfrom yw.util.cmd_util import ArgParser\n\n\nclass FetchDemoGenerator:\n \"\"\"\n Provide an easier way to control the gripper for pick and place task\n \"\"\"\n\n def __init__(self, env, policy, system_noise_level, render):\n self.env = env\n self.policy = policy\n self.system_noise_level = system_noise_level\n self.render = render\n self.num_itr = 0\n\n def reset(self):\n self.num_itr = 0\n\n def generate_using_policy(self):\n self._reset()\n self._use_policy()\n self.num_itr += 1\n return self.episode_obs, self.episode_act, self.episode_rwd, self.episode_info\n\n def _reset(self):\n # store return from 1 episode\n self.episode_act = []\n self.episode_obs = []\n self.episode_info = []\n self.episode_rwd = []\n # clear time step\n self.time_step = 0\n # reset env and store initial observation\n obs = self.env.reset()\n self.episode_obs.append(obs)\n self.num_object = int(obs[\"desired_goal\"].shape[0] / 3)\n self.init_obs = obs.copy()\n self.last_obs = obs.copy()\n\n def _step(self, action):\n action = np.clip(action, -1.0, 1.0) # clip by max_u\n obs, reward, done, info = self.env.step(action)\n self.time_step += 1\n if self.render:\n self.env.render()\n # update stats for the episode\n self.episode_act.append(action)\n self.episode_info.append(info)\n self.episode_obs.append(obs)\n self.episode_rwd.append([reward])\n # update last obs\n self.last_obs = obs\n\n def _use_policy(self):\n while self.time_step <= self.env._max_episode_steps:\n action = self.policy.get_actions(self.last_obs[\"observation\"], self.last_obs[\"desired_goal\"])\n action = action.reshape(-1)\n self._step(action)\n\n def _move_to_object(self, obj_pos_dim, obj_rel_pos_dim, offset, gripper_open):\n object_pos = self.last_obs[\"observation\"][obj_pos_dim : obj_pos_dim + 3]\n object_rel_pos = self.last_obs[\"observation\"][obj_rel_pos_dim : obj_rel_pos_dim + 3]\n object_oriented_goal = object_rel_pos.copy()\n object_oriented_goal[2] += offset\n\n while np.linalg.norm(object_oriented_goal) >= 0.01 and self.time_step <= self.env._max_episode_steps:\n\n action = [0, 0, 0, 0]\n for i in range(len(object_oriented_goal)):\n action[i] = object_oriented_goal[i] * 10 + self.system_noise_level * np.random.normal()\n action[-1] = 0.05 if gripper_open else -0.05 # open\n\n self._step(action)\n\n object_pos = self.last_obs[\"observation\"][obj_pos_dim : obj_pos_dim + 3]\n object_rel_pos = self.last_obs[\"observation\"][obj_rel_pos_dim : obj_rel_pos_dim + 3]\n object_oriented_goal = object_rel_pos.copy()\n object_oriented_goal[2] += offset\n\n def _move_to_goal(self, obj_pos_dim, goal_dim, gripper=-1.0, offset=np.array((0.0, 0.0, 0.0))):\n goal = self.last_obs[\"desired_goal\"][goal_dim : goal_dim + 3] + offset\n object_pos = self.last_obs[\"observation\"][obj_pos_dim : obj_pos_dim + 3]\n\n while np.linalg.norm(goal - object_pos) >= 0.01 and self.time_step <= self.env._max_episode_steps:\n\n action = [0, 0, 0, 0]\n for i in range(len(goal - object_pos)):\n action[i] = (goal - object_pos)[i] * 10 + self.system_noise_level * np.random.normal()\n action[-1] = gripper\n\n self._step(action)\n\n object_pos = self.last_obs[\"observation\"][obj_pos_dim : obj_pos_dim + 3]\n\n def _move_to_interm_goal(self, obj_pos_dim, goal_dim, weight):\n\n goal = self.last_obs[\"desired_goal\"][goal_dim : goal_dim + 3]\n object_pos = self.last_obs[\"observation\"][obj_pos_dim : obj_pos_dim + 3]\n\n interm_goal = object_pos * weight + goal * (1 - weight)\n\n while np.linalg.norm(interm_goal - object_pos) >= 0.01 and self.time_step <= self.env._max_episode_steps:\n\n action = [0, 0, 0, 0]\n for i in range(len(interm_goal - object_pos)):\n action[i] = (interm_goal - object_pos)[i] * 10 + self.system_noise_level * np.random.normal()\n action[-1] = -0.05\n\n self._step(action)\n\n object_pos = self.last_obs[\"observation\"][obj_pos_dim : obj_pos_dim + 3]\n\n def _move_back(self):\n goal = self.init_obs[\"observation\"][0:3]\n grip_pos = self.last_obs[\"observation\"][0:3]\n\n while np.linalg.norm(goal - grip_pos) >= 0.01 and self.time_step <= self.env._max_episode_steps:\n\n action = [0, 0, 0, 0]\n for i in range(len(goal - grip_pos)):\n action[i] = (goal - grip_pos)[i] * 10 + self.system_noise_level * np.random.normal()\n action[-1] = 0.05\n\n self._step(action)\n\n grip_pos = self.last_obs[\"observation\"][0:3]\n\n def _stay(self):\n while self.time_step <= self.env._max_episode_steps:\n\n action = [0, 0, 0, 0]\n for i in range(3):\n action[i] = self.system_noise_level * np.random.normal()\n action[-1] = 0.05 # keep the gripper open\n\n self._step(action)\n\n\ndef store_demo_data(T, num_itr, demo_data_obs, demo_data_acs, demo_data_rewards, demo_data_info):\n result = None\n for epsd in range(num_itr): # we initialize the whole demo buffer at the start of the training\n obs, acts, goals, achieved_goals, rs = [], [], [], [], []\n info_keys = [key.replace(\"info_\", \"\") for key in demo_data_info[0][0].keys()]\n info_values = [np.empty((T, 1, 1), np.float32) for key in info_keys]\n for transition in range(T):\n obs.append([demo_data_obs[epsd][transition].get(\"observation\")])\n acts.append([demo_data_acs[epsd][transition]])\n goals.append([demo_data_obs[epsd][transition].get(\"desired_goal\")])\n achieved_goals.append([demo_data_obs[epsd][transition].get(\"achieved_goal\")])\n rs.append([demo_data_rewards[epsd][transition]])\n for idx, key in enumerate(info_keys):\n info_values[idx][transition, 0] = demo_data_info[epsd][transition][key]\n\n obs.append([demo_data_obs[epsd][T].get(\"observation\")])\n achieved_goals.append([demo_data_obs[epsd][T].get(\"achieved_goal\")])\n\n episode = dict(o=obs, u=acts, g=goals, ag=achieved_goals, r=rs)\n for key, value in zip(info_keys, info_values):\n episode[\"info_{}\".format(key)] = value\n\n # switch to batch major\n episode_batch = {}\n for key in episode.keys():\n val = np.array(episode[key]).copy()\n # make inputs batch-major instead of time-major\n episode_batch[key] = val.swapaxes(0, 1)\n episode = episode_batch\n\n # UNCOMMENT to use the ring replay buffer! convert to (T x dims and add done signal)\n # episode = {k: v.reshape((-1, v.shape[-1])) for k, v in episode.items()}\n # episode[\"o_2\"] = episode[\"o\"][1:, ...]\n # episode[\"o\"] = episode[\"o\"][:-1, ...]\n # episode[\"ag_2\"] = episode[\"ag\"][1:, ...]\n # episode[\"ag\"] = episode[\"ag\"][:-1, ...]\n # episode[\"g_2\"] = episode[\"g\"][...]\n # done = np.zeros(T)\n # done[-1] = 1.0\n # episode[\"done\"] = done.reshape(-1, 1)\n\n if result == None:\n result = episode\n else:\n for k in result.keys():\n result[k] = np.concatenate((result[k], episode[k]), axis=0)\n\n for k, v in result.items():\n print(k, v.shape)\n\n # array(batch_size x (T or T+1) x dim_key), we only need the first one!\n np.savez_compressed(\"demo_data.npz\", **result) # save the file\n","sub_path":"Package/yw/yw/flow/demo_util/generate_demo_fetch_policy.py","file_name":"generate_demo_fetch_policy.py","file_ext":"py","file_size_in_byte":7831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"498404173","text":"# Write your code here :-)\nimport serial\n\n# Open the serial port for sending at speed 115200 bits/second\ndevice = serial.Serial('/dev/ttyACM0', 115200)\n\n# Write string to serial port, and terminate with a line feed character\n##jwc y serialString_Tx = \"22\\n\"\nserialString_Tx = \"Hello Jesus :)\\n\"\n\n##jwc n device.write(\"22\\n\")\ndevice.write(serialString_Tx.encode())\n##jwc n device.write(b'\\x0101')\n\n\n# Close serial port\ndevice.close()","sub_path":"Rpi_To_Microbit-SerialTest-RpiSide.py","file_name":"Rpi_To_Microbit-SerialTest-RpiSide.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"277110420","text":"import re\n\nregexEmail = '^[a-z0-9]+[\\._]?[a-z0-9]+[@]\\w+[.]\\w{2,3}$'\nregexPhone = '^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\\s\\./0-9]*$'\n\n\ndef validationRowXls(row, sheet):\n if row[sheet[0].index('name')]:\n\n if row[sheet[0].index('gender')].lower() == \"female\" or row[sheet[0].index('gender')].lower() == \"male\":\n\n if row[sheet[0].index('age')] >= 18:\n\n if re.search(regexEmail, row[sheet[0].index('email')]):\n\n if re.search(regexPhone, row[sheet[0].index('phone')]):\n return 1\n\n return 0\n\ndef validationRowCSV(row):\n if row['name']:\n\n if row['gender'].lower() == \"female\" or row['gender'].lower() == \"male\":\n\n if int(row['age']) >= 18:\n\n if re.search(regexEmail, row['email']):\n\n if re.search(regexPhone, row['phone']):\n return 1\n\n return 0\n\ndef validationEdite(request):\n if request.POST['name']:\n if request.POST['gender'].lower() == \"female\" or request.POST['gender'].lower() == \"male\":\n if int(request.POST['age']) >= 18:\n if re.search(regexPhone, request.POST['phone']):\n if re.search(regexEmail, request.POST['email']):\n return 1\n return 0","sub_path":"project8-Python-Data-Analysis-Project/Code/dataAnalysis/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"57033733","text":"import GraphAl, GraphAm\nsols=[]\ndef shortPath(g,n,end,visited,distance):\n succs=g.getSuccessors(n)\n visited.append(n)\n if n == end:\n sols.append(distance)\n return 0\n for i in succs:\n if i in visited:\n continue;\n shortPath(g,i,end,visited[:],g.getWeight(n,i)+distance)\n\n\n\n\ndef findPath(g,n,end,path):\n path.append(n)\n ans= []\n if n == end:\n return path\n succs = g.getSuccessors(n)\n for i in succs:\n if i in path:\n continue;\n ans=findPath(g,i,end,path[:])\n return ans\n\ngc = GraphAl.GraphAl(6)\ngc.addArc(0,1,10)\ngc.addArc(0,2,2)\ngc.addArc(0,3,5)\ngc.addArc(4,0,9)\ngc.addArc(1,2,2)\ngc.addArc(3,1,3)\ngc.addArc(4,1,7)\ngc.addArc(2,4,5)\ngc.addArc(4,3,3)\ngc.addArc(2,3,2)\ngc.addArc(3,5,2)\nshortPath(gc,0,1,[],0)\nprint((sols))\nprint(findPath(gc,0,5,[]))\n","sub_path":"laboratorios/lab03/ejercicioEnLinea/punto2.py","file_name":"punto2.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"382318231","text":"'''\n******************************************************************************\n Copyright 2013 EMC Inc.\n\n[Filename]: tc_bmc_ms_CorruptPartialPrimaryBMCImageTest.py\n[Author ]: Cloud.Luo@emc.com\n[Purpose ]: BMC can boot the system if the primary BMC fw images are corrupted in SPI flashs.\n[Contains]: \n tc_bmc_ms_CorruptPartialPrimaryBMCImageTest - class\n __init__\n test\n[History ]:\n******************************************************************************\n VERSION EDITOR DATE COMMENT\n******************************************************************************\n V1.0 Cloud.Luo@emc.com 3/26/2014 First edition\n******************************************************************************\n V1.1 Wendy.Ni@emc.com 07/03/2014 Second edition\n******************************************************************************\n'''\n\nfrom case.CBaseCase import *\n\nclass tc_bmc_ms_CorruptPartialPrimaryBMCImageTest(CBaseCase):\n \n \"\"\"\n ************************************************************************************************\n [Purpose ]: BMC can boot the system if the primary BMC fw images are corrupted in SPI flashs.\n [Author ]: Cloud.Luo@emc.com\n [Method ]:\n [ReqID ]: \n [Sprint ]: Sprint2.0.18\n [Ticket ]: ATOM-734\n [Platform]: Megatron, Triton\n [Type ]: Auto\n ************************************************************************************************\n \"\"\"\n \n def __init__(self):\n CBaseCase.__init__(self, self.__class__.__name__)\n\n \n def test(self):\n\n self.enclosure.sp.sel.start_reserve_sel_in_memory()\n \n self.log('INFO','[1] Boot into Uboot.')\n if self.enclosure.sp.bmc.bmc_boot_to_hornet() != 0:\n self.result(FAIL,'BMC failed to boot to uboot')\n \n self.log('INFO','[2] Corrupt the block of kernal.')\n if self.enclosure.sp.bmc.corrupt_partial_primary_bmc_image() != 0:\n self.log('ERROR','[2] Corrupt the block of kernal fail.')\n self.result(FAIL,'Failed to corrupt BMC primary image')\n \n self.log('INFO','[3] AC cycle the system.') \n self.enclosure.ac_cycle()\n \n# str_result = self.obj_bmc.read_until_strings(\"Flash: Primary bank\", 30)\n# print str_result\n# if self.obj_bmc.int_match_index != 1:\n# self.result(FAIL,'Failed to try to boot from CS0 (Primary bank) and hang up.')\n \n self.obj_bmc.read_until_strings(\"Flash: Redundant bank\", 180)\n if self.obj_bmc.int_match_index != 1:\n self.result(FAIL,'Fail to boot from CS1 (Redundant bank).')\n \n self.delay(180)\n \n self.log('INFO','[4] Right after BMC boot up from CS1, check BMC update status summary .')\n if self.enclosure.sp.bmc.is_bmc_primary_image_recovered() != 0:\n self.result(FAIL, 'BMC primary image is not recovered')\n \n self.log('INFO','[5] Check SEL.') \n if self.enclosure.sp.sel.check_matched_sel_from_memory(\n str_generator_id = '0x20', \n str_sensor_type = '0xc2', \n str_sensor_num = '0xe2', \n str_event_type = '0x6f', \n lst_event_data_and_mask = ['0x05', '0xff', '0xff', '0xff', '0xff', '0xff'],\n int_expected_matched_num = 1) != 0:\n self.result(FAIL,'Check sel fail.')\n self.enclosure.sp.sel.stop_reserve_sel_in_memory()\n \n self.delay(300)\n \n \n \n ","sub_path":"case/OUT_OF_DATE/tc_bmc_ms_CorruptPartialPrimaryBMCImageTest.py","file_name":"tc_bmc_ms_CorruptPartialPrimaryBMCImageTest.py","file_ext":"py","file_size_in_byte":3622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"337570502","text":"import flask\r\nimport shared.RoutingBase\r\n\r\n\r\nclass StaticPages(shared.RoutingBase.RoutingBase):\r\n\r\n def routemap(self) -> dict:\r\n return {\r\n '/': {\r\n 'view_func': self.get_homepage\r\n },\r\n '/contact/': {\r\n 'view_func': self.get_contact\r\n },\r\n '/ranking/': {\r\n 'view_func': self.get_ranking\r\n },\r\n '/map/': {\r\n 'view_func': self.get_map\r\n }\r\n }\r\n\r\n def get_homepage(self):\r\n latest_articles = self.app.datastorage.get_article(\r\n approved=True,\r\n only_n=3\r\n )\r\n return self.app.send_response(flask.render_template(\r\n 'homepage.html',\r\n user=self.app.sessiondata.get_user(),\r\n latest_articles=latest_articles\r\n ))\r\n\r\n def get_contact(self):\r\n return flask.render_template(\r\n 'contact.html',\r\n user=self.app.sessiondata.get_user()\r\n )\r\n\r\n def get_ranking(self):\r\n ranking_data = self.app.datastorage.get_ranking_data()\r\n # print(ranking_data)\r\n return flask.render_template(\r\n 'ranking.html',\r\n user=self.app.sessiondata.get_user(),\r\n ranking_data=ranking_data\r\n )\r\n\r\n def get_map(self):\r\n article_data_by_city = self.app.datastorage.get_article_grouped('city')\r\n # print(article_data_by_city)\r\n return flask.render_template(\r\n 'map.html',\r\n user=self.app.sessiondata.get_user(),\r\n article_data_by_city=article_data_by_city\r\n )\r\n","sub_path":"routing/StaticPages.py","file_name":"StaticPages.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"452616999","text":"inputList = [int(i) for i in input('Enter values... ').split()]\nlength = len(inputList)\n\ninputList.sort()\nprint('Sorted Array: ', inputList)\n\nsearch = eval(input('Enter number to be searched: '))\nfirst = 0\nlast = length - 1\n\ndef binarySearch(li,first,last,search):\n middle = int((first + last) / 2)\n if first <= last:\n if inputList[middle] == search:\n return middle\n elif inputList[middle] > search:\n return binarySearch(li,first,middle-1,search)\n else:\n return binarySearch(li,middle+1,last,search)\n else: \n return -1\n\npos = binarySearch(inputList,first,last,search)\n\nif pos == -1:\n print('Element ', search, 'not found -> STATUS: -1')\nelse:\n print('Element ', search, 'found at index', pos)\n","sub_path":"Day 4 assignment/BinarySearch.py","file_name":"BinarySearch.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"366284840","text":"'''\nPairs with difference K\n\nYou are given with an array of integers and an integer K. You have to find and print the count of all such pairs which have difference K.\nNote: Take absolute difference between the elements of the array.\n\nInput Format:\nThe first line of input contains an integer, that denotes the value of the size of the array. Let us denote it with the symbol n.\nThe following line contains n space separated integers, that denote the value of the elements of the array.\nThe following line contains an integer, that denotes the value of K.\n\nOutput format :\nThe first and only line of output contains count of all such pairs which have an absolute difference of K. \n\nConstraints :\n0 <= n <= 10^4\n\nTime Limit: 1 sec\n\nSample Input 1 :\n4 \n5 1 2 4\n3\n\nSample Output 1 :\n2\n\nSample Input 2 :\n4\n4 4 4 4 \n0\n\nSample Output 2 :\n6\n'''\n\ndef printPairDiffK(l, k):\n #############################\n # PLEASE ADD YOUR CODE HERE #\n d = {}\n for i in l:\n d[i] = d.get(i, 0) + 1\n\n \n count = 0\n import sympy\n if k == 0:\n return sympy.binomial(d[l[0]], 2)\n else:\n for i in l:\n if i in d and i+k in d:\n count += d[i] * d[i+k]\n if i in d and i-k in d:\n count += d[i] * d[i-k]\n if i in d:\n del d[i]\n return count\n #############################\n \n# Main\nn=int(input())\nl=list(int(i) for i in input().strip().split(' '))\nk=int(input())\nprint(printPairDiffK(l, k))","sub_path":"Hashing/Dictionaries_Maps/Pairs_with_difference_K.py","file_name":"Pairs_with_difference_K.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"545038599","text":"\"\"\"\n@Author: genejiang\n@Date: 2019-10-23 13:57:04\n@LastEditTime: 2019-10-23 14:00:23\n@LastEditors: Please set LastEditors\n@Description: In User Settings Edit\n@FilePath:\n\"\"\"\n\n\nclass Solution:\n def two_sum(self, nums, target):\n \"\"\"\n :nums: one list with integer\n :target: the target number\n \"\"\"\n hash_table = {}\n for index, value in enumerate(nums):\n if target - value in hash_table:\n return (hash_table[target-value], index)\n hash_table[value] = index\n\n\nsolution = Solution()\nprint(solution.two_sum([2, 7, 11, 13, 14], 9))\n\n\n","sub_path":"advance/LeetCode/001_two_sum.py","file_name":"001_two_sum.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"570682035","text":"\n\ndef leiadinheiro(msg):\n \"\"\"\n Função para validar a entrada\n :param msg: mensagem de texto para informar o preço\n :return: retorna o valor preço no convertido para float\n \"\"\"\n valido = False\n while not valido:\n entrada = str(input(msg)).replace(',','.').strip()\n if entrada.isalpha() or entrada =='':\n print(f'\\033[0;31m ERRO! O valor {entrada} não é um preço Invalido\\033[m')\n else:\n valido = True\n return float(entrada)\n","sub_path":"Arquivos Exercicios/Aula22_Modulos/Ex111/utilidadesCeV/dado/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"542806115","text":"import pandas as pd\n\nfrom backtesting import Strategy\nfrom ..indicators import moving_average\n\ndef aligator_indicator(green, red, blue):\n try:\n is_red_blue_crossover = red[-2] < blue[-2] and red[-1] > blue[-1]\n is_blue_red_crossover = red[-2] > blue[-2] and red[-1] < blue[-1]\n\n green_over_blue = green[-1] > blue[-1]\n blue_over_green = green[-1] < blue[-1]\n\n green_over_red = green[-1] > red[-1]\n red_over_green = green[-1] < red[-1]\n\n if is_red_blue_crossover and green_over_blue and green_over_red:\n return True\n if is_blue_red_crossover and blue_over_green and red_over_green:\n return False\n return None\n except IndexError:\n return None\n\nclass AligatorIndicator(Strategy):\n def init(self):\n price = self.data.Close\n self.green = self.I(moving_average, price, 5, 3)\n self.red = self.I(moving_average, price, 8, 5)\n self.blue = self.I(moving_average, price, 13, 8)\n\n def next(self):\n indicator = aligator_indicator(self.green, self.red, self.blue)\n if indicator != None:\n if indicator:\n self.position.close()\n self.buy()\n else:\n self.position.close()\n self.sell()\n","sub_path":"src/strategies/aligartor_indicator.py","file_name":"aligartor_indicator.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"534953391","text":"import re\n\nimport yaml\nfrom twython import Twython\n\n\ndef sane_timeline():\n \"\"\"Check if there no duplicated links in the past 200 tweets.\n\n Returns:\n True if there are no duplicates and False, otherwise\n \"\"\"\n with open('/home/jfilter/code/ifg-feed/ttnconfig/config.yaml') as f:\n config = yaml.load(f)\n\n api_key, api_secret, oauth_token, oauth_secret = [config['twitter'][k] for k in (\n 'api_key', 'api_secret', 'oauth_token', 'oauth_secret')]\n\n twitter = Twython(api_key, api_secret,\n oauth_token, oauth_secret)\n\n tweets = twitter.get_user_timeline(count=200)\n all_urls = []\n\n for t in tweets:\n text = t['text']\n cleaned_text = text[text.index(':') + 1:]\n # print(cleaned_text)\n urls = re.findall(r'(https?://\\S+)', cleaned_text)\n all_urls += urls\n #for l in all_urls:\n # if all_urls.count(l) > 1:\n # print(l)\n return len(all_urls) == len(set(all_urls))\n\n\nif __name__ == '__main__':\n print(sane_timeline())\n","sub_path":"safeguard.py","file_name":"safeguard.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"338172353","text":"from Bio.AlignIO import read\nfrom Bio.Phylo import draw\nfrom Bio.Phylo.TreeConstruction import DistanceCalculator, DistanceTreeConstructor\nfrom os.path import join, abspath\nimport matplotlib.pyplot as plt\nfrom CodonU.file_handler import make_dir\nfrom CodonU.file_handler.internal_comp import is_file_writeable\n\n\ndef plot_phy_fas(handle: str, title: str = 'Phylogenetic Tree', save_image: bool = False, folder_path: str = 'Report'):\n \"\"\"\n Plots phylogenetic tree from fasta file\n\n :param handle: Handle to the fasta file\n :param title: Title of the plot\n :param save_image: Options for saving the image (optional)\n :param folder_path: Folder path where image should be saved (optional)\n \"\"\"\n cons = DistanceTreeConstructor()\n aln_file = read(open(handle), 'fasta')\n calc = DistanceCalculator('identity')\n distance_matrix = calc.get_distance(aln_file)\n tree = cons.upgma(distance_matrix)\n tree = tree.as_phyloxml()\n fig, ax = plt.subplots()\n fig.suptitle(title)\n draw(tree, axes=ax)\n if save_image:\n make_dir(folder_path)\n file_name = '_'.join(title.split()) + '_fas.png'\n file_path = join(folder_path, file_name)\n if is_file_writeable(file_path):\n fig.savefig(file_path, dpi=500)\n print(f'Saved file can be found as {abspath(file_path)}')\n plt.close(fig)\n","sub_path":"CodonU/vizualizer/plot_phy_fas.py","file_name":"plot_phy_fas.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"131773135","text":"import psycopg2\nimport sqlite3\n\n# Defining a function to refresh connection and cursor\ndef refresh_connection_and_cursor(conn, curs):\n curs.close()\n conn.close()\n pg_conn = psycopg2.connect(\n dbname=dbname, user=user, password=password, host=host\n )\n pg_curs = pg_conn.cursor()\n return pg_conn, pg_curs\n\n\nif __name__ == \"__main__\":\n\n # Looks similar to sqlite3, but needs auth/host info to connect\n # Note - this is sensitive info (particularly password)\n # and shouldn't be checked into git! More on how to handle next week\n\n dbname = \"ajkuvccu\"\n user = \"ajkuvccu\" # ElephantSQL happens to use same name for db and user\n password = ( # Sensitive! Don't share/commit\n \"FBOFpSpFdAFrxYUG-DBqN39wDQ0Mjc4V\"\n )\n host = \"isilo.db.elephantsql.com\"\n\n # If we make too many connections, the database complains! Be sure to close\n # cursors and connections\n pg_conn = psycopg2.connect(\n dbname=dbname, user=user, password=password, host=host\n )\n\n pg_curs = pg_conn.cursor() # Works the same as SQLite!\n\n # We're connected, but db is empty\n # Let's run a simple example to populate (from the tk)\n create_table_statement = \"\"\"\n CREATE TABLE test_table (\n id SERIAL PRIMARY KEY,\n name varchar(40) NOT NULL,\n data JSONB\n );\n \"\"\"\n # NOTE - these types are PostgreSQL specific. This won't work in SQLite!\n\n # pg_curs.execute(create_table_statement)\n pg_conn.commit() # \"Save\" by committing\n\n # We're connected, let's see what is in the db\n pg_curs.execute(\"SELECT * FROM test_table;\")\n pg_curs.fetchall()\n\n insert_statement = \"\"\"\n INSERT INTO test_table (name, data) VALUES\n (\n 'Zaphod Beeblebrox',\n '{\"key\": \"value\", \"key2\": true}'::JSONB\n )\n \"\"\"\n\n pg_curs.execute(insert_statement)\n pg_conn.commit()\n\n pg_curs.execute(\"SELECT * FROM test_table;\")\n pg_curs.fetchall()\n\n pg_curs.close()\n # pg_conn.close() # If we were really done\n\n # Database constraints from the schema are enforced!\n # This is good - helps ensure data quality\n pg_curs = pg_conn.cursor()\n pg_curs.execute(\"INSERT INTO test_table (name, data) VALUES (null, null);\")\n\n sl_conn = sqlite3.connect(\"rpg_db.sqlite3\")\n sl_curs = sl_conn.cursor()\n\n get_characters = \"SELECT * FROM charactercreator_character;\"\n sl_curs.execute(get_characters)\n characters = sl_curs.fetchall()\n\n # Step 1 complete! We have a list of tuples with all our character data\n # NOTE - this is *not* a pandas dataframe\n # We don't know types - so, for \"Transform\" we need to figure that out\n # Because our destination (PostgreSQL) needs a schema for this data\n\n # Step 2 - Transform\n # Our goal is to make a schema to define a table that fits this data in Postgres\n # We can check the old schema!\n # This is an internal meta sort of query, will vary by database flavor\n sl_curs.execute(\"PRAGMA table_info(charactercreator_character);\")\n sl_curs.fetchall()\n\n # A bunch of integers, and a varchar\n # We need to make a create statement for PostgreSQL that captures this\n create_character_table = \"\"\"\n CREATE TABLE charactercreator_character (\n character_id SERIAL PRIMARY KEY,\n name VARCHAR(30),\n level INT,\n exp INT,\n hp INT,\n strength INT,\n intelligence INT,\n dexterity INT,\n wisdom INT\n );\n \"\"\"\n\n pg_conn, pg_curs = refresh_connection_and_cursor(pg_conn, pg_curs)\n\n # Execute the create table\n # pg_curs.execute(create_character_table)\n pg_conn.commit()\n\n # PostgreSQL comparison to the SQLite pragma\n # We can query tables if we want to check\n # This is a clever optional thing, showing postgresql internals\n show_tables = \"\"\"\n SELECT\n *\n FROM\n pg_catalog.pg_tables\n WHERE\n schemaname != 'pg_catalog'\n AND schemaname != 'information_schema';\n \"\"\"\n pg_curs.execute(show_tables)\n pg_curs.fetchall()\n\n # Done with step 2 (transform)\n # We didn't really change the data, just made sure we could fit it in our target\n # Step 3 - Load!\n characters[0]\n\n # We want to put this tuple in a string w/INSERT INTO...\n # But we don't want the first field (id) - PostgreSQL generates that\n characters[0][1:]\n\n example_insert = (\n \"\"\"\n INSERT INTO charactercreator_character\n (name, level, exp, hp, strength, intelligence, dexterity, wisdom)\n VALUES \"\"\"\n + str(characters[0][1:])\n + \";\"\n )\n\n print(example_insert) # Not running, just inspecting\n\n # If we ran this, we'd insert the first character\n # But we want them all - loops!\n for character in characters:\n insert_character = (\n \"\"\"\n INSERT INTO charactercreator_character\n (name, level, exp, hp, strength, intelligence, dexterity, wisdom)\n VALUES \"\"\"\n + str(character[1:])\n + \";\"\n )\n pg_curs.execute(insert_character)\n\n # Note - we're executing each character one at a time\n # That works, and is simple, but inefficient (lots of roundtrips to database)\n # Stretch/afternoon goal - see if you can combine into a single\n # insert that does them all at once\n pg_conn.commit()\n\n # Let's look at what we've done\n pg_curs.execute(\"SELECT * FROM charactercreator_character LIMIT 5;\")\n pg_curs.fetchall()\n\n # Ids are different (on first run, now fixed)!\n # That's because we had an aborted run\n # Let's fix this by deleting the data and DROPping the table\n # Other tables are fine, but we'll dump the data *and* schema to rerun\n # pg_curs.execute('DROP TABLE charactercreator_character;')\n # pg_conn.commit()\n\n # Now we need to rerun the above... scrolling up and down, because notebooks\n # Specifically rerunning character table create statement and data inserts\n\n # Now the data looks the same! But let's check it systematically\n pg_curs.execute(\"SELECT * FROM charactercreator_character;\")\n pg_characters = pg_curs.fetchall()\n\n # We could do more spot checks, but let's loop and check them all\n # TODO/afternoon task - consider making this a more formal test\n for character, pg_character in zip(characters, pg_characters):\n assert character == pg_character\n\n # No complaints - which means they're all the same!\n # Closing out cursor/connection to wrap up\n pg_curs.close()\n pg_conn.close()\n sl_curs.close()\n sl_conn.close()\n","sub_path":"module2-sql-for-analysis/rpg_postgres.py","file_name":"rpg_postgres.py","file_ext":"py","file_size_in_byte":6448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"366703130","text":"import numpy as np\r\nimport argparse\r\nimport skipthoughts\r\n\r\n\r\ndef main():\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--caption_file', type=str, default='Data/sample_captions.txt',\r\n help='caption file')\r\n parser.add_argument('--data_dir', type=str, default='Data',\r\n help='Data Directory')\r\n\r\n args = parser.parse_args()\r\n with open(args.caption_file) as f:\r\n captions = f.read().split('\\n')\r\n\r\n # captions : Text description of pictures stored in file sample_captions.txt\r\n captions = [cap for cap in captions if len(cap) > 0]\r\n print(captions)\r\n\r\n # create skipthoughts vectors\r\n model = skipthoughts.load_model()\r\n print('Creation of skipthought vectors : loading ....')\r\n caption_vectors = skipthoughts.encode(model, captions)\r\n print('Creation of skipthought vectors : DONE !')\r\n #print(caption_vectors)\r\n #print(np.shape(caption_vectors)).3\r\n\r\n # create tensor vectors with skipthought vectors as input\r\n print('Save skipthought vector : loading ....')\r\n np.save('Data/vectors_files/skipvectors_sample.npy', caption_vectors)\r\n print('Save skipthought vector : DONE !')\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"generate_thought_vectors.py","file_name":"generate_thought_vectors.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"524292396","text":"import torch\nimport torch.nn as nn\nfrom torch.nn.utils import weight_norm\n\nclass ConvolutionBlock(nn.Module):\n \"\"\"Block containing convolutions and weighted normalisation for ResNet.\"\"\"\n def __init__(self, in_channels, out_channels, kernel_size):\n \"\"\"Create a convolution block containing the specified settings.\n\n Args:\n in_channels (int): number of input channels for convolution.\n out_channels (int): number of output channels for convolution.\n kernel_size (int): kernel size for convolutions.\n \"\"\"\n super(type(self), self).__init__()\n\n # Define the network for each block\n self.network = nn.Sequential(\n *[\n # Normalised with a 1D convolution and padding\n weight_norm(\n nn.Conv1d(\n in_channels,\n out_channels,\n kernel_size,\n padding=int(kernel_size / 2),\n )\n ),\n nn.ReLU(),\n # Second sub-block\n weight_norm(\n nn.Conv1d(\n out_channels,\n out_channels,\n kernel_size,\n padding=int(kernel_size / 2),\n )\n ),\n nn.ReLU(),\n ]\n )\n\n def forward(self, x):\n \"\"\"Apply forward network.\n\n Args:\n x (tensor): input data.\n\n Returns:\n out: network applied to input data.\n \"\"\"\n return self.network(x)\n\n\nclass ResidualBlock(nn.Module):\n \"\"\"Block containing residual connections and convolution networks for ResNet.\"\"\"\n def __init__(self, in_channels, out_channels, kernel_size):\n \"\"\"Create a residual block containing the specified settings.\n\n Args:\n in_channels (int): number of input channels for convolution.\n out_channels (int): number of output channels for convolution.\n kernel_size (int): kernel size for convolutions.\n \"\"\"\n super(type(self), self).__init__()\n\n # Block including two weight_norm convolutions with ReLU activation\n self.convolution = ConvolutionBlock(in_channels, out_channels, kernel_size)\n\n # If the number of channels in is not the same as the out channels, use a 1D convolution on residual connection\n self.residual_convolution = (\n nn.Conv1d(in_channels, out_channels, 1)\n if in_channels != out_channels\n else None\n )\n\n def forward(self, x):\n \"\"\"Apply forward network.\n\n Args:\n x (tensor): input data.\n\n Returns:\n out: network applied to input data.\n \"\"\"\n # Apply block to input data\n y = self.convolution(x)\n\n # If the number of input channels is not the same as the output, apply the transformation\n if self.residual_convolution is not None:\n return y + self.residual_convolution(x)\n\n return y + x\n\nclass ResnetGRU(nn.Module):\n \"\"\"Class extending nn.Module from pytorch to define an embedding network for feature extraction on high-fidelity data.\"\"\"\n\n def __init__(\n self,\n depth=9,\n nlayer=2,\n kernel_size=5,\n hidden_conv=4,\n max_hidden=256,\n input_dim=28,\n hidden_dim=1,\n layer_dim=2,\n ):\n \"\"\"Create a Resnet + GRU featuriser network for input data of shape 1x7200, with specified settings. This corresponds to high-fidelity microlensing light curves, which have 10x less observation cadence than is expected from ROMAN.\n\n Args:\n depth (int, optional): number of blocks for ResNet network. Defaults to 9.\n nlayer (int, optional): number of convolution layers in each ResNet block. Defaults to 2.\n kernel_size (int, optional): kernel size for convolution. Defaults to 5.\n hidden_conv (int, optional): starting expansion layers for input. Defaults to 4.\n max_hidden (int, optional): maximum size of hidden dimension. Defaults to 256.\n input_dim (int, optional): computed input dimension for GRU. Defaults to 28.\n hidden_dim (int, optional): hidden dimension for GRU. Defaults to 1.\n layer_dim (int, optional): number of layers for GRU. Defaults to 2.\n \"\"\"\n super(type(self), self).__init__()\n\n network = list()\n\n self.layer_dim = layer_dim\n self.hidden_dim = hidden_dim\n\n # Add the first residual block\n network.append(\n ResidualBlock(\n in_channels=1, out_channels=hidden_conv, kernel_size=kernel_size\n )\n )\n\n # Append more residual blocks until the block size has been reached\n for i in range(nlayer - 1):\n network.append(\n ResidualBlock(\n in_channels=hidden_conv,\n out_channels=hidden_conv,\n kernel_size=kernel_size,\n )\n )\n\n # Append new lots of blocks with MaxPool inbetween\n for i in range(depth - 1):\n # Compute expansion of hidden dimension\n dim_in = min(max_hidden, hidden_conv * 2 ** i)\n dim_out = min(max_hidden, hidden_conv * 2 ** (i + 1))\n\n # Add the maxpool layer between the blocks\n network.append(nn.MaxPool1d(kernel_size=2, stride=2))\n\n # Append the correct number of next blocks\n for j in range(nlayer):\n network.append(\n ResidualBlock(\n in_channels=dim_out if j != 0 else dim_in,\n out_channels=dim_out,\n kernel_size=kernel_size,\n )\n )\n\n # Define sequential network\n self.resnet = nn.Sequential(*network)\n\n # GRU network to be applied after the ResNet\n self.gru = nn.GRU(\n input_dim, hidden_dim, layer_dim, batch_first=True, bidirectional=False\n )\n\n def forward(self, x):\n \"\"\"Apply forward network.\n\n Args:\n x (tensor): input data.\n\n Returns:\n out: feature vector.\n \"\"\"\n # Reshape input to the correct size\n x = x.view(-1, 1, 7200)\n\n # Apply ResNet to input\n x = self.resnet(x)\n\n # Define zero hidden state for GRU\n h0 = torch.zeros(\n self.layer_dim, x.size(0), self.hidden_dim, device=x.device\n ).requires_grad_()\n\n # Apply GRU\n out, _ = self.gru(x, h0.detach())\n\n # Reshape output into the correct size\n out = out.reshape(-1, 256)\n\n return out\n\nif __name__ == \"__main__\":\n model7200 = ResnetGRU()\n\n from torchinfo import summary\n\n summary(model7200, input_size=(1, 7200), depth=5, verbose=1)","sub_path":"source/models/resnet_gru_7200.py","file_name":"resnet_gru_7200.py","file_ext":"py","file_size_in_byte":6927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"418422941","text":"import numpy as np\nfrom .gcForest import *\nfrom time import time\n\n\ndef load_data():\n train_data = np.load()\n train_label = np.load()\n train_weight = np.load()\n test_data = np.load()\n test_label = np.load()\n test_file = np.load()\n return [train_data, train_label, train_weight, test_data, test_label, test_file]\n\n\nif __name__ == '__main__':\n train_data, train_label, train_weight, test_data, test_label, test_file = load_data()\n clf = gcForest(num_estimator=100, num_forests=4, max_layer=2, max_depth=100, n_fold=5)\n start = time()\n clf.train(train_data, train_label, train_weight)\n end = time()\n print(\"fitting time: \" + str(end - start) + \" sec\")\n start = time()\n prediction = clf.predict(test_data)\n end = time()\n print(\"prediction time: \" + str(end - start) + \" sec\")\n result = {}\n for index, item in enumerate(test_file):\n if item not in result:\n result[item] = prediction[index]\n else:\n result[item] = (result[item] + prediction[index]) / 2\n print(result)\n\n\n\n# deep gcForest的伪代码:\n# input = multi_Granined Scanning 的结果\n# for level_i in range(num_levels):\n# # level_i层处理后的结果\n# result = level_i(input)\n# # 更新输入向量,将本层的输入和本轮的输出拼接,作为下一层的输入\n# Input = Concatenate(result, Input)\n# # 对最后一层中每个Forest的结果求均值\n# Score = AVE(最后一层的result)\n# # 将Score中值最大的最为最终预测\n# Class = MAX(Score)\n\n","sub_path":"GCForest/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"451965210","text":"from numpy.random import Generator, PCG64\nimport multiprocessing\nimport concurrent.futures\nimport numpy as np\nfrom brain.performance.multithreaded import multithreaded\n\nfrom typing import Optional\n\n\nclass MultithreadedRNG:\n def __init__(self, threads=None, seed=None):\n rg = PCG64(seed)\n self._random_generators = [rg]\n last_rg = rg\n self.multi_generate = multithreaded(self._multi_generate, threads=threads)\n self.multi_generate.after(self._multi_generate_after)\n self.multi_generate.params(self._multi_params)\n for _ in range(len(self.multi_generate)-1):\n new_rg = last_rg.jumped()\n self._random_generators.append(new_rg)\n last_rg = new_rg\n self._random_generators = [Generator(rg) for rg in self._random_generators]\n\n @staticmethod\n def _multi_generate(rg: Generator, out: np.array, first: int, last: int, p: float):\n out[first:last] = rg.binomial(1, p, out[first:last].shape)\n return out\n\n def _multi_params(self, threads: int, height: int, width: int, prob: float):\n step = np.ceil(height / threads).astype(np.int_)\n out = np.empty((height, width))\n return (((self._random_generators[i], out, i * step, (i + 1) * step, prob), {}) for i in range(threads))\n\n @staticmethod\n def _multi_generate_after(outs):\n return outs[0] if outs else np.empty((0, 0), dtype='float64')\n\n\nif __name__ == '__main__':\n n = 10000\n a = MultithreadedRNG().multi_generate(n, n, 0.1)\n print(np.sum(a) / n**2)\n","sub_path":"brain/performance/multithreaded_rng.py","file_name":"multithreaded_rng.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"281909529","text":"\"\"\"Converting unreal csv annotations to txt annotations for training.\n\nThis file contains helper functions for parsing annotations/labels and\ngenerating formatted data for training.\n\nTodo:\n * Finish documentation\n * Save in actual output file instead of same location\n\n\"\"\"\n\nimport os\nfrom os import walk\nimport numpy as np\nimport argparse\nimport math\nimport csv\n\n\ndef convert_unreal_annotations(label_dir, output, bKeypoints=False):\n \"\"\"Function to convert unreal annotations to ronin-friendly.\n\n Annotation format: (1x15 without predictions | 1x21 with predictions)\n [\n ObjName (e.g: Aqua),\n Object Dimensions (in m): ObjH, ObjW, ObjL,\n 2D Bounding box: xmin, ymin, xmax, ymax,\n GT Quaternions in CF: qw, qx, qy, qz\n GT Translation in camera CF (in m): tx, ty, tz\n Prediction Quaternion: pred_qw, pred_qx, pred_qy, pred_qz [OPTIONAL/ADDED]\n Prediction Translation (in m): pred_tx, pred_ty, pred_tz [OPTIONAL/ADDED]\n ]\n\n Args:\n label_dir (str): Path string to labels.\n output (str): Path string to output labels (usually the same).\n\n Returns:\n bool: True if no issues, False otherwise.\n\n\n\n \"\"\"\n\n print(\"Searching through directory: \", label_dir)\n for (folder, subdirs, files) in walk(label_dir):\n for filename in files:\n if filename.lower().endswith('.csv') and filename.startswith('AllSamples') == False:\n with open(os.path.join(folder, filename), 'rb') as csvfile:\n annotreader = csv.reader(csvfile)\n headers = next(annotreader)[1:] # skip the headers\n annot = dict()\n for row in annotreader:\n image_name = row[0]\n min_x = int(row[8])\n min_y = int(row[9])\n max_x = int(row[10])\n max_y = int(row[11])\n\n tx = float(row[1])/100\n ty = float(row[2])/100\n tz = float(row[3])/100\n\n qx = float(row[12])\n qy = float(row[13])\n qz = float(row[14])\n qw = float(row[15])\n\n if bKeypoints is True:\n kps = np.array([int(kp) for kp in row[22:38]])\n \"\"\"\n Annotation format: (1x15 without predictions | 1x21 with predictions)\n [\n ObjName (e.g: Aqua),\n Object Dimensions (in m): ObjH, ObjW, ObjL,\n 2D Bounding box: xmin, ymin, xmax, ymax,\n GT Quaternions in CF: qw, qx, qy, qz\n GT Translation in camera CF (in m): tx, ty, tz\n Prediction Quaternion: pred_qw, pred_qx, pred_qy, pred_qz [OPTIONAL/ADDED]\n Prediction Translation (in m): pred_tx, pred_ty, pred_tz [OPTIONAL/ADDED]\n ]\"\"\"\n\n final_annotation = \"Aqua \"\n final_annotation += str(0.1275) + \" \"\n final_annotation += str(0.2002) + \" \"\n final_annotation += str(0.6375) + \" \"\n final_annotation += str(min_x) + \" \" # 2d bbox\n final_annotation += str(min_y) + \" \" # 2d bbox\n final_annotation += str(max_x) + \" \" # 2d bbox\n final_annotation += str(max_y) + \" \" # 2d bbox\n final_annotation += str(qw) + \" \" # qw\n final_annotation += str(qx) + \" \" # qx\n final_annotation += str(qy) + \" \" # qy\n final_annotation += str(qz) + \" \" # qz\n final_annotation += str(tx) + \" \" # pos_x\n final_annotation += str(ty) + \" \" # pos_y\n final_annotation += str(tz) + \" \" # pos_z\n\n if bKeypoints is True:\n for kp in kps:\n final_annotation += str(kp) + \" \"\n\n new_lbl_file = open(os.path.join(\n folder, image_name + '.txt'), 'w')\n print(\"[LOG] \" + str(os.path.join(folder, image_name)))\n new_lbl_file.write(final_annotation)\n new_lbl_file.close()\n\n return True\n\n\ndef parse_args():\n \"\"\"Parse input arguments.\"\"\"\n parser = argparse.ArgumentParser(description='Annotations converter (from unreal .CSV to expected .txt)')\n # parser.add_argument('--image', dest = 'image',help='Images path')\n parser.add_argument('-l', '--label_dir',\n dest='label_dir',\n help='annotation file path',\n required=True)\n parser.add_argument('-o', '--output',\n dest='output',\n help='Output path for all annotations',\n default='converted_labels',\n required=True)\n parser.add_argument('-kp', '--keypoints',\n dest='bKeypoints',\n help='Bool: whether to parse keypoints.',\n default=False,\n action='store_true')\n args = parser.parse_args()\n\n return args\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n\n if args.label_dir is None:\n raise IOError(('annotation dir not found.'.format(args.label_dir)))\n\n convert_unreal_annotations(args.label_dir, args.output, args.bKeypoints)\n","sub_path":"scripts/convert_unreal_annotations.py","file_name":"convert_unreal_annotations.py","file_ext":"py","file_size_in_byte":5695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"265023820","text":"import psycopg2\nimport sys\nimport os, re\nfrom os import system, name \nimport csv\nimport json\nimport codecs\nfrom datetime import datetime\n\nimport functions as f\nfrom commodity import commodity\nfrom commodity import davidowen_commodity\n\nfrom duty import duty\nfrom progressbar import ProgressBar\nfrom hierarchy import hierarchy\nfrom hierarchy import subheading_hierarchy\n\nclass application(object):\n\tdef __init__(self):\n\t\tself.clear()\n\t\tself.siv_list = []\n\t\tself.mfn_component_list\t\t= []\n\t\tself.meursing_list\t\t\t= []\n\t\tself.vessels_list = []\n\t\tself.civilair_list\t\t\t= []\n\t\tself.airworthiness_list\t\t= []\n\t\tself.aircraft_list\t\t\t= []\n\t\tself.pharmaceuticals_list\t= []\n\t\tself.ita_list \t\t\t\t= []\n\t\tself.generalrelief_list\t\t= []\n\t\tself.authoriseduse_list\t\t= []\n\t\tself.seasonal_list\t\t\t= []\n\t\tself.special_list\t\t\t= []\n\t\tself.section_chapter_list\t= []\n\t\tself.lstFootnotes\t\t\t= []\n\t\tself.lstFootnotesUnique\t\t= []\n\t\tself.debug\t\t\t\t\t= False\n\t\tself.suppress_duties\t\t= False\n\t\tself.country_codes\t\t\t= \"\"\n\t\tself.siv_data_list\t\t\t= []\n\t\tself.seasonal_fta_duties\t= []\n\t\tself.suspensions_xml\t\t= \"\"\n\t\tself.david_owen_list\t\t= []\n\t\t\n\t\tself.partial_temporary_stops\t= []\n\n\t\tself.BASE_DIR\t\t\t= os.path.dirname(os.path.abspath(__file__))\n\t\tself.SOURCE_DIR\t\t\t= os.path.join(self.BASE_DIR, \"source\")\n\t\tself.OUTPUT_DIR\t\t\t= os.path.join(self.BASE_DIR, \"output\")\n\t\tself.COMPONENT_DIR\t\t= os.path.join(self.BASE_DIR, \"xmlcomponents\")\n\t\tself.CONFIG_DIR\t\t\t= os.path.join(self.BASE_DIR, \"..\")\n\t\tself.CONFIG_DIR\t\t\t= os.path.join(self.CONFIG_DIR, \"..\")\n\t\tself.CONFIG_DIR\t\t\t= os.path.join(self.CONFIG_DIR, \"create-data\")\n\t\tself.CONFIG_DIR\t\t\t= os.path.join(self.CONFIG_DIR, \"config\")\n\t\tself.CONFIG_FILE\t\t= os.path.join(self.CONFIG_DIR, \"config_common.json\")\n\t\tself.CONFIG_FILE_LOCAL\t= os.path.join(self.CONFIG_DIR, \"config_migrate_measures_and_quotas.json\")\n\n\t\tself.BALANCE_DIR\t\t= os.path.join(self.BASE_DIR, \"..\")\n\t\tself.BALANCE_DIR\t\t= os.path.join(self.BALANCE_DIR, \"..\")\n\t\tself.BALANCE_DIR\t\t= os.path.join(self.BALANCE_DIR, \"create-data\")\n\t\tself.BALANCE_DIR\t\t= os.path.join(self.BALANCE_DIR, \"migrate_measures_and_quotas\")\n\t\tself.BALANCE_DIR\t\t= os.path.join(self.BALANCE_DIR, \"source\")\n\t\tself.BALANCE_DIR\t\t= os.path.join(self.BALANCE_DIR, \"quotas\")\n\t\tself.BALANCE_FILE\t\t= os.path.join(self.BALANCE_DIR, \"quota_volume_master.csv\")\n\n\t\targ1 = \"\"\n\t\tself.include_do_only = False\n\t\ttry:\n\t\t\targ1 = sys.argv[1].strip()\n\t\texcept:\n\t\t\targ1 = \"\"\n\t\tif arg1 != \"\":\n\t\t\tself.include_do_only = True\n\t\t\n\n\t\tself.get_config()\n\t\tself.readTemplates()\n\n\tdef clear(self):\n\t\t# for windows\n\t\tif name == 'nt':\n\t\t\t_ = system('cls')\n\t\t# for mac and linux(here, os.name is 'posix')\n\t\telse:\n\t\t\t#_ = system('clear')\n\t\t\t_ = system(\"printf '\\33c\\e[3J'\")\n\n\tdef get_config(self):\n\t\t# Get global config items\n\t\twith open(self.CONFIG_FILE, 'r') as f:\n\t\t\tmy_dict = json.load(f)\n\n\t\tself.DBASE\t\t\t= my_dict['dbase']\n\t\tself.p\t\t\t\t= my_dict['p']\n\t\t#print (self.DBASE)\n\t\t#sys.exit()\n\n\t\t# Get local config items\n\t\twith open(self.CONFIG_FILE_LOCAL, 'r') as f:\n\t\t\tmy_dict = json.load(f)\n\n\t\tself.all_country_profiles = my_dict['country_profiles']\n\n\t\t# Connect to the database\n\t\tself.connect()\n\n\tdef get_country_list(self):\n\t\ttry:\n\t\t\tself.country_codes = self.all_country_profiles[self.country_profile][\"country_codes\"]\n\t\texcept:\n\t\t\tprint (\"Country profile does not exist\")\n\t\t\tsys.exit()\n\t\tself.agreement_name\t\t\t= self.all_country_profiles[self.country_profile][\"agreement_name\"]\n\n\t\tself.agreement_date_short\t= self.all_country_profiles[self.country_profile][\"agreement_date\"]\n\t\ttemp = datetime.strptime(self.agreement_date_short, \"%d/%m/%Y\")\n\t\tself.agreement_date_long\t= datetime.strftime(temp, \"%d %B %Y\")\n\n\t\tself.table_per_country\t\t= self.all_country_profiles[self.country_profile][\"table_per_country\"]\n\t\tself.version\t\t\t\t= self.all_country_profiles[self.country_profile][\"version\"]\n\t\tself.country_name\t\t\t= self.all_country_profiles[self.country_profile][\"country_name\"]\n\n\tdef connect(self):\n\t\tself.conn = psycopg2.connect(\"dbname=\" + self.DBASE + \" user=postgres password=\" + self.p)\n\n\tdef shutDown(self):\n\t\tself.conn.close()\n\n\tdef get_chapter_description(self, chapter_string):\n\t\t###############################################################\n\t\t# Get the chapter description\n\t\t# Relevant to both the classification and the schedule\n\t\tsql = \"SELECT description FROM ml.chapters WHERE chapter = '\" + chapter_string + \"'\"\n\t\tcur = self.conn.cursor()\n\t\tcur.execute(sql)\n\t\trow = cur.fetchone()\n\t\ttry:\n\t\t\tchapter_description = row[0]\n\t\t\tchapter_description = chapter_description.replace(\" Of \", \" of \")\n\t\t\tchapter_description = chapter_description.replace(\" Or \", \" or \")\n\t\texcept:\n\t\t\tchapter_description = \"\"\n\n\t\treturn chapter_description\n\n\tdef getSectionsChapters(self):\n\t\tsql = \"\"\"\n\t\tSELECT LEFT(gn.goods_nomenclature_item_id, 2) as chapter, cs.section_id\n\t\tFROM chapters_sections cs, goods_nomenclatures gn\n\t\tWHERE cs.goods_nomenclature_sid = gn.goods_nomenclature_sid AND gn.producline_suffix = '80'\n\t\tORDER BY 1\n\t\t\"\"\"\n\t\tcur = self.conn.cursor()\n\t\tcur.execute(sql)\n\t\trows_sections_chapters = cur.fetchall()\n\t\tself.section_chapter_list = []\n\t\tfor rd in rows_sections_chapters:\n\t\t\tsChapter = rd[0]\n\t\t\tiSection = rd[1]\n\t\t\tself.section_chapter_list.append([sChapter, iSection, False])\n\t\t\t\n \t\t# The last parameter is \"1\" if the chapter equates to a new section\n\t\tiLastSection = -1\n\t\tfor r in self.section_chapter_list:\n\t\t\tiSection = r[1]\n\t\t\tif iSection != iLastSection:\n\t\t\t\tr[2] = True\n\t\t\tiLastSection = iSection\n\n\tdef readTemplates(self):\n\t\tself.COMPONENT_DIR = os.path.join(self.COMPONENT_DIR, \"\")\n\n\t\tfile = open(os.path.join(self.COMPONENT_DIR, \"document.xml\"), \"r\")\n\t\tself.sDocumentXML = file.read()\n\n\t\tfile = open(os.path.join(self.COMPONENT_DIR, \"tablerow.xml\"), \"r\")\n\t\tself.sTableRowXML = file.read()\n\n\t\tfile = open(os.path.join(self.COMPONENT_DIR, \"tier1.xml\"), \"r\")\n\t\tself.sTier1XML = file.read()\n\n\t\tfile = open(os.path.join(self.COMPONENT_DIR, \"tier2.xml\"), \"r\")\n\t\tself.sTier2XML = file.read()\n\n\t\tfile = open(os.path.join(self.COMPONENT_DIR, \"tier3.xml\"), \"r\")\n\t\tself.sTier3XML = file.read()\n\n\t\tfile = open(os.path.join(self.COMPONENT_DIR, \"tier4.xml\"), \"r\")\n\t\tself.sTier4XML = file.read()\n\n\t\tfile = open(os.path.join(self.COMPONENT_DIR, \"tier5.xml\"), \"r\")\n\t\tself.sTier5XML = file.read()\n\n\t\tfile = open(os.path.join(self.COMPONENT_DIR, \"tier6.xml\"), \"r\")\n\t\tself.sTier6XML = file.read()\n\n\t\tfile = open(os.path.join(self.COMPONENT_DIR, \"tier7.xml\"), \"r\")\n\t\tself.sTier7XML = file.read()\n\n\t\tfile = open(os.path.join(self.COMPONENT_DIR, \"tier8.xml\"), \"r\")\n\t\tself.sTier8XML = file.read()\n\n\t\tfile = open(os.path.join(self.COMPONENT_DIR, \"tier1bullet.xml\"), \"r\")\n\t\tself.sTier1BulletXML = file.read()\n\n\t\tfile = open(os.path.join(self.COMPONENT_DIR, \"tier2bullet.xml\"), \"r\")\n\t\tself.sTier2BulletXML = file.read()\n\n\t\tfile = open(os.path.join(self.COMPONENT_DIR, \"tier3bullet.xml\"), \"r\")\n\t\tself.sTier3BulletXML = file.read()\n\n\t\tfile = open(os.path.join(self.COMPONENT_DIR, \"tier4bullet.xml\"), \"r\")\n\t\tself.sTier4BulletXML = file.read()\n\n\t\tfile = open(os.path.join(self.COMPONENT_DIR, \"tier5bullet.xml\"), \"r\")\n\t\tself.sTier5BulletXML = file.read()\n\n\t\tfile = open(os.path.join(self.COMPONENT_DIR, \"tier6bullet.xml\"), \"r\")\n\t\tself.sTier6BulletXML = file.read()\n\n\t\tfile = open(os.path.join(self.COMPONENT_DIR, \"tier7bullet.xml\"), \"r\")\n\t\tself.sTier7BulletXML = file.read()\n\n\t\tfile = open(os.path.join(self.COMPONENT_DIR, \"tier8bullet.xml\"), \"r\")\n\t\tself.sTier8BulletXML = file.read()\n\n\t\t#bullet = \">\" # chr(149)\n\t\tbullet = chr(149)\n\t\tself.sTier1BulletXML = self.sTier1BulletXML.replace(\"#\", bullet)\n\t\tself.sTier2BulletXML = self.sTier2BulletXML.replace(\"#\", bullet)\n\t\tself.sTier3BulletXML = self.sTier3BulletXML.replace(\"#\", bullet)\n\t\tself.sTier4BulletXML = self.sTier4BulletXML.replace(\"#\", bullet)\n\t\tself.sTier5BulletXML = self.sTier5BulletXML.replace(\"#\", bullet)\n\t\tself.sTier6BulletXML = self.sTier6BulletXML.replace(\"#\", bullet)\n\t\tself.sTier7BulletXML = self.sTier7BulletXML.replace(\"#\", bullet)\n\t\tself.sTier8BulletXML = self.sTier8BulletXML.replace(\"#\", bullet)\n\n\n\t\t# New for authorised use\n\t\tfile = open(os.path.join(self.COMPONENT_DIR, \"starttable.xml\"), \"r\")\n\t\tself.sStartTableXML = file.read()\n\n\t\tfile = open(os.path.join(self.COMPONENT_DIR, \"endtable.xml\"), \"r\")\n\t\tself.sEndTableXML = file.read()\n\n\t\tfile = open(os.path.join(self.COMPONENT_DIR, \"heading1.xml\"), \"r\")\n\t\tself.sHeading1XML = file.read()\n\n\t\tfile = open(os.path.join(self.COMPONENT_DIR, \"heading2.xml\"), \"r\")\n\t\tself.sHeading2XML = file.read()\n\n\n\n\tdef getSivs(self):\n\t\t# Be aware that this is deliberately using old data, meaning that \n\t\t# in reality, the duty charged will be zero\n\t\tsql = \"\"\"SELECT DISTINCT m.goods_nomenclature_item_id\n\t\tFROM measures m, measure_conditions mc\n\t\tWHERE m.measure_sid = mc.measure_sid\n\t\tAND m.validity_start_date > '2018-01-01'\n\t\tAND mc.condition_code = 'V'\n\t\tORDER BY m.goods_nomenclature_item_id\n\t\t\"\"\"\n\t\tcur = self.conn.cursor()\n\t\tcur.execute(sql)\n\t\trows = cur.fetchall()\n\t\tfor r in rows:\n\t\t\tself.siv_list.append(r[0])\n\t\t\n\t\tself.siv_list.append(\"0707000510\")\n\t\tself.siv_list.append(\"0707000520\")\n\t\t\t\n\tdef getVessels(self):\n\t\tsql = \"\"\"SELECT DISTINCT goods_nomenclature_item_id FROM ml.v5_brexit_day m WHERE measure_type_id = '117';\"\"\"\n\t\tcur = self.conn.cursor()\n\t\tcur.execute(sql)\n\t\trows = cur.fetchall()\n\t\tfor r in rows:\n\t\t\tself.vessels_list.append(r[0])\n\n\tdef getCivilAir(self):\n\t\tsql = \"\"\"SELECT DISTINCT gn.goods_nomenclature_item_id\n\t\tFROM goods_nomenclature_descriptions gnd, goods_nomenclatures gn\n\t\tWHERE gn.goods_nomenclature_item_id = gnd.goods_nomenclature_item_id\n\t\tAND (LOWER(description) LIKE '%civil air%' OR LOWER(description) LIKE '%civil use%')\n\t\tAND gn.validity_start_date <= '2019/01/01'\n\t\tAND (gn.validity_end_date >= '2019/03/29' OR gn.validity_end_date IS NULL) ORDER BY 1\"\"\"\n\t\tcur = self.conn.cursor()\n\t\tcur.execute(sql)\n\t\trows = cur.fetchall()\n\t\tfor r in rows:\n\t\t\tself.civilair_list.append(r[0])\n\n\t\t\"\"\"\n\t\tfilename = os.path.join(self.SOURCE_DIR, \"civilair_commodities.csv\")\n\t\twith open(filename, \"r\") as f:\n\t\t\treader = csv.reader(f)\n\t\t\ttemp = list(reader)\n\t\tfor i in temp:\n\t\t\tself.civilair_list.append(i[0])\n\t\t\"\"\"\n\n\tdef getAirworthiness(self):\n\t\tsql = \"\"\"SELECT DISTINCT goods_nomenclature_item_id FROM ml.v5_brexit_day m WHERE measure_type_id = '119';\"\"\"\n\t\tcur = self.conn.cursor()\n\t\tcur.execute(sql)\n\t\trows = cur.fetchall()\n\t\tfor r in rows:\n\t\t\tself.airworthiness_list.append(r[0])\n\n\tdef getAircraft(self):\n\t\tsql = \"\"\"SELECT DISTINCT goods_nomenclature_item_id FROM ml.v5_brexit_day m WHERE measure_type_id = '115' AND regulation_id = 'R953050' ORDER BY 1;\"\"\"\n\t\tcur = self.conn.cursor()\n\t\tcur.execute(sql)\n\t\trows = cur.fetchall()\n\t\tfor r in rows:\n\t\t\tself.aircraft_list.append(r[0])\n\n\tdef getPharmaceuticals(self):\n\t\tsql = \"\"\"SELECT DISTINCT goods_nomenclature_item_id FROM ml.v5_brexit_day m WHERE additional_code_type_id = '2' AND additional_code_id = '500' ORDER BY 1;\"\"\"\n\t\tcur = self.conn.cursor()\n\t\tcur.execute(sql)\n\t\trows = cur.fetchall()\n\t\tfor r in rows:\n\t\t\tself.pharmaceuticals_list.append(r[0])\n\n\tdef getITAProducts(self):\n\t\tfilename = os.path.join(self.SOURCE_DIR, \"ita_commodities.csv\")\n\t\twith open(filename, \"r\") as f:\n\t\t\treader = csv.reader(f)\n\t\t\ttemp = list(reader)\n\t\tfor i in temp:\n\t\t\tself.ita_list.append(i[0])\n\n\tdef getGeneralRelief(self):\n\t\tfilename = os.path.join(self.SOURCE_DIR, \"generalrelief_commodities.csv\")\n\t\twith open(filename, \"r\") as f:\n\t\t\treader = csv.reader(f)\n\t\t\ttemp = list(reader)\n\t\tfor i in temp:\n\t\t\tself.generalrelief_list.append(i[0])\n\n\tdef getAuthorisedUse(self):\n\t\tsql = \"\"\"SELECT DISTINCT goods_nomenclature_item_id FROM ml.v5_2019 m WHERE measure_type_id = '105';\"\"\"\n\t\tcur = self.conn.cursor()\n\t\tcur.execute(sql)\n\t\trows = cur.fetchall()\n\t\tfor r in rows:\n\t\t\tself.authoriseduse_list.append(r[0])\n\t\t\n\t\t# Also add in cucumbers: the data cannot find these, therefore manually added\n\t\tself.authoriseduse_list.append(\"0707000510\")\n\t\tself.authoriseduse_list.append(\"0707000520\")\n\t\t\n\tdef getSpecials(self):\n\t\tfilename = os.path.join(self.SOURCE_DIR, \"special_notes.csv\")\n\t\twith open(filename, \"r\") as f:\n\t\t\treader = csv.reader(f)\n\t\t\ttemp = list(reader)\n\t\tfor row in temp:\n\t\t\tcommodity_code\t= row[0]\n\t\t\tnote\t\t\t= row[1]\n\t\t\toSpecial = special(commodity_code, note)\n\n\t\t\tself.special_list.append(oSpecial)\n\n\tdef getSeasonal(self):\n\t\tfilename = os.path.join(self.SOURCE_DIR, \"seasonal_commodities.csv\")\n\t\twith open(filename, \"r\") as f:\n\t\t\treader = csv.reader(f)\n\t\t\ttemp = list(reader)\n\t\tfor row in temp:\n\t\t\tcommodity_code\t\t= row[0]\n\t\t\tseason1_start\t\t= row[1]\n\t\t\tseason1_end\t\t\t= row[2]\n\t\t\tseason1_expression\t= row[3]\n\t\t\tseason2_start\t\t= row[4]\n\t\t\tseason2_end\t\t\t= row[5]\n\t\t\tseason2_expression\t= row[6]\n\t\t\tseason3_start\t\t= row[7]\n\t\t\tseason3_end\t\t\t= row[8]\n\t\t\tseason3_expression\t= row[9]\n\t\t\toSeasonal = seasonal(commodity_code, season1_start, season1_end, season1_expression, season2_start, season2_end, season2_expression, season3_start, season3_end, season3_expression)\n\n\t\t\tself.seasonal_list.append(oSeasonal)\n\n\tdef getSIVProducts(self):\n\t\t# The SQL below gets all products that have a V condition, therefore entry price system against them\n\t\t\"\"\"SELECT DISTINCT goods_nomenclature_item_id FROM measures m, measure_conditions mc\n\t\tWHERE m.measure_sid = mc.measure_sid\n\t\tAND mc.condition_code = 'V'\n\t\tAND m.validity_start_date >= '2018-01-01' AND (m.validity_end_date <= '2020-01-01' OR m.validity_end_date IS NULL)\n\t\tORDER BY 1\"\"\"\n\t\tfilename = os.path.join(self.SOURCE_DIR, \"siv_products.csv\")\n\t\twith open(filename, \"r\") as f:\n\t\t\treader = csv.reader(f)\n\t\t\ttemp = list(reader)\n\t\tfor i in temp:\n\t\t\tself.siv_list.append(i[0])\n\n\tdef getCountryAdValoremForSIV(self):\n\t\tsql = \"\"\"SELECT m.goods_nomenclature_item_id, mcc.duty_amount, mcc.duty_expression_id, m.validity_start_date, m.validity_end_date\n\t\tFROM measures m, measure_conditions mc, measure_condition_components mcc\n\t\tWHERE m.measure_sid = mc.measure_sid\n\t\tAND mcc.measure_condition_sid = mc.measure_condition_sid\n\t\tAND m.geographical_area_id IN (\"\"\" + self.geo_ids + \"\"\")\n\t\tAND mc.condition_code = 'V'\n\t\tAND mcc.duty_expression_id = '01'\n\t\tAND validity_start_date <= CURRENT_DATE\n\t\tAND (validity_end_date >= CURRENT_DATE OR validity_end_date IS NULL)\n\t\tORDER BY validity_start_date DESC\"\"\"\n\t\t#print (sql)\n\t\tcur = self.conn.cursor()\n\t\tcur.execute(sql)\n\t\trows = cur.fetchall()\n\t\tself.partial_temporary_stops = []\n\t\tfor rw in rows:\n\t\t\tgoods_nomenclature_item_id\t= rw[0]\n\t\t\tduty_amount\t\t\t\t\t= rw[1]\n\t\t\tduty_expression_id\t\t\t= rw[2]\n\t\t\tvalidity_start_date\t\t\t= rw[3]\n\t\t\tvalidity_end_date\t\t\t= rw[4]\n\n\t\t\tsiv = siv_data(goods_nomenclature_item_id, duty_amount, duty_expression_id, validity_start_date, validity_end_date)\n\t\t\tself.siv_data_list.append (siv)\n\n\t\t# Ensure that there is only one (the latest record listed here; delete all the others)\n\t\tunique_siv_data_list_commodities_only\t= []\n\t\tunique_siv_data_list\t\t\t\t\t= []\n\t\tfor item in self.siv_data_list:\n\t\t\tif item.goods_nomenclature_item_id not in unique_siv_data_list_commodities_only:\n\t\t\t\tunique_siv_data_list.append (item)\n\n\t\t\tunique_siv_data_list_commodities_only.append (item.goods_nomenclature_item_id)\n\n\t\tself.siv_data_list = unique_siv_data_list\n\t\t\n\n\tdef get_authorised_use_commodities(self):\n\t\tsql = \"\"\"\n\t\t-- Ships (2357 commodities); this is the whole of 117\n\t\tSELECT DISTINCT measure_sid, goods_nomenclature_item_id, 'ships' as measure_type FROM ml.v5 m WHERE measure_type_id = '117'\n\n\t\tUNION\n\n\t\t-- Non preferential duty under end-use (479 commodities) - this is the whole of 105\n\t\tSELECT DISTINCT measure_sid, goods_nomenclature_item_id, 'non-pref' as measure_type\n\t\tFROM ml.v5 m\n\t\tWHERE measure_type_id = '105' AND (m.additional_code_id IS NULL OR m.additional_code_id = '550')\n\n\t\tUNION\n\n\t\t-- Aircraft (0 commodies: 732 rows)\n\t\tSELECT DISTINCT m.measure_sid, m.goods_nomenclature_item_id, 'certainair' as measure_type\n\t\tFROM goods_nomenclature_descriptions gnd, goods_nomenclatures gn, ml.v5 m\n\t\tWHERE gn.goods_nomenclature_item_id = m.goods_nomenclature_item_id\n\t\tAND gn.goods_nomenclature_item_id = gnd.goods_nomenclature_item_id\n\t\tAND (LOWER(description) LIKE '%aircraft%' OR LOWER(description) LIKE '%aircraft%')\n\t\tAND m.measure_type_id = '115'\n\t\tORDER BY 2\n\t\tLIMIT 10000\n\t\t\"\"\"\n\n\t\tmeasure_list_string = \"\"\n\t\tcur = self.conn.cursor()\n\t\tcur.execute(sql)\n\t\trows = cur.fetchall()\n\t\tself.commodity_list = []\n\t\tfor row in rows:\n\t\t\tmeasure_sid\t\t\t\t\t= row[0]\n\t\t\tgoods_nomenclature_item_id\t= row[1]\n\t\t\tmeasure_type\t\t\t\t= row[2]\n\t\t\tif 2 > 1:\n\t\t\t#if goods_nomenclature_item_id[0:2] == \"94\":\n\t\t\t\tvalidity_start_date\t\t\t= \"\"\n\t\t\t\tmy_commodity = commodity(measure_sid, goods_nomenclature_item_id, validity_start_date, measure_type)\n\t\t\t\tself.commodity_list.append(my_commodity)\n\n\t\t\t\tmeasure_list_string\t\t\t+= \"'\" + str(measure_sid) + \"', \"\n\n\t\tmeasure_list_string = measure_list_string.strip()\n\t\tmeasure_list_string = measure_list_string.strip(\",\")\n\n\t\t#print (measure_list_string)\n\n\t\tsql = \"\"\"\n\t\tSELECT mc.measure_sid, mc.duty_expression_id, mc.duty_amount, mc.monetary_unit_code, measurement_unit_code,\n\t\tmeasurement_unit_qualifier_code, m.goods_nomenclature_item_id\n\t\tFROM measure_components mc, ml.v5 m\n\t\tWHERE m.measure_sid = mc.measure_sid\n\t\tAND m.measure_sid IN (\"\"\" + measure_list_string + \"\"\")\n\t\tORDER BY m.goods_nomenclature_item_id, duty_expression_id\n\t\t\"\"\"\n\n\t\tcur = self.conn.cursor()\n\t\tcur.execute(sql)\n\t\trows = cur.fetchall()\n\n\t\tself.duty_list = []\n\t\tfor row in rows:\n\t\t\tmeasure_sid\t\t\t\t\t\t= row[0]\n\t\t\tduty_expression_id\t\t\t\t= row[1]\n\t\t\tduty_amount\t\t\t\t\t\t= row[2]\n\t\t\tmonetary_unit_code\t\t\t\t= row[3]\n\t\t\tmeasurement_unit_code\t\t\t= row[4]\n\t\t\tmeasurement_unit_qualifier_code\t= row[5]\n\t\t\tgoods_nomenclature_item_id\t\t= row[6]\n\n\t\t\tmy_duty = duty(goods_nomenclature_item_id, \"\", \"\", \"\", duty_expression_id, duty_amount, monetary_unit_code, measurement_unit_code, measurement_unit_qualifier_code, measure_sid)\n\t\t\tself.duty_list.append(my_duty)\n\n\n\t\t# Put the MFN commodities into a set\n\t\tmfn_list = []\n\t\tfor mfn in self.mfn_component_list:\n\t\t\tmfn_list.append(mfn.commodity_code)\n\n\t\tmfn_set = set(mfn_list)\n\t\t#print (len(mfn_set))\n\t\t#sys.exit()\n\n\t\tfor my_commodity in self.commodity_list:\n\t\t\tif my_commodity.goods_nomenclature_item_id in mfn_set:\n\t\t\t\tprint (my_commodity.goods_nomenclature_item_id, \"non-zero\")\n\t\t\t\tfor my_duty in self.duty_list:\n\t\t\t\t\tif my_duty.measure_sid == my_commodity.measure_sid:\n\t\t\t\t\t\tmy_commodity.duty_list.append(my_duty)\n\t\t\t\t\t\t#break\n\t\t\telse:\n\t\t\t\t#print (\"zero\")\n\t\t\t\tmy_commodity.append_zero_duty()\n\n\t\t# Now add in the military set\n\t\tfilename = os.path.join(self.SOURCE_DIR, \"military_list.csv\")\n\t\twith open(filename, \"r\") as f:\n\t\t\treader = csv.reader(f)\n\t\t\trows = list(reader)\n\t\t\n\t\tfor row in rows:\n\t\t\tgoods_nomenclature_item_id\t= row[0]\n\t\t\tmeasure_sid\t\t\t\t\t= int(goods_nomenclature_item_id)\n\t\t\tvalidity_start_date\t\t\t= \"\"\n\t\t\tmeasure_type\t\t\t\t= \"military\"\n\t\t\tmy_commodity = commodity(measure_sid, goods_nomenclature_item_id, validity_start_date, measure_type)\n\n\t\t\tduty_expression_id\t\t\t\t= \"01\"\n\t\t\tduty_amount\t\t\t\t\t\t= 0\n\t\t\tmonetary_unit_code\t\t\t\t= \"\"\n\t\t\tmeasurement_unit_code\t\t\t= \"\"\n\t\t\tmeasurement_unit_qualifier_code\t= \"\"\n\n\t\t\tmy_duty = duty(goods_nomenclature_item_id, \"\", \"\", \"\", duty_expression_id, duty_amount, monetary_unit_code, measurement_unit_code, measurement_unit_qualifier_code, measure_sid)\n\t\t\tmy_commodity.duty_list.append(my_duty)\n\n\t\t\tself.commodity_list.append(my_commodity)\n\n\t\t# Now the military list is added, the whole list needs to be resorted\n\t\tself.commodity_list.sort(key=lambda x: x.goods_nomenclature_item_id, reverse = False)\n\n\n\t\tprint (\"Combining duties\")\n\t\tfor my_commodity in self.commodity_list:\n\t\t\tmy_commodity.combineDuties()\n\n\t\tsubheading_list = []\n\t\tfor my_commodity in self.commodity_list:\n\t\t\tsubheading_list.append(my_commodity.subheading)\n\t\t\n\t\tprint(\"Getting subheading hierarchies\")\n\t\tself.list_of_hierarchies = []\n\t\tmy_set = set(subheading_list)\n\t\tp = ProgressBar(len(my_set), sys.stdout)\n\t\tcnt = 1\n\t\tfor subheading in my_set:\n\t\t\tobj_hierarchy = self.get_hierarchy(subheading)\n\n\t\t\tp.print_progress(cnt)\n\t\t\tcnt +=1\n\t\t\tobj_subheading_hierarchy = subheading_hierarchy(subheading, obj_hierarchy)\n\t\t\tself.list_of_hierarchies.append(obj_subheading_hierarchy)\n\n\t\tself.list_of_hierarchies.sort(key=lambda x: x.subheading, reverse = False)\n\n\t\tprint(\"\\n\\nWriting XML for Word document\")\n\t\tp = ProgressBar(len(self.commodity_list), sys.stdout)\n\t\tcnt = 1\n\n\t\t# We need to form a new table wherever the chapter changes\n\t\t# The overarching document is formed of\n\t\t#\t- a single document.xml, which has a placeholder entitles [TABLES]\n\t\t#\t- into which the multiple chapter tables are inserted\n\t\t# \t- a new chapter is created whenever the commodity's chapter property changes\n\t\t#\t- at which point a heading 1 object, followed by a start table object, then the full table, and eventually an end table object are inserted\n\n\t\tself.table_xml = \"\"\n\t\tlast_chapter = \"-1\"\n\n\t\tlast_goods_nomenclature_item_id = \"dummy\"\n\t\tlast_combined_duty\t\t\t\t= \"dummy\"\n\t\tlast_context\t\t\t\t\t= \"dummy\"\n\n\t\tfor my_commodity in self.commodity_list:\n\t\t\tif my_commodity.include:\n\t\t\t\tmy_context = my_commodity.goods_nomenclature_item_id + my_commodity.combined_duty\n\t\t\t\tif my_context != \"a dummy string\": # last_context:\n\t\t\t\t\tmy_commodity.get_hierarchy()\n\t\t\t\t\trow_xml = \"\"\n\t\t\t\t\tif my_commodity.chapter != last_chapter:\n\t\t\t\t\t\tif last_chapter != \"-1\":\n\t\t\t\t\t\t\trow_xml += self.sEndTableXML\n\n\t\t\t\t\t\theading1_xml = self.sHeading1XML\n\t\t\t\t\t\tchapter_description = \"Chapter \" + str(int(my_commodity.chapter)) + \" : \" + self.get_chapter_description(my_commodity.chapter)\n\t\t\t\t\t\theading1_xml = heading1_xml.replace(\"[HEADING]\", chapter_description)\n\t\t\t\t\t\trow_xml += heading1_xml\n\t\t\t\t\t\trow_xml += self.sStartTableXML\n\n\t\t\t\t\trow = self.sTableRowXML\n\t\t\t\t\trow = row.replace(\"[COMMODITY_CODE]\", \tmy_commodity.goods_nomenclature_item_id)\n\t\t\t\t\trow = row.replace(\"[DESCRIPTION]\", \t\tmy_commodity.hierarchy)\n\t\t\t\t\trow = row.replace(\"[DUTY_EXPRESSION]\",\tmy_commodity.combined_duty)\n\t\t\t\t\trow_xml += row\n\t\t\t\t\tself.table_xml += row_xml\n\t\t\t\t\tlast_chapter = my_commodity.chapter\n\n\t\t\tlast_goods_nomenclature_item_id = my_commodity.goods_nomenclature_item_id\n\t\t\tlast_combined_duty\t\t\t\t= my_commodity.combined_duty\n\t\t\tlast_context = last_goods_nomenclature_item_id + last_combined_duty\n\n\t\t\tp.print_progress(cnt)\n\t\t\tcnt +=1\n\n\t\tself.table_xml += self.sEndTableXML\n\t\tself.cleanse_xml()\n\t\t\n\t\tself.suspensions_xml = self.sDocumentXML\n\t\tself.suspensions_xml = self.suspensions_xml.replace(\"[TABLES]\", self.table_xml)\n\n\tdef get_hierarchy(self, subheading):\n\t\t# This gets an entire section of the catalogue: it is not a hierarchy in itself\n\t\tsql = \"\"\"\n\t\tSELECT goods_nomenclature_item_id, producline_suffix, number_indents, description\n\t\tFROM ml.goods_nomenclature_export3('\"\"\" + subheading + \"\"\"%')\n\t\tORDER BY goods_nomenclature_item_id, producline_suffix\n\t\t\"\"\"\n\t\tcur = self.conn.cursor()\n\t\tcur.execute(sql)\n\t\trows = cur.fetchall()\n\t\thierarchy_list = []\n\n\t\tfor row in rows:\n\t\t\tgoods_nomenclature_item_id\t= row[0]\n\t\t\tproducline_suffix\t\t\t= row[1]\n\t\t\tnumber_indents\t\t\t\t= row[2]\n\t\t\tdescription\t\t\t\t\t= row[3]\n\t\t\tmy_hierarchy = hierarchy(goods_nomenclature_item_id, producline_suffix, number_indents, description)\n\t\t\thierarchy_list.append(my_hierarchy)\n\t\treturn hierarchy_list\n\n\tdef cleanse_xml(self):\n\t\tself.table_xml = re.sub(\"(.*)m2\", \"\\g<1>m2\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"(.*)m3\", \"\\g<1>m3\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"(.*)K2O\", \"\\g<1>K2O\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"(.*)H2O2\", \"\\g<1>H2O2\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"(.*)P2O5\", \"\\g<1>P2O5\", self.table_xml, flags=re.MULTILINE)\n\t\t\n\t\t# Subscripts\n\t\tself.table_xml = re.sub(\"@(.)\", '\\\\1', self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"\\$(.)\", '\\\\1 ', self.table_xml, flags=re.MULTILINE)\n\n\t\t# Missing commas\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]) kg\", \"\\\\1.\\\\2 kg\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]) Kg\", \"\\\\1.\\\\2 kg\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]) C\", \"\\\\1.\\\\2 C\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9])kg\", \"\\\\1.\\\\2kg\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]{1,3}) g\", \"\\\\1.\\\\2 g\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]{1,3})g\", \"\\\\1.\\\\2g\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]{1,3}) dl\", \"\\\\1.\\\\2 dl\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]{1,3}) m\", \"\\\\1.\\\\2 m\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]{1,3})m\", \"\\\\1.\\\\2m\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]{1,3}) decitex\", \"\\\\1.\\\\2 decitex\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]{1,3}) l\", \"\\\\1.\\\\2 l\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]{1,3}) kW\", \"\\\\1.\\\\2 kW\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]{1,3}) W\", \"\\\\1.\\\\2 W\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]{1,3}) V\", \"\\\\1.\\\\2 V\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]{1,3}) Ah\", \"\\\\1.\\\\2 Ah\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]{1,3}) bar\", \"\\\\1.\\\\2 bar\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]{1,3}) cm\", \"\\\\1.\\\\2 cm\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]{1,3}) Nm\", \"\\\\1.\\\\2 Nm\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]{1,3}) kV\", \"\\\\1.\\\\2 kV\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]{1,3}) kHz\", \"\\\\1.\\\\2 kHz\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]{1,3}) kV\", \"\\\\1.\\\\2 kV\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]{1,3}) MHz\", \"\\\\1.\\\\2 MHz\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]{1,3}) μm\", \"\\\\1.\\\\2 μm\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]{1,3}) Ohm\", \"\\\\1.\\\\2 Ohm\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]{1,3}) dB\", \"\\\\1.\\\\2 dB\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"([0-9]),([0-9]{1,3}) kvar\", \"\\\\1.\\\\2 kvar\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"±([0-9]),([0-9]{1,3})\", \"±\\\\1.\\\\2\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = re.sub(\"€ ([0-9]{1,3}),([0-9]{1,3})\", \"€ \\\\1.\\\\2\", self.table_xml, flags=re.MULTILINE)\n\t\tself.table_xml = self.table_xml.replace(\" %\", \"%\")\n\n\tdef write_file(self):\n\t\tbasedir = os.path.dirname(os.path.abspath(__file__))\n\n\t\tfilename = os.path.join(basedir, \"model\")\n\t\tfilename = os.path.join(filename, \"word\")\n\t\tfilename = os.path.join(filename, \"document.xml\")\n\n\t\tprint (filename)\n\n\t\tfile = codecs.open(filename, \"w\", \"utf-8\")\n\t\tfile.write(self.suspensions_xml)\n\t\tfile.close() \n\n\t\t###########################################################################\n\t\t## Finally, ZIP everything up\n\t\t###########################################################################\n\t\tself.word_filename = os.path.join(self.OUTPUT_DIR, \"Authorised_use_rates_document.docx\")\n\t\tf.zipdir(self.word_filename)\n\n\tdef get_DavidOwen_list(self):\n\t\tfilename = os.path.join(self.SOURCE_DIR, \"david_owen_excel.csv\")\n\t\twith open(filename, \"r\") as f:\n\t\t\treader = csv.reader(f)\n\t\t\ttemp = list(reader)\n\t\tfor i in temp:\n\t\t\tgoods_nomenclature_item_id\t= i[0]\n\t\t\tduty_expression\t\t\t\t= i[1]\n\t\t\tend_date\t\t\t\t\t= i[2]\n\t\t\tobj_do = davidowen_commodity(goods_nomenclature_item_id, duty_expression, end_date)\n\t\t\tself.david_owen_list.append(obj_do)\n\n\tdef get_mfn_rates(self):\n\t\t# Get a list of the MFN components\n\t\tfilename = os.path.join(self.SOURCE_DIR, \"mfn_components.csv\")\n\t\twith open(filename, \"r\") as f:\n\t\t\treader = csv.reader(f)\n\t\t\trows = list(reader)\n\t\tcnt = 0\n\t\tfor row in rows:\n\t\t\tcnt += 1\n\t\t\t# commodity_code = \"\", additional_code_type_id = \"\", additional_code_id = \"\", measure_type_id = \"\", duty_expression_id = \"\", duty_amount = 0, monetary_unit_code = \"\",\n\t\t\t# measurement_unit_code = \"\", measurement_unit_qualifier_code = \"\", measure_sid = 0, quota_order_number_id = \"\"):\n\t\t\t# 0201100000,04,176.8,EUR,DTN,\n\t\t\t#print (\"doing\", str(cnt))\n\t\t\tcommodity_code\t\t\t\t\t= row[0]\n\t\t\tadditional_code_type_id\t\t\t= \"\"\n\t\t\tadditional_code_id\t\t\t\t= \"\"\n\t\t\tmeasure_type_id\t\t\t\t\t= \"\"\n\t\t\tduty_expression_id\t\t\t\t= str(row[1])\n\t\t\tduty_amount\t\t\t\t\t\t= float(row[2])\n\t\t\tmonetary_unit_code\t\t\t\t= row[3]\n\t\t\tmeasurement_unit_code\t\t\t= row[4]\n\t\t\tmeasurement_unit_qualifier_code = row[5]\n\t\t\tmeasure_sid\t\t\t\t\t\t= \"\"\n\t\t\tquota_order_number_id\t\t\t= \"\"\n\t\t\tmy_duty = duty(commodity_code, additional_code_type_id, additional_code_id, measure_type_id, duty_expression_id, duty_amount, monetary_unit_code,\n\t\t\tmeasurement_unit_code, measurement_unit_qualifier_code, measure_sid, quota_order_number_id)\n\t\t\tself.mfn_component_list.append(my_duty)\n\n\tdef get_special_paragraphs(self):\n\t\t# Get ships\n\t\tfilename = os.path.join(self.SOURCE_DIR, \"ships.txt\")\n\t\tself.para_ships = []\n\t\twith open(filename, \"r\", encoding=\"utf-8\") as f:\n\t\t\treader = csv.reader(f, delimiter=\"|\")\n\t\t\trows = list(reader)\n\t\t\tfor row in rows:\n\t\t\t\tself.para_ships.append(row[0])\n\n\t\t# Get civil air\n\t\tfilename = os.path.join(self.SOURCE_DIR, \"civilair.txt\")\n\t\tself.para_civilair = []\n\t\twith open(filename, \"r\", encoding=\"utf-8\") as f:\n\t\t\treader = csv.reader(f, delimiter=\"|\")\n\t\t\trows = list(reader)\n\t\t\tfor row in rows:\n\t\t\t\tself.para_civilair.append(row[0])\n\n\t\t# Get ships\n\t\tfilename = os.path.join(self.SOURCE_DIR, \"certainair.txt\")\n\t\tself.para_certainair = []\n\t\twith open(filename, \"r\", encoding=\"utf-8\") as f:\n\t\t\treader = csv.reader(f, delimiter=\"|\")\n\t\t\trows = list(reader)\n\t\t\tfor row in rows:\n\t\t\t\tself.para_certainair.append(row[0])\n\n\t\t# Get military\n\t\tfilename = os.path.join(self.SOURCE_DIR, \"military.txt\")\n\t\tself.para_military = []\n\t\twith open(filename, \"r\", encoding=\"utf-8\") as f:\n\t\t\treader = csv.reader(f, delimiter=\"|\")\n\t\t\trows = list(reader)\n\t\t\tfor row in rows:\n\t\t\t\tself.para_military.append(row[0])","sub_path":"tariff-reference/authorised_use/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":30871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"433461561","text":"def BTtoDll(root):\n if root ==None:\n return root\n if root.left:\n left = BTtoDll(root.left) # traverse to the leftmost subtree\n while left.right:\n left = left.right # find the inorder predecssor of current root\n\n left.right = root #connect predecessor's right to root\n root.left = left # connect root's left to predecessor\n\n if root.right:\n right = BTtoDll(root.right) # traverse to right subtree\n while right.left:\n right = right.left # find inorder successor of root\n\n root.right = right\n right.left = root\n return root\n\ndef returnHead(root):\n head = BTtoDll(root)\n if not head:\n return None\n while head.left: # find the pointer to the head of the link list since some node which is not head was returned\n head = head.left\n return head\n \n \n","sub_path":"Linked-List/Binary_tree_to_Doubly_linked_list.py","file_name":"Binary_tree_to_Doubly_linked_list.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"319954314","text":"import os, pygame, platform\nfrom Game import *\nfrom Dice import *\nfrom tkinter import *\nfrom PIL import Image, ImageTk\nfrom pygame.locals import *\n\n# Select video driver on windows.\nif platform.system() == 'Windows':\n os.environ['SDL_VIDEODRIVER'] = 'windib'\n\n# Gebruikte Afbeeldingen\nstart = pygame.image.load(\"Images/MenuKnoppen/start.png\").convert_alpha()\nstart2 = pygame.image.load(\"Images/MenuKnoppen/start 2.png\").convert_alpha()\ninstructies = pygame.image.load(\"Images/MenuKnoppen/instructies.png\").convert_alpha()\ninstructies2 = pygame.image.load(\"Images/MenuKnoppen/instructies 2.png\").convert_alpha()\nstop = pygame.image.load(\"Images/MenuKnoppen/stop.png\").convert_alpha()\nstop2 = pygame.image.load(\"Images/MenuKnoppen/stop 2.png\").convert_alpha()\nicon = pygame.image.load(\"Images/Logo/logo_icon.png\").convert_alpha()\n\n# Screen size\nsize = width, height = 782, 644 # aangepast zodat scherm precies past\nscreen = pygame.display.set_mode(size)\n# Screen Title\npygame.display.set_caption(\"Survivor\")\n\n# Icon display\npygame.display.set_icon(icon)\n\n# Fill background\nbackground = pygame.Surface(screen.get_size())\nbackground = background.convert()\nbackground.fill((255,255,255)) # Now white\n\n# Make the Logo\nlogo = pygame.image.load(\"Images/Logo/logo_m.png\").convert_alpha()\nlogoWidth = int(391 - (494 / 2)) # Width screen - Width image\nlogoHeight = int(175 - (290 / 2)) # Width screen - Width image\nlogoPosition = logoWidth, logoHeight\n\n\n# Zorgt voor de popup bij instellingen\ndef popUp():\n root = Tk()\n canvas = Canvas(root, width=500, height=750)\n canvas.pack()\n canvas.configure(scrollregion=(0, -125, 0, 0))\n img = Image.open(\"Images/instructies.jpg\")\n img = img.resize((500, 750), Image.ANTIALIAS)\n tk_img = ImageTk.PhotoImage(img)\n canvas.create_image(250, 250, image=tk_img)\n root.mainloop()\n\n\n# Maakt de buttons aan en laat een nieuwe geblit plaatje zien, zodra de muis op het icoontje komt\ndef button(posX, posY, image):\n cursor = pygame.mouse.get_pos()\n clickCheck = pygame.mouse.get_pressed()\n if posX + 280 > cursor[0] and cursor[0] > posX and posY + 70 > cursor[1] and cursor[1] > posY:\n if image == start:\n image = start2\n screen.blit(image, (posX, posY))\n if clickCheck[0] == 1 and image == start2:\n game()\n if image == instructies:\n image = instructies2\n screen.blit(image, (posX, posY))\n if clickCheck[0] == 1 and image == instructies2:\n popUp()\n if image == stop:\n image = stop2\n screen.blit(image, (posX, posY))\n if clickCheck[0] == 1 and image == stop2:\n pygame.quit()\n quit()\n\n if clickCheck[0] == 0:\n if image == start:\n screen.blit(image, (posX, posY))\n if image == instructies:\n screen.blit(image, (posX, posY))\n if image == stop:\n screen.blit(image, (posX, posY))\n\n\nscreen.blit(background, (0, 0))\nscreen.blit(logo, logoPosition)\n\n\n# Menu loop\ndef menu():\n menu = True\n\n while menu:\n button(251, 355, start)\n button(251, 455, instructies)\n button(251, 555, stop)\n\n for event in pygame.event.get():\n # Pygame screen close\n if event.type == QUIT:\n pygame.quit()\n quit()\n pygame.display.update()\n pygame.display.flip()\nmenu()\n","sub_path":"New_Menu.py","file_name":"New_Menu.py","file_ext":"py","file_size_in_byte":3433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"2554114","text":"import torch\nfrom pytorch_pretrained_bert import BertTokenizer, BertModel, BertForMaskedLM\n\n# Load pre-trained model tokenizer (vocabulary)\nmodelpath = \"bert-base-uncased\"\ntokenizer = BertTokenizer.from_pretrained(modelpath)\n\ntext = \"dummy. although he had already eaten a large meal, he was still very hungry.\"\ntarget = \"hungry\"\ntokenized_text = tokenizer.tokenize(text)\n\n# Mask a token that we will try to predict back with `BertForMaskedLM`\nmasked_index = tokenized_text.index(target)\ntokenized_text[masked_index] = '[MASK]'\n\n# Convert token to vocabulary indices\nindexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text)\n# Define sentence A and B indices associated to 1st and 2nd sentences (see paper)\nsegments_ids = [1] * len(tokenized_text)\n# this is for the dummy first sentence.\nsegments_ids[0] = 0\nsegments_ids[1] = 0\n\n# Convert inputs to PyTorch tensors\ntokens_tensor = torch.tensor([indexed_tokens])\nsegments_tensors = torch.tensor([segments_ids])\n# Load pre-trained model (weights)\nmodel = BertForMaskedLM.from_pretrained(modelpath)\nmodel.eval()\n\n# Predict all tokens\npredictions = model(tokens_tensor, segments_tensors)\npredicted_index = torch.argmax(predictions[0, masked_index]).item()\npredicted_token = tokenizer.convert_ids_to_tokens([predicted_index])\n\nprint(\"Original:\", text)\nprint(\"Masked:\", \" \".join(tokenized_text))\n\nprint(\"Predicted token:\", predicted_token)\nprint(\"Other options:\")\n# just curious about what the next few options look like.\nfor i in range(10):\n predictions[0,masked_index,predicted_index] = -11100000\n predicted_index = torch.argmax(predictions[0, masked_index]).item()\n predicted_token = tokenizer.convert_ids_to_tokens([predicted_index])\n print(predicted_token)","sub_path":"bert_generate_text.py","file_name":"bert_generate_text.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"652981826","text":"import socket\n\nMAX_BYTES = 65535\n\n\ndef client(hostname, port):\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n # Saindo do modo promíscuo e aceitando respostas\n # apenas do servidor hostname\n sock.connect((hostname, port))\n print('Client socket name is {}'.format(sock.getsockname()))\n\n delay = 0.1 # atraso em segundos\n text = 'This is another message'\n data = text.encode('ascii')\n\n while True:\n # O cliente envia os dados e fica aguardando a resposta.\n # Um timeout é configurado para a espera.\n # Caso o timeout seja alcaçado, um novo envio é realizado.\n sock.send(data)\n print('Waiting up to {} seconds for a reply'.format(delay))\n sock.settimeout(delay)\n\n try:\n data = sock.recv(MAX_BYTES)\n except socket.timeout as exc:\n # se a resposta não for recebida dentro do intervalo\n # estabelecido, a exceção é acionada e o intervalo de\n # espera é dobrado\n delay *= 2\n\n # Se a espera for maior que 2 segundos o cliente\n # desiste da solicitação\n if delay > 2.0:\n raise RuntimeError('I think the server is down') from exc\n else:\n break # Se a resposta é recebida, saímos do loop.\n\n print('The server says {!r}'.format(data.decode('ascii')))\n\n\nif __name__ == '__main__':\n client('192.168.1.7', 1060)","sub_path":"3_udp/client_remote.py","file_name":"client_remote.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"244740380","text":"import sys,os\nimport numpy as np\nfrom numpy.linalg import norm\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport matplotlib.colors as colors\nimport matplotlib.cm as cm\nimport streets_in_region\n\n#https://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/\n\nnparticles = 100\n\nnp.random.seed(12827)\nconfig = np.random.random_sample((nparticles,2))\nangle = np.random.random_sample((nparticles,))*2*np.pi\n#angle = np.asarray([np.pi/4, np.pi - np.pi/4])\n#print(np.mean(angle))\norient = np.asarray((np.cos(angle),np.sin(angle))).T\n#print(angle, orient)\n#print(np.sum(orient/np.sqrt(np.sum(orient*orient)),axis = 1))\nbox_bound = 1\nspeed = box_bound*0.0005\ndist_cut = box_bound*0.01\nroad_width = box_bound*0.01\n#config = np.asarray([(0.5,1)])\nskip = 10\ndist_cut_squared = dist_cut*dist_cut\nnoise = 0.1*np.ones((nparticles,))\nconst_noise = 0.3\n\nsegment_temp = streets_in_region.scaled\nsegment = []\n\nfor i in segment_temp:\n if (i[1][0] - i[0][0])**2 + (i[1][1] - i[0][1])**2 > 0.00000001:\n segment.append(i)\n\n\nsegment = [[[0,0.5],[1,0.5]],[[0.5,0],[0.5,1]]]\n\n\nseg_angle = [[(i[1][0] - i[0][0])/np.sqrt((i[1][0] - i[0][0])**2 + (i[1][1] - i[0][1])**2),(i[1][1] - i[0][1])/np.sqrt((i[1][0] - i[0][0])**2 + (i[1][1] - i[0][1])**2), (i[1][0]*i[0][1] - i[1][1]*i[0][1])/np.sqrt((i[1][0] - i[0][0])**2 + (i[1][1] - i[0][1])**2), np.sqrt((i[1][0] - i[0][0])**2 + (i[1][1] - i[0][1])**2)] for i in segment]\n\n\ndef point_to_line(point, seg):\n seg = np.asarray(seg)\n point = np.asarray(point)\n return norm(np.cross(seg[1]-seg[0], seg[1] - point))/norm(seg[1] - seg[0])\n\n\n\ndef translate(config, orient):\n config = np.modf(config + speed*orient + 2)[0]\n return config\n\ndef rotate(orient):\n# global orient,config\n neighbor_angle_av = orient\n for i in range(0,nparticles-1):\n for j in range(i+1,nparticles):\n sep_vec = (config[i] - config[j])\n sep_vec = sep_vec - np.rint(sep_vec / box_bound)*box_bound\n if(np.sum(sep_vec*sep_vec) < dist_cut_squared):\n neighbor_angle_av[i] += orient[j]\n neighbor_angle_av[j] += orient[i]\n neighbor_angle_av /= np.sqrt(np.sum(neighbor_angle_av*neighbor_angle_av,axis=1))[:,None]\n return neighbor_angle_av \n\ndef add_noise(orient):\n #global orient\n noise_term = noise*(np.random.random_sample((nparticles,))-0.5)*2*np.pi\n sine = np.sin(noise_term)\n cosine = np.cos(noise_term)\n xarray = orient[0:,0]\n yarray = orient[0:,1]\n #rotation matrix\n return np.asarray((xarray*cosine - yarray*sine, xarray*sine + yarray*cosine)).T\n\n\ndef stay_on_road(config, orient):\n for i in range(nparticles):\n dist_min = 100\n for jc,j in enumerate(segment):\n distance = point_to_line(config[i], j)\n if(distance < dist_min):\n dist_min = distance\n closest_s_id = jc\n if dist_min > road_width:\n p_coord = config[i]\n c_seg = np.asarray(segment[closest_s_id])\n #two ways to do this:\n #1: turn particle back straight onto road (seems like there might be issues when there are neighbors)\n sign = np.sign(np.cross(p_coord - c_seg[0], c_seg[1] - p_coord))\n orient[i] = np.asarray([(-sign*seg_angle[closest_s_id][1], sign*seg_angle[closest_s_id][0])])\n noise[i] = 0\n else: \n noise[i] = const_noise\n return orient\n\n\n\n# set up figure and animation\nfig = plt.figure()\nfig.subplots_adjust(left=0, right=1, bottom=0, top=1)\nax = fig.add_subplot(111, aspect='equal', autoscale_on=False,\n xlim=(-0.1,1.1), ylim=(-0.1, 1.1))\n\n# particles holds the locations of the particles\ncoolwarm = plt.get_cmap('coolwarm')\n\nparticles, = ax.plot([], [], 'bo', ms=1)#, c=noise)#, cmap='coolwarm')\n\n# rect is the box edge\nbounds = [0,box_bound,0,box_bound]\nrect = plt.Rectangle(bounds[::2],\n bounds[1] - bounds[0],\n bounds[3] - bounds[2],\n ec='none', lw=2, fc='none')\n#roadmap = np.asarray(segment)\n#road_plot = plt.plot(roadmap[:,:,0].T,roadmap[:,:,1].T, c='black')\nax.add_patch(rect)\n\ndef init():\n \"\"\"initialize animation\"\"\"\n global rect\n particles.set_data([], [])\n rect.set_edgecolor('none')\n return particles, rect\n\ndef animate(i):\n \"\"\"perform animation step\"\"\"\n global rect, dt, ax, fig, config, orient, noise\n for f in range(skip):\n config = translate(config, orient)\n if(i > 10):\n orient = rotate(orient)\n orient = add_noise(orient)\n orient = stay_on_road(config, orient)\n \n ms = int(fig.dpi * 2 * 0.005 * fig.get_figwidth()\n / np.diff(ax.get_xbound())[0])\n \n # update pieces of the animation\n rect.set_edgecolor('k')\n particles.set_data(config[:, 0], config[:, 1])\n particles.set_markersize(ms)\n# plt.savefig(str(frame)+'.png', bbox_inches = tight)\n return particles,rect\n\nani = animation.FuncAnimation(fig, animate, frames=500,\n interval = 20, blit=True, init_func=init)\n\n\n# save the animation as an mp4. This requires ffmpeg or mencoder to be\n# installed. The extra_args ensure that the x264 codec is used, so that\n# the video can be embedded in html5. You may need to adjust this for\n# your system: for more information, see\n# http://matplotlib.sourceforge.net/api/animation_api.html\n#Writer = animation.writers['ffmpeg']\n#writer=animation.FFMpegWriter(bitrate=500)\n\n#writer = Writer(fps=30, metadata=dict(artist='jhard'), bitrate=100)\n#ani.save('vicsek.gif', writer='imagemagick', fps=15)\n#ani.save('vicsek.mp4', fps=30, extra_args=['-vcodec', 'libx264'])\n\n#plt.show()\n","sub_path":"vicsek_segments.py","file_name":"vicsek_segments.py","file_ext":"py","file_size_in_byte":5704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"244743092","text":"from keyword_library import keywords,isfloat,default\ninfile='run.in'\noutfile='processed_run.in'\n\n\"\"\"\nFind the keywords defined in the input file\n\"\"\"\n\nlocated={}\nwith open(infile, 'r') as input:\n for line in input:\n for word in keywords: \n if word == line.split()[0]:\n if ( line.split()[1].isdigit() ) == True:\n located.update( { line.split()[0] : int( line.split()[1] ) } )\n elif ( isfloat(line.split()[1]) ) == True:\n located.update( { line.split()[0] : float( line.split()[1] ) } )\n else:\n located.update( { line.split()[0] : line.split()[1] } )\n\n\"\"\"\nIf not found in input file, add them with their default valued\nthat are defined in keyword_library\n\"\"\"\n\nfor word in keywords:\n if word not in located:\n located.update( {word : default(word) })\n\n\"\"\"\nwrite the new input in standardized format\n\"\"\"\n\nwith open(outfile,'w') as output:\n for word in sorted(located):\n output.write( word + '\\t' + str( located[word]) + '\\n' )\n","sub_path":"examples/pldm/harmonic_bilinear_absorption/process_input.py","file_name":"process_input.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"378654753","text":"#!/usr/bin/env python3\r\n\r\nimport numpy as np\r\nimport pyopencl as cl\r\nimport pyopencl.array\r\nimport pyopencl.clrandom\r\n# loopy currently requires on pyopencl \r\nimport loopy as lp\r\nlp.set_caching_enabled(False)\r\nfrom warnings import filterwarnings, catch_warnings\r\nfilterwarnings('error', category=lp.LoopyWarning)\r\nctx = cl.create_some_context(interactive=False)\r\nqueue = cl.CommandQueue(ctx)\r\n# Set up pyopencl.Context & CommandQueue\r\n\r\nn = 16*16\r\nx_vec_dev = cl.clrandom.rand(queue, n, dtype=np.float32) # device side\r\ny_vec_dev = cl.clrandom.rand(queue, n, dtype=np.float32)\r\nz_vec_dev = cl.clrandom.rand(queue, n, dtype=np.float32)\r\na_mat_dev = cl.clrandom.rand(queue, (n, n), dtype=np.float32)\r\nb_mat_dev = cl.clrandom.rand(queue, (n, n), dtype=np.float32)\r\nx_vec_host = np.random.randn(n).astype(np.float32) # host side\r\ny_vec_host = np.random.randn(n).astype(np.float32)\r\n\r\nknl = lp.make_kernel(\r\n \"{ [i,j,ii,jj]: 0<=i,j,ii,jj=1\")\r\nknl = lp.split_iname(knl, \"i\", 16) # split loop variable\r\nknl = lp.prioritize_loops(knl, \"i_outer,i_inner\")\r\nknl = lp.set_options(knl, \"write_cl\")\r\nevt, (out,) = knl(queue, a=x_vec_dev)\r\n\r\nknl = lp.make_kernel(\r\n \"{ [i]: 0<=i=0 and n mod 4 = 0\")\r\norig_knl = knl # copy kernel, test assumptions, and unrolling\r\nknl = lp.split_iname(knl, \"i\", 4)\r\nknl = lp.tag_inames(knl, dict(i_inner=\"unr\"))\r\nknl = lp.prioritize_loops(knl, \"i_outer,i_inner\")\r\nknl = lp.set_options(knl, \"write_cl\")\r\nevt, (out,) = knl(queue, a=x_vec_dev, b=y_vec_dev, c=z_vec_dev)\r\n\r\nfrom warnings import resetwarnings, filterwarnings\r\nresetwarnings() # surpress some warnings during stats\r\nfilterwarnings('ignore', category=Warning)\r\n\r\nknl = lp.add_and_infer_dtypes(knl,\r\n dict(a=np.float32, b=np.float32, c=np.float32))\r\nop_map = lp.get_op_map(knl) # get operations counting\r\nprint(lp.stringify_stats_mapping(op_map))\r\n\r\nmem_map = lp.get_mem_access_map(knl) # get memory access(load, store) counting\r\nprint(lp.stringify_stats_mapping(mem_map))\r\n\r\n","sub_path":"loo.py_run.py","file_name":"loo.py_run.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"265274339","text":"# Django settings for usginmetadata project.\n\nDEBUG = True\nTEMPLATE_DEBUG = True\n\nADMINS = (\n ('Enter your username here', 'and your email address here'),\n)\n\nMANAGERS = ADMINS\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.contrib.gis.db.backends.postgis',\n 'NAME': 'Enter the name of your django database here',\n 'USER': 'and the name of your django user here',\n 'PASSWORD': 'and that user\\'s password here',\n 'HOST': 'probably 127.0.0.1',\n 'PORT': 'your postgres port'\n }\n}\n\nTIME_ZONE = 'your timezone'\nLANGUAGE_CODE = 'your language'\nSITE_ID = 1\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\nMEDIA_ROOT = '/absolute/path/from/root/to/media/folder'\nMEDIA_URL = '/media/'\nSTATIC_ROOT = '/absolute/path/from/root/to/static/folder'\nSTATIC_URL = '/static/'\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder'\n)\n\nSECRET_KEY = 'generated auto-magically with two fingers by django'\n\nTEMPLATE_LOADERS = (\n ('pyjade.ext.django.Loader',(\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n )),\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n \"django.contrib.auth.context_processors.auth\",\n \"django.core.context_processors.debug\",\n \"django.core.context_processors.i18n\",\n \"django.core.context_processors.media\",\n \"django.core.context_processors.static\",\n \"django.core.context_processors.tz\",\n \"django.contrib.messages.context_processors.messages\",\n \"ui.context_processors.basics\"\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n)\n\nROOT_URLCONF = 'generated auto-magically with two fingers by django'\n\nWSGI_APPLICATION = 'generated auto-magically with two fingers by django'\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.gis',\n 'django.contrib.admin',\n 'django.contrib.admindocs',\n 'metadatadb',\n 'registry',\n 'ui',\n 'captcha',\n)\n\nRECAPTCHA_PUBLIC_KEY = 'go here -- https://www.google.com/recaptcha/admin/create'\nRECAPTCHA_PRIVATE_KEY = 'go here -- https://www.google.com/recaptcha/admin/create'\nEMAIL_HOST = 'merton.webserversystems.com'\nEMAIL_PORT = 2525\nEMAIL_HOST_USER = 'metadata@usgin.org'\nEMAIL_HOST_PASSWORD = 'paEWNKQj'\nEMAIL_USE_TLS = False\nSERVER_EMAIL = EMAIL_HOST_USER\nSITE_ID = 1\nAUTH_PROFILE_MODULE = 'ui.UserProfile'\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n","sub_path":"django-example/settings-example.py","file_name":"settings-example.py","file_ext":"py","file_size_in_byte":3309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"94798284","text":"valid = 0\narr = [[], [], []]\n\nwith open('input') as f:\n for x in f.readlines():\n line = [int(x) for x in x.split()]\n for i in range(0, 3):\n arr[i].append(line[i])\n\nfor row in arr:\n for i in range(0, len(row)-1, 3):\n values = row[i:i+3]\n _max = max(values)\n values.remove(_max)\n if sum(values) > _max: valid += 1\n\nprint(valid)\n","sub_path":"03/part-2.py","file_name":"part-2.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"457330827","text":"\"\"\"Workflow to calculate NAC params.\"\"\"\nimport time\n\nfrom aiida.engine import WorkChain, append_, calcfunction, if_, while_\nfrom aiida.orm import Group, QueryBuilder, WorkChainNode, load_group\nfrom aiida.plugins import DataFactory, WorkflowFactory\nfrom phonopy.structure.symmetry import symmetrize_borns_and_epsilon\n\nfrom aiida_phonopy.common.builders import (\n get_calculator_process,\n get_plugin_names,\n get_vasp_immigrant_inputs,\n get_workchain_inputs,\n)\nfrom aiida_phonopy.common.utils import (\n get_structure_from_vasp_immigrant,\n phonopy_atoms_from_structure,\n)\n\nFloat = DataFactory(\"float\")\nStr = DataFactory(\"str\")\nDict = DataFactory(\"dict\")\nArrayData = DataFactory(\"array\")\nStructureData = DataFactory(\"structure\")\n\n\ndef _get_nac_params(ctx, symmetry_tolerance):\n \"\"\"Obtain Born effective charges and dielectric constants in primitive cell.\n\n When Born effective charges and dielectric constants are calculated within\n phonopy workchain, those values are calculated in the primitive cell.\n However using immigrant, the cell may not be primitive cell and can be\n unit cell. In this case, conversion of data is necessary. This conversion\n needs information of the structure where those values were calcualted and\n the target primitive cell structure.\n\n When using immigrant, structure is in the immigrant calculation but not\n the workchain. 'structure' should be accessible in the vasp immigrant\n workchain level, and this should be fixed in aiida-vasp.\n\n \"\"\"\n if ctx.plugin_names[0] == \"vasp.vasp\":\n calc = ctx.nac_params_calcs[0]\n if \"structure\" in calc.inputs:\n structure = calc.inputs.structure\n else:\n structure = get_structure_from_vasp_immigrant(calc)\n nac_params = get_vasp_nac_params(\n calc.outputs.born_charges,\n calc.outputs.dielectrics,\n structure,\n symmetry_tolerance,\n )\n elif ctx.plugin_names[0] == \"quantumespresso.pw\":\n pw_calc = ctx.nac_params_calcs[0]\n ph_calc = ctx.nac_params_calcs[1]\n nac_params = get_qe_nac_params(\n ph_calc.outputs.output_parameters,\n pw_calc.inputs.pw.structure,\n symmetry_tolerance,\n )\n else:\n nac_params = None\n return nac_params\n\n\n@calcfunction\ndef get_qe_nac_params(output_parameters, structure, symmetry_tolerance, primitive=None):\n \"\"\"Return NAC params ArrayData created from QE results.\"\"\"\n nac_params = _get_nac_params_array(\n output_parameters[\"effective_charges_eu\"],\n output_parameters[\"dielectric_constant\"],\n structure,\n symmetry_tolerance.value,\n primitive=primitive,\n )\n return nac_params\n\n\n@calcfunction\ndef get_vasp_nac_params(\n born_charges, epsilon, structure, symmetry_tolerance, primitive=None\n):\n \"\"\"Return NAC params ArrayData created from VASP results.\"\"\"\n nac_params = _get_nac_params_array(\n born_charges.get_array(\"born_charges\"),\n epsilon.get_array(\"epsilon\"),\n structure,\n symmetry_tolerance.value,\n primitive=primitive,\n )\n return nac_params\n\n\ndef _get_nac_params_array(\n born_charges, epsilon, structure, symmetry_tolerance, primitive=None\n):\n phonopy_cell = phonopy_atoms_from_structure(structure)\n if primitive is not None:\n phonopy_primitive = phonopy_atoms_from_structure(primitive)\n else:\n phonopy_primitive = None\n borns_, epsilon_ = symmetrize_borns_and_epsilon(\n born_charges,\n epsilon,\n phonopy_cell,\n symprec=symmetry_tolerance,\n primitive=phonopy_primitive,\n )\n nac_params = ArrayData()\n nac_params.set_array(\"born_charges\", borns_)\n nac_params.set_array(\"epsilon\", epsilon_)\n nac_params.label = \"born_charges & epsilon\"\n return nac_params\n\n\nclass NacParamsWorkChain(WorkChain):\n \"\"\"Wrapper to compute non-analytical term correction parameters.\"\"\"\n\n @classmethod\n def define(cls, spec):\n \"\"\"Define inputs, outputs, and outline.\"\"\"\n super().define(spec)\n spec.input(\"structure\", valid_type=StructureData, required=True)\n spec.input(\"calculator_inputs\", valid_type=dict, required=True, non_db=True)\n spec.input(\"symmetry_tolerance\", valid_type=Float, default=lambda: Float(1e-5))\n spec.input(\"immigrant_calculation_folder\", valid_type=Str, required=False)\n spec.input(\"queue_name\", valid_type=Str, required=False)\n\n spec.outline(\n cls.initialize,\n while_(cls.continue_calculation)(\n if_(cls.import_calculation_from_files)(\n cls.read_calculation_from_folder,\n ).else_(\n if_(cls.use_queue)(cls.submit_to_queue),\n cls.run_calculation,\n ),\n ),\n cls.finalize,\n )\n\n spec.output(\"nac_params\", valid_type=ArrayData, required=True)\n\n spec.exit_code(\n 1001,\n \"ERROR_NO_NAC_PARAMS\",\n message=(\"NAC params could not be retrieved from calculaton.\"),\n )\n spec.exit_code(\n 1004,\n \"ERROR_WAITING_TIMEOUT\",\n message=\"time out in queue waiting.\",\n )\n\n def continue_calculation(self):\n \"\"\"Return boolen for outline.\"\"\"\n if self.ctx.iteration >= self.ctx.max_iteration:\n return False\n self.ctx.iteration += 1\n return True\n\n def import_calculation_from_files(self):\n \"\"\"Return boolen for outline.\"\"\"\n return \"immigrant_calculation_folder\" in self.inputs\n\n def use_queue(self):\n \"\"\"Use queue to wait for submitting calculation.\"\"\"\n return \"queue_name\" in self.inputs\n\n def initialize(self):\n \"\"\"Initialize outline control parameters.\"\"\"\n self.report(\"initialization\")\n self.ctx.iteration = 0\n if \"steps\" in self.inputs.calculator_inputs.keys():\n self.ctx.max_iteration = len(self.inputs.calculator_inputs[\"steps\"])\n else:\n self.ctx.max_iteration = 1\n\n self.ctx.plugin_names = get_plugin_names(self.inputs.calculator_inputs)\n\n def submit_to_queue(self):\n \"\"\"Wait until being ready to submit calculation.\"\"\"\n self.report(\"waiting\")\n g = load_group(self.inputs.queue_name.value + \"/submit\")\n g.add_nodes(self.node)\n for i in range(1000):\n qb = QueryBuilder()\n qb.append(Group, filters={\"label\": \"queue/run\"}, tag=\"group\")\n qb.append(\n WorkChainNode, with_group=\"group\", filters={\"uuid\": self.node.uuid}\n )\n if qb.count() > 0:\n return\n time.sleep(10)\n return self.exit_codes.ERROR_WAITING_TIMEOUT\n\n def run_calculation(self):\n \"\"\"Run NAC params calculation.\"\"\"\n self.report(\n \"calculation iteration %d/%d\" % (self.ctx.iteration, self.ctx.max_iteration)\n )\n\n if \"steps\" in self.inputs.calculator_inputs.keys():\n calculator_inputs = self.inputs.calculator_inputs[\"steps\"][\n self.ctx.iteration - 1\n ]\n else:\n calculator_inputs = self.inputs.calculator_inputs\n label = \"nac_params_%d\" % self.ctx.iteration\n\n process_inputs = get_workchain_inputs(\n calculator_inputs,\n self.inputs.structure,\n ctx=self.ctx,\n label=label,\n )\n i = self.ctx.iteration - 1\n CalculatorProcess = get_calculator_process(plugin_name=self.ctx.plugin_names[i])\n future = self.submit(CalculatorProcess, **process_inputs)\n self.report(\"nac_params: {}\".format(future.pk))\n self.to_context(nac_params_calcs=append_(future))\n\n def read_calculation_from_folder(self):\n \"\"\"Import supercell force calculation using immigrant.\"\"\"\n self.report(\n \"import calculation data in files %d/%d\"\n % (self.ctx.iteration, self.ctx.max_iteration)\n )\n label = \"nac_params_%d\" % self.ctx.iteration\n force_folder = self.inputs.immigrant_calculation_folder\n inputs = get_vasp_immigrant_inputs(\n force_folder.value, self.inputs.calculator_inputs.dict, label=label\n )\n VaspImmigrant = WorkflowFactory(\"vasp.immigrant\")\n future = self.submit(VaspImmigrant, **inputs)\n self.report(\"nac_params: {}\".format(future.pk))\n self.to_context(nac_params_calcs=append_(future))\n\n def finalize(self):\n \"\"\"Finalize NAC params calculation.\"\"\"\n self.report(\"finalization\")\n\n nac_params = _get_nac_params(self.ctx, self.inputs.symmetry_tolerance)\n if nac_params is None:\n return self.exit_codes.ERROR_NO_NAC_PARAMS\n\n self.out(\"nac_params\", nac_params)\n","sub_path":"aiida_phonopy/workflows/nac_params.py","file_name":"nac_params.py","file_ext":"py","file_size_in_byte":8811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"620978554","text":"# -*- coding:utf-8 -*-\n\nimport queue\nimport collections\nimport os\nimport threading\n\ndef main():\n opts, path = parse_options()\n data = collections.defaultdict(list)\n for root, dirs, files in os.walk(path):\n for filename in files:\n fullname = os.path.join(root, filename)\n try:\n key = (os.path.getsize(fullname), filename)\n except EnvironmentError:\n continue\n if key[0] == 0:\n continue\n data[key].append(fullname)\n\n work_queue = queue.PriorityQueue()\n results_queue = queue.Queue()\n md5_from_filename = {}\n for i in range(opts.count):\n number = \"{0}: \".format(i + 1) if opts.debug else \"\"\n worker = Worker(work_queue, md5_from_filename, results_queue, number)\n worker.daemon = True\n worker.start()\n\n results_thread = threading.Thread(target=lambda: print_results(results_queue))\n results_thread.daemon = True\n results_thread.start()\n\n for size, filename in sorted(data):\n names = data[size, filename]\n if len(names) > 1:\n work_queue.put((size, names))\n work_queue.join()\n results_queue.join()\n\ndef print_results(results_queue):\n while True:\n try:\n results = results_queue.get()\n if results:\n print(results)\n finally:\n results_queue.task_done()\n\nclass Worker(threading.Thread):\n\n Md5_lock = threading.Lock()\n\n def __init__(self, work_queue, md5_from_filename, results_queue, number):\n super().__init__()\n self.work_queue = work_queue\n self.md5_from_filename = md5_from_filename\n self.results_queue = results_queue\n self.number = number\n\n def run(self):\n while True:\n try:\n size, names = self.work_queue.get()\n self.process(size, names)\n finally:\n self.work_queue.task_done()\n\n def process(self, size, filenames):\n md5s = collections.defaultdict(set)\n for filename in filenames:\n with self.Md5_lock:\n md5 = self.md5_from_filename.get(filename, None)\n if md5 is not None:\n md5s[md5].add(filename)\n else:\n try:\n md5 = hashlib.md5()\n with open(filename, \"rb\") as fh:\n md5.update(fh.read())\n md5 = md5.digest()\n md5s[md5].add(filename)\n with self.Md5_lock:\n self.md5_from_filename[filename] = md5\n except EnvironmentError:\n continue\n for filenames in md5.values():\n if len(filenames) == 1:\n continue\n self.results_queue.put(\"{0}Duplicate files ({1 : n} bytes):\"\"\\n\\t{2}\".format(self.number, size, \"\\n\\t\".join(sorted(filenames))))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python3 progamming/findduplicates-t.py","file_name":"findduplicates-t.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"222330193","text":"#split_train_test.py\nimport os\nimport shutil\nimport random\nimport numpy as np\n\nsrc_folder_path = '../data/pdfs/TS_MET_notes/ALL/'\nout_sets = [\n'../data/pdfs/TS_MET_notes/SET0/',\n'../data/pdfs/TS_MET_notes/SET1/',\n'../data/pdfs/TS_MET_notes/SET2/',\n'../data/pdfs/TS_MET_notes/SET3/',\n'../data/pdfs/TS_MET_notes/ARCHIVE/'\n]\nout_set = '../data/pdfs/TS_MET_notes/REDO/'\n\n# for file_path in out_sets:\n# if os.path.isdir(file_path):\n# shutil.rmtree(file_path)\n# os.mkdir(out_set)\nsrc_file_names = os.listdir(src_folder_path)\n\nredo_files = [\n]\n# random.shuffle(src_file_names)\n\nfor file_name in src_file_names:\n # print()\n if file_name.split('_')[1] in redo_files:\n print(file_name.split('_')[1])\n shutil.copy(src_folder_path+file_name, out_set + file_name)\n\n# cnt = 1\n# for file_name in src_file_names:\n# if not os.path.exists(out_set + file_name):\n# print (cnt)\n# cnt+=1\n# shutil.copy(src_folder_path+file_name, out_set + file_name)\n# print(src_file_names)\n# patient_ids = [f.split(\"_\")[0] for f in src_file_names]\n# note_date = [int((f.split(\"_\")[1])[:8]) for f in src_file_names]\n# print(note_date)\n# cnt = 0\n# set0_patients = []\n# for i in range(len(src_file_names)):\n# if cnt < 50 and note_date[i] > 20180000 and patient_ids[i] not in set0_patients:\n# print (cnt)\n# cnt += 1\n# set0_patients.append(patient_ids[i])\n# shutil.copy(src_folder_path+src_file_names[i], out_sets[0] +src_file_names[i])\n# elif cnt < 100 and note_date[i] > 20180000 and patient_ids[i] not in set0_patients:\n# print (cnt)\n# cnt += 1\n# set0_patients.append(patient_ids[i])\n# shutil.copy(src_folder_path+src_file_names[i], out_sets[1] +src_file_names[i])\n# elif cnt < 150 and note_date[i] > 20180000 and patient_ids[i] not in set0_patients:\n# print (cnt)\n# cnt += 1\n# set0_patients.append(patient_ids[i])\n# shutil.copy(src_folder_path+src_file_names[i], out_sets[2] +src_file_names[i])\n\n# elif cnt < 300 and note_date[i] > 20180000 and patient_ids[i] not in set0_patients:\n# print (cnt)\n# cnt += 1\n# set0_patients.append(patient_ids[i])\n# shutil.copy(src_folder_path+src_file_names[i], out_sets[3] +src_file_names[i])\n# else:\n# # print (cnt)\n# # set0_patients.append(patient_ids[i])\n# shutil.copy(src_folder_path+src_file_names[i], out_sets[4] +src_file_names[i])\n\n\n\n# # for shuffle_file_name in shuffle_file_names[:50]:\n# # shutil.move(src_folder_path+shuffle_file_name, out_0_folder_path +shuffle_file_name)\n\n# # for shuffle_file_name in shuffle_file_names[50:100]:\n# # shutil.move(src_folder_path+shuffle_file_name, out_1_folder_path +shuffle_file_name)\n","sub_path":"dataset_splitter.py","file_name":"dataset_splitter.py","file_ext":"py","file_size_in_byte":2767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"260397979","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('opciones', '0007_actividadecoturismo_atractivoecoturismo'),\n ('predio', '0009_auto_20150422_1559'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='viviendapredio',\n name='energia_preparacion_alimentos',\n ),\n migrations.AddField(\n model_name='viviendapredio',\n name='energia_preparacion_alimentos',\n field=models.ManyToManyField(blank=True, to='opciones.FuenteEnergiaPreparacionAlimentos', null=True, related_name='fuente energia+'),\n ),\n ]\n","sub_path":"predio/migrations/0010_auto_20150422_1609.py","file_name":"0010_auto_20150422_1609.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"205341782","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# ---------- ---------- ---------- ---------- ---------- ---------- ---------- #\n# @file pyTestSuite #\n# @author Hanno Sternberg #\n# #\n# This file contains the TestSuite for grouping Tests together. #\n# #\n# @license MIT #\n# #\n# This software is licensed under the MIT License #\n# #\n# Copyright (c) 2012-2015 Hanno Sternberg #\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 #\n# deal in the Software without restriction, including without limitation the #\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or #\n# sell copies of the Software, and to permit persons to whom the Software is #\n# furnished to do so, subject to the following conditions: #\n# #\n# The above copyright notice and this permission notice shall be included in #\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 #\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS #\n# IN THE SOFTWARE. #\n# ---------- ---------- ---------- ---------- ---------- ---------- ---------- #\n\n\nfrom pyTest import Test, TestState\nfrom pyTestUtils import logger, TermColor\n\n\nclass TestSuiteMode:\n # __slots__ = ['Continuous', 'BreakOnFail', 'BreakOnError']\n \"\"\"Enumeration for testsuite modes \"\"\"\n BreakOnFail = 0\n \"\"\"Halt on first failed test\"\"\"\n BreakOnError = 1\n \"\"\"Halt on first erroneous test\"\"\"\n Continuous = 2\n \"\"\"Run all test\"\"\"\n\n @staticmethod\n def toString(mode):\n \"\"\"\n Converts the enumeration value into a string\n\n @type mode: int\n @param mode: Enumeration value\n \"\"\"\n if mode == TestSuiteMode.BreakOnFail:\n return \"Break On Fail\"\n if mode == TestSuiteMode.Continuous:\n return \"Continuous\"\n if mode == TestSuiteMode.BreakOnError:\n return \"Break on Error\"\n return \"Unknown mode\"\n\n\nclass TestSuite(object):\n \"\"\"A testsuite is a collection of tests\"\"\"\n\n def __init__(self, *tests, **options):\n \"\"\"\n Initialises a test suite\n\n @type tests: List\n @param tests: List of tests, default is an empty list\n\n @type mode: TestSuiteMode\n @param mode: The initial mode of the testsuite\n @type DUT: str\n @param DUT: The path to the Device Under Test\n @type timeout: float\n @param timeout: The time out be before the DUT gets killed\n @type pipe: Boolean\n @param pipe: Flag, set if the output streams should be piped\n @type outputOnFail: Boolean\n @param outputOnFail: Flag, set if the output streams should be piped on failed test\n \"\"\"\n self.options = {'mode': TestSuiteMode.BreakOnFail,\n 'pipe': None,\n 'outputOnFail': None,\n 'timeout': None,\n 'DUT': None,\n 'ignoreEmptyLines': None,\n 'commands': False,\n 'pipeLimit': None}\n self.options.update(options)\n self.setMode(self.options['mode'])\n \"\"\"The test suite mode\"\"\"\n self.testList = [t for t in tests]\n self.setAll(pipe=self.options['pipe'],\n out=self.options['outputOnFail'],\n timeout=self.options['timeout'],\n ignoreEmptyLines=self.options['ignoreEmptyLines'],\n pipeLimit=self.options['pipeLimit'])\n self.setDUT(self.options['DUT'])\n \"\"\"The collection of tests\"\"\"\n self.success = 0\n \"\"\"The number of successful tests\"\"\"\n self.failed = 0\n \"\"\"The number of failed tests\"\"\"\n self.count = 0\n \"\"\"A counter for the executed tests\"\"\"\n self.error = 0\n \"\"\"The number of errors occured during the testrun\"\"\"\n self.timedout = 0\n \"\"\"The total number of timed out tests\"\"\"\n self.assertions = 0\n \"\"\"The total number of tests that caused an assertion\"\"\"\n self.segfaults = 0\n \"\"\"The total number of tests that caused a segfault\"\"\"\n self.lastResult = TestState.Waiting\n \"\"\"The result of the last test\"\"\"\n self.rate = 0\n \"\"\"The successrate of the testrun\"\"\"\n\n def __len__(self):\n return len(self.testList)\n\n def __iter__(self):\n for test in self.testList:\n yield test\n raise StopIteration()\n\n def __getitem__(self, key):\n return self.testList[key]\n\n def __setitem(self, key, val):\n self.testList[key] = val\n\n def getRate(self):\n \"\"\"Returns the success rate\"\"\"\n return self.rate\n\n def setMode(self, mode):\n \"\"\"\n Sets the mode of the testsuite\n\n @type mode: TestSuiteMode\n @param mode: New mode\n \"\"\"\n self.mode = mode\n\n def setDUT(self, DUT=None):\n \"\"\"Define the 'Device under Test'\"\"\"\n if DUT is not None:\n self.DUT = DUT\n for t in self.testList:\n t.DUT = DUT\n else:\n self.DUT = None\n\n def addTest(self, test):\n \"\"\"\n Adds a test to the suite\n\n @type test: Test\n @param test: Test to add\n \"\"\"\n self.testList.append(test)\n\n def getTests(self):\n return self.testList\n\n def setAll(self, state=TestState.Waiting, pipe=None, out=None, diff=None, timeout=None, linesep=None, ignoreEmptyLines=None, pipeLimit=None):\n for t in self.testList:\n t.state = state\n if pipe is not None:\n t.pipe = pipe\n if out is not None:\n t.outputOnFail = out\n if diff is not None:\n t.diff = diff\n if timeout is not None:\n t.timeout = timeout\n if linesep is not None:\n t.linesep = linesep\n if ignoreEmptyLines is not None:\n t.ignoreEmptyLines = ignoreEmptyLines\n if pipeLimit is not None:\n t.pipeLimit = pipeLimit\n\n def _getTests(self, tests):\n if len(tests) == 0:\n tests = xrange(len(self))\n for t in tests:\n if t < len(self):\n yield self[t]\n raise StopIteration()\n\n def run(self, quiet=False, tests=[]):\n \"\"\"\n Runs the whole suite of tests\n\n @type quiet: Boolean\n @param quiet: Flag, passed along to the logger\n \"\"\"\n self.success = 0\n self.failed = 0\n self.count = 0\n self.error = 0\n self.lastResult = TestState.Waiting\n for t in self._getTests(tests):\n self.lastResult = t.run()\n if t.descr is not None:\n logger.log(\"{}[{: 03}] {} - {}: {}\".format(TermColor.colorText(\"Test\", TermColor.Purple), self.count, t.name, t.descr, TestState.toString(t.state)))\n else:\n logger.log(\"{}[{: 03}] {}: {}\".format(TermColor.colorText(\"Test\", TermColor.Purple), self.count, t.name, TestState.toString(t.state)))\n if self.options['commands']:\n logger.log(\" --> {}\".format(t.cmd), showTime=False)\n logger.flush(quiet)\n if self.lastResult in [TestState.Success, TestState.Clean]:\n self.success += 1\n elif self.lastResult == TestState.Fail:\n self.failed += 1\n elif self.lastResult == TestState.Error:\n self.error += 1\n elif self.lastResult == TestState.Timeout:\n self.timedout += 1\n elif self.lastResult == TestState.SegFault:\n self.segfaults += 1\n elif self.lastResult == TestState.Assertion:\n self.assertions += 1\n self.count = self.count + 1\n yield t\n if self.lastResult != TestState.Disabled:\n if (self.mode == TestSuiteMode.BreakOnFail) and (self.lastResult != TestState.Success):\n break\n if (self.mode == TestSuiteMode.BreakOnError) and (self.lastResult == TestState.Error):\n break\n raise StopIteration()\n\n def calcRate(self):\n self.rate = float(self.success) / float(len(self)) * 100\n return self.rate\n\n def stats(self, quiet=False):\n \"\"\"\n Generate and write the stats\n\n @type quiet: Boolean\n @param quiet: Flag, passed along to the logger\n \"\"\"\n if (self.lastResult != TestState.InfoOnly):\n logger.log(\"I ran {} out of {} tests in total\".format(self.count, len(self.testList)))\n fails = self.count - self.success\n logger.log(TermColor.colorText(\"\\tSuccess: {}\".format(self.success), TermColor.Green))\n if (self.failed > 0):\n logger.log(TermColor.colorText(\"\\tFailed: {}\".format(self.failed), TermColor.Red))\n if (self.error > 0):\n logger.log(TermColor.colorText(\"\\tErrors: {}\".format(self.error), TermColor.Yellow))\n if (self.assertions > 0):\n logger.log(TermColor.colorText(\"\\tAssertions: {}\".format(self.assertions), TermColor.Yellow))\n if (self.segfaults > 0):\n logger.log(TermColor.colorText(\"\\tSegFaults: {}\".format(self.segfaults), TermColor.Yellow))\n\n if (self.timedout > 0):\n logger.log(TermColor.colorText(\"\\tTimeouts: {}\".format(self.timedout), TermColor.Purple))\n # A little bit of fun\n if (self.success == len(self) and self.count > 3):\n logger.log(\"\\tCongratulations, you passed all tests!\")\n logger.log(\"\\t`grep` yourself a refreshing \" + TermColor.colorText(\"Beer\", TermColor.Yellow, style=TermColor.Bold))\n logger.log(\"\")\n logger.log(\" \\033[1;37m,%%%%.\\033[0m\")\n logger.log(\" \\033[1;37mi\\033[36m====\\033[1;37mi\\033[1;36m_\\033[0m\")\n logger.log(\" \\033[1;36m|\\033[1;33m####\\033[36m| |\\033[0m\")\n logger.log(\" \\033[1;36m|\\033[1;33m####\\033[36m|-'\\033[0m\")\n logger.log(\" \\033[1;36m`-==-'\\033[0m\")\n logger.log(\"\")\n elif (self.success == 0 and self.count > 3 and self.failed > 0):\n logger.log(\"\\tWhat is wrong with you, not even a single test?\")\n elif fails > 0 and self.count > 3:\n if self.assertions / fails > 0.6:\n logger.log(\"\\tYou do realise that assertions do not replace error handling?\")\n elif self.assertions / fails > 0.3:\n logger.log(\"\\tWe're a bit lazy with calling environments, aren't we?\")\n if self.segfaults / fails > 0.6:\n logger.log(\"\\tMay the CPU-Gods have mercy with that poor memory management units soul!\")\n elif self.segfaults / fails > 0.3:\n logger.log(\"\\tYou know, memory garbage doesn't collect itself?!\")\n return self.calcRate()\n\n def __str__(self):\n self.toString(prefix=\"\")\n\n def toString(self, prefix=\"\"):\n s = prefix + '[\\n'\n for test in self:\n s += prefix\n s += test.toString(\"\\t\")\n s += \",\\n\"\n s += prefix + ']\\n'\n","sub_path":"pyTestSuite.py","file_name":"pyTestSuite.py","file_ext":"py","file_size_in_byte":12701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"494731423","text":"import json\nfrom django.http import JsonResponse\nfrom django.core import serializers\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.exceptions import ValidationError, NotFound\nfrom ..models import Patrocinador, Proyecto\n\n\n#Atiende las peticiones de los Patrocinadores\n@csrf_exempt\ndef patrocinadores(request):\n\n if request.method == 'POST':\n data = json.loads(request.body)\n patrocinador = Patrocinador()\n if data.has_key(\"id\"):\n patrocinador.id = data[\"id\"]\n if data.has_key(\"nombre\"):\n patrocinador.nombre = data[\"nombre\"]\n patrocinador.save()\n return HttpResponse(serializers.serialize(\"json\", [patrocinador]), content_type=\"application/json\")\n\n elif request.method == 'GET':\n patrocinadores = Patrocinador.objects.all()\n return HttpResponse(serializers.serialize(\"json\", patrocinadores), content_type=\"application/json\")\n else:\n raise NotFound(detail=\"No se encuentra comando rest patrocinadores con metodo \" + request.method)\n\n\n#Atiende las peticiones de un Patrocinador determinado\n@csrf_exempt\ndef patrocinadores_id(request, id):\n\n if request.method == 'DELETE':\n try:\n patrocinador = Patrocinador.objects.get(id=id)\n except:\n raise ValidationError({'id': ['No existe patrocinador ' + id]})\n patrocinador.delete()\n return JsonResponse({\"Mensaje\":\"Patrocinador \" + id + \" borrado\"})\n\n elif request.method == 'PUT':\n try:\n patrocinador = Patrocinador.objects.get(id=id)\n except:\n raise ValidationError({'id': ['No existe patrocinador ' + id]})\n data = json.loads(request.body)\n algoCambio = False\n if data.has_key(\"nombre\"):\n patrocinador.nombre = data[\"nombre\"]\n algoCambio = True\n if algoCambio:\n patrocinador.save()\n return HttpResponse(serializers.serialize(\"json\", [patrocinador]), content_type=\"application/json\")\n\n elif request.method == 'GET':\n try:\n patrocinador = Patrocinador.objects.get(id=id)\n except:\n raise ValidationError({'id': ['No existe patrocinador ' + id]})\n return HttpResponse(serializers.serialize(\"json\", [patrocinador]), content_type=\"application/json\")\n else:\n raise NotFound(detail=\"No se encuentra comando rest patrocinadores/{id} con metodo \" + request.method)\n\n#Atiende las peticiones de un Patrocinador determinado\n@csrf_exempt\ndef patrocinadores_id_proyectos(request, id):\n\n if request.method == 'GET':\n try:\n patrocinador = Patrocinador.objects.get(id=id)\n except:\n raise ValidationError({'id': ['No existe patrocinador ' + id]})\n proyectos = Proyecto.objects.filter(patrocinador=patrocinador)\n return HttpResponse(serializers.serialize(\"json\", proyectos), content_type=\"application/json\")\n else:\n raise NotFound(detail=\"No se encuentra comando rest patrocinadores/{id}/proyectos con metodo \" + request.method)\n","sub_path":"laboratorio/views/viewsPatrocinador.py","file_name":"viewsPatrocinador.py","file_ext":"py","file_size_in_byte":3087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"508632427","text":"from setuptools import setup\n\nsetup(setup_requires='pypandoc')\n\npackages = [\n 'pilifana',\n 'pilifana.clients',\n 'pilifana.conversion'\n]\n\ndependencies = [\n 'schedule',\n 'pypandoc',\n 'pyyaml',\n 'daemonize'\n]\n\ndef convert_markdown(file):\n try:\n import pypandoc\n long_description = pypandoc.convert(file, 'rst')\n long_description = long_description.replace(\"\\r\", \"\")\n\n except Exception as e:\n import io\n print(\"Cannot load package description: {0}.\".format(e))\n print(\"Using raw content as fallback\")\n with io.open('README.md', encoding=\"utf-8\") as f:\n long_description = f.read()\n return long_description\n\nsetup(\n name='pilifana',\n version='1.0.1',\n license='MIT',\n description='Send values of pilight devices to KairosDB for use on Grafana dashboards',\n long_description=convert_markdown('README.md'),\n author='Damian Lippok',\n author_email='mail.dalee@gmail.com',\n packages=packages,\n install_requires=dependencies,\n data_files=[('/etc/pilifana', ['configuration/config.yaml'])],\n entry_points = {\n 'console_scripts': [\n 'pilifana = pilifana.main:main'\n ],\n }\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"240771549","text":"import sys\n\nimport requests\n\nif __name__ == \"__main__\":\n import logging\n\n logging.basicConfig(filename=\"route-engine.log\",\n level=logging.WARNING,\n format=\"%(asctime)s %(message)s\")\n\n if len(sys.argv) < 3:\n print(\"please provide two params: local route-engine port and urls.txt file.\")\n sys.exit(1)\n\n port = sys.argv[1]\n url_file = sys.argv[2]\n\n prefix = \"http://127.0.0.1:\" + port + \"/route?\"\n\n with open(url_file, \"r\") as f:\n urls = f.readlines()\n\n for url in urls:\n url = url.rstrip()\n try:\n # # logging.info(\" + start grabroad: %s -> %s\", origin, destination)\n r = requests.get(prefix + url)\n data = r.json()\n\n # logging.info(\" - end grabroad.\")\n if data[\"status\"] != 0:\n logging.warn(\" !no route: %s\", url)\n continue\n\n logging.warn(\"(%f, %f): %s\", data[\"legs\"][0][\"duration\"], data[\"legs\"][0][\"distance\"], url)\n\n except Exception as e:\n logging.warn(\" - exception %s\", url)\n","sub_path":"route-engine/perf_route-engine.py","file_name":"perf_route-engine.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"353253148","text":"import os\nimport shutil\nimport datetime\nimport time\nfrom tkinter import *\nfrom tkinter import ttk, messagebox, filedialog\nimport sqlite3\n\nconnection = sqlite3.connect('transferHistory_dB')\n\nc = connection.cursor()\nc.execute(\"CREATE TABLE IF NOT EXISTS History (Timestamp INT)\")\nc.execute(\"SELECT MAX(Timestamp) FROM History\")\n\nlastTransfer = c.fetchall()\n\nclass Filemover:\n\n def __init__(self, master):\n \n master.title('File Transfer UI')\n master.resizable(False, False)\n master.configure(background = '#FFFFFF')\n \n self.style = ttk.Style()\n self.style.configure('TFrame', background = '#FFFFFF')\n self.style.configure('TButton', background = '#FFFFFF')\n self.style.configure('TLabel', background = '#FFFFFF', font = ('Arial', 11))\n self.style.configure('Header.TLabel', font = ('Arial', 18, 'bold')) \n\n self.frame_header = ttk.Frame(master)\n self.frame_header.pack()\n \n self.logo = PhotoImage(file = 'filetransfer.png').subsample(2)\n ttk.Label(self.frame_header, image = self.logo).grid(row = 0, column = 0, rowspan = 2)\n ttk.Label(self.frame_header, text = 'Let\\'s Transfer Files!', style = 'Header.TLabel').grid(row = 0, column = 1, columnspan = 2)\n ttk.Label(self.frame_header, wraplength = 300,\n text = (\"Please choose the directory you would like to scan and \"\n \"the destination folder. Any files modified in the last \"\n \"24 hours will be moved to the new folder.\")).grid(row = 1, column = 1, columnspan = 2)\n \n self.frame_content = ttk.Frame(master)\n self.frame_content.pack()\n\n \n self.source_button = ttk.Button(self.frame_content, text = 'Choose Source', command = self.browseSource)\n self.destination_button = ttk.Button(self.frame_content, text = 'Choose Destination', command = self.browseDestination)\n\n self.source_entry = ttk.Entry(self.frame_content, width = 40, font = ('Arial', 10))\n self.destination_entry = ttk.Entry(self.frame_content, width = 40, font = ('Arial', 10))\n \n self.source_button.grid(row = 1, column = 0, padx = 5)\n self.destination_button.grid(row = 1, column = 1, padx = 5)\n \n submit = ttk.Button(self.frame_content, text = 'Submit', command = self.submit)\n submit.grid(row = 3, column = 0, padx = 5, pady = 5, columnspan =2)\n\n ttk.Label(self.frame_header, text = \"Date of last transfer: \").grid(row = 2, column = 1)\n ttk.Label(self.frame_header, text = lastTransfer).grid(row = 2, column = 2, sticky = W)\n\n def browseSource(self):\n source = filedialog.askdirectory()\n self.source_entry.grid(row = 2, column = 0, padx = 5)\n self.source_entry.insert(0,source)\n return source\n \n def browseDestination(self):\n destination = filedialog.askdirectory()\n self.destination_entry.grid(row = 2, column = 1, padx = 5)\n self.destination_entry.insert(0,destination)\n return destination\n \n def submit(self):\n source = (self.source_entry.get() + \"\\\\\")\n destination = (self.destination_entry.get() + \"\\\\\")\n print(source)\n print(destination)\n now = datetime.datetime.now()\n last24 = now-datetime.timedelta(hours=24)\n\n for filename in os.listdir(source):\n stats = os.stat(source+filename)\n lastMod = datetime.datetime.fromtimestamp(stats[8])\n if(lastMod >= last24):\n print(lastMod)\n shutil.move( source + filename, destination)\n print(destination + filename)\n currentTime = time.time()\n c.execute(\"INSERT INTO History VALUES (CURRENT_TIMESTAMP)\")\n connection.commit()\n connection.close()\n messagebox.showinfo(title = 'File Transfer Complete', message = 'Your files have been transferred.')\n\ndef main(): \n \n root = Tk()\n filemover = Filemover(root)\n root.mainloop()\n \nif __name__ == \"__main__\": main()\n","sub_path":"Item 66/Item 66.py","file_name":"Item 66.py","file_ext":"py","file_size_in_byte":4099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"524694438","text":"\n\n# target price should be under vi price\n\n\nclass SuppressBox:\n\n def __init__(self, code, open_candle, yday_high, year_high):\n self.today_longest = open_candle['highest_price'] - open_candle['lowest_price']\n self.current_strong_candle = None\n self.sup_count = 0\n self.code = code\n self.yday_high = yday_high\n self.year_high = year_high\n self.today_high = open_candle['highest_price']\n\n def calc_body_ratio(self, candle):\n if candle['highest_price'] == candle['lowest_price']:\n return 0.0\n\n return (candle['close_price'] - candle['start_price']) / (candle['highest_price'] - candle['lowest_price'])\n\n def add_candle(self, candle):\n candle_height = \"{0:.2f}\".format((candle['highest_price'] - candle['lowest_price']) / candle['lowest_price'] * 100.0)\n candle_ratio = \"{0:.2f}\".format(self.calc_body_ratio(candle))\n if self.today_high < candle['close_price']:\n self.today_high = candle['close_price']\n #print(candle['time'], candle_height, candle_ratio, 'high', candle['start_price'], candle['highest_price'], candle['lowest_price'], candle['close_price'])\n if self.current_strong_candle is not None:\n one_third = (self.current_strong_candle['highest_price'] - self.current_strong_candle['start_price']) / 3\n if candle['lowest_price'] >= self.current_strong_candle['highest_price'] - one_third and candle['highest_price'] <= self.current_strong_candle['highest_price'] + one_third:\n self.sup_count += 1\n #print('suppressed')\n else:\n self.sup_count = 0\n self.current_strong_candle = None\n elif candle['lowest_price'] * 1.01 <= candle['highest_price'] and candle['highest_price'] - candle['lowest_price'] > self.today_longest and self.calc_body_ratio(candle) > 0.7 and candle['highest_price'] > self.today_high and candle['highest_price'] > self.yday_high:\n self.today_longest = candle['highest_price'] - candle['lowest_price']\n self.current_strong_candle = candle\n self.sup_count = 0\n\n def is_suppressed(self):\n if self.sup_count >= 2:\n return True\n return False\n\n def get_point(self, current_candle):\n if (not self.is_suppressed() or\n current_candle['close_price'] < current_candle['start_price'] or\n current_candle['highest_price'] - current_candle['lowest_price'] > self.today_longest):\n #print(self.is_suppressed(), current_candle['open'], current_candle['close'])\n return 0\n \n point = 0\n price_point = []\n if current_candle['close_price'] < self.year_high and current_candle['close_price'] + self.today_longest > self.year_high:\n point += 1\n\n if current_candle['close_price'] < self.yday_high and current_candle['close_price'] + self.today_longest > self.yday_high:\n point += 1\n\n if current_candle['close_price'] < self.high and current_candle['close_price'] + self.today_longest > self.high:\n point += 1 \n\n return point\n","sub_path":"clients/search_rank/candidate/suppressbox3.py","file_name":"suppressbox3.py","file_ext":"py","file_size_in_byte":3148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"579659640","text":"from bs4 import BeautifulSoup\n\nhtml = \"\"\"\n\n\t\n\t\t

this is a test

\n\t\t

this is in another p

\n\t\n\n\"\"\"\n\nsoup = BeautifulSoup(html, \"html.parser\")\n\ntitle = soup.find(id=\"title\")\nbody = soup.find(id=\"body\")\n\n# make sure to remember to acceess to string\n# otherwise it will return html code\nprint(title.string)\nprint(body.string)","sub_path":"bs-test2.py","file_name":"bs-test2.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"515939160","text":"# -*- coding: utf-8 -*-\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright (c) 2010-2012, GEM Foundation.\n#\n# OpenQuake is free software: you can redistribute it and/or modify it\n# 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# OpenQuake 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 GNU Affero General Public License\n# along with OpenQuake. If not, see .\n\n\n\"\"\"\nThis module implements supervise(), a function that monitors an OpenQuake job.\n\nUpon job termination, successful or for an error of whatever level or gravity,\nsupervise() will:\n\n - ensure a cleanup of the resources used by the job\n - update status of the job record in the database\n\"\"\"\n\nimport logging\nimport os\nimport signal\nfrom datetime import datetime\n\ntry:\n # setproctitle is optional external dependency\n # apt-get installl python-setproctitle or\n # http://pypi.python.org/pypi/setproctitle/\n from setproctitle import setproctitle\nexcept ImportError:\n setproctitle = lambda title: None # pylint: disable=C0103\n\nfrom openquake.db.models import OqJob, ErrorMsg, JobStats\nfrom openquake import supervising\nfrom openquake import kvs\nfrom openquake import logs\nfrom openquake.utils import stats\n\n\nLOG_FORMAT = ('[%(asctime)s #%(job_id)s %(hostname)s %(levelname)s '\n '%(processName)s/%(process)s %(name)s] %(message)s')\n\n\ndef ignore_sigint():\n \"\"\"\n Setup signal handler on SIGINT in order to ignore it.\n\n This is needed to avoid premature death of the supervisor and is called\n from :func:`openquake.engine.run_job` for job parent process and\n from :func:`supervise` for supervisor process.\n \"\"\"\n signal.signal(signal.SIGINT, signal.SIG_IGN)\n\n\ndef terminate_job(pid):\n \"\"\"\n Terminate an openquake job by killing its process.\n\n :param pid: the process id\n :type pid: int\n \"\"\"\n\n logging.debug('Terminating job process %s', pid)\n\n os.kill(pid, signal.SIGKILL)\n\n\ndef record_job_stop_time(job_id):\n \"\"\"\n Call this when a job concludes (successful or not) to record the\n 'stop_time' (using the current UTC time) in the uiapi.job_stats table.\n\n :param job_id: the job id\n :type job_id: int\n \"\"\"\n logging.debug('Recording stop time for job %s to job_stats', job_id)\n\n job_stats = JobStats.objects.get(oq_job=job_id)\n job_stats.stop_time = datetime.utcnow()\n job_stats.save(using='job_superv')\n\n\ndef cleanup_after_job(job_id):\n \"\"\"\n Release the resources used by an openquake job.\n\n :param job_id: the job id\n :type job_id: int\n \"\"\"\n logging.debug('Cleaning up after job %s', job_id)\n\n kvs.cache_gc(job_id)\n\n\ndef get_job_status(job_id):\n \"\"\"\n Return the status of the job stored in its database record.\n\n :param job_id: the id of the job\n :type job_id: int\n :return: the status of the job\n :rtype: string\n \"\"\"\n\n return OqJob.objects.get(id=job_id).status\n\n\ndef update_job_status_and_error_msg(job_id, error_msg=None):\n \"\"\"\n Store in the database the status of a job and optionally an error message.\n\n :param job_id: the id of the job\n :type job_id: int\n :param error_msg: the error message, if any\n :type error_msg: string or None\n \"\"\"\n job = OqJob.objects.get(id=job_id)\n job.is_running = False\n job.save()\n\n if error_msg:\n ErrorMsg.objects.using('job_superv')\\\n .create(oq_job=job, detailed=error_msg)\n\n\ndef _update_log_record(self, record):\n \"\"\"\n Massage a log record before emitting it. Intended to be used by the\n custom log handlers defined in this module.\n \"\"\"\n if not hasattr(record, 'hostname'):\n record.hostname = '-'\n if not hasattr(record, 'job_id'):\n record.job_id = self.job_id\n logger_name_prefix = 'oq.job.%s' % record.job_id\n if record.name.startswith(logger_name_prefix):\n record.name = record.name[len(logger_name_prefix):].lstrip('.')\n if not record.name:\n record.name = 'root'\n\n\nclass SupervisorLogStreamHandler(logging.StreamHandler):\n \"\"\"\n Log stream handler intended to be used with\n :class:`SupervisorLogMessageConsumer`.\n \"\"\"\n\n def __init__(self, job_id):\n super(SupervisorLogStreamHandler, self).__init__()\n self.setFormatter(logging.Formatter(LOG_FORMAT))\n self.job_id = job_id\n\n def emit(self, record): # pylint: disable=E0202\n _update_log_record(self, record)\n super(SupervisorLogStreamHandler, self).emit(record)\n\n\nclass SupervisorLogFileHandler(logging.FileHandler):\n \"\"\"\n Log file handler intended to be used with\n :class:`SupervisorLogMessageConsumer`.\n \"\"\"\n\n def __init__(self, job_id, log_file):\n super(SupervisorLogFileHandler, self).__init__(log_file)\n self.setFormatter(logging.Formatter(LOG_FORMAT))\n self.job_id = job_id\n self.log_file = log_file\n\n def emit(self, record): # pylint: disable=E0202\n _update_log_record(self, record)\n super(SupervisorLogFileHandler, self).emit(record)\n\n\nclass SupervisorLogMessageConsumer(logs.AMQPLogSource):\n \"\"\"\n Supervise an OpenQuake job by:\n\n - handling its \"critical\" and \"error\" messages\n - periodically checking that the job process is still running\n \"\"\"\n # Failure counter check delay, translates to 20 seconds with the current\n # settings.\n FCC_DELAY = 20\n\n def __init__(self, job_id, job_pid, timeout=1):\n self.selflogger = logging.getLogger('oq.job.%s.supervisor' % job_id)\n self.selflogger.debug('Entering supervisor for job %s', job_id)\n logger_name = 'oq.job.%s' % job_id\n key = '%s.#' % logger_name\n super(SupervisorLogMessageConsumer, self).__init__(timeout=timeout,\n routing_key=key)\n self.job_id = job_id\n self.job_pid = job_pid\n self.joblogger = logging.getLogger(logger_name)\n self.jobhandler = logging.Handler(logging.ERROR)\n self.jobhandler.emit = self.log_callback\n self.joblogger.addHandler(self.jobhandler)\n # Failure counter check delay value\n self.fcc_delay_value = 0\n\n def run(self):\n \"\"\"\n Wrap superclass' method just to add cleanup.\n \"\"\"\n started = datetime.utcnow()\n super(SupervisorLogMessageConsumer, self).run()\n stopped = datetime.utcnow()\n self.selflogger.info('Job %s finished in %s',\n self.job_id, stopped - started)\n self.joblogger.removeHandler(self.jobhandler)\n self.selflogger.debug('Exiting supervisor for job %s', self.job_id)\n\n def log_callback(self, record):\n \"\"\"\n Handles messages of severe level from the supervised job.\n \"\"\"\n if record.name == self.selflogger.name:\n # ignore error log messages sent by selflogger.\n # this way we don't try to kill the job if its\n # process has crashed (or has been stopped).\n # we emit selflogger's error messages from\n # timeout_callback().\n return\n\n terminate_job(self.job_pid)\n\n update_job_status_and_error_msg(self.job_id, record.getMessage())\n\n record_job_stop_time(self.job_id)\n\n cleanup_after_job(self.job_id)\n\n self.stop()\n\n def timeout_callback(self):\n \"\"\"\n On timeout expiration check if the job process is still running\n and whether it experienced any failures.\n\n Terminate the job process in the latter case.\n \"\"\"\n def failure_counters_need_check():\n \"\"\"Return `True` if failure counters should be checked.\"\"\"\n self.fcc_delay_value += 1\n result = self.fcc_delay_value >= self.FCC_DELAY\n if result:\n self.fcc_delay_value = 0\n return result\n\n process_stopped = job_failed = False\n message = None\n\n if not supervising.is_pid_running(self.job_pid):\n message = ('job process %s crashed or terminated' % self.job_pid)\n process_stopped = True\n elif failure_counters_need_check():\n # Job process is still running.\n failures = stats.failure_counters(self.job_id)\n if failures:\n terminate_job(self.job_pid)\n message = \"job terminated with failures: %s\" % failures\n job_failed = True\n\n if job_failed or process_stopped:\n job_status = get_job_status(self.job_id)\n if process_stopped and job_status == 'complete':\n message = 'job process %s succeeded' % self.job_pid\n self.selflogger.debug(message)\n elif not job_status == 'complete':\n # The job crashed without having a chance to update the\n # status in the database, or it has been running even though\n # there were failures. We update the job status here.\n self.selflogger.error(message)\n update_job_status_and_error_msg(self.job_id, error_msg=message)\n\n record_job_stop_time(self.job_id)\n cleanup_after_job(self.job_id)\n raise StopIteration()\n\n\ndef supervise(pid, job_id, timeout=1, log_file=None):\n \"\"\"\n Supervise a job process, entering a loop that ends only when the job\n terminates.\n\n :param pid: the process id\n :type pid: int\n :param job_id: the job id\n :type job_id: int\n :param timeout: timeout value in seconds\n :type timeout: float\n :param str log_file:\n Optional log file location. If specified, log messages will be appended\n to this file. If not specified, log messages will be printed to the\n console.\n \"\"\"\n # Set the name of this process (as reported by /bin/ps)\n setproctitle('openquake supervisor for job_id=%s job_pid=%s'\n % (job_id, pid))\n ignore_sigint()\n\n if log_file is not None:\n logging.root.addHandler(SupervisorLogFileHandler(job_id, log_file))\n else:\n logging.root.addHandler(SupervisorLogStreamHandler(job_id))\n\n supervisor = SupervisorLogMessageConsumer(job_id, pid, timeout)\n supervisor.run()\n","sub_path":"noq/openquake/supervising/supervisor.py","file_name":"supervisor.py","file_ext":"py","file_size_in_byte":10509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"274209785","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom plugins.BookScheduler import BookScheduler\nfrom configs.Config import Config\n\nschedulers = []\n\n\ndef init_all_schedulers():\n config = Config()\n\n settings = config.get_reservation_settings()\n stadiums = config.get_stadiums()\n timings = config.get_timings()\n sender = config.get_mail_account()\n\n for setting in settings:\n # noinspection PyTypeChecker\n account_name = setting['account']\n # noinspection PyTypeChecker\n setting_name = setting['setting_name']\n user = config.get_default_account(account_name)\n\n scheduler = BookScheduler()\n # noinspection PyTypeChecker\n scheduler.init(user, setting['tasks'], timings, config.get_logger(setting_name), sender,\n config.get_mail_receivers(setting_name), stadiums)\n schedulers.append(scheduler)\n\n\ndef start_all_schedulers():\n for scheduler in schedulers:\n scheduler.start()\n\n\ndef stop_all_schedulers():\n for scheduler in schedulers:\n scheduler.stop()\n\n\nif __name__ == \"__main__\":\n start_all_schedulers()\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"282258923","text":"class Car(object):\n \n\n\n def __init__(self,car_name=\"\",car_model=\"\",car_type=\"\"):\n\n self.speed = 0\n\n\n\n if len(car_name)>0:\n\n self.name=car_name\n\n else:\n\n self.name=\"General\"\n\n if len(car_type)>0:\n\n self.type=car_type\n\n else:\n\n self.type=\"salon\"\n\n if len(car_model)>0:\n\n self.model=car_model\n\n else:\n\n self.model=\"GM\"\n\n if self.name==\"Porshe\" or self.name==\"Koenigsegg\":\n\n self.num_of_doors=2\n\n else:\n\n self.num_of_doors=4\n\n if self.type==\"trailer\":\n\n self.num_of_wheels=8\n\n else:\n\n self.num_of_wheels=4\n\n\n\n def is_saloon(self):\n\n return self.type\n\n\n\n def drive(self, v):\n\n if v == 3:\n\n self.speed = 1000\n\n elif v == 7:\n\n self.speed = 77\n\n return self","sub_path":"DAY TWO/carlabs/carlabs.py","file_name":"carlabs.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"625495759","text":"import datetime as dt\nimport numpy as np\nimport sobol_seq\nfrom time import sleep\nfrom flask import Blueprint, request, jsonify\nfrom flask_api import status\nfrom thor.optimization import BayesianOptimization\nfrom thor.models import GaussianProcess\nfrom ...models import Experiment, Observation\nfrom ... import db\nfrom ...utils import (\n require_apikey,\n encode_recommendation,\n decode_recommendation,\n create_space\n)\n\n\nrecommendations = Blueprint(\"recommendations\", __name__)\n\n\n@recommendations.route(\"/api/create_recommendation/\", methods=[\"POST\"])\n@require_apikey\ndef create_recommendation(user):\n # Extract parameters.\n experiment_id = request.json[\"experiment_id\"]\n date = dt.datetime.today()\n # Get the experiment corresponding to this observation.\n e = Experiment.query.filter_by(id=experiment_id).first()\n dims = e.dimensions.all()\n n_dims = len(dims)\n space = create_space(dims)\n\n # Probability of selecting a random configuration.\n if request.json.get(\"rand_prob\", None):\n rand_prob = request.json[\"rand_prob\"]\n else:\n rand_prob = 0.\n # Number of model estimation iterations to perform. Note that the meaning of\n # this parameter changes when switching from a Gaussian process to a\n # Bayesian neural network.\n if request.json.get(\"n_model_iters\", None):\n n_model_iters = request.json[\"n_model_iters\"]\n else:\n n_model_iters = 5 * n_dims\n # Number of randomly positioned observations to create.\n n_random = 1 * n_dims\n\n # Either use Bayesian optimization or generate a random point depending on\n # the number of observations collected so far. Note that an input parameter\n # can be provided to determine the chance of selecting a configuration at\n # random. Setting this parameter to one is equivalent to assuming a policy\n # of pure exploration.\n n_observed = e.observations.filter_by(pending=False).count()\n n_obs = e.observations.count()\n if n_observed < n_random or np.random.uniform() < rand_prob:\n # rec = encode_recommendation(space.sample().ravel(), dims)\n sobol_rec = sobol_seq.i4_sobol(n_dims, n_obs+1)[0]\n rec = encode_recommendation(space.invert(sobol_rec).ravel(), dims)\n else:\n # Get pending and non-pending observations.\n observed = e.observations.filter(Observation.pending==False).all()\n pending = e.observations.filter(Observation.pending==True).all()\n X, y = decode_recommendation(observed, dims)\n X_pending = (\n decode_recommendation(pending, dims)[0]\n if len(pending) > 0 else None\n )\n # Create a recommendation with Bayesian optimization.\n bo = BayesianOptimization(e, space)\n c = bo.recommend(X, y, X_pending, GaussianProcess, n_model_iters)\n rec = encode_recommendation(c, dims)\n\n # Submit recommendation to user and store in the Thor database. It is\n # created initially without a response and is marked as pending.\n obs = Observation(str(rec), date)\n e.observations.append(obs)\n # Commit changes.\n db.session.commit()\n sleep(1)\n\n return jsonify(obs.to_dict())\n\n@recommendations.route(\"/api/submit_recommendation/\", methods=[\"POST\"])\n@require_apikey\ndef submit_recommendation(user):\n # Extract recommendation identifier and observed value.\n identifier = request.json[\"recommendation_id\"]\n value = request.json[\"value\"]\n # Update observation.\n obs = Observation.query.filter_by(id=identifier).first()\n\n if obs is not None:\n e = Experiment.query.filter_by(id=obs.experiment_id).first()\n if e.user_id == user.id:\n obs.target = value\n obs.pending = False\n # Commit changes.\n db.session.commit()\n\n return jsonify({\"id\": identifier, \"submitted\": True})\n else:\n err = {\"error\": \"Observation does not exist.\"}\n print(err)\n return (jsonify(err), status.HTTP_400_BAD_REQUEST)\n\n@recommendations.route(\"/api/pending_recommendations/\", methods=[\"POST\"])\n@require_apikey\ndef pending_recommendations(user):\n # Extract experiment.\n experiment_id = request.json[\"experiment_id\"]\n exp = user.experiments.filter(Experiment.id==experiment_id).first()\n\n if exp:\n pending_obs = exp.observations.filter(Observation.pending==True).all()\n return jsonify([o.to_dict() for o in pending_obs])\n else:\n err = {\n \"error\": \"Experiment with identifier {} does not exist.\".format(\n experiment_id\n )\n }\n print(err)\n return (jsonify(err), status.HTTP_400_BAD_REQUEST)\n","sub_path":"website/views/api/recommendations.py","file_name":"recommendations.py","file_ext":"py","file_size_in_byte":4627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"292305582","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('core', '0022_datasourcesettings'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='measure',\n name='type',\n field=models.CharField(default='integer', max_length=50, verbose_name='\\u0422\\u0438\\u043f \\u0438\\u0437\\u043c\\u0435\\u0440\\u0435\\u043d\\u0438\\u044f', choices=[('string', 'string'), ('integer', 'integer'), ('numeric', 'numeric'), ('boolean', 'boolean'), ('date', 'date'), ('time', 'time'), ('timestamp', 'timestamp'), ('bytea', 'bytea')]),\n ),\n ]\n","sub_path":"core/migrations/0023_auto_20151229_1231.py","file_name":"0023_auto_20151229_1231.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"127339342","text":"import os\nimport re\nimport subprocess\n\nfrom .._toolchain import *\nfrom . import rtlil\n\n\n__all__ = [\"YosysError\", \"convert\", \"convert_fragment\"]\n\n\nclass YosysError(Exception):\n pass\n\n\ndef _yosys_version():\n yosys_path = require_tool(\"yosys\")\n version = subprocess.check_output([yosys_path, \"-V\"], encoding=\"utf-8\")\n m = re.match(r\"^Yosys ([\\d.]+)(?:\\+(\\d+))?\", version)\n tag, offset = m[1], m[2] or 0\n return tuple(map(int, tag.split(\".\"))), offset\n\n\ndef _convert_il_text(il_text, strip_src):\n version, offset = _yosys_version()\n if version < (0, 9):\n raise YosysError(\"Yosys %d.%d is not suppored\", *version)\n\n attr_map = []\n if strip_src:\n attr_map.append(\"-remove src\")\n\n script = \"\"\"\n# Convert nMigen's RTLIL to readable Verilog.\nread_ilang <=25:\n i.set_color('r')\n else:\n i.set_color('g')\n \n plt.xticks(y_pos, image_dates, rotation=45)\n plt.ylabel('% of cloud cover')\n plt.xlabel('Image acquition dates')\n plt.title('Sentinel 2A images cloud cover')\n x = stats.mean(cloud_percent)\n y = stats.median(cloud_percent)\n a = stats.stdev(cloud_percent)\n b = stats.variance(cloud_percent)\n\n cloud_stats=\"\"\" mean :\"\"\"+format(x, '.2f')+\"\"\"\n median :\"\"\"+format(y, '.2f')+\"\"\"\n stdev :\"\"\"+format(a, '.2f')+\"\"\"\n variance:\"\"\"+format(b, '.2f')+\"\"\" \"\"\"\n\n\n plt.axhline(y=25, color='b', linestyle='-')\n\n plt.text(len(cloud_percent),(max(cloud_percent))*0.4,cloud_stats, fontsize=20)\n \n plt.savefig('result.png', bbox_inches=\"tight\")\n\n subprocess.call(\"rm *.vrt *.tif *.jpg *.xml *.img *.txt\", shell=True)\n\n # udatate status content\n return {'type': 'raster', 'status': 'PROCESSED', 'image_size': img_size, 'extent': img_extent, 'result': 'All Steps are finished successfully'}\n\n\n\n\n@app.route('/longtask', methods=['POST'])\ndef longtask():\n with open('in_bbox.txt', 'w') as outfile:\n json.dump(request.json, outfile)\n task = long_task.apply_async()\n return jsonify({}), 202, {'Location': url_for('taskstatus',\n task_id=task.id)}\n\n\n@app.route('/status/')\ndef taskstatus(task_id):\n task = long_task.AsyncResult(task_id)\n \n if task.state == 'PENDING':\n response = {\n 'state': task.state,\n 'current': 0,\n 'total': 1,\n 'status': 'Pending...'\n }\n elif task.state != 'FAILURE':\n response = {\n 'state': task.state,\n 'extent': task.info.get('extent', ''),\n 'type': task.info.get('type', ''),\n 'name': task.info.get('name', ''),\n 'image_size' : task.info.get('image_size', ''),\n 'image_dates': task.info.get('image_dates', '')\n }\n if 'result' in task.info:\n response['result'] = task.info['result']\n else:\n # something went wrong in the background job\n response = {\n 'state': task.state,\n 'current': 1,\n 'total': 1,\n 'status': str(task.info), # this is the exception raised\n }\n return jsonify(response)\n\n\n@app.route('/')\ndef route():\n return \"bleek\"\n\n@app.route('/index', methods=['GET'])\ndef index():\n return \"Hello, World!\"\n\n# TODO: discuss about route should be with parameters or with out.\n# The format of route is kind of analysis/algorithm/name of the satellite data/\n@app.route('/cloud-cover/fmask/sentinel2', methods=['POST'])\ndef cloud_cover(): \n\n # Storing user given input values so it can be opened in longtask function\n with open('in_dict.txt', 'w') as outfile:\n json.dump(request.json, outfile)\n\n input_dict = json.loads(request.data.decode())\n\n bbox = input_dict[\"bbox\"]\n\n # getting integer part from epsd code.\n in_srs_code = int(input_dict[\"srs\"].split(\":\")[1]) \n\n # Create ring\n ring = ogr.Geometry(ogr.wkbLinearRing)\n\n for point in bbox[0]:\n ring.AddPoint(point[0], point[1])\n\n # Create polygon\n in_poly = ogr.Geometry(ogr.wkbPolygon)\n in_poly.AddGeometry(ring) \n \n # creating projection\n in_srs = osr.SpatialReference()\n in_srs.ImportFromEPSG(in_srs_code)\n\n out_srs = osr.SpatialReference()\n out_srs.ImportFromEPSG(4326)\n\n transform = osr.CoordinateTransformation(in_srs, out_srs)\n\n in_poly.AssignSpatialReference(in_srs)\n\n \n # multi polygon for output\n out_multi_poly = ogr.Geometry(ogr.wkbMultiPolygon)\n\n out_multi_poly.AddGeometry(in_poly)\n \n # shortlisting images in given time and spatila extent.\n\n time_range = input_dict[\"date_range\"]\n satellite = input_dict[\"satellite\"]\n time_range = range(int(time_range[0].replace(\"-\", \"\")), int(time_range[1].replace(\"-\", \"\") ))\n \n\n data_dir = \"/mnt/c/Users/pgulla/Desktop/thesis/openeo/webapp/data\"+os.sep+satellite\n\n image_dates = []\n # Temporal subset\n tmp_subset = []\n for img_dir in os.listdir(data_dir):\n date_img_dir = int(img_dir.split(\"_\")[2].split(\"T\")[0])\n image_date = str(date_img_dir)\n image_dates.append(image_date[:4]+\"-\"+image_date[4:6]+\"-\"+image_date[6:8])\n if date_img_dir in time_range:\n tmp_subset.append(img_dir)\n\n # TODO:spatial subset, optimise sp_subset as global array\n sp_subset = []\n for img_dir in tmp_subset:\n \n #TODO: img extent is read from xml then we can exclude images with dark part. which is not possible if we use gdalinfo.\n img_xml_tree = etree.parse(data_dir+os.sep+img_dir+os.sep+'INSPIRE.xml')\n img_xml_root = img_xml_tree.getroot()\n # extracting image boundary polygon from xml\n img_bbox_char = img_xml_root[9][0][1][0].text.split(\" \")\n\n # removing last element as it is empty string\n img_bbox_char.pop()\n # converting list to iter for pairwaise iteration\n img_bbox_char = iter(img_bbox_char)\n\n img_bbox = []\n # open layers takes in different order for x,y\n for x in img_bbox_char:\n img_bbox.append([float(next(img_bbox_char)), float(x)])\n \n\n # Create ring\n ring = ogr.Geometry(ogr.wkbLinearRing)\n\n for point in img_bbox:\n ring.AddPoint(point[0], point[1])\n\n # Create polygon\n img_poly = ogr.Geometry(ogr.wkbPolygon)\n img_poly.AddGeometry(ring) \n\n # creating projection\n img_srs = osr.SpatialReference()\n img_srs.ImportFromEPSG(4326)\n\n img_poly.AssignSpatialReference(img_srs)\n\n transform = osr.CoordinateTransformation(img_srs, in_srs)\n\n img_poly.Transform(transform)\n\n\n if in_poly.Intersects(img_poly):\n sp_subset.append(img_dir)\n \n\n # writing sp_subset arry to file so we can access it in longterm task function. \n # TODO: optimise this step later\n thefile = open('sp_subset.txt', 'w')\n\n for img in sp_subset:\n thefile.write(\"%s\\n\" % img) \n\n thefile = open('image_dates.txt', 'w')\n\n for img in image_dates:\n thefile.write(\"%s\\n\" % img) \n \n task = long_task.apply_async()\n \n return jsonify({}), 202, {'Location': url_for('taskstatus',task_id=task.id)}\n\nif __name__ == '__main__':\n app.run(port=5000, debug=True) #on local host\n # works under internal network. enble this to run back-end for ifgi server. Then back end can be accesed inside wwu or with vpn on ifgi server.\n # app.run(host = '0.0.0.0', port = 5000, debug= False) \n","sub_path":"app/views_with_feedback.py","file_name":"views_with_feedback.py","file_ext":"py","file_size_in_byte":15570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"468564347","text":"# -*- coding: utf-8 -*\n\nimport cv2\nimport numpy as np\nimport time\n#ARマーカーの設定\n#aruco = cv2.aruco\n#dictionary = aruco.getPredefinedDictionary(aruco.DICT_4X4_50)\n#カメラからの取得\n#cap = cv2.VideoCapture(1)\n\n\ndef main_detect (count):\n #ARマーカーの設定\n aruco = cv2.aruco\n dictionary = aruco.getPredefinedDictionary(aruco.DICT_4X4_50)\n\n #カメラからの取得\n cap = cv2.VideoCapture(1)\n \n while True:\n #処理の円滑化\n time.sleep(0.1)\n #準備\n ret, row = cap.read()\n cv2.imshow('row', row)\n k = cv2.waitKey(1) # 1msec待つ\n if k == 13: # ESCキーで終了 ENTERは13\n break\n frame = cv2.cvtColor(row, cv2.COLOR_BGR2GRAY)\n \n\n #ARマーカーの情報\n corners, ids, rejectedImgPoints = aruco.detectMarkers(frame, dictionary)\n\n #ARマーカーを4つ認識したら\n if ids is not None:\n if sum(ids)[0] == 6 and len(ids) == 4:\n pos = [0,0,0,0]\n #ARマーカーの座標取得と整理\n for i, corner in enumerate( corners ):\n points = corner[0].astype(np.int32)\n pos[ids[i][0]] = list(corner[0][ids[i][0]].astype(np.int32))\n \n #print pos\n\n #マスの大きさの決定\n x1 = (pos[1][0]+pos[2][0])/2\n x2 = (pos[0][0]+pos[3][0])/2\n\n y1 = (pos[2][1]+pos[3][1])/2\n y2 = (pos[0][1]+pos[1][1])/2\n\n w = (x2-x1)/3\n h = (y2-y1)/3\n\n s = w*h\n\n #print x1,x2,y1,y2,w,h\n\n #○が書かれているか判定\n result = np.zeros((3,3))\n for i in range (0,3):\n for j in range (0,3):\n #切抜→白黒→ガウシアンフィルタ二値化\n result[i][j] = cv2.countNonZero(cv2.adaptiveThreshold(frame[y1+i*h:y1+(i+1)*h,x1+j*w:x1+(j+1)*w],255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2))/float(s)\n\n\n #print result\n result = np.where(result <= 0.79, 1, 0)\n #print result\n test = np.sum(result)\n if test == count:\n return result\n \n\n \n#main_detect(3)\n \n","sub_path":"main_detect_2.py","file_name":"main_detect_2.py","file_ext":"py","file_size_in_byte":2395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"206774882","text":"\"\"\"\nMFCC のトレーニング\n\"\"\"\n\nfrom librosa.feature import mfcc\nfrom librosa import load\nimport numpy as np\nfrom sklearn.svm import SVC\nfrom sklearn.utils import resample\nfrom sklearn.preprocessing import StandardScaler\nimport pickle\nimport os\n\n\ndef dircount(path):\n dirlist = []\n for dir in os.listdir(path):\n if os.path.isdir(os.path.join(path, dir)):\n dirlist.append(dir)\n return len(dirlist)\n\n\n\ndef create_ceps(fn):\n y, sr = load(fn)\n ceps = mfcc(y, sr)\n ceps = ceps.T\n np.save(fn + \".ceps.npy\", ceps)\n\n\ndef read_ceps(n_people):\n X = np.zeros(20)\n y = np.array([[0]])\n\n grouppath = \"./Dropbox/group/\"\n ngroup = dircount(grouppath)\n\n for i in range(int(n_people)):\n dirname = os.path.join(grouppath, \"group{}/speaker{}/\".format(ngroup - 1, i))\n fn = os.path.join(dirname, \"speaker{}.wav.ceps.npy\".format(i))\n ceps = np.load(fn)\n X = np.vstack((X, ceps))\n t = i * np.ones((ceps.shape[0], 1), dtype=\"int8\")\n y = np.vstack((y, t))\n return np.array(X), np.array(y)\n\n\ndef main():\n n_people = 3\n\n grouppath = \"./Dropbox/group/\"\n ngroup = dircount(grouppath)\n\n for i in range(n_people):\n dirname = os.path.join(grouppath, \"group{}/speaker{}/\".format(ngroup - 1, i))\n fname = os.path.join(dirname, \"speaker{}.wav\".format(i))\n create_ceps(fname)\n x, y = read_ceps(n_people)\n\n x = x[1:, :]\n y = y[1:, :]\n y = y.reshape(-1, )\n\n x, y = resample(x, y, n_samples=len(y))\n sc = StandardScaler()\n sc.fit(x)\n x = sc.transform(x)\n svc = SVC(kernel=\"rbf\", random_state=0, gamma=0.2, C=1.0)\n svc.fit(x, y)\n\n pickle.dump(svc, open(os.path.join(\"./Dropbox/group/group{}\".format(ngroup-1), \"model.sav\"), \"wb\"))\n pickle.dump(sc, open(os.path.join(\"./Dropbox/group/group{}\".format(ngroup-1), \"sc.sav\"), \"wb\"))\n \"\"\"\n svc.fit(x[200:,:],y[200:])\n print(svc.score(x[:200,:],y[:200]))\n prediction = svc.predict(x[:200,:]) \n \"\"\"\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/main_train_mfcc.py","file_name":"main_train_mfcc.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"185590374","text":"\nn = 100\n\ndef add_spam1(menu = None):\n if menu is None:\n menu = []\n menu.append(\"spam\")\n return menu\n\ndef add_spam(menu=[]):\n menu.append(\"spam\")\n return menu\nprint(add_spam())\nprint(add_spam())\nfor _ in range(4):\n print(add_spam())\n\nimport sys\ndef convert(s):\n try:\n return int(s)\n except (ValueError, TypeError) as e:\n print(\"Conversion error {}\".format((e)))\n return -1\n\nconvert(\"fail\")\n\ndef first(iterable):\n iterator = iter(iterable)\n try:\n return next(iterator)\n except StopIteration:\n raise ValueError(\"iterable is empty\")\niterable = ['first','snd','third']\n#print(first(iterable))\n#print(first(iterable))\n#print(first(iterable))\n#print(first(iterable))\n\ndef gen123():\n yield 100\n #yield 2\n yield 3\n\ng = gen123()\n\nfor i in g:\n print(i)\n#The first stateful generator take()\n\ndef take(count, iterable):\n counter = 0\n for i in iterable:\n if counter == count:\n return\n counter += 1\n yield i\n\ndef run_take():\n items = [ 2,4,6,8,10]\n for item in take(3,items):\n print(item)\n\nrun_take()\n\nprint(\"distinct\")\ndef distinct(iterable):\n seen = set()\n for i in iterable:\n if i in seen:\n continue\n yield i\n seen.add(i)\n\nd_i = [5,7,7,6,5,5]\nfor i in distinct(d_i):\n print(i)\n\n\nclass Temperature:\n \n\n def __init__(self, ftmp=32.0):\n self.ftmp = ftmp\n\n @property # ctmp \"getter\" method\n def ctmp(self):\n return (self.ftmp - 32.0) / 1.8\n\n @ctmp.setter # ctmp \"setter\" method\n def ctmp(self, ctmp):\n self.ftmp = ctmp * 1.8 + 32.0\n\n\nmy_tmp = Temperature()\n\nmy_tmp.ctmp = 0\n\n#print('0 C. is', my_tmp.ftmp, 'F.')\n\n\nmy_tmp.ctmp = 100\n\n#print('100C. is', my_tmp.ftmp, 'F.')\n\n\nmy_tmp.ctmp = 50\n\n#print('50C. is', my_tmp.ftmp, 'F.')\n\n\nmy_tmp.ftmp = 86\n\n#print('86F. is', my_tmp.ctmp, 'C.')\n\ndef outer(bt_fun, n=1):\n\n print('bt in test.')\n bt_fun()\n print(\"exit bt test\")\n\n@outer\ndef bt_fun():\n print(\"BT doesn't work\")\n#bt_fun()\n\nfrom time import time\n\ndef diagnostics(f):\n\n def wrapper(*args, **kwargs):\n\n print('Executed', f.__name__, 'at', time())\n\n value = f(*args, **kwargs)\n\n print('Exited ', f.__name__, 'at', time())\n\n print('Arguments:', args)\n\n print('Value returned:', value, '\\n')\n\n return value\n\n return wrapper\n\n@diagnostics\ndef print_nums():\n for i in range(4):\n print(i, end='\\t')\n print()\n\n\n\n@diagnostics\ndef calc_hypotenuse(a, b):\n\n return ((a*a + b*b) ** 0.5)\n\n\n\nprint_nums()\n\nprint (calc_hypotenuse(3, 4))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Py_op/py_dataStruc/test_log2.py","file_name":"test_log2.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"643256411","text":"import nltk\nfrom collections import Counter\nfrom nltk.corpus import stopwords\nimport theano\nimport theano.tensor as T\nimport numpy as np\nimport random\nfrom sklearn import linear_model\n\n#read from text file\nfile = open(\"amazon_cells_labelled.txt\", \"r\")\nfile1 = open(\"imdb_labelled.txt\", \"r\")\ndata1 = file1.read().decode(\"utf8\")\ndata = file.read().decode(\"utf8\")\n\n#tokenize the data\ntokens = nltk.word_tokenize(data)\ntokens1 = nltk.word_tokenize(data1)\n\n#make all words lowercase\nfor i in range(len(tokens)):\n tokens[i] = tokens[i].lower()\nfor i in range(len(tokens1)):\n tokens1[i] = tokens1[i].lower()\n#put into a dictionary\ncnt = Counter()\nfor i in range(len(tokens)):\n word = tokens[i]\n cnt[word]+= 1\n\nfor i in range(len(tokens1)):\n word = tokens1[i]\n cnt[word]+= 1\n\n#len cnt 4279\n\n#maps each word to an index number\nindex = dict()\ni = 0\nfor k in cnt.keys():\n index[k] = i\n i+=1\n\nrows = 2000\ncols = len(cnt.keys()) #4279\nmatrix = [ ([0] * cols) for row in range(rows) ]\noutputs = [0] * rows\n\n\nfile2 = open(\"imdb_labelled.txt\", \"r\")\nfile3 = open(\"amazon_cells_labelled.txt\", \"r\")\ndef preproc(file1):\n lineNum = 0\n for line in file2:\n token = nltk.word_tokenize(line.decode(\"utf8\"))\n lineNum +=1 \n y = token[len(token)-1]\n outputs[lineNum-1] = int(y)\n token.pop()\n for word in token:\n lookup = index[word.lower()]\n matrix[lineNum-1][lookup]= 1\n for line in file3:\n token = nltk.word_tokenize(line.decode(\"utf8\"))\n lineNum +=1 \n y = token[len(token)-1]\n outputs[lineNum-1] = int(y)\n token.pop()\n for word in token:\n lookup = index[word.lower()]\n matrix[lineNum-1][lookup]= 1\n\n #matrix with binary equivalent of data\n #print(matrix)\n return (matrix, outputs)\n #return outputs\n(array, outputs1) = preproc(file1)\ntestD = list()\ntestO = list()\ntrainD = list()\ntrainO = list()\n\nrandom.seed(2)\n\nranNum = random.sample(range(2000), 200)\nfor i in range(2000):\n if (i in ranNum): \n testD.append(array[i])\n testO.append(outputs[i])\n else:\n trainD.append(array[i])\n trainO.append(outputs[i])\n\nlogreg = linear_model.LogisticRegression(dual=False, random_state= 2)\n#logreg.fit(trainD, trainO, sample_weight = None)\nlogreg.fit(array, outputs1, sample_weight = None)\n\n#new = logreg.predict(testD)\nnew = logreg.predict(array)\n\ncounter = 0\nfor i in range(2000):\n #if(new[i-1] == testO[i-1]):\n if(new[i-1] == outputs1[i-1]):\n counter= counter +1\nprint(counter)\n","sub_path":"logamazimdb.py","file_name":"logamazimdb.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"114542097","text":"\"\"\"\nCopyright (c) <2017> \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nimport re\nfrom urllib2 import urlopen\n\ndef search_term_to_GSM(terms):\n result_ids = set()\n result_gsms = set()\n\n for term in terms:\n cur_result_ids = readid(\"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=gds&term=GSM%5BETYP%5D\"+term+\"&retmax=10000\")\n\n result_ids = result_ids.union(cur_result_ids)\n\n result_ids = list(result_ids)\n\n for i in range(0, len(result_ids), 500):\n ids = \",\".join(result_ids[i:i+500])\n gsm_url = \"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=gds&version=2.0&id=\" + ids\n\n f = urlopen(gsm_url)\n content = str(f.read())\n cur_gsms = [x.strip() for x in re.findall('\\sGSM[0-9]+\\s', content)]\n result_gsms = result_gsms.union(cur_gsms)\n gsms = set()\n\n for gsm in result_gsms:\n gsms.add(gsm.strip())\n\n return gsms\n\n\ndef readid(url):\n f = urlopen(url)\n content = str(f.read())\n content = content[content.find(\"\") + 8:content.find(\"\")-1]\n content = content.replace(\"\", \" \")\n content = content.replace(\"\", \" \")\n result_ids = set(content.split())\n return result_ids\n\n\nclass GSM:\n def __init__(self, GSM_id):\n self.id = GSM_id\n self.series = []\n self.platForm = \"\"\n self.characteristics = {}\n self.supplementaryData = {}\n self.relations = {}\n self.libraryStrategy = \"\"\n self.SRA = \"\"\n self.type = \"\"\n self.features = \"\"\n self.title = \"\"\n self.InstrumentID = \"\"\n self.organism = \"\"\n self.url = \"https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=\"+GSM_id+\"&targ=self&form=text&view=quick\"\n\n # potential attributes\n self.antibody = {}\n self.treatment = {}\n self.tissue = \"\"\n self.disease = \"\"\n self.cellLine = \"\"\n self.cellType = \"\"\n self.genotype = {}\n self.title_found = False\n self.ab_found = False\n self.title_ab = False\n self.input = \"\"\n self.encode = \"\"\n self.roadmap = \"\"\n self.organ = \"\"\n","sub_path":"sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"527160348","text":"import sys\nimport os\nfrom PIL import Image, ImageFont, ImageDraw\nimport random\n\ncolors = [\n (254, 209, 65),\n (255, 157, 110),\n (246, 117, 153),\n (221, 127, 211),\n (149, 149, 210),\n (139, 184, 232),\n (100, 204, 201),\n (136, 139, 141)]\n\nstyleData = {\n 'joy': {'price': 60, 'sizes': ['xs', 's', 'm', 'l', 'xl']},\n 'tween': {'price': 23},\n 'tall_&_curvy': {'price': 25},\n 'kids_s/m': {'price': 23},\n 'sloan': {'price': 28, 'sizes': [2, 4, 6, 8, 10, 12, 14]},\n 'sarah': {'price': 70, 'sizes': ['xs', 's', 'm', 'l', 'xl']},\n 'randy': {'price': 35, 'sizes': ['xxs', 'xs', 's', 'm', 'l', 'xl', '2xl', '3xl']},\n 'perfect_t': {'price': 36, 'sizes': ['xxs', 'xs', 's', 'm', 'l', 'xl', '2xl', '3xl']},\n 'patrick': {'price': 40, 'sizes': ['m', 'l', 'xl', '2xl', '3xl']},\n 'one_size': {'price': 25},\n 'nicole': {'price': 48, 'sizes': ['xxs', 'xs', 's', 'm', 'l', 'xl', '2xl', '3xl']},\n 'monroe': {'price': 48, 'sizes': ['s', 'l']},\n 'maxi': {'price': 42, 'sizes': ['xxs', 'xs', 's', 'm', 'l', 'xl', '2xl', '3xl']},\n 'madison': {'price': 48, 'sizes': ['xs', 's', 'm', 'l', 'xl', '2xl', '3xl']},\n 'kids_l/xl': {'price': 23},\n 'lucy': {'price': 52, 'sizes': ['xxs', 'xs', 's', 'm', 'l', 'xl', '2xl']},\n 'lola': {'price': 48, 'sizes': ['xxs', 'xs', 's', 'm', 'l', 'xl', '2xl']},\n 'lindsay': {'price': 48, 'sizes': ['s', 'm', 'l']},\n 'kids_azure': {'price': 25, 'sizes': [2, 4, 6, 8, 10, 12, 14]},\n 'julia': {'price': 45, 'sizes': ['xxs', 'xs', 's', 'm', 'l', 'xl', '2xl', '3xl']},\n 'jordan': {'price': 65, 'sizes': ['xs', 's', 'm', 'l', 'xl', '2xl']},\n 'jill': {'price': 55, 'sizes': ['xxs', 'xs', 's', 'm', 'l', 'xl', '2xl']},\n 'jade': {'price': 55, 'sizes': ['xs', 's', 'm', 'l', 'xl', '2xl']},\n 'irma': {'price': 35, 'sizes': ['xxs', 'xs', 's', 'm', 'l', 'xl', '2xl', '3xl']},\n 'gracie': {'price': 28, 'sizes': [2, 4, 6, 8, 10, 12, 14]},\n 'dotdotsmile': {'price': 36, 'sizes': [2, '3/4', '5/6', 7, '8/10', '12/14']},\n 'classic_t': {'price': 35, 'sizes': ['xxs', 'xs', 's', 'm', 'l', 'xl', '2xl', '3xl']},\n 'cassie': {'price': 35, 'sizes': ['xs', 's', 'm', 'l', 'xl', '2xl', '3xl']},\n 'azure': {'price': 35, 'sizes': ['xs', 's', 'm', 'l', 'xl', '2xl', '3xl']},\n 'ana': {'price': 60, 'sizes': ['xs', 's', 'm', 'l', 'xl', '2xl', '3xl']},\n 'amelia': {'price': 65, 'sizes': ['xxs', 'xs', 's', 'm', 'l', 'xl', '2xl']},\n 'carly': {'price': 55, 'sizes': ['xs', 's', 'm']}\n}\n\n# Globals\ncolor = colors[random.randrange(0, len(colors) - 1)]\nrunning_total = 0\nfolder = sys.argv[1] + '/'\nlogo = Image.open('logo.jpg')\nfinalWidth = 612\n\ndef formatStyle(styleType):\n styleType = styleType.replace('_', ' ')\n return styleType.upper()\n\ndef centerText(draw, msg, font):\n w, h = draw.textsize(msg.upper(), font=font)\n return finalWidth + ((finalWidth / 2) - w) / 2\n\ndef filePath(style, size, i):\n return style + \"_\" + size + \"_\" + str(i) + '.jpg'\n\ndef getStyleSize(fn):\n aPath = fn.split('/')\n size = aPath[len(aPath) - 2]\n style = aPath[len(aPath) - 3]\n return [style, size]\n\ndef isLularizedName(fn, style, size):\n fileName = os.path.basename(fn)\n\n if len(fileName) < 1:\n return False\n if fileName.count('_') < 2:\n return False\n if fileName[:fileName.rfind('_')] == style + '_' + size:\n return True\n return False\n\ndef processImage(file, folder):\n photo_increment = 1\n info = getStyleSize(file)\n style = info[0]\n size = info[1]\n\n if isLularizedName(file, style, size):\n return\n\n img = Image.open(file)\n\n img.thumbnail((finalWidth, 816))\n newImage = Image.new(\"RGBA\", size=(int(finalWidth * 1.5), 816), color=(255,255,255))\n newImage.paste(img, (0, 0, finalWidth, 816))\n newImage.paste(logo, (624, 520, 909, 805))\n draw = ImageDraw.Draw(newImage)\n\n font = ImageFont.truetype(\"MavenProLight-300.otf\", 42)\n draw.text((32, 760), \"LuLaRoe Stacy Leasure-Broski\", (0, 0, 0), font=font)\n draw.text((30, 758), \"LuLaRoe Stacy Leasure-Broski\", color, font=font)\n\n # Style\n draw.rectangle([(finalWidth, 0), (int(finalWidth * 1.5), 130)], fill=color)\n msg = formatStyle(style)\n font = ImageFont.truetype(\"steelfish rg.ttf\", 80)\n draw.text((centerText(draw, msg, font), 15), msg, (255, 255, 255), font=font)\n\n # Size\n draw.text((centerText(draw, size.upper(), font), 150), size.upper(), color, font=font)\n\n # Price\n font = ImageFont.truetype(\"steelfish rg.ttf\", 100)\n msg = \"$\" + str(styleData[style]['price'])\n draw.text((centerText(draw, msg, font), 275), msg, color, font=font)\n\n # Save image\n while os.path.exists(folder + filePath(style, size, photo_increment)):\n photo_increment += 1\n\n newImage.save(folder + filePath(style, size, photo_increment))\n os.remove(file)\n\n global running_total\n running_total += 1\n\ndef processFolder(folder):\n for fn in os.listdir(folder):\n if os.path.isfile(folder + fn) and os.path.splitext(fn)[1] == '.jpg':\n print('processing ' + folder)\n processImage(folder + fn, folder)\n elif os.path.isdir(folder + fn):\n processFolder(folder + fn + '/')\n\nif __name__ == \"__main__\":\n print('Lularizing folder: ' + folder)\n processFolder(folder)\n print('Lularized ' + str(running_total) + ' photos.')\n","sub_path":"lularize.py","file_name":"lularize.py","file_ext":"py","file_size_in_byte":5325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"177608121","text":"# you can write to stdout for debugging purposes, e.g.\n# print(\"this is a debug message\")\n\n\ndef solution(N):\n ones = [n for n in range(N.bit_length()) if N >> n & 1]\n print(ones)\n diffs = [ones[n] - ones[n - 1] for n in range(1, len(ones))]\n print(diffs)\n return max(diffs) - 1 if len(diffs) else 0\n\nif __name__ == '__main__':\n assert (solution(1041) == 5)\n assert (solution(32) == 0)\n assert (solution(2147483647) == 0)\n\n","sub_path":"binary-gap.py","file_name":"binary-gap.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"9098586","text":"\"\"\"Logging handler that logs to the posgres database.\"\"\"\nimport logging\nimport time\nfrom database_API import Log\n\n\nclass Logger:\n \"\"\"Logger class that sets up the logging.\"\"\"\n\n def __init__(self, session, logger_name, log_level):\n \"\"\"\n Create a Logger object.\n\n :param session: sessionmaker object\n :param logger_name: name of the logger\n :param log_level: minimum log level to be recorded\n \"\"\"\n logging_handler = LoggingHandler(session)\n logging.getLogger('').addHandler(logging_handler)\n self.log = logging.getLogger(logger_name)\n self.log.setLevel(log_level)\n\n def get_logger(self):\n \"\"\"Return a log object.\"\"\"\n return self.log\n\n\nclass LoggingHandler(logging.Handler):\n \"\"\"Logging handler that logs to the posgres database.\"\"\"\n\n def __init__(self, session):\n \"\"\"\n Create a LoggingHandler object.\n\n :param session: sessionmaker object\n \"\"\"\n logging.Handler.__init__(self)\n self.session = session\n\n def emit(self, record):\n \"\"\"\n Store log in database.\n\n :param record: record object that stores the information about the log\n \"\"\"\n try:\n time_created = time.strftime(\"%Y-%m-%d %H:%M:%S\",\n time.localtime(record.created))\n time_created += \".\" + str(record.msecs)[:3]\n print(str(record.msg).strip())\n Log.insert(self.session, record.levelno,\n str(record.levelname), str(record.filename),\n record.lineno, str(record.funcName),\n str(record.msg).strip(), time_created,\n str(record.name), record.process,\n str(record.processName), record.thread,\n str(record.threadName))\n except Exception:\n Log.insert(self.session, 40, \"ERROR\", \"database_logger.py\",\n 58, \"emit\", \"Error logging to database\",\n time.strftime(\"%Y-%m-%d %H:%M:%S\",\n time.localtime(record.created)),\n \"Database Logger\", 0, \"N/A\", 0, \"N/A\")\n","sub_path":"server/src/database_logger.py","file_name":"database_logger.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"440142030","text":"import os\nfrom setuptools import setup\n\nLONG_DESCRIPTION = \"\"\"\nThe wq command line tool.\n\"\"\"\n\n\ndef readme():\n try:\n readme = open('README.md')\n except IOError:\n return LONG_DESCRIPTION\n return readme.read()\n\n\ndef create_wq_namespace():\n \"\"\"\n Generate the wq namespace package\n (not checked in, as it technically is the parent of this folder)\n \"\"\"\n if os.path.isdir(\"wq\"):\n return\n os.makedirs(\"wq\")\n init = open(os.path.join(\"wq\", \"__init__.py\"), 'w')\n init.write(\"__import__('pkg_resources').declare_namespace(__name__)\")\n init.close()\n\n\ncreate_wq_namespace()\n\nsetup(\n name='wq.core',\n use_scm_version=True,\n author='S. Andrew Sheppard',\n author_email='andrew@wq.io',\n url='https://wq.io/',\n license='MIT',\n packages=['wq', 'wq.core'],\n package_dir={\n 'wq.core': '.',\n },\n install_requires=[\n 'click<6',\n 'PyYAML',\n ],\n setup_requires=[\n 'setuptools_scm',\n ],\n namespace_packages=['wq'],\n entry_points='''\n [console_scripts]\n wq=wq.core:wq\n [wq]\n wq.core=wq.core.info\n ''',\n description=LONG_DESCRIPTION.strip(),\n long_description=readme(),\n long_description_content_type='text/markdown',\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Environment :: Web Environment',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Programming Language :: JavaScript',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Topic :: Software Development :: Libraries :: Application Frameworks',\n 'Topic :: Software Development :: Build Tools',\n ]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"539447305","text":"import csv\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport signalproc\n\ndef build(output_name, coef_func):\n train_out = {}\n with open(\"train_data.csv\", \"r\") as file:\n reader = csv.reader(file)\n for row in reader:\n train_out[int(row[0])] = [int(x) for x in row[1:]]\n\n def process_file(file_no):\n a = signalproc.AudioSignal(\"train/nips4b_birds_trainfile{0:03}.wav\".format(file_no))\n\n return coef_func(a)\n\n\n train_in = {}\n for i in sorted(train_out):\n print(output_name, i)\n train_in[i] = process_file(i)\n\n with open(\"Data/{0}\".format(output_name), \"w\") as file:\n for i in train_in:\n if np.all(np.array(train_out[i]) == 0):\n file.write(\"{0}\\n{1}\\n\".format(list(train_in[i]), train_out[i] + [1]))\n else:\n file.write(\"{0}\\n{1}\\n\".format(list(train_in[i]), train_out[i] + [0]))\n\n#build(\"mel-spectra-mean-std-40.txt\", lambda x: x.mel_spectra())\n#build(\"mel-spectra-mean-fft-440.txt\", lambda x: x.mel_spectra_fft())\nbuild(\"mfcc-mean-13.txt\", lambda x: x.mfcc())\n","sub_path":"build_learning_data.py","file_name":"build_learning_data.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"558431287","text":"\r\nimport numpy as np\r\nimport cv2\r\n\r\nfilename = 'chessboard.jpg'\r\nimg = cv2.imread(filename)\r\ngray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\n\r\ngray = np.float32(gray)\r\ncorner = cv2.cornerHarris(gray,2,3,0.04)\r\n\r\nkernel = np.ones((5,5),np.uint8)\r\ncorner = cv2.dilate(corner,kernel,iterations =1)\r\nimg[corner>0.00001*corner.max()]=[255,0,0]\r\n\r\ncv2.namedWindow('corner', cv2.WINDOW_NORMAL)\r\ncv2.imshow('corner',img)\r\ncv2.waitKey(0) \r\ncv2.destroyAllWindows()\r\n\r\n\r\n\r\n","sub_path":"HarrisCorner_final.py","file_name":"HarrisCorner_final.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"169677600","text":"\"\"\"\n SoftLayer.firewall\n ~~~~~~~~~~~~~~~~~~\n Firewall Manager/helpers\n\n :license: MIT, see LICENSE for more details.\n\"\"\"\nfrom SoftLayer import utils\n\nRULE_MASK = ('mask[orderValue,action,destinationIpAddress,'\n 'destinationIpSubnetMask,protocol,destinationPortRangeStart,'\n 'destinationPortRangeEnd,sourceIpAddress,sourceIpSubnetMask,'\n 'version]')\n\n\ndef has_firewall(vlan):\n \"\"\" Helper to determine whether or not a VLAN has a firewall.\n\n :param dict vlan: A dictionary representing a VLAN\n :returns: True if the VLAN has a firewall, false if it doesn't.\n \"\"\"\n return bool(\n vlan.get('dedicatedFirewallFlag', None) or\n vlan.get('highAvailabilityFirewallFlag', None) or\n vlan.get('firewallInterfaces', None) or\n vlan.get('firewallNetworkComponents', None) or\n vlan.get('firewallGuestNetworkComponents', None)\n )\n\n\nclass FirewallManager(utils.IdentifierMixin, object):\n\n \"\"\" Manages firewalls.\n\n :param SoftLayer.API.Client client: the API client instance\n\n \"\"\"\n\n def __init__(self, client):\n self.client = client\n self.account = self.client['Account']\n self.prod_pkg = self.client['Product_Package']\n\n def get_standard_package(self, server_id, is_cci=True):\n \"\"\" Retrieves the standard firewall package for the CCI.\n\n :param int server_id: The ID of the server to create the firewall for\n :param bool is_cci: True if the id provided is for a CCI,\n False for a server\n :returns: A dictionary containing the standard CCI firewall package\n \"\"\"\n mask = ('mask[primaryNetworkComponent[speed]]')\n if is_cci:\n svc = self.client['Virtual_Guest']\n else:\n svc = self.client['Hardware_Server']\n\n item = svc.getObject(mask=mask, id=server_id)\n\n _filter = utils.NestedDict({})\n _value = \"%s%s\" % (item['primaryNetworkComponent']['speed'],\n \"Mbps Hardware Firewall\")\n _filter['items']['description'] = utils.query_filter(_value)\n\n kwargs = utils.NestedDict({})\n kwargs['id'] = 0 # look at package id 0\n kwargs['filter'] = _filter.to_dict()\n return self.prod_pkg.getItems(**kwargs)\n\n def get_dedicated_package(self, ha_enabled=False):\n \"\"\" Retrieves the dedicated firewall package.\n\n :param bool ha_enabled: True if HA is to be enabled on the firewall\n False for No HA\n :returns: A dictionary containing the dedicated CCI firewall package\n \"\"\"\n\n fwl_filter = 'Hardware Firewall (Dedicated)'\n ha_fwl_filter = 'Hardware Firewall (High Availability)'\n _filter = utils.NestedDict({})\n if ha_enabled:\n _filter['items']['description'] = utils.query_filter(ha_fwl_filter)\n else:\n _filter['items']['description'] = utils.query_filter(fwl_filter)\n\n kwargs = utils.NestedDict({})\n kwargs['id'] = 0 # look at package id 0\n kwargs['filter'] = _filter.to_dict()\n return self.prod_pkg.getItems(**kwargs)\n\n def cancel_firewall(self, firewall_id, dedicated=False):\n \"\"\" Cancels the specified firewall.\n\n :param int firewall_id: Firewall ID to be cancelled.\n :param bool dedicated: If true, the firewall instance is dedicated,\n otherwise, the firewall instance is shared.\n \"\"\"\n fwl_billing = self._get_fwl_billing_item(firewall_id, dedicated)\n billing_id = fwl_billing['billingItem']['id']\n billing_item = self.client['Billing_Item']\n return billing_item.cancelService(id=billing_id)\n\n def add_standard_firewall(self, server_id, is_cci=True):\n \"\"\" Creates a firewall for the specified CCI/Server\n\n :param int cci_id: The ID of the CCI to create the firewall for\n :param bool is_cci: If false, will create the firewall for a server,\n otherwise for a CCI\n :returns: A dictionary containing the standard CCI firewall order\n \"\"\"\n package = self.get_standard_package(server_id, is_cci)\n if is_cci:\n product_order = {\n 'complexType': 'SoftLayer_Container_Product_Order_Network_'\n 'Protection_Firewall',\n 'quantity': 1,\n 'packageId': 0,\n 'virtualGuests': [{'id': server_id}],\n 'prices': [{'id': package[0]['prices'][0]['id']}]\n }\n else:\n product_order = {\n 'complexType': 'SoftLayer_Container_Product_Order_Network_'\n 'Protection_Firewall',\n 'quantity': 1,\n 'packageId': 0,\n 'hardware': [{'id': server_id}],\n 'prices': [{'id': package[0]['prices'][0]['id']}]\n }\n return self.client['Product_Order'].placeOrder(product_order)\n\n def add_vlan_firewall(self, vlan_id, ha_enabled=False):\n \"\"\" Creates a firewall for the specified vlan\n\n :param int vlan_id: The ID of the vlan to create the firewall for\n :param bool ha_enabled: If True, Ha firewall will be created\n\n :returns: A dictionary containing the VLAN firewall order\n \"\"\"\n package = self.get_dedicated_package(ha_enabled)\n product_order = {\n 'complexType': 'SoftLayer_Container_Product_Order_Network_'\n 'Protection_Firewall_Dedicated',\n 'quantity': 1,\n 'packageId': 0,\n 'vlanId': vlan_id,\n 'prices': [{'id': package[0]['prices'][0]['id']}]\n }\n return self.client['Product_Order'].placeOrder(product_order)\n\n def _get_fwl_billing_item(self, firewall_id, dedicated=False):\n \"\"\" Retrieves the billing item of the firewall\n\n :param int firewall_id: Firewall ID to get the billing item for\n :param bool dedicated: whether the firewall is dedicated or standard\n :returns: A dictionary of the firewall billing item.\n \"\"\"\n mask = ('mask[id,billingItem[id]]')\n if dedicated:\n fwl_svc = self.client['Network_Vlan_Firewall']\n else:\n fwl_svc = self.client['Network_Component_Firewall']\n return fwl_svc.getObject(id=firewall_id, mask=mask)\n\n def get_firewalls(self):\n \"\"\" Returns a list of all firewalls on the account.\n\n :returns: A list of firewalls on the current account.\n \"\"\"\n mask = ('firewallNetworkComponents,'\n 'networkVlanFirewall,'\n 'dedicatedFirewallFlag,'\n 'firewallGuestNetworkComponents,'\n 'firewallInterfaces,'\n 'firewallRules,'\n 'highAvailabilityFirewallFlag')\n\n return [firewall\n for firewall in self.account.getNetworkVlans(mask=mask)\n if has_firewall(firewall)]\n\n def get_standard_fwl_rules(self, firewall_id):\n \"\"\" Get the rules of a standard firewall\n\n :param integer firewall_id: the instance ID of the standard firewall\n :returns: A list of the rules.\n \"\"\"\n svc = self.client['Network_Component_Firewall']\n return svc.getRules(id=firewall_id, mask=RULE_MASK)\n\n def get_dedicated_fwl_rules(self, firewall_id):\n \"\"\" Get the rules of a dedicated firewall\n\n :param integer firewall_id: the instance ID of the dedicated firewall\n :returns: A list of the rules.\n \"\"\"\n svc = self.client['Network_Vlan_Firewall']\n return svc.getRules(id=firewall_id, mask=RULE_MASK)\n\n def edit_dedicated_fwl_rules(self, firewall_id, rules):\n \"\"\" Edit the rules for dedicated firewall\n\n :param integer firewall_id: the instance ID of the dedicated firewall\n :param dict rules: the rules to be pushed on the firewall\n \"\"\"\n mask = ('mask[networkVlan[firewallInterfaces'\n '[firewallContextAccessControlLists]]]')\n svc = self.client['Network_Vlan_Firewall']\n fwl = svc.getObject(id=firewall_id, mask=mask)\n network_vlan = fwl['networkVlan']\n\n for fwl1 in network_vlan['firewallInterfaces']:\n if fwl1['name'] == 'inside':\n continue\n for control_list in fwl1['firewallContextAccessControlLists']:\n if control_list['direction'] == 'out':\n continue\n fwl_ctx_acl_id = control_list['id']\n\n template = {\n 'firewallContextAccessControlListId': fwl_ctx_acl_id,\n 'rules': rules\n }\n\n svc = self.client['Network_Firewall_Update_Request']\n return svc.createObject(template)\n\n def edit_standard_fwl_rules(self, firewall_id, rules):\n \"\"\" Edit the rules for standard firewall\n\n :param integer firewall_id: the instance ID of the standard firewall\n :param dict rules: the rules to be pushed on the firewall\n \"\"\"\n rule_svc = self.client['Network_Firewall_Update_Request']\n template = {\n \"networkComponentFirewallId\": firewall_id,\n \"rules\": rules}\n\n return rule_svc.createObject(template)\n","sub_path":"SoftLayer/managers/firewall.py","file_name":"firewall.py","file_ext":"py","file_size_in_byte":9248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"56863438","text":"# import modules\nimport globalvariable as v\n\n# retrieve file object\ncurrentpage = open(\"pages/versinfopage.txt\", \"r\")\n\n# define number of dashes\ndash = \"-\" * 24\n\n# assemle page variable\nversinfopage = currentpage.read() % (v.name, v.version, v.name, v.version,\n v.creator, dash)\n\n# close file\ncurrentpage.close()\n","sub_path":"pages/versinfopage.py","file_name":"versinfopage.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"216773224","text":"yas = 100\r\nyas = int(input(\"lütfen yaşınızı giriniz\"))\r\nif yas < 100:\r\n if yas < 50:\r\n print(\"yaşınız 0-50 aralığındadır\")\r\n if yas > 50:\r\n print(\"yaşınız 50-100 aralığındadır\")\r\nelse:\r\n yas > 100\r\n print(\"lütfen 50-100 aralığında bir yaş değeri giriniz\")\r\n\r\n\r\n","sub_path":"kosul_deyimi.py","file_name":"kosul_deyimi.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"351334442","text":"from django.shortcuts import render\nfrom django.contrib.auth.decorators import login_required\n\nfrom history.models import History\n\n\n\n@login_required\ndef index(request):\n context = dict()\n user = request.user\n if user is not None:\n if user.is_superuser:\n histories = History.objects.all()\n else:\n histories = History.objects.filter(user=user) \n context['active'] = \"index_hone\"\n context['histories'] = histories\n return render(request, 'index.html', context)\n\n","sub_path":"vhproject2021/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"195684361","text":"import requests\nfrom bs4 import BeautifulSoup as bs\nfrom time import sleep\n\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',\n 'Pragma': 'no-cache'\n }\n\n\ndef fetch_raw(recipe_url):\n html = None\n print('Processing..{}'.format(recipe_url))\n try:\n r = requests.get(recipe_url, headers=headers)\n if r.status_code == 200:\n html = r.text\n except Exception as ex:\n print('Exception while accessing raw html')\n print(str(ex))\n finally:\n return html.strip()\n\n\ndef get_recipes():\n recipes = []\n url = 'https://www.allrecipes.com/recipes/96/salad/'\n print('Accessing list')\n\n try:\n r = requests.get(url, headers=headers)\n if r.status_code == 200:\n html = r.text\n soup = bs(html, 'html.parser')\n links = soup.select('.fixed-recipe-card__h3 a')\n idx = 0\n for link in links:\n sleep(2)\n recipe = fetch_raw(link['href'])\n recipes.append(recipe)\n idx += 1\n if idx > 2:\n break\n except Exception as ex:\n print('Exception in get_recipes')\n print(str(ex))\n finally:\n return recipes\n","sub_path":"fetch.py","file_name":"fetch.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"143721513","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom telegram.ext import Updater, CommandHandler, CallbackQueryHandler\nfrom telegram import InlineKeyboardButton, InlineKeyboardMarkup\nfrom Salfeld import extension, status, stats, shutdown, sendmessage, lockpc, validate\nfrom random import randint\nimport datetime\n\nupdater = Updater(token='')# Your token here\ndispatcher = updater.dispatcher\n\n\ndef erfolg(bot, queryid):\n ant = [\"Bin Fertig! Alles gut gelaufen.\",\n \"Ok work done!\",\n \"Jetzt habe Ich aber frei!\",\n \"Joap, das sollte es gewesen sein!\",\n \"alles gemacht!\",\n \"Fertig! Das macht 6,50€\",\n \"schon erledigt!\",\n \"rekordzeit! so schnell ging es noch nie!\",\n \"Alles nach deinem wunsch erledigt!\"]\n bot.sendMessage(chat_id=queryid, text=ant[randint(0, len(ant)-1)])\n\n\ndef fehler(bot, queryid):\n ant = [\"Irgendwas doofes ist gerade passiert!\",\n \"Ochh nee irgendwo ist ein Fehler aufgetreten!\",\n \"[*BIIEEP*] FEHLER, FEHLER, FEHLER [*BIIEEP*]\",\n \"Sorry aber die Elektronen sind gerade alle rausgefallen\",\n \"Hoppla da ging was schief\",\n \"da ging was schief oder haben wir wirklich das Jahr 1967 ???\"]\n bot.sendMessage(chat_id=queryid, text=ant[randint(0, len(ant) - 1)])\n\n\ndef work(bot, queryid):\n ant = [\"Bin dabei!\",\n \"wörk wörk wörk\",\n \"Ich sollte einer Gewerkschaft beitreten!\",\n \"Geht klar Chef!\",\n \"Wenn du das so willst!\",\n \"Ich wünschte ich könnte nein sagen!\",\n \"Warte kurz\",\n \"Du denkst aber auch das ich nichts anderes zu tun habe oder?\",\n \"OKII DOKI\"]\n bot.sendMessage(chat_id=queryid, text=ant[randint(0, len(ant) - 1)])\n\n\ndef verung(bot, update, args):\n if args:\n try:\n zeit = int(args[0])\n work(bot, update.message.chat_id)\n except IndexError:\n zeit = False\n bot.sendMessage(chat_id=update.message.chat_id,\n text=\"Wie um alles in der Welt soll ich denn eine Verlängerung von Buchstaben setzten?\")\n else:\n zeit = False\n bot.sendMessage(chat_id=update.message.chat_id,\n text=\"Was soll den dieser Mist? soll Ich jetzt raten wie lange ich machen soll?\")\n\n if zeit:\n print(zeit)\n check = extension(zeit)\n if check:\n bot.sendMessage(chat_id=update.message.chat_id,\n text=\"Sehr gut {} Minuten Verlängerung wurden gesetzt!\".format(zeit))\n else:\n fehler(bot, update.message.chat_id)\n\n\ndef statuscall(bot, update):\n work(bot, update.message.chat_id)\n data = status()\n if data[1]:\n computer = \"eingeschalten\"\n else:\n computer = \"nicht eingeschalten\"\n if data[0] == 0:\n verlangerung = \"es ist keine Verlängerung gesetzt\"\n else:\n verlangerung = \"es ist eine Verlängerung von {} Minuten gesetzt\".format(data[0])\n bot.sendMessage(chat_id=update.message.chat_id,\n text=\"Ok. der Computer ist {} und {}\".format(computer, verlangerung))\n\n\ndef statistik(bot, update):\n keyboard = [[InlineKeyboardButton(\"Heute\", callback_data='0'),\n InlineKeyboardButton(\"Gestern\", callback_data='1')],\n\n [InlineKeyboardButton(\"Diese Woche\", callback_data='2')]]\n\n reply_markup = InlineKeyboardMarkup(keyboard)\n update.message.reply_text('Joap, von wann willst du die Statisitken haben?', reply_markup=reply_markup)\n\n\ndef button(bot, update):\n opt = {0: 'Heute', 1: 'Gestern', 2: 'Diese Woche'}\n query = update.callback_query\n nr = int(query.data)\n bot.editMessageText(text=query.message.text, chat_id=query.message.chat_id, message_id=query.message.message_id)\n if nr <= 2:\n zeit = stats(nr)\n bot.sendMessage(text=\"{} war der Computer {} Stunden an\".format(opt[nr], zeit), chat_id=query.message.chat_id)\n elif nr == 3 or nr == 4:\n if nr == 3:\n work(bot, query.message.chat_id)\n check = shutdown()\n if check:\n erfolg(bot, query.message.chat_id)\n else:\n fehler(bot, query.message.chat_id)\n else:\n bot.sendMessage(text=\"dann eben nicht!\", chat_id=query.message.chat_id)\n elif 5 <= nr <= 7:\n if nr < 7:\n work(bot, query.message.chat_id)\n if nr == 5:\n now = datetime.datetime.now() + datetime.timedelta(days=1)\n else:\n now = datetime.date.today() + datetime.timedelta(weeks=1)\n success = lockpc(now.strftime('%Y-%m-%d %H:%M:%S'))\n if success:\n erfolg(bot, query.message.chat_id)\n\n else:\n fehler(bot, query.message.chat_id)\n else:\n bot.editMessageText(chat_id=query.message.chat_id, message_id=query.message.message_id,\n text=\"Gut dann machen wir das so!\\n\"\n \"Gib mir bitte ein Datum nach diesem Schema:\\n\"\n \"/sperren JJ-MM-TT HH:MM:SS\\n\"\n \"Beispiel: /sperren 2016-12-24 12:34:00\")\n\n elif nr == 8:\n bot.sendMessage(text=\"dann eben nicht!\", chat_id=query.message.chat_id)\n\n\ndef delverung(bot, update):\n work(bot, update.message.chat_id)\n verlangerung(0)\n erfolg(bot, update.message.chat_id)\n\n\ndef hilfe(bot, update):\n bot.sendMessage(chat_id=update.message.chat_id,\n text=\"Alle Befehle:\\n/verung - Verlängerung setzten\\n\"\n \"/status - zeigt pc status und alle Verlängerungen\\n\"\n \"/statistik - zeigt wie lange der PC benutz wurde\\n\"\n \"/delverung - löscht alle Verlängerungen\\n\"\n \"/shutdown - Computer Herunterfahren\\n\"\n \"/msg - Sendet eine Nachricht an den PC\\n\"\n \"/sperren - sperrt den Computer für eine def. Zeit\\n\"\n \"/delsperren - löscht alle Sperrungen\")\n\n\ndef runter(bot, update):\n check = status()\n if check[1]:\n keyboard = [[InlineKeyboardButton(\"Ja\", callback_data='3'),\n InlineKeyboardButton(\"Neej\", callback_data='4')]]\n reply_markup = InlineKeyboardMarkup(keyboard)\n update.message.reply_text('Bist du dir sicher?', reply_markup=reply_markup)\n else:\n bot.sendMessage(chat_id=update.message.chat_id,\n text=\"Geht nicht weil der Computer nicht an ist!\")\n\n\ndef msg(bot, update, args):\n work(bot, update.message.chat_id)\n response = sendmessage(args[0])\n bot.sendMessage(chat_id=update.message.chat_id,\n text=response)\n\n\ndef sperr(bot, update, args):\n if args:\n date = args[0]+args[1]\n if validate(date):\n work(bot, update.message.chat_id)\n if lockpc(date) == 1:\n erfolg(bot, update.message.chat_id)\n else:\n fehler(bot, update.message.chat_id)\n else:\n fehler(bot, update.message.chat_id)\n bot.sendMessage(chat_id=update.message.chat_id, text=\"Irgendwie kann dein Datum nicht stimmen!\\n\"\n \"Es entspricht meiner meinung nach nicht diesem Muster:\\n\"\n \"JJ-MM-TT HH:MM:SS\")\n else:\n keyboard = [[InlineKeyboardButton(\"Morgen\", callback_data='5'),\n InlineKeyboardButton(\"Diese Woche\", callback_data='6')],\n [InlineKeyboardButton(\"Eigenes Datum\", callback_data='7')],\n [InlineKeyboardButton(\"Ich will doch nicht!\", callback_data='8')]]\n reply_markup = InlineKeyboardMarkup(keyboard)\n update.message.reply_text('Bis wann soll ich den Computer Sperren ?', reply_markup=reply_markup)\n\n\ndef delsperr(bot,update):\n work(bot, update.message.chat_id)\n now = datetime.datetime.now()\n check = lockpc(now.strftime('%Y-%m-%d %H:%M:%S'))\n if check == 1:\n erfolg(bot, update.message.chat_id)\n else:\n fehler(bot, update.message.chat_id)\n\nVerung_handler = CommandHandler('verung', verung, pass_args=True)\ndispatcher.add_handler(Verung_handler)\nStatus_handler = CommandHandler('status', statuscall)\ndispatcher.add_handler(Status_handler)\nStatistik_handler = CommandHandler('statistik', statistik)\ndispatcher.add_handler(Statistik_handler)\ndispatcher.add_handler(CallbackQueryHandler(button))\ndelverung_handler = CommandHandler('delverung', delverung)\ndispatcher.add_handler(delverung_handler)\nhelp_handler = CommandHandler('help', hilfe)\ndispatcher.add_handler(help_handler)\nmsg_handler = CommandHandler('msg', msg, pass_args=True)\ndispatcher.add_handler(msg_handler)\nShutdown_handler = CommandHandler('shutdown', runter)\ndispatcher.add_handler(Shutdown_handler)\nsperren_handler = CommandHandler('sperren', sperr, pass_args=True)\ndispatcher.add_handler(sperren_handler)\ndelsperren_handler = CommandHandler('delsperren', delsperr)\ndispatcher.add_handler(delsperren_handler)\n\nupdater.start_polling()\n","sub_path":"Bot.py","file_name":"Bot.py","file_ext":"py","file_size_in_byte":9193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"320863211","text":"import pytest\nfrom click.testing import CliRunner\nfrom mybar.db import DataBase\nfrom mybar.app import App\nfrom mybar.helpers import get_config\n\n\n@pytest.fixture()\ndef config():\n config = get_config()\n config.DATABASE_URL = \"sqlite:///:memory:\"\n\n yield config\n\n\n@pytest.fixture()\ndef db(config):\n db = DataBase(url=config.DATABASE_URL)\n db.create_all()\n\n yield db\n\n db.drop_all()\n\n\n@pytest.fixture()\ndef app(config):\n app = App(config=config)\n app.db.create_all()\n\n yield app\n\n app.db.drop_all()\n\n\n@pytest.fixture(scope=\"module\")\ndef cli_runner():\n runner = CliRunner()\n\n yield runner\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"79361006","text":"import logging, json, random\nfrom flask import Blueprint\nfrom flask_restful import Api, Resource, reqparse, marshal\n# ===== Untuk import db =====\nfrom blueprints import db\nfrom flask_jwt_extended import jwt_required, get_jwt_claims\nfrom blueprints.client import *\nfrom blueprints.auth import *\n\n# ===== Untuk import __init__.py =====\nfrom . import *\n\nbp_bank = Blueprint('bank', __name__)\napi = Api(bp_bank)\n\n\n#### book RESOURCE CLASS\n#### All Data\nclass BankResource(Resource):\n @jwt_required\n def get(self, id=None):\n if id == None:\n # if get_jwt_claims()['type'] == 'client':\n parser = reqparse.RequestParser()\n parser.add_argument('p', location='args', type=int, default=1)\n parser.add_argument('rp', location='args', type=int, default=5)\n args = parser.parse_args()\n\n # Rumus (p*rp)-rp\n offset = (args['p'] * args['rp']) - args['rp']\n \n # Memunculkan data semua (ditampilkan sesuai jumlah rp)\n bank_all = Banks.query\n get_all = []\n for get_data in bank_all.limit(args['rp']).offset(offset).all():\n get_all.append(marshal(get_data, Banks.response_field))\n return get_all, 200, { 'Content-Type': 'application/json' }\n \n else:\n # if get_jwt_claims()['type'] == 'client':\n bank = Banks.query.get(id)\n if bank is not None:\n return marshal(bank, Banks.response_field), 200, { 'Content-Type': 'application/json' }\n return {'status': 'NOT_FOUND', 'message': 'Anda belum membeli apapun'}, 404, { 'Content-Type': 'application/json' }\n\n @jwt_required\n def post(self):\n if get_jwt_claims()['type'] == 'admin' or get_jwt_claims()['type'] == \"superadmin\":\n parser = reqparse.RequestParser()\n parser.add_argument('nama_bank', location='json', required=True)\n parser.add_argument('no_rekening', location='json', type=int, required=True)\n parser.add_argument('nama_pemilik', location='json', required=True)\n parser.add_argument('image', location='json', required=True)\n args = parser.parse_args()\n \n # ==========(sentralize)==========\n bank = Banks(None, args['nama_bank'], args['no_rekening'], args['nama_pemilik'], args['image'])\n db.session.add(bank)\n db.session.commit()\n return marshal(bank, Banks.response_field), 200, { 'Content-Type': 'application/json' }\n return { 'status': 'ADMIN_ONLY', 'message': 'Only allowed for admin' }, 404, { 'Content-Type': 'application/json' }\n\n @jwt_required\n def put(self, id=None):\n if get_jwt_claims()['type'] == 'admin' or get_jwt_claims()['type'] == \"superadmin\":\n parser = reqparse.RequestParser()\n parser.add_argument('id', location='json', type=int, required=True)\n parser.add_argument('nama_bank', location='json')\n parser.add_argument('no_rekening', location='json', type=int)\n parser.add_argument('nama_pemilik', location='json')\n args = parser.parse_args()\n \n # ambil dari resi json\n bank = Banks.query.get(args['id'])\n temp = bank\n # ==========(sentralize)========= \n if bank == None:\n return {'status':'NOT_AVAILABLE', 'message':'Bank does not exist'}, 200, { 'Content-Type': 'application/json' }\n\n if bank != None:\n # Untuk bank\n if args['nama_bank'] != None:\n bank.nama_bank = args['nama_bank']\n if args['no_rekening'] != None:\n bank.no_rekening = args['no_rekening']\n if args['nama_pemilik'] != None:\n bank.nama_pemilik = args['nama_pemilik']\n \n if bank.nama_bank == None:\n bank.nama_bank = temp['nama_bank']\n if bank.no_rekening == None:\n bank.no_rekening = temp['no_rekening']\n if bank.nama_pemilik == None:\n bank.nama_pemilik = temp['nama_pemilik']\n db.session.commit()\n return marshal(bank, Banks.response_field), 200, { 'Content-Type': 'application/json' }\n return {'status': 'ADMIN_ONLY', 'message': 'Only for Admin'}, 404, { 'Content-Type': 'application/json' }\n\n @jwt_required\n def delete(self, id=None):\n if get_jwt_claims()['type'] == 'admin' or get_jwt_claims()['type'] == \"superadmin\":\n parser = reqparse.RequestParser()\n parser.add_argument('id', location='json', type=int)\n args = parser.parse_args()\n # return \"TES\"\n\n if id == None:\n bank = Banks.query.get(args['id'])\n if id != None:\n bank = Banks.query.get(id)\n\n if bank == None:\n return { 'status':'NOT_FOUND', 'message': 'Bank data not found' }, 200, { 'Content-Type': 'application/json' }\n if bank != None:\n db.session.delete(bank)\n db.session.commit()\n return { 'status':'COMPLETE', 'message': 'Delete complete' }, 200, { 'Content-Type': 'application/json' }\n return {'status': 'ADMIN_ONLY', 'message': 'Only for Admin'}, 404, { 'Content-Type': 'application/json' }\n\n\napi.add_resource(BankResource,'', '/')","sub_path":"blueprints/bank/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":5483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"99507819","text":"from flask import Blueprint, abort\nfrom app.models import User\nfrom flask_login import current_user\nfrom app.extensions import db\n\nadmin_bp = Blueprint('admin', __name__)\n\n\n@admin_bp.route('/delete_user/', methods=['DELETE'])\ndef delete_user(user_id):\n user = User.query.get_or_404(user_id)\n if not current_user.is_admin:\n abort(403)\n\n if user.is_admin:\n abort(400)\n\n db.session.delete(user)\n db.session.commit()\n return '', 204\n\n","sub_path":"app/blueprints/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"549571500","text":"import turtle as t\r\nt.bgcolor(\"black\")\r\nt.pensize(1)\r\nt.speed(100)\r\ncolors = ('yellow', 'red')\r\nfor i in range(200):\r\n t.forward(i*4)\r\n t.right(91)\r\n t.color(colors[i % 5])\r\n for x in range(3):\r\n t.forward(x * 4)\r\n t.right(91)\r\n for a in range(2):\r\n t.forward(a * 4)\r\n t.right(91)\r\n for m in range(739):\r\n t.forward(m * 4)\r\n t.right(89)\r\n","sub_path":"Turtle1.py","file_name":"Turtle1.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"522501126","text":"import click\nimport sys\nimport json\nfrom copy import deepcopy\nfrom functools import wraps\n\nfrom sqlalchemy.orm import joinedload\nfrom sqlalchemy.orm.exc import NoResultFound\n\nfrom api.util.useradmin import (\n change_password,\n deactivate_user,\n modify_user,\n get_user,\n generate_password,\n add_user,\n)\nfrom vardb.datamodel import user\nfrom vardb.deposit.deposit_users import import_groups\n\n\nfrom cli.decorators import cli_logger, session\n\n\nclass UserGroupNotFound(NoResultFound):\n \"\"\"Raised when a named user grouped can't be found in the database\"\"\"\n\n pass\n\n\n# Decorators\n\n\ndef convert(join, *split_args):\n \"\"\"\n Since click splits all options on whitespace, add this decorator before and after option decorators.\n\n Allows for whitespace in command line, e.g.\n\n ./cli foo --some_parameter_with_whitespace foo bar\n\n will pass argument some_parameter_with_whitespace as 'foo bar'\n\n Usage:\n @commandgroup.command(\"mycommand\")\n @convert(True, \"--some_parameter_with_whitespace\")\n @options(\"--some_parameter_with_whitespace\")\n @convert(False, \"--some_parameter_with_whitespace\")\n\n :param join: Boolean. Join or split arguments. Join and split arguments with '&'.\n :param split_args: Arguments to join/split on whitespace/&, e.g. --first_name\n :return:\n \"\"\"\n if join:\n d = dict()\n k = None\n new_argv = []\n for arg in sys.argv:\n if arg.startswith(\"--\"):\n if arg in split_args:\n k = arg\n d[k] = []\n new_argv.append(k)\n new_argv.append(None)\n continue\n else:\n new_argv.append(arg)\n k = None\n continue\n elif k is None:\n new_argv.append(arg)\n continue\n else:\n if new_argv[-1] is None:\n new_argv[-1] = arg\n else:\n new_argv[-1] += \"&\" + arg\n sys.argv = new_argv\n\n def _split(func):\n @wraps(func)\n def inner(*args, **kwargs):\n for k in kwargs:\n if \"--\" + k in split_args:\n if kwargs[k] is not None:\n kwargs[k] = \" \".join(kwargs[k].split(\"&\"))\n\n return func(*args, **kwargs)\n\n return inner\n\n return _split\n\n\n# Helper functions\n\n\ndef encode(s):\n if isinstance(s, str):\n return s.encode(\"utf-8\")\n else:\n return str(s)\n\n\ndef _user_exists(session, username):\n return session.query(user.User).filter(user.User.username == username).one_or_none() is not None\n\n\ndef _modify_user(session, username, echo_func, **kwargs):\n u = deepcopy(\n session.query(user.User)\n .options(joinedload(\"group\"))\n .filter(user.User.username == username)\n .one()\n )\n\n if \"new_username\" in kwargs:\n kwargs[\"username\"] = kwargs.pop(\"new_username\")\n modified = {k: v for k, v in kwargs.items() if v is not None}\n\n u_mod = modify_user(session, username, **modified)\n\n n_changes = 0\n for k in modified:\n if k == \"group_id\":\n k = \"usergroup\"\n from_val = u.group.name\n to_val = u_mod.group.name\n else:\n from_val = encode(getattr(u, k))\n to_val = encode(getattr(u_mod, k))\n if from_val != to_val:\n n_changes += 1\n if n_changes == 1:\n echo_func(\n \"User {username} ({last_name}, {first_name}) has been modified: \".format(\n username=username, first_name=u.first_name, last_name=u.last_name\n )\n )\n echo_func(\n \"\\t{key}: {from_val} ---> {to_val}\".format(key=k, from_val=from_val, to_val=to_val)\n )\n\n if n_changes == 0:\n echo_func(\n \"No modifications made to {username} ({last_name}, {first_name}).\".format(\n username=username, first_name=u.first_name, last_name=u.last_name\n )\n )\n\n return u_mod\n\n\ndef _add_user(session, echo_func, **kwargs):\n u, pw = add_user(\n session,\n kwargs[\"username\"],\n kwargs[\"first_name\"],\n kwargs[\"last_name\"],\n kwargs.get(\"email\"),\n kwargs[\"group_id\"],\n )\n echo_func(\n \"Added user {username} ({last_name}, {first_name}, {email}) with password {password}\".format(\n username=u.username,\n first_name=u.first_name,\n last_name=u.last_name,\n email=u.email,\n password=pw,\n )\n )\n return u\n\n\n# Commands\n\n\n@click.group(help=\"User actions\")\ndef users():\n pass\n\n\n@users.command(\"list\")\n@click.option(\n \"--group\",\n multiple=True,\n help=\"Limit the display to users belonging to specific usergroups, multiple options allowed.\"\n + \"If 'ALL' is given as option all users are displayed\",\n)\n@click.option(\"--username\", multiple=False, help=\"Display only a single user.\")\n@session\ndef cmd_users_list(session, group, username):\n accounts = None\n if username:\n accounts = session.query(user.User).filter(user.User.username == username).all()\n elif group and \"ALL\" not in group:\n accounts = (\n session.query(user.User)\n .join(user.UserGroup)\n .filter(user.UserGroup.name.in_(group))\n .all()\n )\n else:\n accounts = session.query(user.User).all()\n\n if not accounts:\n click.echo(\"No result\")\n return\n\n header_user = {\n \"id\": \"id\",\n \"username\": \"username\",\n \"first_name\": \"first_name\",\n \"last_name\": \"last_name\",\n \"password_expiry\": \"password_expiry\",\n }\n header_user_genpanel = {\"usergroup\": \"usergroup\", \"genepanels\": \"genepanels\"}\n header = header_user.copy()\n header.update(header_user_genpanel)\n row_format = (\n \"{id:^10}| {username:<20} | {first_name:<30} |\"\n + \"{last_name:<30} | {password_expiry:<30} | \"\n + \"{usergroup:<10} | {genepanels:<100}\"\n )\n click.echo(row_format.format(**header))\n click.echo(\n row_format.format(\n **{\n \"id\": \"-\" * 10,\n \"username\": \"-\" * 20,\n \"first_name\": \"-\" * 30,\n \"last_name\": \"-\" * 30,\n \"password\": \"-\" * 60,\n \"password_expiry\": \"-\" * 40,\n \"usergroup\": \"-\" * 10,\n \"genepanels\": \"-\" * 20,\n }\n )\n )\n for a in accounts:\n d = {h: str(getattr(a, h)) for h in header_user}\n d.update(\n {\n \"usergroup\": a.group.name,\n \"genepanels\": \", \".join([p.name + \"_\" + p.version for p in a.group.genepanels]),\n }\n )\n click.echo(row_format.format(**d))\n\n\n@users.command(\"activity\")\n@session\n@cli_logger() # Not logging output, just usage\ndef cmd_users_activity(logger, session):\n \"\"\"\n List latest activity by users, sorted by last activity\n \"\"\"\n usersessions = (\n session.query(user.UserSession).order_by(user.UserSession.lastactivity.desc()).all()\n )\n\n header = {\n \"id\": \"id\",\n \"username\": \"username\",\n \"first_name\": \"first_name\",\n \"last_name\": \"last_name\",\n \"last_activity\": \"last_activity\",\n }\n row_format = (\n \"{id:^10}| {username:<20} | {first_name:<30} | {last_name:<30} | {last_activity:<35} |\"\n )\n click.echo(row_format.format(**header))\n click.echo(\n row_format.format(\n id=\"-\" * 10,\n username=\"-\" * 20,\n first_name=\"-\" * 30,\n last_name=\"-\" * 30,\n last_activity=\"-\" * 35,\n )\n )\n\n for u in usersessions:\n click.echo(\n row_format.format(\n id=u.user.id,\n username=u.user.username,\n first_name=u.user.first_name,\n last_name=u.user.last_name,\n last_activity=str(u.lastactivity),\n )\n )\n\n\n@users.command(\"add_many\", help=\"Import users from a json file\")\n@click.argument(\"json_file\")\n@click.option(\n \"--group\",\n multiple=True,\n help=\"Limit the import to users belonging to specific usergroups, multiple options allowed.\"\n + \"If not given, all users are imported\",\n)\n@click.option(\"-dry\", is_flag=True, help=\"List users that would be imported\")\n@session\n@cli_logger()\ndef cmd_add_many_users(\n logger, session, json_file, group, dry\n): # group is a tuple of names given as --group options\n from functools import partial\n\n users = json.load(open(json_file, \"r\"))\n\n def is_usergroup_configured_to_be_imported(group_names, user):\n return (\n user[\"group\"]\n and user[\"group\"].strip()\n and group_names\n and user[\"group\"].strip().lower() in [s.strip().lower() for s in group_names]\n )\n\n filtered_users = (\n users\n if not group\n else list(filter(partial(is_usergroup_configured_to_be_imported, group), users))\n )\n\n for u in filtered_users:\n u[\"group_id\"] = (\n session.query(user.UserGroup.id).filter(user.UserGroup.name == u.pop(\"group\")).one()[0]\n )\n if _user_exists(session, u[\"username\"]):\n u = _modify_user(session, u.pop(\"username\"), logger.echo, **u)\n else:\n u = _add_user(session, logger.echo, **u)\n\n if dry:\n logger.echo(\"!!! DRY RUN: Rolling back changes\")\n session.rollback()\n else:\n session.commit()\n logger.echo(\"Users added successfully\")\n\n\n@users.command(\"add_groups\", help=\"Import user groups from a json file\")\n@click.argument(\"json_file\")\n@click.option(\n \"--name\",\n multiple=True,\n help=\"Limit the import to these groups, multiple options allowed.\"\n + \" If not set, imports all groups.\",\n)\n@click.option(\"-dry\", is_flag=True, help=\"List groups that would be imported\")\n@session\n@cli_logger()\ndef cmd_add_many_groups(\n logger, session, json_file, name, dry\n): # name is a tuple of names given as --name options\n from functools import partial\n\n groups = json.load(open(json_file, \"r\"))\n\n def is_usergroup_configured_to_be_imported(group_filter, group):\n return (\n group[\"name\"]\n and group[\"name\"].strip()\n and group_filter\n and group[\"name\"].strip().lower() in [s.strip().lower() for s in group_filter]\n )\n\n filtered_groups = (\n groups\n if not name\n else list(filter(partial(is_usergroup_configured_to_be_imported, name), groups))\n )\n if dry:\n for g in filtered_groups:\n logger.echo(\"Would add group '{name}'\".format(name=g[\"name\"]))\n return\n\n import_groups(session, filtered_groups, log=logger.echo)\n\n\n@users.command(\"reset_password\")\n@click.argument(\"username\")\n@session\n@cli_logger()\ndef cmd_reset_password(logger, session, username):\n \"\"\"\n Reset password for user (new password generated)\n \"\"\"\n password, _ = generate_password()\n change_password(session, username, None, password, override=True)\n u = session.query(user.User).filter(user.User.username == username).one()\n\n click.echo(\n \"Reset password for user {username} ({last_name}, {first_name}) with password {password}\".format(\n username=username, first_name=u.first_name, last_name=u.last_name, password=password\n )\n )\n logger.echo(\n \"Reset password for user {username} ({last_name}, {first_name}) with password *********\".format(\n username=username, first_name=u.first_name, last_name=u.last_name\n ),\n db_only=True,\n )\n\n\n@users.command(\"lock\")\n@click.argument(\"username\")\n@session\n@cli_logger(prompt_reason=True)\ndef cmd_invalidate_user(logger, session, username):\n \"\"\"\n Invalidate a user and all sessions.\n\n TODO: Add possibility to delete user, but only allow if user is not associated with any assessments or interpretations\n \"\"\"\n\n u = get_user(session, username)\n deactivate_user(session, u)\n\n logger.echo(\n \"User {username} ({last_name}, {first_name}) has been deactivated\".format(\n username=username, first_name=u.first_name, last_name=u.last_name\n )\n )\n\n\n@users.command(\"modify\")\n@convert(True, \"--first_name\", \"--last_name\")\n@click.argument(\"username\")\n@click.option(\"--new_username\")\n@click.option(\"--first_name\")\n@click.option(\"--last_name\")\n@click.option(\"--email\")\n@click.option(\"--user_group\")\n@convert(False, \"--first_name\", \"--last_name\")\n@session\n@cli_logger()\ndef cmd_modify_user(logger, session, username, **kwargs):\n \"\"\"\n Example: .. users modify --first_name Lars Marius -- lmarius\\n\n The -- marks when a new parameter starts\n \"\"\"\n\n answer = input(\n \"Are you sure you want to modify user with command line arguments? If not, consider using the 'add_many' command to import with json-file. Type 'y' to confirm.\"\n )\n\n if answer != \"y\":\n logger.echo(\"Aborting\")\n\n if \"user_group\" in kwargs:\n kwargs[\"group_id\"] = (\n session.query(user.UserGroup.id)\n .filter(user.UserGroup.name == kwargs.pop(\"user_group\"))\n .scalar()\n )\n\n _modify_user(session, username, logger.echo, **kwargs)\n logger.echo(\"User {} modified\".format(username))\n session.commit()\n","sub_path":"src/cli/commands/users/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":13396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"482167149","text":"#!/usr/bin/env python\n# coding=UTF-8\n\n__author__ = \"Pierre-Yves Langlois\"\n__copyright__ = \"https://github.com/pylanglois/uwsa/blob/master/LICENCE\"\n__credits__ = [\"Pierre-Yves Langlois\"]\n__license__ = \"BSD\"\n__maintainer__ = \"Pierre-Yves Langlois\"\n\nfrom string import Template\n\nfrom uwsas.common import *\nfrom uwsas.core import L\nfrom uwsas.core import CONF_MAP\nfrom uwsas import core\n\nfrom uwsas.commands.command_manager import cmanager\nfrom uwsas.commands.install import InstallCommand\n\nfrom uwsas.helpers import files\n\nclass InstallUWSACommand(InstallCommand):\n\n NAME = 'uwsa'\n\n def __init__(self):\n InstallCommand.__init__(self)\n self.add_package(\"python-ldap\")\n self.add_package(\"python-iniparse\")\n self.add_package(\"python-mysqldb\")\n\n self.add_folder('/var/log/uwsa')\n self.add_folder('/etc/uwsa')\n self.add_folder('/var/lib/uwsa/')\n self.add_folder('/var/lib/uwsa/user_scripts')\n self.add_folder(CONF_MAP('site','conf_path'))\n self.add_folder(CONF_MAP('site','wordpress_template_path'))\n self.add_folder(CONF_MAP('site','wikimedia_template_path'))\n self.add_folder(CONF_MAP('site','typo3_template_path'))\n self.add_folder(CONF_MAP('site','vhost_path'))\n\n self.add_file('/etc/uwsa/uwsa.conf', fix_func=self.fix_uwsa_conf)\n self.add_file('/etc/logrotate.d/uwsa', fix_func=self.fix_logrotate)\n\n self.add_file('/var/log/uwsa/*.log', perm={'u':'rw', 'g':'r', 'o':''})\n self.add_file('/var/lib/uwsa/user_scripts/*.py', ck_func=self.check_user_scripts)\n self.add_file('/var/lib/uwsa/auto_mount/*', ck_func=self.check_user_scripts, perm={'u':'rx', 'g':'rx', 'o':''})\n\n def check_user_scripts(self,element):\n\n file_list = files.ls(element['name'])\n is_ok = True if len(file_list) == 0 else False\n for f in file_list:\n if files.is_file(f) and files.check_perm(f,**element['perm']):\n is_ok = True\n\n return is_ok\n\n def fix_uwsa_conf(self, element):\n\n with open(files.get_rel_path(\"data/uwsa.conf.tpl\")) as f:\n files.create(element['name'], f.read())\n\n core.CONFIG.load(element['name'])\n core.CONFIG.save_to_file(element['name'])\n\n def fix_logrotate(self, element):\n logrotate_template = Template(open(files.get_rel_path(\"data/logrotate_uwsa.tpl\")).read())\n files.create(element['name'], logrotate_template.safe_substitute())\n\ncmanager.get(InstallCommand.NAME).register(InstallUWSACommand.NAME, InstallUWSACommand())\n","sub_path":"uwsas/commands/install_uwsa.py","file_name":"install_uwsa.py","file_ext":"py","file_size_in_byte":2550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"124450851","text":"from django.shortcuts import render, get_object_or_404\nfrom django.http import Http404, HttpResponse, HttpResponseRedirect\nfrom django.urls import reverse\nfrom django.db.models import F\nfrom django.views import generic\nfrom polls.models import Question, Choice\n\n# Create your views here.\n\n\ndef index(request):\n latest_question_list = Question.objects.order_by('-pub_date')[:10]\n context = {\n 'latest_question_list': latest_question_list,\n }\n return render(request, template_name='polls/index.html', context=context)\n\n\ndef detail(request, question_id):\n try:\n # question = Question.objects.get(id=question_id)\n question = get_object_or_404(Question, pk=question_id)\n except Question.DoesNotExist:\n raise Http404('Question Does not Exist')\n return render(request, 'polls/details.html', context={'question': question})\n\n# Implement this using Generic view\n# def results(request, question_id):\n# question = get_object_or_404(Question, pk=question_id)\n# return render(request, 'polls/results.html', context={'question': question})\n\n\ndef vote(request, question_id):\n question = get_object_or_404(Question, pk=question_id)\n try:\n selected_choice = question.choice_set.get(pk=request.POST['choice'])\n except (KeyError, Choice.DoesNotExist):\n context = {\n 'question': question,\n 'error_message': \"You didn't select a choice\"\n }\n return render(request, template_name='polls/details.html', context=context)\n else:\n selected_choice.votes = F('votes')+1 # Avoiding Race Condition Problem\n selected_choice.save()\n # Always return an HttpResponseRedirect after successfully dealing\n # with POST data. This prevents data from being posted twice if a\n # user hits the Back button.\n return HttpResponseRedirect(reverse(viewname='polls:results', args=(question.id,)))\n # reverse() - This function helps avoid having to hardcode a URL in the view function.\n # It is given the name of the view that we want to pass control to and the variable portion of the URL pattern\n # that points to that view.\n\n# Class Based Views (Generic View) Concept:\n# Generic views abstract common patterns to the point where you don’t even need to write Python code to write an app.\n# Let’s convert our poll app to use the generic views system:\n # Convert the URLconf.\n # Delete some of the old, unneeded views.\n # Introduce new views based on Django’s generic views.\n\n# Generally, when writing a Django app, you’ll evaluate whether generic views are a good fit for your problem,\n# and you’ll use them from the beginning, rather than refactoring your code halfway through.\n# By default, the DetailView generic view uses a template called /_detail.html.\n# In our case, it would use the template \"polls/question_detail.html,\n# Similarly, the ListView generic view uses a default template called /_list.html\n\n\nclass ResultsView(generic.DetailView):\n model = Question\n template_name = 'polls/results.html'\n\n","sub_path":"polls/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"573498797","text":"# -*- coding: utf-8 -*-\n\nfrom time import sleep\nfrom lettuce import world\nfrom salad.steps.everything import *\n\nfrom theeye.steps.browser import wait_until_clickable\n\n\n# popular methods\ndef click_xpath(xpath):\n world.browser.find_by_xpath(xpath)[0].click()\n\n\ndef click_css(css):\n world.browser.find_by_css(css)[0].click()\n\n\ndef fill_xpath(xpath, words):\n world.browser.find_by_xpath(xpath)[0].value = words\n\n\ndef fill_css(css, words):\n world.browser.find_by_css(css)[0].value = words\n\n\n# steps on menu page\n@step(r'empty the basket')\ndef empty_basket(step):\n assert world.browser.is_text_present(\"Bitte lege etwas in den Warenkorb\")\n world.browser.find_by_css(\".icon-delete\")[0].click()\n sleep(1)\n click_xpath(\"//div[text()[contains(.,'Coupons small')]]\")\n\n\n@step(r'fill in the address widget')\ndef fill_address_widget(step):\n assert world.browser.find_by_css(\"input.street-name\")\n fill_css(\"input.street-name\", \"Karl-Marx-Allee 11\")\n fill_css(\"input.zipcode\", \"15320\")\n click_css(\".lightbox [data-qa='find_restaurants']\")\n\n\n@step(r'add \"([^\"]+)\" to the basket')\ndef add_item_to_basket(step, name):\n sleep(2)\n assert world.browser.find_by_xpath(\"//div[text()[contains(.,'%s')]]\" %\n (name, ))\n click_xpath(\"//div[text()[contains(.,'%s')]]\" % (name, ))\n sleep(4)\n wait_until_clickable(\".checkout\", \"css\")\n sleep(2)\n click_css(\".checkout\")\n\n\n# steps on checkout page\n@step(r'order using \"([^\"]+)\" payment')\ndef pay_with_method(step, name):\n assert name in ['cash', 'paypal', 'credit', 'debit']\n css = \"li.%s\" % (name, )\n wait_until_clickable(css, \"css\")\n click_css(css)\n sleep(5)\n world.browser.execute_script(\"$('input#tos').click()\")\n click_css(\"input[value='Jetzt bestellen']\")\n","sub_path":"de/features/sources/newplattform_steps.py","file_name":"newplattform_steps.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"227476177","text":"import hashlib\nimport requests\nimport json\nfrom flask import Blueprint\nfrom flask_jwt_extended import create_access_token, get_jwt_claims, get_jwt_identity, jwt_required\nfrom flask_restful import Api, Resource, marshal, reqparse\nfrom ..toko.models import Toko, Barang, harga_bahan\nfrom ..auth.models import User\nfrom ..barang.models import Keranjang\nfrom blueprints import db, app\n\nbp_keranjang = Blueprint('keranjang', __name__)\napi = Api(bp_keranjang)\n\n\nclass ListKeranjangResource(Resource):\n @jwt_required\n def get(self):\n parser = reqparse.RequestParser()\n parser.add_argument('p', type=int, location='args', default=1)\n parser.add_argument('rp', type=int, location='args', default=20)\n parser.add_argument('search', location='args')\n parser.add_argument('orderby', location='args',\n help='invalid orderby value', choices=('harga', 'id'))\n parser.add_argument('sort', location='args',\n help='invalid sort value', choices=('desc', 'asc'))\n args = parser.parse_args()\n # Menentukan offset buat limit hasil pencarian\n offset = (args['p'] * args['rp']) - args['rp']\n # Filter keranjang by user_id from jwt claims\n claims = get_jwt_claims()\n user_id = claims['id']\n qry_keranjang = Keranjang.query.filter_by(user_id=user_id)\n qry_keranjang = qry_keranjang.filter_by(checkout_status=False)\n if args['search'] is not None:\n search = \"%{}%\".format(args['search'])\n qry_keranjang = qry_keranjang.filter(\n Keranjang.nama_barang.like(search))\n if args['orderby'] is not None:\n if args['orderby'] == \"harga\":\n if args['sort'] == 'desc':\n qry_keranjang = qry_keranjang.order_by(\n (Keranjang.harga_barang_int*Keranjang.jumlah).desc())\n else:\n qry_keranjang = qry_keranjang.order_by(\n (Keranjang.harga_barang_int*Keranjang.jumlah))\n else:\n if args['sort'] == 'desc':\n qry_keranjang = qry_keranjang.order_by(Keranjang.id.desc())\n else:\n qry_keranjang = qry_keranjang.order_by(Keranjang.id)\n keranjang_limit = qry_keranjang.limit(args['rp']).offset(offset)\n list_keranjang = []\n for keranjang in keranjang_limit:\n keranjang_marshal = marshal(keranjang, Keranjang.response_fields)\n total_harga = keranjang.harga_barang_int*keranjang.jumlah\n keranjang_marshal['total_harga'] = total_harga\n list_keranjang.append(keranjang_marshal)\n return list_keranjang, 200, {'Content-type': 'application/json'}\n\n @jwt_required\n def patch(self):\n parser = reqparse.RequestParser()\n parser.add_argument('id', type=int, location='json', required=True)\n parser.add_argument('jumlah', type=int, location='json')\n parser.add_argument('ukuran', location='json')\n args = parser.parse_args()\n claims = get_jwt_claims()\n user_id = claims['id']\n # get keranjang by id\n keranjang = Keranjang.query.get(args['id'])\n if keranjang is not None and keranjang.user_id == user_id:\n # edit jumlah\n if args['jumlah'] is not None:\n keranjang.jumlah = args['jumlah']\n total_harga = keranjang.harga_barang_int*keranjang.jumlah\n # edit ukuran\n if args['ukuran'] is not None:\n keranjang.ukuran = args['ukuran']\n db.session.add(keranjang)\n db.session.commit()\n keranjang_marshal = marshal(keranjang, Keranjang.response_fields)\n keranjang_marshal['Total Harga'] = total_harga\n return {\"status\": \"edit keranjang berhasil\", \"detail\": keranjang_marshal}, 200, {'Content-type': 'application/json'}\n else:\n return {\"status\": \"edit keranjang gagal\"}, 400\n\n # Checkout keranjang\n # Tambah API untuk ngirim email ke pendaftar atau Telegram\n @jwt_required\n def put(self):\n parser = reqparse.RequestParser()\n # id keranjang yang mau checkout (berupa list)\n # parser.add_argument('id', type=list, location='json', required=True)\n args = parser.parse_args()\n claims = get_jwt_claims()\n user_id = claims['id']\n list_checkout = []\n total_harga = 0\n list_keranjang = Keranjang.query.all()\n for keranjang in list_keranjang:\n # check jika keranjang tersebut punya dia\n if keranjang.user_id == user_id and keranjang.checkout_status == False:\n keranjang.checkout_status = True\n # db.session.add(keranjang)\n db.session.commit()\n harga = keranjang.harga_barang_int * keranjang.jumlah\n total_harga += harga\n total = \"Rp. {}\".format(harga)\n keranjang_marshal = marshal(\n keranjang, Keranjang.response_fields)\n keranjang_marshal['total harga'] = total\n list_checkout.append(keranjang_marshal)\n if len(list_checkout) > 0:\n return {\"status\": \"silahkan lakukan konfirmasi pemesanan\", \"total harga\": total_harga, \"detail\": list_checkout}, 200, {'Content-type': 'application/json'}\n else:\n return {\"status\": \"checkout gagal\"}, 403\n\n # Menghapus Keranjang\n @jwt_required\n def delete(self):\n parser = reqparse.RequestParser()\n # id keranjang yang mau dihapus (berupa list)\n parser.add_argument('id', type=int, location='json')\n args = parser.parse_args()\n claims = get_jwt_claims()\n user_id = claims['id']\n list_keranjang = Keranjang.query.filter_by(user_id=user_id)\n hapus_counter = 0\n if args['id'] is None or args['id'] == 0:\n for keranjang in list_keranjang:\n if keranjang.checkout_status == False:\n db.session.delete(keranjang)\n db.session.commit()\n return {\"status\": \"semua barang di keranjang berhasil dihapus\"}, 200, {'Content-type': 'application/json'}\n else:\n for keranjang in list_keranjang:\n if keranjang.id == args['id'] and keranjang.checkout_status == False:\n hapus_counter += 1\n db.session.delete(keranjang)\n db.session.commit()\n return {\"status\": \"{} barang di keranjang berhasil dihapus\".format(hapus_counter)}, 200, {'Content-type': 'application/json'}\n\n def options(self):\n return {}, 200\n\n\napi.add_resource(ListKeranjangResource, '')\n","sub_path":"blueprints/keranjang/resource.py","file_name":"resource.py","file_ext":"py","file_size_in_byte":6743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"643796456","text":"# !/usr/bin/env python\n# -*- coding:utf-8 -*-\n# author;鸿\nfrom xpinyin import Pinyin\nimport json\nimport urllib.request as r\ncity = str(input(\"请输入需要查询的城市:\"))\np = Pinyin()\ncity_pinyin = p.get_pinyin(city, \"\")\nurl = \"http://api.openweathermap.org/data/2.5/forecast?q={},cn&mode=json&lang=zh_cn&&APPID=6a67ed641c0fda8b69715c43518b6996&units=metric\".format(city_pinyin)\ndata = r.urlopen(url).read().decode(\"utf-8\")\ndata = json.loads(data)\n\ndef get_temp(n):\n i = 0\n j = 0\n temp = []\n while j < n:\n ls = data[\"list\"][i]\n if ls[\"dt_txt\"].endswith(\"18:00:00\"):\n j += 1\n temp.append(ls[\"main\"][\"temp\"])\n i += 1\n return temp\ntemp = get_temp(5)\ntemp_sum=sum([i for i in temp])#列表推导式\ntemp_mean=temp_sum/len(temp)\nprint(city+'未来'+str(len(temp))+'天的平均温度为:{:.2f}'.format(temp_mean))","sub_path":"阶段一/列表推导式算平均气温.py","file_name":"列表推导式算平均气温.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"81528246","text":"import argparse\nimport sys\n\nimport dendropy\n\nfrom fixedOrderEmbedder import embedTree\nfrom node import Node\n\ndef normalize(tree):\n distances = tree.calc_node_root_distances(return_leaf_distances_only=False)\n\n #Remove uniques\n distances = list(set(distances))\n\n distances.sort()\n distanceMap = dict()\n for i,d in enumerate(distances):\n distanceMap[d] = 4*i\n\n for n in tree:\n n.norm_root_distance = distanceMap[n.root_distance]\n\n return tree\n\ndef create(dNode):\n\n children = []\n for dc in dNode.child_node_iter():\n child = create(dc)\n children.append(child)\n\n node = Node(dNode, dNode.norm_root_distance, children)\n\n return node\n\ndef hasEdgeLengths(rawTree):\n\n if rawTree.length() == 0:\n return False\n\n zeroLengthEdges = rawTree.edges(lambda e : e.length == None)\n\n return True\n\ndef fixZeroLengthEdges(node):\n\n if node.parent:\n if node.parent.height >= node.height:\n node.height = node.parent.height + 2\n\n for c in node.children:\n fixZeroLengthEdges(c)\n\ndef read(path, schema):\n\n rawTree = dendropy.Tree.get(path=path, schema=schema)\n\n rawTree = normalize(rawTree)\n\n #rawTree.print_plot()\n\n #for n in rawTree:\n # print(str(n.norm_root_distance) + \"\\t\" + str(n.root_distance) + \"\\t\" + str(n))\n\n #What do with forests?\n root = create(rawTree.seed_node)\n\n fixZeroLengthEdges(root)\n\n return root\n\ndef readTrees(path, schema):\n\n rawTrees = dendropy.TreeList.get(path=path, schema=schema, suppress_internal_node_taxa=True, suppress_leaf_node_taxa=True)\n\n trees = []\n for i,rawTree in enumerate(rawTrees):\n #Filter out trees without edge lengths\n if not hasEdgeLengths(rawTree):\n print(\"Warning tree \" + str(i) + \" has no edge lengths, skipping\")\n continue\n\n try:\n rawTree = normalize(rawTree)\n\n tree = create(rawTree.seed_node)\n tree.label = rawTree.label\n\n fixZeroLengthEdges(tree)\n except:\n print(\"Warning tree \" + str(i) + \" ran into an error, skipping\")\n continue\n\n trees.append(tree)\n\n return trees\n\n\ndef cleanFile(path, schema, outputPath):\n\n def unclean(tree):\n if not hasEdgeLengths(tree):\n return False\n\n #large degree nodes?\n maxDegreeNode = max(tree, key = lambda node : len(node.child_nodes()))\n\n #print(\"Max degree: \" + str(len(maxDegreeNode.child_nodes())) )\n\n if len(maxDegreeNode.child_nodes()) > 3:\n print(\"Removing tree maxDegree = \" + str(len(maxDegreeNode.child_nodes())))\n return False\n\n #if len(tree.nodes()) > 50 or len(tree.nodes()) < 41:\n # return False\n\n return True\n\n\n try:\n inputTrees = dendropy.TreeList.get(path=path, schema=schema, suppress_internal_node_taxa=True, suppress_leaf_node_taxa=True)\n except Exception as ex:\n print(ex)\n print(\"Tip: When downloading trees from TreeBase:\\n\\tSome trees may be missing a semi-colon(;) at the end of their definiton.\\n\\tOr have an empty definition.\\n\\tCheck your tree file.\")\n return\n\n print(\"Read in \" + str(len(inputTrees)) + \" trees\\nCleaning...\")\n\n trees = dendropy.TreeList(filter(unclean, [dendropy.Tree(t) for t in inputTrees]))\n\n trees.purge_taxon_namespace()\n\n print(\"Writing \" + str(len(trees)) + \" trees\")\n\n sizes = [len(t.nodes()) for t in trees]\n maxN = max(sizes)\n minN = min(sizes)\n avgN = sum(sizes) / len(trees)\n\n print(\"\\tMax: \" + str(maxN) + \"\\n\\tMin: \" + str(minN) + \"\\n\\tAvg: \" + str(avgN))\n\n trees.write(path=outputPath, schema=schema)\n\ndef main():\n print(\"Welcome to the reader utility\")\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"inputPath\", help =\"Path to file with trees\")\n parser.add_argument(\"schema\" , help = 'Schema of input file (\"newick\", \"nexus\", \"nexml\")')\n parser.add_argument(\"outputPath\", help =\"Path to output path with cleaned trees\")\n\n args = parser.parse_args()\n\n print(\"Welcome to the reader utility\")\n cleanFile(args.inputPath, args.schema, args.outputPath)\n\nif __name__ == \"__main__\":\n main()\n\n#trees = readTrees(\"Trees/50TaxaTrees.nex\", \"nexus\")\n\n#tree = read(\"Trees/T72324.nex\", \"nexus\")\n#\n#tree.printMe(0)\n#\n#embedTree(tree)\n#\n#tree.printMe(0)\n","sub_path":"readTree.py","file_name":"readTree.py","file_ext":"py","file_size_in_byte":4337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"209576034","text":"'''\nWrite a program to find the node at which the intersection of two singly linked lists begins.\n\nFor example, the following two linked lists:\n A: a1 → a2\n ↘\n c1 → c2 → c3\n ↗\n B: b1 → b2 → b3\nbegin to intersect at node c1.\n\nNotes:\n If the two linked lists have no intersection at all, return null.\n The linked lists must retain their original structure after the function returns.\n You may assume there are no cycles anywhere in the entire linked structure.\n Your code should preferably run in O(n) time and use only O(1) memory.\n'''\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param two ListNodes\n # @return the intersected ListNode\n\n # If one of them reaches the end earlier then reuse it\n # by moving it to the beginning of other list.\n # Once both of them go through reassigning,\n # they will be equidistant from the collision point.\n\n def getIntersectionNode(self, headA, headB):\n # define two pointers starting moving at head of each LL\n currNodeA = headA\n currNodeB = headB\n\n # while they do not meet(case of having intersection) or do not reach end together(case of not having intersection)\n while currNodeA != currNodeB:\n if currNodeA == None: # if currNodeA reaches listA's end, switch to listB's head\n currNodeA = headB\n else: # otherwise keep moving in listA\n currNodeA = currNodeA.next\n\n if currNodeB == None: # same operation for currNodeB\n currNodeB = headA\n else:\n currNodeB = currNodeB.next\n # when the while loop breaks, it's either both reach ends or an intersection occurs\n # they will either both pointing to the common node or pointing to Nones, it meets the requirements what we want\n return currNodeA\n\n # Note: currNodeA and currNodeB will eventualy meet or both poiting to Nones at the same time because:\n # currNodeA track: listA -> listB\n # currNodeB track listB -> listA\n # their total maximum travel distance (case of no intersection) will be len(listA+listB), and they both travel 1node/loop,\n # so they either meet together at intersection, or they both meet a lists' end at the same time\n","sub_path":"Python/160-IntersectionOfTwoLinkedLists.py","file_name":"160-IntersectionOfTwoLinkedLists.py","file_ext":"py","file_size_in_byte":2475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"289183506","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\nfrom __future__ import print_function, division\nfrom numpy.testing import assert_allclose\nimport numpy as np\nfrom astropy.table import Table\nfrom astropy.units import Quantity\nfrom astropy.tests.helper import pytest\nfrom ....datasets import load_atnf_sample\nfrom ...source import Pulsar, SimplePulsar\n\ntry:\n import scipy\n HAS_SCIPY = True\nexcept ImportError:\n HAS_SCIPY = False\n\npulsar = Pulsar()\nt = Quantity([1E2, 1E4, 1E6, 1E8], 'yr')\n\n\ndef test_SimplePulsar_atnf():\n \"\"\"Test functions against ATNF pulsar catalog values\"\"\"\n atnf = load_atnf_sample()\n P = Quantity(atnf['P0'], 's')\n P_dot = Quantity(atnf['P1'], '')\n simple_pulsar = SimplePulsar(P=P, P_dot=P_dot)\n assert_allclose(simple_pulsar.tau.to('yr'), atnf['AGE'], rtol=0.01)\n assert_allclose(simple_pulsar.luminosity_spindown.to('erg s^-1'), atnf['EDOT'], rtol=0.01)\n assert_allclose(simple_pulsar.magnetic_field.to('gauss'), atnf['BSURF'], rtol=0.01)\n\n\ndef test_Pulsar_period():\n \"\"\"Test pulsar period\"\"\"\n reference = [0.10000001, 0.10000123, 0.10012331, 0.11270709]\n assert_allclose(pulsar.period(t), reference)\n\n\ndef test_Pulsar_peridod_dot():\n \"\"\"Test pulsar period derivative\"\"\"\n reference = [9.76562380e-19, 9.76550462e-19, 9.75359785e-19, 8.66460603e-19]\n assert_allclose(pulsar.period_dot(t), reference)\n\n\ndef test_Pulsar_luminosity_spindown():\n \"\"\"Test pulsar spin down luminosity\"\"\"\n reference = [3.85531469e+31, 3.85536174e+31, 3.86006820e+31, 4.34521233e+31]\n assert_allclose(pulsar.luminosity_spindown(t), reference)\n\n\n@pytest.mark.skipif('not HAS_SCIPY')\ndef test_Pulsar_energy_integrated():\n \"\"\"Test against numerical integration\"\"\"\n energies = []\n from scipy.integrate import quad\n\n def lumi(t):\n t = Quantity(t, 's')\n return pulsar.luminosity_spindown(t).value\n\n for t_ in t:\n energy = quad(lumi, 0, t_.cgs.value, epsrel=0.01)[0]\n energies.append(energy)\n # The last value is quite inaccurate, because integration is over\n # several decades\n assert_allclose(energies, pulsar.energy_integrated(t), rtol=0.2)\n\n\ndef test_Pulsar_magnetic_field():\n \"\"\"Test against numerical integration\"\"\"\n reference = np.ones_like(t) * 10 ** pulsar.logB\n assert_allclose(pulsar.magnetic_field(t), reference)\n","sub_path":"gammapy/astro/source/tests/test_pulsar.py","file_name":"test_pulsar.py","file_ext":"py","file_size_in_byte":2351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"114634379","text":"from pyrogram import Client, filters\nfrom pyrogram.errors import FirstnameInvalid, FloodWait, UsernameInvalid, UsernameNotModified, UsernameOccupied\nfrom pyrogram.types import Message\n\nfrom app.utils import clean_up, get_args, quote_html\n\n\n@Client.on_message(filters.me & filters.command(\"stats\", prefixes=\".\"))\nasync def stats(client: Client, message: Message):\n \"\"\"\n Gather profile stats containing chats info to share it to anyone.\n \"\"\"\n await message.edit_text(\"Gathering info...\")\n user_list = []\n peak_unread_chat = None\n total_chats = channels = privates = groups = pinned = unread = peak_unread_count = bots = 0\n async for dialog in client.iter_dialogs():\n total_chats += 1\n if dialog.is_pinned:\n pinned += 1\n if dialog.unread_messages_count > 0:\n unread += 1\n if dialog.unread_messages_count > peak_unread_count:\n peak_unread_count = dialog.unread_messages_count\n peak_unread_chat = dialog.chat.title\n\n if dialog.chat.type == \"channel\":\n channels += 1\n elif dialog.chat.type in (\"group\", \"supergroup\"):\n groups += 1\n else:\n privates += 1\n user_list.append(dialog.chat.id)\n\n full_users = await client.get_users(user_list)\n for user in full_users:\n if user.is_bot:\n bots += 1\n\n contacts = await client.get_contacts_count()\n if peak_unread_chat:\n unread_data = f\"{peak_unread_count} in {quote_html(peak_unread_chat)}\"\n else:\n unread_data = f\"{peak_unread_count}\"\n\n await message.edit_text(\n f\"Total chats: {total_chats}\\nPinned: {pinned}\\nUnread: {unread}\\n\"\n f\"Channels: {channels}\\nPrivates: {privates}\\nBots: {bots}\\nGroups: {groups}\"\n f\"\\n\\nTelegram contacts: {contacts}\\nPeak value of unread per chat: {unread_data}\"\n )\n await clean_up(client, message.chat.id, message.message_id, clear_after=20)\n\n\n@Client.on_message(filters.me & filters.command(\"name\", prefixes=\".\"))\nasync def name(client: Client, message: Message):\n \"\"\"\n Change profile name, this command is flexible and has an auto-balancer for long names.\n \"\"\"\n args = get_args(message.text or message.caption, maximum=0)\n if not args:\n await message.edit_text(\"Pass your new name.\\n.name I'm a superman!\")\n else:\n if len(args) == 1:\n first_name = args[0][:64]\n last_name = \"\"\n elif len(args) == 2:\n first_name = args[0][:64]\n last_name = args[1][:64]\n else: # A quite complex name specified, so we have to balance it a little\n divider = len(args) // 2\n first_name = \" \".join(args[:divider])[:64]\n last_name = \" \".join(args[divider:])[:64]\n\n try:\n await client.update_profile(first_name=first_name, last_name=last_name)\n result = f\"{first_name} {last_name}\" if last_name else first_name\n await message.edit_text(f\"Your name's been changed to:\\n{quote_html(result)}\")\n except FirstnameInvalid:\n await message.edit_text(\"Your new first name is invalid.\")\n except FloodWait as ex:\n await message.edit_text(f\"FloodWait, retry in {ex.x} seconds.\")\n\n await clean_up(client, message.chat.id, message.message_id)\n\n\n@Client.on_message(filters.me & filters.command(\"username\", prefixes=\".\"))\nasync def username(client: Client, message: Message):\n \"\"\"\n Change profile username. Supports \"del\" argument to delete the current username if there is one.\n \"\"\"\n new_username = get_args(message.text or message.caption, maximum=1).lstrip(\"@\")\n if not new_username:\n await message.edit_text(\"Pass your new username.\\n.username del to delete it.\")\n else:\n if new_username == \"del\":\n new_username = None\n text = \"Your username's been deleted.\"\n else:\n text = f\"Your username's been changed to:\\n@{quote_html(new_username)}\"\n\n try:\n await client.update_username(new_username)\n await message.edit_text(text)\n except UsernameNotModified:\n await message.edit_text(\"This username is not different from the current one.\")\n except UsernameOccupied:\n await message.edit_text(\"This username is already taken.\")\n except UsernameInvalid:\n if len(new_username) > 32:\n await message.edit_text(\"This username is too long.\")\n else:\n await message.edit_text(\"This username is invalid.\")\n except FloodWait as ex:\n await message.edit_text(f\"FloodWait, retry in {ex.x} seconds.\")\n\n await clean_up(client, message.chat.id, message.message_id)\n\n\n@Client.on_message(filters.me & filters.command([\"bio\", \"about\"], prefixes=\".\"))\nasync def bio(client: Client, message: Message):\n \"\"\"\n Change about info block. Supports \"del\" argument to clear the current bio.\n \"\"\"\n args = get_args(message.text or message.caption, maximum=1)\n if not args:\n await message.edit_text(\"Pass your new about info.\\n.bio del to delete it.\")\n else:\n if args == \"del\":\n args = \"\"\n text = \"Your bio's been deleted.\"\n else:\n text = f\"Your bio's been updated to:\\n{quote_html(args[:70])}\"\n\n try:\n await client.update_profile(bio=args[:70]) # Max bio length is 70 chars\n await message.edit_text(text)\n except FloodWait as ex:\n await message.edit_text(f\"FloodWait, retry in {ex.x} seconds.\")\n\n await clean_up(client, message.chat.id, message.message_id)\n","sub_path":"app/plugins/userdata.py","file_name":"userdata.py","file_ext":"py","file_size_in_byte":5868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"90438889","text":"# coding=utf-8\nimport random\nimport unittest\nfrom framework.logger import Logger\nfrom framework.browser_engine import BrowserEngine\nfrom fky_common.login import Login\nfrom fky_common.logout import Logout\nfrom fky_pageobjects.financialPayment import FinancialPayment\n\nlogger = Logger(logger=\"Payment\").getlog()\n\n\nclass Payment(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n browser = BrowserEngine(cls)\n cls.driver = browser.open_browser(cls)\n # 登录\n login = Login()\n login.log_in(cls)\n cwzf = FinancialPayment(cls.driver)\n cwzf.into_cwzf()\n\n @classmethod\n def tearDownClass(cls):\n # 登出\n logout = Logout()\n logout.log_out(cls)\n cls.driver.quit()\n\n # 收款人-查询\n def test01_query_sker(self):\n cwzf = FinancialPayment(self.driver)\n cwzf.click_zhankai()\n n = random.randint(1, len(cwzf.get_sker_list())) - 1\n sker_n = cwzf.get_sker_list()[n]\n cwzf.input_query_sker(sker_n)\n cwzf.click_query()\n if cwzf.get_data():\n sker_list = cwzf.get_sker_list()\n for sker in sker_list:\n self.assertIn(sker_n, sker, \"通过收款人查询财务支付单据失败!\")\n logger.info(\"通过收款人查询财务支付单据成功!\")\n else:\n self.assertEqual(['单据编号',\n '单据类型',\n '应付金额',\n '已支付金额',\n '未支付金额',\n '申请部门',\n '申请人',\n '创建日期',\n '收款人'],\n cwzf.get_biaotou(),\n \"通过单据类型查询财务支付单据失败!\")\n cwzf.click_clear()\n\n # 单据类型-查询\n def test02_query_type(self):\n cwzf = FinancialPayment(self.driver)\n cwzf.click_zhankai()\n n = random.randint(1, len(cwzf.get_dj_type())) - 1\n type_n = cwzf.get_dj_type()[n]\n cwzf.select_query_type(\"社保缴纳单\")\n cwzf.click_query()\n if cwzf.get_data():\n self.assertEqual(\"社保缴纳单\", cwzf.get_dj_type()[0], \"通过单据类型查询财务支付单据失败!\")\n logger.info(\"通过单据类型查询财务支付单据成功!\")\n print(cwzf.get_biaotou())\n else:\n self.assertEqual(['单据编号',\n '单据类型',\n '应付金额',\n '已支付金额',\n '未支付金额',\n '申请部门',\n '申请人',\n '创建日期',\n '收款人'],\n cwzf.get_biaotou(),\n \"通过单据类型查询财务支付单据失败!\")\n # 获取列表数据时出现问题无法解决\n # type_list = cwzf.get_dj_type()\n # for type in type_list:\n # self.assertEqual(\"社保缴纳单\", type, \"通过单据类型查询财务支付单据失败!\")\n # logger.info(\"通过单据类型查询财务支付单据成功!\")\n cwzf.click_clear()\n\n def test03_query_sqr(self):\n cwzf = FinancialPayment(self.driver)\n cwzf.click_zhankai()\n n = random.randint(1, len(cwzf.get_sqr())) - 1\n print(cwzf.get_sqr())\n sqr_n = cwzf.get_sqr()[n]\n cwzf.input_query_sqr(sqr_n)\n cwzf.click_query()\n if cwzf.get_data():\n sker_list = cwzf.get_sqr()\n for sqr in sker_list:\n self.assertIn(sqr_n, sqr, \"通过申请人查询财务支付单据失败!\")\n logger.info(\"通过申请人查询财务支付单据成功!\")\n else:\n self.assertEqual(['单据编号',\n '单据类型',\n '应付金额',\n '已支付金额',\n '未支付金额',\n '申请部门',\n '申请人',\n '创建日期',\n '收款人'],\n cwzf.get_biaotou(),\n \"通过申请人查询财务支付单据失败!\")\n cwzf.click_clear()\n\n \"\"\"\n def test04_query_sqbm(self):\n cwzf = FinancialPayment(self.driver)\n cwzf.click_zhankai()\n n = random.randint(1, len(cwzf.get_sqbm())) - 1\n sqbm_n = cwzf.get_sqbm()[n]\n cwzf.input_query_sqbm(sqbm_n)\n cwzf.click_query()\n if cwzf.get_data():\n sqbm_list = cwzf.get_sqbm()\n for sqbm in sqbm_list:\n self.assertIn(sqbm_n, sqbm, \"通过申请部门查询财务支付单据失败!\")\n logger.info(\"通过申请部门查询财务支付单据成功!\")\n else:\n self.assertEqual(['单据编号',\n '单据类型',\n '应付金额',\n '已支付金额',\n '未支付金额',\n '申请部门',\n '申请人',\n '创建日期',\n '收款人'],\n cwzf.get_biaotou(),\n \"通过申请部门查询财务支付单据失败!\")\n cwzf.click_clear()\n \"\"\"\n\n # 导出\n def test04_export(self):\n cwzf = FinancialPayment(self.driver)\n cwzf.click_export()\n cwzf.click_queding()\n name_list = cwzf.file_name(r\"C:\\\\Users\\Kejie\\Downloads\")\n self.assertIn(\"财务支付待付款信息.xls\", name_list, \"财务支付待付款信息导出失败!\")\n logger.info(\"财务支付待付款信息导出成功!\")\n cwzf.remover_file(\"财务支付待付款信息\")\n cwzf.wait(1)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"fky_testsuits/test26_financial_payment.py","file_name":"test26_financial_payment.py","file_ext":"py","file_size_in_byte":6240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"307299223","text":"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Runs a ResNet model on the ImageNet dataset.\"\"\"\n\nfrom typing import Dict\n\nimport tensorflow as tf\n\nfrom nninst.backend.tensorflow.model import resnet\n\n_DEFAULT_IMAGE_SIZE = 32\n_NUM_CHANNELS = 3\n_NUM_CLASSES = 10\n\n_NUM_IMAGES = {\"train\": 50000, \"validation\": 10000}\n\n\n###############################################################################\n# Running the model\n###############################################################################\nclass CifarModel(resnet.Model):\n def __init__(\n self,\n resnet_size,\n data_format=None,\n num_classes=_NUM_CLASSES,\n version=resnet.DEFAULT_VERSION,\n gated=False,\n with_gates: bool = True,\n ):\n \"\"\"These are the parameters that work for Imagenet data.\n\n Args:\n resnet_size: The number of convolutional layers needed in the model.\n data_format: Either 'channels_first' or 'channels_last', specifying which\n data format to use when setting up the model.\n num_classes: The number of output classes needed from the model. This\n enables users to extend the same model to their own datasets.\n version: Integer representing which version of the ResNet network to use.\n See README for details. Valid values: [1, 2]\n \"\"\"\n\n # For bigger models, we want to use \"bottleneck\" layers\n if resnet_size < 50:\n bottleneck = False\n final_size = 512\n else:\n bottleneck = True\n final_size = 2048\n\n super(CifarModel, self).__init__(\n resnet_size=resnet_size,\n bottleneck=bottleneck,\n num_classes=num_classes,\n num_filters=64,\n kernel_size=3,\n conv_stride=1,\n first_pool_size=None,\n first_pool_stride=None,\n second_pool_size=4,\n second_pool_stride=1,\n block_sizes=_get_block_sizes(resnet_size),\n block_strides=[1, 2, 2, 2],\n final_size=final_size,\n version=version,\n data_format=data_format,\n gated=gated,\n with_gates=with_gates,\n )\n\n def __call__(\n self,\n inputs,\n training=False,\n gate_variables: Dict[str, tf.Variable] = None,\n batch_size: int = 1,\n ):\n return super().__call__(inputs, training, gate_variables)\n\n\ndef _get_block_sizes(resnet_size):\n \"\"\"The number of block layers used for the Resnet model varies according\n to the size of the model. This helper grabs the layer set we want, throwing\n an error if a non-standard size has been selected.\n \"\"\"\n choices = {\n 18: [2, 2, 2, 2],\n 34: [3, 4, 6, 3],\n 50: [3, 4, 6, 3],\n 101: [3, 4, 23, 3],\n 152: [3, 8, 36, 3],\n 200: [3, 24, 36, 3],\n }\n\n try:\n return choices[resnet_size]\n except KeyError:\n err = (\n \"Could not find layers for selected Resnet size.\\n\"\n \"Size received: {}; sizes allowed: {}.\".format(resnet_size, choices.keys())\n )\n raise ValueError(err)\n","sub_path":"src/nninst/backend/tensorflow/model/resnet_cifar.py","file_name":"resnet_cifar.py","file_ext":"py","file_size_in_byte":3804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"485154306","text":"from ..core import Core\nfrom ..utils.exchangeversion import ExchangeVersion\n\n\nclass ResolveNames(Core):\n '''Resolve names based on the provided UserConfiguration object.\n \n This class is used as an alternative to Autodiscover since ResolveNames endpoint\n is a common endpoint across all versions of Microsoft Exchange & Office 365.\n \n Examples:\n \n To use any service class you must provide a UserConfiguration object first.\n Like all service classes, you can access formatted properties from the EWS endpoint using the `response` property.\n \n By passing in a UserConfiguration object we can \n \n ```python\n userConfig = UserConfiguration(\n 'first.last@company.com',\n 'mypassword123'\n )\n print(ResolveNames(userConfig))\n ```\n\n Args:\n userconfiguration (UserConfiguration): A UserConfiguration object created using the UserConfiguration class\n '''\n def __init__(self, userconfiguration):\n super(ResolveNames, self).__init__(userconfiguration)\n\n def __parse_response(self, value):\n '''Creates and sets a response object\n\n Args:\n value (str): The raw response from a SOAP request\n '''\n return_dict = {}\n if value.find('ResolveNamesResponse'):\n temp = value.find('ServerVersionInfo')\n return_dict['server_version_info'] = temp\n ver = \"{major}.{minor}\".format(\n major=temp['MajorVersion'],\n minor=temp['MinorVersion']\n )\n self.exchange_version = ExchangeVersion(ver).exchangeVersion\n for item in value.find('ResolutionSet'):\n if item.find('Mailbox'):\n for i in item.find('Mailbox'):\n return_dict[self.camel_to_snake(i.name)] = i.string\n if item.find('Contact'):\n for i in item.find('Contact').descendants:\n if i.name == 'Entry' and i.string:\n return_dict[self.camel_to_snake(i.name)] = i.string\n else:\n if i.name and i.string:\n return_dict[self.camel_to_snake(i.name)] = i.string\n return return_dict\n\n def run(self):\n self.raw_xml = self.invoke(self.soap())\n return self.__parse_response(self.raw_xml)\n\n def soap(self):\n '''Creates the SOAP XML message body\n\n Returns:\n str: Returns the SOAP XML request body\n '''\n return '''\n\n\n \n \n \n \n {email}\n \n \n\n '''.format(\n version=self.userconfiguration.exchange_version, \n email=self.userconfiguration.credentials.email_address)\n","sub_path":"pyews/service/resolvenames.py","file_name":"resolvenames.py","file_ext":"py","file_size_in_byte":3397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"268110347","text":"import sys\nfrom collections import deque\nsys.stdin = open(\"1325_효율적인 해킹.txt\", \"rt\")\n\n\ndef solution(N, M, adj):\n def BFS(start):\n dq = deque()\n dq.append(start)\n visited = [False] * (N + 1)\n visited[start] = True\n while dq:\n curr = dq.popleft()\n for post in adj[curr]:\n if not visited[post]:\n visited[post] = True\n dq.append(post)\n return sum(visited)\n\n counts = [0] * (N + 1)\n for start in range(1, N + 1):\n counts[start] = BFS(start)\n\n max_cnt = max(counts)\n for i in range(1, N + 1):\n if counts[i] == max_cnt:\n print(i, end=\" \")\n\n\nif __name__ == \"__main__\":\n input = sys.stdin.readline\n N, M = map(int, input().split())\n adj = {i: [] for i in range(1, N+1)}\n for _ in range(M):\n s, e = map(int, input().split())\n adj[e].append(s)\n\n solution(N, M, adj)\n","sub_path":"BaekJoon/분류 안 된 문제들/BFS/1325_효율적인 해킹.py","file_name":"1325_효율적인 해킹.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"408657212","text":"\"\"\"\n------------------------------------\n@Time : 2019/11/13 10:00\n@Auth : wangfei\n@File : logfile.py\n@IDE : PyCharm\n@Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error!\n------------------------------------\n\"\"\"\nimport logging\nimport os\nimport platform\nfrom os import path\n\n\nclass Log(object):\n def __init__(self, name=__name__, path='{}.log'.format(os.path.split(__file__)[-1].split(\".\")[0]), level='ERROR'):\n print(path)\n self.__name = name\n self.__path = path\n if platform.system() == 'Windows':\n log_path = '\\\\'.join(path.split('\\\\')[0:-1])\n else:\n log_path = '/'.join(path.split('/')[0:-1])\n if not os.path.exists(log_path):\n os.makedirs(log_path)\n self.__level = level\n self.__logger = logging.getLogger(self.__name)\n self.__logger.setLevel(self.__level)\n\n def __ini_handler(self):\n \"\"\"初始化handler\"\"\"\n stream_handler = logging.StreamHandler()\n file_handler = logging.FileHandler(self.__path, encoding='utf-8')\n return stream_handler, file_handler\n\n def __set_handler(self, stream_handler, file_handler, level='DEBUG'):\n \"\"\"设置handler级别并添加到logger收集器\"\"\"\n stream_handler.setLevel(level)\n file_handler.setLevel(level)\n self.__logger.addHandler(stream_handler)\n self.__logger.addHandler(file_handler)\n\n def __set_formatter(self, stream_handler, file_handler):\n \"\"\"设置日志输出格式\"\"\"\n formatter = logging.Formatter('[%(asctime)s] [%(name)s] [%(filename)s] [line:%(lineno)d]'\n '[%(levelname)s]: %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S')\n stream_handler.setFormatter(formatter)\n file_handler.setFormatter(formatter)\n\n def __close_handler(self, stream_handler, file_handler):\n \"\"\"关闭handler\"\"\"\n stream_handler.close()\n file_handler.close()\n\n @property\n def Logger(self):\n \"\"\"构造收集器,返回looger\"\"\"\n stream_handler, file_handler = self.__ini_handler()\n self.__set_handler(stream_handler, file_handler)\n self.__set_formatter(stream_handler, file_handler)\n self.__close_handler(stream_handler, file_handler)\n return self.__logger\n\n\nif __name__ == '__main__':\n log_path = os.path.join(os.path.abspath(os.path.dirname(os.getcwd()) + os.path.sep), 'log')\n log = Log(path=log_path + '/log' + '/' + os.path.split(__file__)[-1].split(\".\")[0] + r\".log\")\n logger = log.Logger\n logger.debug('I am a debug message')\n logger.info('I am a info message')\n logger.warning('I am a warning message')\n logger.error('I am a error message')\n logger.critical('I am a critical message')\n","sub_path":"loggtaas/loggtaas.py","file_name":"loggtaas.py","file_ext":"py","file_size_in_byte":2811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"367122590","text":"# author: nvx\n# created: 2021.03.01 21:29:08\n# \n# Простая структура данных; почти как\n# словарь, только обращаться к полям\n# через точку\n#\n\nclass sct:\n\tdef __init__(self, **kargs):\n\t\tfor key, value in kargs.items():\n\t\t\tself.__dict__[key] = value\n\t\treturn\n\n\tdef __str__(self):\n\t\treturn '{' + ', '.join( self._extract(val) for val in self.__dict__.values() ) + '}'\n\n\tdef __repr__(self):\n\t\treturn '<' + ', '.join(\n\t\t\t'%s=%s' % (str(key), self._extract(value))\n\t\t\tfor key, value in self.__dict__.items()\n\t\t) + '>'\n\n\tdef __getitem__(self, key):\n\t\tpoint = key.find('.')\n\t\tif point < 0: \n\t\t\treturn self.__dict__[key]\n\t\tpkey = key[:point]\n\t\treturn self.__dict__[pkey][key[point+1:]]\n\n\tdef __setitem__(self, key, value):\n\t\tpoint = key.find('.')\n\t\tif point < 0:\n\t\t\tself.__dict__[key] = value\n\t\t\treturn\n\t\tpkey = key[:point]\n\t\tif pkey not in self.__dict__:\n\t\t\tself.__dict__[pkey] = sct()\n\t\tself.__dict__[pkey][key[point+1:]] = value\n\t\treturn\n\n\tdef __iter__(self):\n\t\tfor item in self.__dict__.items():\n\t\t\tyield item\n\n\tdef pretty(self, tab='', name='sct'):\n\t\tlength = max(list(map(\n\t\t\tlambda s: len(s),\n\t\t\tfilter(\n\t\t\t\tlambda key: not isinstance(self.__dict__[key], sct),\n\t\t\t\tself.__dict__.keys()\n\t\t\t)\n\t\t)) + [0])\n\t\ts = tab + name + ':\\n'\n\t\ttab += ' '\n\t\tfor key in self.__dict__.keys():\n\t\t\tobj = self.__dict__[key]\n\t\t\tif isinstance(obj, sct):\n\t\t\t\ts += obj.pretty(tab, name=key)\n\t\t\telse:\n\t\t\t\ts += (\n\t\t\t\t\ttab + (key + (length - len(key))*' ') + ' : ' +\n\t\t\t\t\tself._extract(self.__dict__[key]) + '\\n'\n\t\t\t\t)\n\t\treturn s\n\n\n\t@staticmethod\n\tdef _extract(val):\n\t\tif isinstance(val, str):\n\t\t\treturn \"'\" + val + \"'\"\n\t\treturn str(val)\n\n\n\n\n\n# END\n","sub_path":"agario/nvxsct.py","file_name":"nvxsct.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"558866995","text":"''' взять матрицу произвольную разделить на 4 ровные части и покрутить \n\tэти части 3 раза против часовой стрелки меняя их местами'''\n\nfrom functions.print_matrix import print_matrix\nfrom functions.generate_matrix import generate_matrix\nfrom functions.zero_matrix import zero_matrix\n\n\ndef rotate_matrix(matrix, dimension):\n\tnew_matrix = zero_matrix(dimension, dimension)\n\tfor x in range(len(matrix)):\n\t\tfor y in range(len(matrix)):\n\t\t\tnew_matrix[x][y] = matrix[y][::-1][x]\n\tmatrix = new_matrix\n\treturn matrix\n\t\n\ndef cut_matrix(matrix):\n\tcentre = len(matrix) // 2\n\tresult = [[] for x in range(4)]\n\tfor i in range(len(matrix)):\n\t\tfor j in range(len(matrix)):\n\t\t\tif i > centre -1:\n\t\t\t\tif j > centre -1:\n\t\t\t\t\tresult[3].append(matrix[i][j])\n\t\t\t\telse: \n\t\t\t\t\tresult[2].append(matrix[i][j])\n\t\t\telse:\n\t\t\t\tif j > centre -1:\n\t\t\t\t\tresult[1].append(matrix[i][j])\n\t\t\t\telse:\n\t\t\t\t\tresult[0].append(matrix[i][j])\t\t\t\n\treturn result\n\t\t\n\ndef create_matrix(arr, dimension):\n\tmatrix = [[] for x in range(dimension)]\n\tj = 0\n\tfor i in range(len(arr)):\n\t\tif i % dimension == 0 and i != 0:\n\t\t\tj += 1\n\t\tmatrix[j].append(arr[i])\t\n\treturn matrix\t\n\n\ndef main():\n\tdimension = int(input('Dimension: '))\n\tmatrix = generate_matrix(1, 10, dimension, dimension)\n\tprint_matrix(matrix)\n\tsquares = cut_matrix(matrix)\n\tmatr_arr = [create_matrix(x, dimension//2) for x in squares]\n\tmatr = None\n\tfor y in range(len(matr_arr)):\n\t\tfor x in range(4):\t\n\t\t\tif x == 0:\n\t\t\t\tmatr = \tmatr_arr[y]\n\t\t\t\tprint_matrix(matr, text='Square №{} before rotation'.format(y+1))\n\t\t\telse:\t\n\t\t\t\tmatr = rotate_matrix(matr, dimension//2)\n\t\t\t\tprint_matrix(matr, text='Square №{} after rotation №{}'.format(y+1, x))\n\t\tprint('\\n')\t\t\n\n\n\nif __name__ == '__main__':\n\tmain()\t","sub_path":"task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"287708663","text":"\"\"\"\nLC490 The maze\nThere is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.\n\nGiven the ball's start position, the destination and the maze, determine whether the ball could stop at the destination.\n\nThe maze is represented by a binary 2D array. 1 means the wall and 0 means the empty space. You may assume that the borders of the maze are all walls. The start and destination coordinates are represented by row and column indexes.\n\"\"\"\n\n\n# dfs\n# Runtime: 336 ms, faster than 56.66% of Python3 online submissions for The Maze.\n# Memory Usage: 15.8 MB, less than 7.69% of Python3 online submissions for The Maze.\nclass Solution:\n def hasPath(self, maze, start, destination) -> bool:\n # using dfs\n if len(maze) == 0:\n return False\n visited = set()\n n_row = len(maze)\n n_col = len(maze[0])\n \n def dfs(start_loc):\n x, y = start_loc\n visited.add((x, y))\n reachable = []\n for i in range(y+1, n_col):\n if (x, i) in visited:\n continue\n if maze[x][i] == 1:\n break\n if (i == n_col - 1) or maze[x][i+1] == 1:\n reachable.append([x, i])\n for i in range(y-1, -1, -1):\n if (x, i) in visited:\n continue\n if maze[x][i] == 1:\n break\n if (i == 0) or maze[x][i-1] == 1:\n reachable.append([x, i])\n \n for j in range(x+1, n_row):\n if (j, y) in visited:\n continue\n if maze[j][y] == 1:\n break\n if (j == n_row - 1) or maze[j+1][y] == 1:\n reachable.append([j, y])\n for j in range(x-1, -1, -1):\n if (j, y) in visited:\n continue\n if maze[j][y] == 1:\n break\n if (j == 0) or maze[j-1][y] == 1:\n reachable.append([j, y])\n if len(reachable) == 0:\n return False\n if destination in reachable:\n return True\n for loc in reachable:\n if dfs(loc):\n return True\n return False\n \n return dfs(start)\n \n\n\n\n\n","sub_path":"Widen/LC490_the_maze.py","file_name":"LC490_the_maze.py","file_ext":"py","file_size_in_byte":2528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"117277217","text":"import pymongo\r\n#import dns\r\n\r\n# you will need to change this connection string to match your own instance\r\n#client = pymongo.MongoClient(\"Get this from Atlas and change to your password (and remove the <>)\")\r\n#client = pymongo.MongoClient(\"mongodb+srv://Mansee:deargeo@clustersmp-s6rtd.azure.mongodb.net/test?retryWrites=true&w=majority\")\r\n#client = pymongo.MongoClient(\"mongodb+srv://Mansee:deargeo@clustersmp-s6rtd.azure.mongodb.net/test?retryWrites=true&w=majority\")\r\n#clustersmp-shard-00-01-s6rtd.azure.mongodb.net:27017\r\n#client = pymongo.MongoClient2822mongodb2Bsrv3A2F2FManseedeareo40clustersmp2Dshard2D002D012Ds6rtd2Eazure2Emongodb2Enet2229\r\nclient =pymongo.MongoClient2822mongodb2Bsrv3A2F2FMansee60deargeo40clustersmp2Ds6rtd2Dazure2Emongodb2Enet2Ftest3FretryWrites3Dtrue&w3Dmajority2229\r\n#client =pymongo.MongoClient(\"mongodb+srv://mansee:deargeo@clustersmp-s6rtd.azure.mongodb.net/test?retryWrites=true&w=majority\")\r\n# remember that if you have special characters in your password, you need to \"escape\" them\r\n# or import and use urllib.parse.quote_plus\r\n# More info: https://pymongo.readthedocs.io/en/stable/examples/authentication.html\r\n# Ascii codes: https://ascii.cl/\r\n\r\nmydb = client[\"sample_airbnb\"]\r\nmycollection = mydb[\"listingsAndReviews\"]\r\n\r\n# this finds and returns the first document with the field \"name\" equal to \"White House\"\r\nmydocument = mycollection.find_one({\"name\":\"White House\"})\r\nprint(mydocument)","sub_path":"ClientConnection.py","file_name":"ClientConnection.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"582269056","text":"ZONE_FONT_SIZE = 26\nTEMPERATURE_FONT_SIZE = 16\nTIME_FONT_SIZE = 58\nLONG_DATE_FONT_SIZE = 16\nSHORT_DATE_FONT_SIZE = 14\nICON_SIZE = 100\n\nWEATHER_API = \"fa9c8f3fd20a97c87395fab36bf09a47\"\nTIME_FORMAT = \"%H:%M:%S\"\nLONG_DATE_FORMAT = \"%A %d %B %Y\"\nSHORT_DATE_FORMAT = \"%d/%m/%y\"\nWEATHER_UPDATE_INTERVAL = 60\nDEFAULT_DATA_VALUE = \"\"\nZONE_CODE_FORMAT = \"%Z\"\nESCAPE_KEY = 16777216\n\nFONT_LOCATION = \"Roboto-Medium.ttf\"\n","sub_path":"Constants.py","file_name":"Constants.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"592728318","text":"DATASET_NAME = 'pascal'\nPIXEL_MEAN = 0\nTRAIN_RPN_CLOOBER_POSITIVES = False\nRPN_IOU_POSITIVE_THRESHOLD = 0.7\nRPN_IOU_NEGATIVE_THRESHOLD = 0.3\nRPN_MINIBATCH_SIZE = 256\nRPN_POSITIVE_RATE = 0.5\nANCHOR_SCALE_FACTORS = None\n\nFAST_RCNN_MINIBATCH_SIZE = 256\nADD_GTBOXES_TO_TRAIN = False\nFAST_RCNN_POSITIVE_RATE = 0.25\nCLASS_NUM = 20\nROI_SCALE_FACTORS = [10., 10., 5.0, 5.0]\nFAST_RCNN_IOU_POSITIVE_THRESHOLD = 0.5\nFAST_RCNN_IOU_NEGATIVE_THRESHOLD = 0.0 # 0.1 < IOU < 0.5 is negative\n\nRPN_SIGMA = 3.0\nRPN_CLASSIFICATION_LOSS_WEIGHT = 1.0\nRPN_LOCATION_LOSS_WEIGHT = 1.\nFAST_RCNN_MINIBATCH_SIZE = 256 # if is -1, that is train with OHEM\nFASTRCNN_SIGMA = 1.0\n\nFAST_RCNN_LOCATION_LOSS_WEIGHT = 1.0\nFAST_RCNN_CLASSIFICATION_LOSS_WEIGHT = 1.0\n\nFAST_RCNN_NMS_MAX_BOXES_PER_CLASS = 100\nFAST_RCNN_NMS_IOU_THRESHOLD = 0.3 # 0.6\nSHOW_SCORE_THRSHOLD = 0.5 # only show in tensorboard\n\nADD_BOX_IN_TENSORBOARD=True\nDECAY_STEP = [50000, 70000] # 50000, 70000\n\nEPSILON = 1e-5\nMOMENTUM = 0.9\nLR = 0.001 # 0.001 # 0.0003\n\nMUTILPY_BIAS_GRADIENT = None # 2.0 # if None, will not multipy\nGRADIENT_CLIPPING_BY_NORM = None # 10.0 if None, will not clip\nMAX_ITERATION = 200000\n\nSHOW_TRAIN_INFO_INTE = 10\nSMRY_ITER = 100\nSAVE_WEIGHTS_INTE = 10000\n\nRESTORE_FROM_RPN = False\nPRETRAINED_CKPT = ''\n\nVERSION = 'FasterRCNN_20180517'\n\nPIXEL_MEAN=[123.68, 116.779, 103.939]\nBATCH_SIZE=1\nIMG_SHORT_SIDE_LEN = 600\nIMG_MAX_LENGTH = 1000","sub_path":"cfgs.py","file_name":"cfgs.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"110192329","text":"# coding: utf-8\nfrom deepvoice3_pytorch.frontend.text.symbols import symbols\n#import sys\n#import nltk\nfrom random import random\n\nn_vocab = len(symbols)\n\n#nltk.download('cmudict')\n_xsampa = {}\n_ipa = {}\nwith open(\"/lium/corpus/synthese/SynPaFlex-1.1/synpaflex-pronunciation-dictionary.txt\") as fdict:\n for line in fdict:\n tab = line.split(';')\n word = tab[0]\n if word in _xsampa:\n continue\n else:\n _xsampa[word] = tab[1]\n _ipa[word] = tab[2]\n\n\ndef _maybe_get_arpabet(word, p):\n try:\n phonemes = _xsampa[word]\n #phonemes = \" \".join(phonemes)\n except KeyError:\n return word\n\n return '{%s}' % phonemes if random() < p else word\n\ndef _dont_get_arpabet(word, phone, p):\n try:\n if phone == \"\\n\":\n phonemes = word\n else:\n phonemes = phone\n except KeyError:\n return word\n return '{%s}' % phonemes if random() < p else word\n #return phonemes if random() < p else word\n\ndef mix_pronunciation(text, phonetic, p):\n phones = list(phone for phone in phonetic.split('§'))\n text_new = ''\n i = 0\n for word in text.split(' '):\n text_new += _dont_get_arpabet(word, phones[i], p)\n text_new += ' '\n i += 1\n return text_new\n\ndef text_to_sequence(text, phonetic, p=0.0):\n\t# 'text' = WordJTrans\n\t# Called during train.py.\n if p >= 0:\n text = mix_pronunciation(text, phonetic, p)\n from deepvoice3_pytorch.frontend.text import text_to_sequence\n text = text_to_sequence(text, [\"french_cleaners\"])\n return text\n\ndef text_to_sequence_original(text, p):\n from deepvoice3_pytorch.frontend.text import text_to_sequence\n text = text_to_sequence(text, [\"french_cleaners\"])\n return text\nfrom deepvoice3_pytorch.frontend.text import sequence_to_text\n","sub_path":"deepvoice3_world/deepvoice3_pytorch/frontend/fr/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"501553572","text":"#!/usr/bin/python3\n\nfrom flask import Flask, render_template, url_for, redirect, request, g, jsonify, session\nfrom depicts import (utils, wdqs, commons, mediawiki, artwork, database,\n wd_catalog, human, wikibase, wikidata_oauth, wikidata_edit)\nfrom depicts.pager import Pagination, init_pager\nfrom depicts.model import (DepictsItem, DepictsItemAltLabel, Edit, ArtworkItem,\n Language, WikidataQuery)\nfrom depicts.error_mail import setup_error_mail\nfrom requests_oauthlib import OAuth1Session\nfrom werkzeug.exceptions import InternalServerError\nfrom werkzeug.debug.tbtools import get_current_traceback\nfrom sqlalchemy import func, distinct\nfrom collections import defaultdict\nimport json\nimport os\nimport locale\nimport random\n\nlocale.setlocale(locale.LC_ALL, 'en_US.UTF-8')\nuser_agent = 'Mozilla/5.0 (X11; Linux i586; rv:32.0) Gecko/20160101 Firefox/32.0'\n\napp = Flask(__name__)\napp.config.from_object('config.default')\ndatabase.init_db(app.config['DB_URL'])\ninit_pager(app)\nsetup_error_mail(app)\n\nfind_more_props = {\n 'P135': 'movement',\n 'P136': 'genre',\n 'P170': 'artist',\n 'P195': 'collection',\n 'P276': 'location',\n 'P495': 'country of origin',\n 'P127': 'owned by',\n 'P179': 'part of the series',\n 'P921': 'main subject',\n 'P186': 'material used',\n 'P88': 'commissioned by',\n 'P1028': 'donated by',\n 'P1071': 'location of final assembly',\n 'P138': 'named after',\n 'P1433': 'published in',\n 'P144': 'based on',\n 'P2079': 'fabrication method',\n 'P2348': 'time period',\n 'P361': 'part of',\n 'P608': 'exhibition history',\n 'P180': 'depicts',\n 'P31': 'instance of',\n\n # possible future props\n # 'P571': 'inception',\n # 'P166': 'award received', (only 2)\n # 'P1419': 'shape', (only 2)\n # 'P123': 'publisher', (only 1)\n}\n\nisa_list = [\n 'Q60520', # sketchbook\n 'Q93184', # drawing\n 'Q3305213', # painting\n 'Q15123870', # lithograph\n 'Q18761202', # watercolor painting\n 'Q79218', # triptych\n 'Q2647254', # study\n 'Q46686' # reredos\n]\n\n@app.teardown_appcontext\ndef shutdown_session(exception=None):\n database.session.remove()\n\n@app.errorhandler(InternalServerError)\ndef exception_handler(e):\n tb = get_current_traceback()\n return render_template('show_error.html', tb=tb), 500\n\n@app.template_global()\ndef set_url_args(endpoint=None, **new_args):\n if endpoint is None:\n endpoint = request.endpoint\n args = request.view_args.copy()\n args.update(request.args)\n args.update(new_args)\n args = {k: v for k, v in args.items() if v is not None}\n return url_for(endpoint, **args)\n\n@app.template_global()\ndef current_url():\n args = request.view_args.copy()\n args.update(request.args)\n return url_for(request.endpoint, **args)\n\n@app.before_request\ndef init_profile():\n g.profiling = []\n\n@app.before_request\ndef global_user():\n g.user = wikidata_oauth.get_username()\n\n@app.route('/find_more_setting')\ndef flip_find_more():\n session['no_find_more'] = not session.get('no_find_more')\n display = {True: 'on', False: 'off'}[not session['no_find_more']]\n\n return 'flipped. find more is ' + display\n\ndef existing_edit(item_id, depicts_id):\n q = Edit.query.filter_by(artwork_id=item_id, depicts_id=depicts_id)\n return q.count() != 0\n\n@app.route('/save/Q', methods=['POST'])\ndef save(item_id):\n depicts = request.form.getlist('depicts')\n username = wikidata_oauth.get_username()\n assert username\n\n token = wikidata_oauth.get_token()\n\n artwork_item = ArtworkItem.query.get(item_id)\n if artwork_item is None:\n artwork_entity = mediawiki.get_entity_with_cache(f'Q{item_id}')\n label = wikibase.get_entity_label(artwork_entity)\n artwork_item = ArtworkItem(item_id=item_id, label=label, entity=artwork_entity)\n database.session.add(artwork_item)\n database.session.commit()\n\n for depicts_qid in depicts:\n depicts_id = int(depicts_qid[1:])\n\n depicts_item = DepictsItem.query.get(depicts_id)\n if depicts_item is None:\n depicts_item = wikidata_edit.create_depicts_item(depicts_id)\n database.session.add(depicts_item)\n database.session.commit()\n\n for depicts_qid in depicts:\n depicts_id = int(depicts_qid[1:])\n if existing_edit(item_id, depicts_id):\n continue\n\n r = create_claim(item_id, depicts_id, token)\n reply = r.json()\n if 'error' in reply:\n return 'error:' + r.text\n print(r.text)\n saved = r.json()\n lastrevid = saved['pageinfo']['lastrevid']\n assert saved['success'] == 1\n edit = Edit(username=username,\n artwork_id=item_id,\n depicts_id=depicts_id,\n lastrevid=lastrevid)\n database.session.add(edit)\n database.session.commit()\n\n return redirect(url_for('next_page', item_id=item_id))\n\n@app.route('/settings', methods=['GET', 'POST'])\ndef user_settings():\n return render_template('user_settings.html')\n\n@app.route('/test/lookup')\ndef test_lookup_page():\n return render_template('test_lookup.html')\n\n@app.route(\"/property/P\")\ndef property_query_page(property_id):\n pid = f'P{property_id}'\n g.title = find_more_props[pid]\n sort = request.args.get('sort')\n sort_by_name = sort and sort.lower().strip() == 'name'\n\n rows = wdqs.run_from_template_with_cache('query/property.sparql',\n cache_name=pid,\n pid=pid,\n isa_list=isa_list)\n\n no_label_qid = [row['object']['value'].rpartition('/')[2]\n for row in rows\n if 'objectLabel' not in row and '/' in row['object']['value']]\n\n if no_label_qid:\n extra_label = get_labels(no_label_qid, name=f'{pid}_extra_labels')\n if extra_label:\n for row in rows:\n item = row['object']['value']\n if 'objectLabel' in row or '/' not in item:\n continue\n qid = item.rpartition('/')[2]\n if extra_label.get(qid):\n row['objectLabel'] = {'value': extra_label[qid]}\n\n if sort_by_name:\n # put rows with no English label at the end\n no_label = [row for row in rows if 'objectLabel' not in row]\n has_label = sorted((row for row in rows if 'objectLabel' in row),\n key=lambda row: locale.strxfrm(row['objectLabel']['value']))\n rows = has_label + no_label\n\n return render_template('property.html',\n label=g.title,\n order=('name' if sort_by_name else 'count'),\n pid=pid,\n rows=rows)\n\n@app.route('/')\ndef start():\n return random_artwork()\n username = wikidata_oauth.get_username()\n username = None\n return render_template('start.html', username=username)\n\n@app.route('/next')\ndef random_artwork():\n rows = wdqs.run_from_template_with_cache('query/artwork_no_depicts.sparql')\n has_depicts = True\n while has_depicts:\n item_id = wdqs.row_id(random.choice(rows))\n if ArtworkItem.query.get(item_id):\n continue\n entity = mediawiki.get_entity_with_cache(f'Q{item_id}', refresh=True)\n en_label = wikibase.get_en_label(entity)\n if en_label and en_label.startswith('Page from '):\n # example: Q60467422\n # title: Page from Tales of a Parrot (Tuti-nama): text page\n # this is not a painting\n continue\n has_depicts = 'P180' in entity['claims']\n\n session[f'Q{item_id}'] = 'from redirect'\n return redirect(url_for('item_page', item_id=item_id))\n\n@app.route('/oauth/start')\ndef start_oauth():\n next_page = request.args.get('next')\n if next_page:\n session['after_login'] = next_page\n\n client_key = app.config['CLIENT_KEY']\n client_secret = app.config['CLIENT_SECRET']\n base_url = 'https://www.wikidata.org/w/index.php'\n request_token_url = base_url + '?title=Special%3aOAuth%2finitiate'\n\n oauth = OAuth1Session(client_key,\n client_secret=client_secret,\n callback_uri='oob')\n fetch_response = oauth.fetch_request_token(request_token_url)\n\n session['owner_key'] = fetch_response.get('oauth_token')\n session['owner_secret'] = fetch_response.get('oauth_token_secret')\n\n base_authorization_url = 'https://www.wikidata.org/wiki/Special:OAuth/authorize'\n authorization_url = oauth.authorization_url(base_authorization_url,\n oauth_consumer_key=client_key)\n return redirect(authorization_url)\n\n@app.route(\"/oauth/callback\", methods=[\"GET\"])\ndef oauth_callback():\n base_url = 'https://www.wikidata.org/w/index.php'\n client_key = app.config['CLIENT_KEY']\n client_secret = app.config['CLIENT_SECRET']\n\n oauth = OAuth1Session(client_key,\n client_secret=client_secret,\n resource_owner_key=session['owner_key'],\n resource_owner_secret=session['owner_secret'])\n\n oauth_response = oauth.parse_authorization_response(request.url)\n verifier = oauth_response.get('oauth_verifier')\n access_token_url = base_url + '?title=Special%3aOAuth%2ftoken'\n oauth = OAuth1Session(client_key,\n client_secret=client_secret,\n resource_owner_key=session['owner_key'],\n resource_owner_secret=session['owner_secret'],\n verifier=verifier)\n\n oauth_tokens = oauth.fetch_access_token(access_token_url)\n session['owner_key'] = oauth_tokens.get('oauth_token')\n session['owner_secret'] = oauth_tokens.get('oauth_token_secret')\n\n next_page = session.get('after_login')\n return redirect(next_page) if next_page else random_artwork()\n\n@app.route('/oauth/disconnect')\ndef oauth_disconnect():\n for key in 'owner_key', 'owner_secret', 'username', 'after_login':\n if key in session:\n del session[key]\n return redirect(url_for('browse_page'))\n\ndef create_claim(artwork_id, depicts_id, token):\n artwork_qid = f'Q{artwork_id}'\n value = json.dumps({'entity-type': 'item',\n 'numeric-id': depicts_id})\n params = {\n 'action': 'wbcreateclaim',\n 'entity': artwork_qid,\n 'property': 'P180',\n 'snaktype': 'value',\n 'value': value,\n 'token': token,\n 'format': 'json',\n 'formatversion': 2,\n }\n return wikidata_oauth.api_post_request(params)\n\ndef image_with_cache(qid, image_filename, width):\n filename = f'cache/{qid}_{width}_image.json'\n if os.path.exists(filename):\n detail = json.load(open(filename))\n else:\n detail = commons.image_detail([image_filename], thumbwidth=width)\n json.dump(detail, open(filename, 'w'), indent=2)\n\n return detail[image_filename]\n\ndef existing_depicts_from_entity(entity):\n if 'P180' not in entity['claims']:\n return []\n existing = []\n new_depicts = False\n for claim in entity['claims']['P180']:\n item_id = claim['mainsnak']['datavalue']['value']['numeric-id']\n\n item = DepictsItem.query.get(item_id)\n if not item:\n item = wikidata_edit.create_depicts_item(item_id)\n database.session.add(item)\n new_depicts = True\n d = {\n 'label': item.label,\n 'description': item.description,\n 'qid': f'Q{item.item_id}',\n 'count': item.count,\n 'existing': True,\n }\n existing.append(d)\n if new_depicts:\n database.session.commit()\n return existing\n\ndef get_institution(entity, other):\n if 'P276' in entity['claims']:\n location = wikibase.first_datavalue(entity, 'P276')\n if location:\n return other[location['id']]\n if 'P195' in entity['claims']:\n collection = wikibase.first_datavalue(entity, 'P195')\n if collection:\n return other[collection['id']]\n\n@app.route(\"/item/Q\")\ndef item_page(item_id):\n qid = f'Q{item_id}'\n item = artwork.Artwork(qid)\n from_redirect = qid in session and session.pop(qid) == 'from redirect'\n entity = mediawiki.get_entity_with_cache(qid, refresh=not from_redirect)\n\n existing_depicts = existing_depicts_from_entity(entity)\n\n width = 800\n image_filename = item.image_filename\n if image_filename:\n image = image_with_cache(qid, image_filename, width)\n else:\n image = None\n\n # hits = item.run_query()\n label_and_language = get_entity_label_and_language(entity)\n if label_and_language:\n label = label_and_language['label']\n else:\n label = None\n other = get_other(item.entity)\n\n people = human.from_name(label) if label else None\n\n artwork_item = ArtworkItem.query.get(item_id)\n if artwork_item is None:\n artwork_item = ArtworkItem(item_id=item_id, label=label, entity=entity)\n database.session.add(artwork_item)\n\n catalog = wd_catalog.get_catalog_from_artwork(entity)\n if not catalog.get('institution'):\n catalog['institution'] = get_institution(entity, other)\n\n label_languages = label_and_language['languages'] if label_and_language else []\n show_translation_links = all(lang.code != 'en' for lang in label_languages)\n return render_template('item.html',\n qid=qid,\n item_id=item_id,\n item=item,\n catalog=catalog,\n labels=find_more_props,\n entity=item.entity,\n username=g.user,\n label=label,\n label_languages=label_languages,\n show_translation_links=show_translation_links,\n existing_depicts=existing_depicts,\n image=image,\n people=people,\n other=other,\n # hits=hits,\n title=item.display_title)\n\ndef get_languages(codes):\n return Language.query.filter(Language.wikimedia_language_code.in_(codes))\n\ndef get_entity_label_and_language(entity):\n '''\n Look for a useful label and return it with a list of languages that have that label.\n\n If the entity has a label in English return it.\n\n Otherwise check if all languages have the same label, if so then return it.\n '''\n\n group_by_label = defaultdict(set)\n for language, l in entity['labels'].items():\n group_by_label[l['value']].add(language)\n\n if 'en' in entity['labels']:\n label = entity['labels']['en']['value']\n return {'label': label,\n 'languages': get_languages(group_by_label[label])}\n\n if len(group_by_label) == 1:\n label, languages = list(group_by_label.items())[0]\n return {'label': label,\n 'languages': get_languages(languages)}\n\ndef get_labels(keys, name=None):\n keys = sorted(keys, key=lambda i: int(i[1:]))\n if name is None:\n name = '_'.join(keys)\n filename = f'cache/{name}_labels.json'\n labels = []\n if os.path.exists(filename):\n from_cache = json.load(open(filename))\n if isinstance(from_cache, dict) and from_cache.get('keys') == keys:\n labels = from_cache['labels']\n if not labels:\n for cur in utils.chunk(keys, 50):\n labels += mediawiki.get_entities(cur, props='labels')\n\n json.dump({'keys': keys, 'labels': labels},\n open(filename, 'w'), indent=2)\n\n return {entity['id']: wikibase.get_entity_label(entity) for entity in labels}\n\ndef build_other_set(entity):\n other_items = set()\n for key in find_more_props.keys():\n if key not in entity['claims']:\n continue\n for claim in entity['claims'][key]:\n if 'datavalue' in claim['mainsnak']:\n other_items.add(claim['mainsnak']['datavalue']['value']['id'])\n return other_items\n\ndef get_other(entity):\n other_items = build_other_set(entity)\n return get_labels(other_items)\n\n@app.route(\"/edits\")\ndef list_edits():\n edit_list = Edit.query.order_by(Edit.timestamp.desc())\n\n item_count = (database.session\n .query(func.count(distinct(Edit.artwork_id)))\n .scalar())\n\n user_count = (database.session\n .query(func.count(distinct(Edit.username)))\n .scalar())\n\n return render_template('list_edits.html',\n edits=Edit.query,\n edit_list=edit_list,\n item_count=item_count,\n user_count=user_count)\n\n@app.route(\"/user/\")\ndef user_page(username):\n edit_list = (Edit.query.filter_by(username=username)\n .order_by(Edit.timestamp.desc()))\n\n item_count = (database.session\n .query(func.count(distinct(Edit.artwork_id)))\n .filter_by(username=username)\n .scalar())\n\n return render_template('user_page.html',\n username=username,\n edits=Edit.query,\n edit_list=edit_list,\n item_count=item_count)\n\n@app.route(\"/next/Q\")\ndef next_page(item_id):\n qid = f'Q{item_id}'\n\n entity = mediawiki.get_entity_with_cache(qid)\n\n width = 800\n image_filename = wikibase.first_datavalue(entity, 'P18')\n image = image_with_cache(qid, image_filename, width)\n\n label = wikibase.get_entity_label(entity)\n other = get_other(entity)\n\n other_list = []\n for key, prop_label in find_more_props.items():\n if key == 'P186': # skip material used\n continue # too generic\n claims = entity['claims'].get(key)\n if not claims:\n continue\n\n values = []\n\n for claim in claims:\n if 'datavalue' not in claim['mainsnak']:\n continue\n value = claim['mainsnak']['datavalue']['value']\n claim_qid = value['id']\n if claim_qid == 'Q4233718':\n continue # anonymous artist\n numeric_id = value['numeric-id']\n href = url_for('find_more_page', property_id=key[1:], item_id=numeric_id)\n values.append({\n 'href': href,\n 'qid': claim_qid,\n 'label': other.get(claim_qid),\n })\n\n if not values:\n continue\n\n qid_list = [v['qid'] for v in values]\n\n other_list.append({\n 'label': prop_label,\n 'image_lookup': url_for('find_more_json', pid=key, qid=qid_list),\n 'pid': key,\n 'values': values,\n 'images': [],\n })\n\n return render_template('next.html',\n qid=qid,\n label=label,\n image=image,\n labels=find_more_props,\n other=other,\n entity=entity,\n other_props=other_list)\n\n@app.route('/P/Q')\ndef find_more_page(property_id, item_id):\n pid, qid = f'P{property_id}', f'Q{item_id}'\n return redirect(url_for('browse_page', **{pid: qid}))\n\n@app.route('/toolinfo.json')\ndef tool_info():\n info = {\n 'name': 'wade',\n 'title': 'Wikidata Art Depiction Explorer',\n 'description': 'Add depicts statements to works of art.',\n 'url': 'https://art.wikidata.link/',\n 'keywords': 'art, depicts, paintings, depiction',\n 'author': 'Edward Betts',\n 'repository': 'https://github.com/edwardbetts/depicts.git',\n }\n return jsonify(info)\n\ndef get_facets(params):\n properties = [pid for pid in find_more_props.keys()\n if pid not in request.args]\n\n bindings = wdqs.run_from_template_with_cache('query/facet.sparql',\n params=params,\n isa_list=isa_list,\n properties=properties)\n\n facets = {key: [] for key in find_more_props.keys()}\n for row in bindings:\n pid = row['property']['value'].rpartition('/')[2]\n qid = row['object']['value'].rpartition('/')[2]\n label = row['objectLabel']['value']\n count = int(row['count']['value'])\n\n if pid not in find_more_props:\n continue\n facets[pid].append({'qid': qid, 'label': label, 'count': count})\n\n return {\n key: sorted(values, key=lambda i: i['count'], reverse=True)[:15]\n for key, values in facets.items()\n if values\n }\n\ndef get_artwork_params():\n return [(pid, qid) for pid, qid in request.args.items()\n if pid.startswith('P') and qid.startswith('Q')]\n\ndef filter_artwork(params):\n return wdqs.run_from_template_with_cache('query/find_more.sparql',\n params=params,\n isa_list=isa_list)\n\n@app.route('/catalog')\ndef catalog_page():\n params = get_artwork_params()\n bindings = filter_artwork(params)\n page = utils.get_int_arg('page') or 1\n page_size = 45\n\n item_ids = set()\n for row in bindings:\n item_id = wdqs.row_id(row)\n item_ids.add(item_id)\n\n qids = [f'Q{item_id}' for item_id in sorted(item_ids)]\n\n entities = mediawiki.get_entities_with_cache(qids)\n\n items = []\n other_items = set()\n for entity in entities:\n other_items.update(build_other_set(entity))\n item = {\n 'label': wikibase.get_entity_label(entity),\n 'qid': entity['id'],\n 'item_id': int(entity['id'][1:]),\n 'image_filename': wikibase.first_datavalue(entity, 'P18'),\n 'entity': entity,\n }\n items.append(item)\n\n other = get_labels(other_items)\n\n flat = '_'.join(f'{pid}={qid}' for pid, qid in params)\n thumbwidth = 400\n # FIXME cache_name can be too long for filesystem\n cache_name = f'{flat}_{page}_{page_size}_{thumbwidth}'\n detail = get_image_detail_with_cache(items, cache_name, thumbwidth=thumbwidth)\n\n for item in items:\n item['url'] = url_for('item_page', item_id=item['item_id'])\n item['image'] = detail[item['image_filename']]\n\n item_labels = get_labels(qid for pid, qid in params)\n title = ' / '.join(find_more_props[pid] + ': ' + item_labels[qid]\n for pid, qid in params)\n\n return render_template('catalog.html',\n labels=find_more_props,\n items=items,\n other=other,\n title=title)\n\ndef get_image_detail_with_cache(items, cache_name, thumbwidth=None, refresh=False):\n filenames = [cur['image_filename'] for cur in items]\n\n if thumbwidth is None:\n thumbwidth = app.config['THUMBWIDTH']\n\n filename = f'cache/{cache_name}_images.json'\n if not refresh and os.path.exists(filename):\n detail = json.load(open(filename))\n else:\n detail = commons.image_detail(filenames, thumbwidth=thumbwidth)\n json.dump(detail, open(filename, 'w'), indent=2)\n\n return detail\n\ndef browse_index():\n return render_template('browse_index.html', props=find_more_props)\n\n@app.route('/debug/show_user')\ndef debug_show_user():\n userinfo = wikidata_oauth.userinfo_call()\n return '
' + json.dumps(userinfo, indent=2) + '
'\n\n@app.route('/browse/facets.json')\ndef browse_facets():\n params = get_artwork_params()\n if not params:\n return jsonify(notice='facet criteria missing')\n\n facets = get_facets(params)\n\n for key, values in facets.items():\n for v in values:\n v['href'] = set_url_args(endpoint='browse_page', **{key: v['qid']})\n\n return jsonify(params=params,\n facets=facets,\n prop_labels=find_more_props)\n\n@app.route('/browse')\ndef browse_page():\n params = get_artwork_params()\n\n if not params:\n return browse_index()\n\n flat = '_'.join(f'{pid}={qid}' for pid, qid in params)\n\n item_labels = get_labels(qid for pid, qid in params)\n\n g.title = ' / '.join(find_more_props[pid] + ': ' + item_labels[qid]\n for pid, qid in params)\n\n bindings = filter_artwork(params)\n\n try:\n facets = get_facets(params)\n except wdqs.QueryError:\n facets = {}\n\n\n page_size = 45\n\n item_map = wdqs.build_browse_item_map(bindings)\n\n all_items = []\n for item in item_map.values():\n if len(item['image_filename']) != 1:\n continue\n item['image_filename'] = item['image_filename'][0]\n all_items.append(item)\n\n page = utils.get_int_arg('page') or 1\n pager = Pagination(page, page_size, len(all_items))\n\n items = pager.slice(all_items)\n\n cache_name = f'{flat}_{page}_{page_size}'\n detail = get_image_detail_with_cache(items, cache_name)\n cache_refreshed = False\n\n for item in items:\n item['url'] = url_for('item_page', item_id=item['item_id'])\n image_filename = item['image_filename']\n if not cache_refreshed and image_filename not in detail:\n detail = get_image_detail_with_cache(items, cache_name, refresh=True)\n cache_refreshed = True\n item['image'] = detail[image_filename]\n\n catalog_url = url_for('catalog_page', **dict(params))\n\n return render_template('find_more.html',\n facets=facets,\n prop_labels=find_more_props,\n label=g.title,\n pager=pager,\n params=params,\n item_map=item_map,\n catalog_url=catalog_url,\n page=page,\n labels=find_more_props,\n bindings=bindings,\n total=len(item_map),\n items=items)\n\n@app.route('/find_more.json')\ndef find_more_json():\n pid = request.args.get('pid')\n qid_list = request.args.getlist('qid')\n limit = 6\n\n filenames = []\n cache_name = f'{pid}={\",\".join(qid_list)}_{limit}'\n bindings = wdqs.run_from_template_with_cache('query/find_more_basic.sparql',\n cache_name=cache_name,\n qid_list=qid_list,\n pid=pid,\n limit=limit)\n\n items = []\n for row in bindings:\n item_id = wdqs.row_id(row)\n row_qid = f'Q{item_id}'\n image_filename = wdqs.commons_uri_to_filename(row['image']['value'])\n filenames.append(image_filename)\n items.append({'qid': row_qid,\n 'item_id': item_id,\n 'href': url_for('item_page', item_id=item_id),\n 'filename': image_filename})\n\n thumbheight = 120\n detail = commons.image_detail(filenames, thumbheight=thumbheight)\n\n for item in items:\n item['image'] = detail[item['filename']]\n\n return jsonify(items=items)\n\ndef wikibase_search(terms):\n hits = []\n r = mediawiki.api_call({\n 'action': 'wbsearchentities',\n 'search': terms,\n 'limit': 'max',\n 'language': 'en'\n })\n for result in r.json()['search']:\n hit = {\n 'label': result['label'],\n 'description': result.get('description') or None,\n 'qid': result['id'],\n 'count': 0,\n }\n if result['match']['type'] == 'alias':\n hit['alt_label'] = result['match']['text']\n hits.append(hit)\n\n return hits\n\ndef add_images_to_depicts_lookup(hits):\n qid_to_item = {hit['qid']: hit for hit in hits}\n all_qids = [hit['qid'] for hit in hits]\n entities = mediawiki.get_entities_with_cache(all_qids)\n\n for entity in entities:\n qid = entity['id']\n item = qid_to_item[qid]\n item.entity = entity\n database.session.commit()\n\n for hit in hits:\n item = qid_to_item[hit['qid']]\n if item.entity:\n image_filename = wikibase.first_datavalue(item.entity, 'P18')\n hit['image_filename'] = image_filename\n\n filenames = [hit['image_filename']\n for hit in hits\n if hit.get('image_filename')]\n filenames = filenames[:50]\n thumbwidth = 200\n detail = commons.image_detail(filenames, thumbwidth=thumbwidth)\n\n for hit in hits:\n filename = hit.get('image_filename')\n if not filename or filename not in detail:\n continue\n hit['image'] = detail[filename]\n\n@app.route('/lookup')\ndef depicts_lookup():\n terms = request.args.get('terms')\n if not terms:\n return jsonify(error='terms parameter is required')\n\n terms = terms.strip()\n if len(terms) < 3:\n return jsonify(\n count=0,\n hits=[],\n notice='terms too short for lookup',\n )\n\n item_ids = []\n hits = []\n q1 = DepictsItem.query.filter(DepictsItem.label.ilike(terms + '%'))\n seen = set()\n for item in q1:\n hit = {\n 'label': item.label,\n 'description': item.description,\n 'qid': item.qid,\n 'count': item.count,\n }\n item_ids.append(item.item_id)\n hits.append(hit)\n seen.add(item.qid)\n\n cls = DepictsItemAltLabel\n q2 = cls.query.filter(cls.alt_label.ilike(terms + '%'),\n ~cls.item_id.in_(item_ids))\n\n for alt in q2:\n item = alt.item\n hit = {\n 'label': item.label,\n 'description': item.description,\n 'qid': item.qid,\n 'count': item.count,\n 'alt_label': alt.alt_label,\n }\n hits.append(hit)\n seen.add(item.qid)\n\n hits.sort(key=lambda hit: hit['count'], reverse=True)\n\n if app.config.get('LOOKUP_INCLUDES_IMAGES'):\n add_images_to_depicts_lookup(hits)\n\n if app.config.get('SEARCH_WIKIDATA'):\n search_hits = wikibase_search(terms)\n hits += [hit for hit in search_hits if hit['qid'] not in seen]\n\n ret = {\n 'count': q1.count() + q2.count(),\n 'hits': hits,\n 'terms': terms,\n }\n\n return jsonify(ret)\n\n@app.route('/report/missing_image')\ndef missing_image_report():\n limit = utils.get_int_arg('limit') or 1000\n q = DepictsItem.query.order_by(DepictsItem.count.desc()).limit(limit)\n\n qids = [item.qid for item in q]\n entities = mediawiki.get_entities_dict_with_cache(qids)\n\n item_list = []\n\n for depicts in q:\n entity = entities[depicts.qid]\n if any(wikibase.first_datavalue(entity, prop) for prop in ('P18', 'P2716')):\n continue\n item_list.append(depicts)\n\n # TODO: call wikidata search to find images that depict item\n\n return render_template('missing_image.html', item_list=item_list)\n\n@app.route('/report/wdqs')\ndef wikidata_query_list():\n q = WikidataQuery.query.order_by(WikidataQuery.start_time.desc())\n return render_template('query_list.html', q=q)\n\n\nif __name__ == \"__main__\":\n app.debug = True\n app.run(host='0.0.0.0', debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":31682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"182540931","text":"import sys\n\nsys.stdin = open('input_5162.txt', 'r')\n# sys.stdout = open('output_5162.txt', 'w')\n\nT = int(input())\nfor t in range(1, T+1):\n A, B, C = map(int, input().split())\n\n lst = [C // A, C // B, (C // (A+B)) * 2]\n print('#{} {}'.format(t, (max(lst))))\n\n\n","sub_path":"SWEA/5162_두가지빵의딜레마.py","file_name":"5162_두가지빵의딜레마.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"311363315","text":"import pandas as pd\nimport numpy as np\n\npurchase_1 = pd.Series({'Name':'Chris','Item Purchased':'Dog Food','Cost':22})\npurchase_2 = pd.Series({'Name':'Martin','Item Purchased':'Cat Food','Cost':30})\npurchase_3 = pd.Series({'Name':'John','Item Purchased':'Man Food','Cost':90})\n\ndf = pd.DataFrame([purchase_1, purchase_2,purchase_3], index=['Store1','Store1','Store2'])\n\ndf['Date'] = [\"December 1\",\"January 1\",\"Mid-may\"] #as long as length is same Here 3 or you can add scalar one as it will be broadcast\ndf[\"Feedback\"] = [\"Positive\", None, \"Negative\"]\n\nadf = df.reset_index() #Won't reset it as it returns a copy not view,you need to say inplace=True to make it work\n #also, the index becl=omes a column name here\nadf['Date'] = pd.Series({0:\"December 1\", 2:\"January 1\"}) #Add new column base on the index values\nprint(adf)\n\nprint(\"------------------MERGING DATAFRAME-----------------------------\")\nstaff_df = pd.DataFrame([{'Name': 'Kelly', 'Role': 'Director of HR'}, #Create df like this as well, list with same keys dicts\n {'Name': 'Sally', 'Role': 'Course liasion'},\n {'Name': 'James', 'Role': 'Grader'}])\nstaff_df = staff_df.set_index('Name')\nstudent_df = pd.DataFrame([{'Name': 'James', 'School': 'Business'},\n {'Name': 'Mike', 'School': 'Law'},\n {'Name': 'Sally', 'School': 'Engineering'}])\nstudent_df = student_df.set_index('Name')\n\nouter_joined = pd.merge(staff_df, student_df, how='outer', left_index=True, right_index=True)\nprint(outer_joined)\nprint()\ninner_joined = pd.merge(staff_df, student_df, how='inner', left_index=True,right_index=True) #Must pass both\nprint(inner_joined)\nprint()\nleft_joined = pd.merge(staff_df, student_df,how='left', left_index=True, right_index=True)\nprint(left_joined)\nprint(\"---------------------JOIN WITHOUT INDEX----------------------------\")\nstaff_df.reset_index(inplace=True)\nstudent_df.reset_index(inplace=True)\nnon_index_merge = pd.merge(staff_df, student_df, how='left', left_on='Name', right_on='Name') #Then you provide column name of each side\nprint(non_index_merge)\n\nprint(\"--------------CONFLICTING ONES-------------------------\")\nstaff_df = pd.DataFrame([{'Name': 'Kelly', 'Role': 'Director of HR', 'Location': 'State Street'},\n {'Name': 'Sally', 'Role': 'Course liasion', 'Location': 'Washington Avenue'},\n {'Name': 'James', 'Role': 'Grader', 'Location': 'Washington Avenue'}])\nstudent_df = pd.DataFrame([{'Name': 'James', 'School': 'Business', 'Location': '1024 Billiard Avenue'},\n {'Name': 'Mike', 'School': 'Law', 'Location': 'Fraternity House #22'},\n {'Name': 'Sally', 'School': 'Engineering', 'Location': '512 Wilson Crescent'}])\n\nmerged_one = pd.merge(staff_df, student_df, how=\"outer\", left_on=\"Name\", right_on=\"Name\")\nprint(merged_one) #loc_x loc_y are created to show which one belonged where\n\"\"\"\nKeep in mind if you have product_id as index in one and product_id as column in second (Very much possible)\nmerge using pd.merge(one, two, left_index=True, right_on=\"product_id\")\nAlso you can join on multiple columns\npd.merge(one, two, left_on=[\"\",\"\"], right_on=[\"\",\"\"])\n\"\"\"\nprint(\"----------------------USING APPLY--------------------------------\")\ndef diff(row):\n diff = max(row) - min(row)\n return pd.Series({'diff':diff})\n\nn = np.random.randint(10,30,12).reshape(4,3)\ndf1 = pd.DataFrame(data=n, columns=[\"a\",\"b\",\"c\"])\n\ndf1[\"max\"] = df1.apply(max, axis=1) #Simple max min can be done like this\ndf1[\"min\"] = df1.apply(min, axis=1)\ndf1[\"mean\"] = df1.mean(axis=1)\ndf1[\"diff\"] = df1.apply(diff, axis=1) #Using user defined function here\ndf1[\"sum\"] = df1.apply(lambda x: sum(x[[\"a\",\"b\",\"c\"]]), axis=1) #Using lambda here itself\nprint(df1)\n\nprint(\"---------------------USING GROUPBY---------------------------------\")\ndf1[\"gb\"] = [1,1,2,2]\nprint(df1.groupby(\"gb\").agg({\"max\":np.sum})) #agg takes dict, key-column name(s) val-Function to apply\nprint(df1.groupby(\"gb\").size())\n\"\"\"\nIf you want to groupby using index columns, you can do df1.groupby(level=0)\nSee soemthing interesting here\ndf.set_index(\"STNAME\").groupby(level=0)[\"CENSUS2010POP\"].agg({'avg':np.av},'max':np.max))\n->Shows two new columns avg and max along with statenames that avg,max calculated on CENSUS2010POP\n->This is groupby on series.\n\ndf.set_index(\"STNAME\").groupby(level=0)['POPEST2010','POPEST2011'].agg({'avg':np.avg, 'max':np.max})\nSo when you run it you will get nice op/ with two headers avg, sum, then two columns that avg and max was calulated upon.\nThis is groupby on dataframe\n\n\nSO either specify column name in agg or do a projection. Don't do both of them.\nEspecielly with dataframe groupby\n\"\"\"\n\n\"\"\"\nprint(df.groupby('Category').apply(lambda df,a,b: sum(df[a] * df[b]), 'Weight (oz.)', 'Quantity'))\n\n\n# Or alternatively without using a lambda:\n# def totalweight(df, w, q):\n# return sum(df[w] * df[q])\n#\n# print(df.groupby('Category').apply(totalweight, 'Weight (oz.)', 'Quantity'))\n\nOne argument is implicit the df object itself. 2nd and 3rd are coumn names.\nA new way of dealing YAY..\n\nDoing projection on grouped by data. Selecting a and b columns\ndf.groupby(\"gb\")[\"a\",\"b\"].agg({'max':np.max})\n\nBEWARE,\nIf you do df.groupby(\"gb\")[\"a\",\"b\"].agg({'a':np.max}), the original column would be replaced.\n\"\"\"\n\nprint(\"--------SOME EXPERIMENT WITH CUT----------------\")\nraw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'],\n 'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'],\n 'name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'],\n 'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],\n 'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}\ndf5 = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'name', 'preTestScore', 'postTestScore'])\nprint(df5.head())\n\nbins = [0, 25, 50, 75, 100] #Bins 0 to 25, 25 to 50 etc\ngroup_names = ['Low', 'Okay', 'Good', 'Great']\n\ncategories = pd.cut(df5['postTestScore'], bins=bins , labels=group_names)\ndf5['Categories'] = pd.cut(df5['postTestScore'], bins=bins , labels=group_names)\nprint(df5)\n\"\"\"\nWe created range (bins), the number of the ranges should be equal to lenght of group_names\nthen we categorise based on postTestScore and name the range as group_names.\n\"\"\"\n\ncount = pd.value_counts(categories)\nprint(\"-------- With bins range-----------\") #Specifies how many fit into the range(labels)\nprint(count)\n\nprint(\"----------------PIVOT TABLE--------------------\")\npivot_df = pd.pivot_table(df5, index=['regiment', 'company'], aggfunc='mean') #Making these two as index and get mean over pre/postTestScore\nprint(pivot_df)\npivot_df1 = pd.pivot_table(df5, values='preTestScore', index='regiment', columns='company', aggfunc=[np.mean, len], fill_value=0)\n\"\"\"\nAbove we specify which columns we need the aggfunc to be applied on by calling values=\ncolumns= would provide different column names to data frame here, 1st 2nd Basically which company they belong to\nindex= the index on which the stuff needs to be done.\naggfunc is self explainatory\nfill_value if Nan is fucking you\n\"\"\"\nprint(pivot_df1)","sub_path":"basics/pandas_merge_df.py","file_name":"pandas_merge_df.py","file_ext":"py","file_size_in_byte":7381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"241917071","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 19 11:41:26 2017\n\n@author: FQ\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom time import time\nfrom scipy.stats import zscore\nfrom scipy.stats import itemfreq\nnp.set_printoptions(threshold=np.nan, suppress=True)\npd.set_option('display.width', 1000)\n\ndef label_freq(y):\n # func returns frequcy of labels as list (#0's, #1's, #-1's)\n item_freq = itemfreq(y) \n label_freq = [item_freq[1,1], item_freq[2,1], item_freq[0,1]]\n return label_freq\n\ndef quote_data_labels(data):\n \n #check how many time multiple transactions occur at same time\n #i.e. multiple data rows with same t\n t_vals, t_counts = np.unique(data[:,0], return_counts=True)\n t_dup_trans = np.sum(t_counts[t_counts>1])\n print (\"{} instances with multiple transactions at same time:\".format(t_dup_trans))\n \n #get price i.e. mid-quotes\n quote = (data[:,6] + data[:,8])*0.5\n \n #get price diff i.e. p(t+1) - p(t) \n labels = np.diff(quote)\n labels[labels>0] = 1\n labels[labels<0] = -1\n \n # np.diff returns array with one less element, so add 0 for last row / latest time\n labels = np.append(labels, 0)\n #data = data[:-1]\n \n ones = (labels[labels==1].size)/labels.size\n negs = (labels[labels==-1].size)/labels.size\n zeros = 1 - negs - ones\n print (\"Labels Generated 0:1:-1 = {}:{}:{}\".format(round(zeros*100,2), round(ones*100,2), round(negs*100,2))) \n \n return data, labels\n\n\ndef smooth_data (data_in, k_list=[20], min_list=[1], debug='n'):\n \n if debug=='y':\n sm_label_freq = []\n nres = 0\n \n return_list = []\n \n for k in k_list:\n for min in min_list:\n \n data = np.array(data_in)\n q = (data[:,6] + data[:,8])*0.5\n q_win = np.empty((q.size-2*k))\n data = data[k:-k,:]\n \n q1 = np.diff(q)\n thresh = np.min(np.absolute(q1[np.nonzero(q1)])) * min\n \n for i, qi in enumerate(q_win):\n #print (i, k, qi)\n q_win[i] = np.mean(q[i+k:i+2*k], axis=0) - np.mean(q[i:i+k], axis=0)\n \n if q_win[i] > thresh:\n q_win[i] = 1\n elif q_win[i] < -1*thresh: \n q_win[i] = -1\n else:\n q_win[i] = 0\n \n res_string = 'Smooth-' + repr(k) + '-' + repr(min)\n return_list.append((res_string, data, q_win))\n \n if debug =='y': \n #print (res_string, data.shape, q_win.shape)\n sm_label_freq.append(label_freq(q_win))\n \n if debug =='y': \n print (sm_label_freq)\n pd.DataFrame(sm_label_freq).to_csv('SmoothLabelFreq.csv')\n return return_list\n\n \ndef Order_Data(X):\n \n rows = X[:,0].size\n X_ord = np.array(X[:,:6]) # all order columns, remove LOB columns\n X_ord_time = np.array(X_ord[:,0]).reshape((rows,1)) # only time column\n X_ord_type = np.array(X_ord[:,1]).reshape((rows,1))\n X_ord_dir = np.array(X_ord[:,5]).reshape((rows,1))\n X_ord_id = np.array(X_ord[:,2]).reshape((rows,1))\n X_ord_det = np.array(X_ord[:,3:6])\n \n return_list = [('Orders-All', X_ord), ('Order-Time', X_ord_time), \n ('Order-Type', X_ord_type), ('Order-Dir', X_ord_dir), \n ('Order-ID', X_ord_id), ('Order-Details', X_ord_det)]\n\n return return_list\n\ndef LOB_Depths(X):\n \n XT = np.delete(X,[1,2,3,4,5],axis=1) # remove messages columns\n XT10 = XT[:,-40:]\n XT5 = XT[:,-20:]\n XT4 = XT[:,-16:]\n XT3 = XT[:,-12:]\n XT2 = XT[:,-8:]\n XT1 = XT[:,-4:]\n #print (XT.shape, XT10.shape, XT5.shape, XT1.shape)\n \n return_list = [('LOB-10', XT10), ('LOB-5', XT5), \n ('LOB-4', XT4), ('LOB-3', XT3), \n ('LOB-2', XT2), ('LOB-1', XT1)]\n \n return return_list\n\ndef LOB_Imbalance(X):\n XT = np.delete(X,[0,1,2,3,4,5],axis=1) # remove messages columns\n \n X_time = X[:,0].reshape((X[:,0].size,1))\n \n # bid - ask [Gould, Bonart 2015]\n XT10_diff = XT[:,[3,7,11,15,19,23,27,31,35,39]] - XT[:,[1,5,9,13,17,21,25,29,33,37]] \n XT10_sum = XT[:,[3,7,11,15,19,23,27,31,35,39]] + XT[:,[1,5,9,13,17,21,25,29,33,37]]\n XT10 = XT10_diff / XT10_sum\n \n #print (XT10_diff[10], XT10_sum[10], XT10[10])\n \n XT10 = np.concatenate((X_time, XT10), axis=1)\n XT5 = np.concatenate((X_time, XT10[:,:5]), axis=1)\n XT4 = np.concatenate((X_time, XT10[:,:4]), axis=1)\n XT3 = np.concatenate((X_time, XT10[:,:3]), axis=1)\n XT2 = np.concatenate((X_time, XT10[:,:2]), axis=1)\n XT1 = np.concatenate((X_time, XT10[:,:1]), axis=1)\n \n #print (XT10.shape, XT5.shape, XT4.shape, XT3.shape, XT2.shape, XT1.shape)\n\n return_list = [('IMB-10', XT10), ('IMB-5', XT5), \n ('IMB-4', XT4), ('IMB-3', XT3), \n ('IMB-2', XT2), ('IMB-1', XT1)]\n \n return return_list\n \ndef Normalize_Data (X, X_imb):\n # calculate zscores for X, except for columns 0,1,2,5\n XT = np.array(X)\n XT = zscore(XT)\n XT[:,0] = X[:,0]\n XT[:,1] = X[:,1]\n XT[:,2] = X[:,2]\n XT[:,5] = X[:,5]\n \n #claculate zscores for all cols of imbalance dataset\n XT_imb = np.array(X_imb)\n XT_imb = zscore(XT_imb) \n\n return XT, XT_imb\n \ndef Order_Arrival_Rates(X, y, t_thresh=5):\n # This function sums the order creations, cancels and executions \n # for a given historic window (t_thresh)\n # XT cols = Create Vol Buy, Create Vol Sell, Canc Vol Buy, Canc Vol Sell, Exec Vol\n \n fn_start = X[0,0]\n cutoff_t = fn_start + t_thresh \n \n XT = np.array(X[(X[:,0]>cutoff_t)][:,:14])\n yT = np.array(y[(X[:,0]>cutoff_t)])\n #print (X.shape, XT.shape, y.shape, yT.shape)\n XT[:,1:14] = 0\n \n t1 = time()\n\n for i, row in enumerate (XT):\n t_end = XT[i,0]\n t_start = t_end - t_thresh\n \n win = np.array(X[(X[:,0]>t_start) & (X[:,0]= win[:,8])][:,3])\n create_vol_sell_lob = np.sum(win[(win[:,1] == 1) & (win[:,5] == -1) & (win[:,4] <= win[:,6])][:,3])\n create_vol_diff_lob = create_vol_buy_lob - create_vol_sell_lob \n \n canc_vol_buy = np.sum(win[((win[:,1] == 2) | (win[:,1] == 3)) & (win[:,5] == 1)][:,3])\n canc_vol_sell = np.sum(win[((win[:,1] == 2) | (win[:,1] == 3)) & (win[:,5] == -1)][:,3])\n canc_vol_diff = canc_vol_buy - canc_vol_sell\n \n canc_vol_buy_lob = np.sum(win[((win[:,1] == 2) | (win[:,1] == 3)) & (win[:,5] == 1) & (win[:,4] >= win[:,8])][:,3])\n canc_vol_sell_lob = np.sum(win[((win[:,1] == 2) | (win[:,1] == 3)) & (win[:,5] == -1) & (win[:,4] <= win[:,6])][:,3])\n canc_vol_diff_lob = canc_vol_buy_lob - canc_vol_sell_lob\n \n exec_vol = np.sum(win[(win[:,1] == 4) | (win[:,1] == 5)][:,3]) \n \n #print (create_vol_buy, create_vol_sell)\n #print (canc_vol_buy, canc_vol_sell)\n #print (exec_vol)\n \n XT[i,1:] = [create_vol_buy, create_vol_sell, create_vol_diff, \n canc_vol_buy, canc_vol_sell, canc_vol_diff, exec_vol,\n create_vol_buy_lob, create_vol_sell_lob, create_vol_diff_lob, \n canc_vol_buy_lob, canc_vol_sell_lob, canc_vol_diff_lob] \n \n XT_rate_ords = np.array(XT[:,0:8])\n XT_rate_lobords = np.array(XT[:,(1,8,9,10,11,12,13)])\n \n print (\"Vrate Data Setup Time\", time()-t1)\n \n return XT, XT_rate_ords, XT_rate_lobords, yT\n \ndef Combine_Tranformed_Data (X, X_imb, X_arrt_1, y):\n \n fn_start = X[0,0]\n fn_end = X[-1,0]\n \n cutoff_start = fn_start + 30\n cutoff_end = fn_end -30\n \n X_ind_st = X[X[:,0]cutoff_end][:,0].size\n \n Xarrt_ind_st = X_arrt_1[X_arrt_1[:,0]cutoff_end][:,0].size\n \n print (X_ind_st,X_ind_end,Xarrt_ind_st,Xarrt_ind_end)\n \n X1 = np.array(X[X_ind_st:-X_ind_end,:])\n X2 = np.array(X_imb[X_ind_st:-X_ind_end,:])\n X3 = np.array(X_arrt_1[Xarrt_ind_st:-Xarrt_ind_end,:])\n \n print (X1[:,0].size,X2[:,0].size,X3[:,0].size)\n yT = np.array(y[X_ind_st:-X_ind_end])\n \n XT = np.concatenate ((X1, X2, X3), axis=1)\n\n return XT, yT\n \n \ndef LOB_Change_Rates(X, y, t_thresh=1):\n \n # XT cols = Create Vol Buy, Create Vol Sell, Canc Vol Buy, Canc Vol Sell, Exec Vol\n '''\n fn_start = X[0,0]\n cutoff_t = fn_start + t_thresh \n \n XT = np.concatenate((X[:,0],np.array(X[(X[:,0]>cutoff_t)][:,6:])), axis=1)\n yT = np.array(y[(X[:,0]>cutoff_t)])\n print (X.shape, XT.shape, y.shape, yT.shape)\n #XT[:,:] = 0\n \n t1 = time()\n\n for i, row in enumerate (XT):\n t_end = XT[i,0]\n t_start = t_end - t_thresh\n \n win = np.array(X[(X[:,0]>t_start) & (X[:,0]\")\napi.add_resource(Post, \"/p/\")\n\n\nif __name__ == \"__main__\":\n\tapp.run(host='0.0.0.0', debug=True)\n","sub_path":"Web/Insta-Flask/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"421145940","text":"from django.urls import path\n\nfrom . import views\n\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('login/', views.login, name='login'),\n path('registered/', views.registered, name='registered'),\n path('personal/', views.personal, name='personal'),\n path('exit/', views.exit, name='exit'),\n path('searchunit/', views.searchUnit, name='searchunit'),\n path('applyUnit/', views.applyUnit, name='applyunit'),\n path('searchunit/unitdetail/', views.unitDetail, name='unitdetail'),\n path('searchunit/generateenter', views.generateEnterApplication, name='generateenter'),\n path('indexenterapplication/', views.indexEnterApplication, name='indexenterapplication'),\n path('handleenter/', views.handleEnterApplication, name='handleenter'),\n path('gencontract/', views.generateContract, name='gencontract'),\n\n path('enterapplist/', views.enter_app_list, name='enterapplist'),\n path('enterappdetail/', views.enter_app_detial, name='enterappdetial'),\n\n path('management/', views.management, name='management'),\n\n path('success/', views.success, name=\"success\"), # 成功支付\n path('pay_imp//', views.pay_imp, name='payimp'), # 支付接口\n\n # 支付测试\n path('pay/', views.pay, name='pay'),\n path('successpay/', views.successpay, name='successpay'),\n\n\n # 测试页面专用\n path('test/', views.test, name='test'),\n]\napp_name = \"forlease\"\n\n","sub_path":"oasis/forlease/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"22713378","text":"# For GPU use \nfrom numba import autojit, jit, cuda, float32\nfrom timeit import default_timer as timer\nimport cupy as cp\n\n# The rest\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom scipy.io import loadmat\nimport random\nimport math\n\n# Importing data\ntest = loadmat('C:/Users/turbo/Python projects/Algos from scratch/Algos_from_scratch/ex3data1.mat')\ninput_array = cp.array(test['X'])\noutput_array = test['y']\n\n# Cleaning output array\ntransformed_y = []\nfor i in [i[0] for i in test['y']]:\n foo = [0,0,0,0,0,0,0,0,0,0].copy()\n foo[i-1]=True\n transformed_y.append(foo)\noutput_array = cp.array(transformed_y)\n\n\ndef neural_net(input_array, output_array, n_iterations, layer_n_list, gamma=0, visualize_error=0):\n layer_N_list = [input_array.shape[1]] + layer_n_list\n\n # Procedurally initiate matrix of weights\n weights_matrix = initialize_random_weights(layer_N_list)\n\n # Gradient descent iteration\n error = []\n for i in np.arange(n_iterations):\n\n # Forward propagation\n node_array = propagate(input_array,weights_matrix,layer_n_list)\n\n # Backpropagation\n grad_adjustment_vector, iter_error = backpropagate(node_array, output_array, weights_matrix, layer_n_list)\n\n for i in cp.arange(len(layer_n_list)):\n weights_matrix[int(i)] -= (grad_adjustment_vector[int(i)] + gamma*weights_matrix[int(i)]) / 5000\n error.append(iter_error.sum())\n\n final_error = (output_array - node_array[-1].round()).mean()\n \n if visualize_error == True:\n plt.plot(error)\n plt.show()\n\n return final_error\n\n# \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \n## EXPERIMENTATION SECTION ##\n# \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \n\n# layer_n_list = [25,10]\n# layer_N_list = [400, 25, 10]\n\n# list_of_structures = [[100, 50, 30, 10], [25, 10],[50, 25, 10],[50, 40, 30, 10],[800, 100, 10],[100, 50, 30, 10],[25, 10],[50, 25, 10],[50, 40, 30, 10],[800, 100, 10],[100, 50, 30, 10],[25, 10],[50, 25, 10],[50, 40, 30, 10],[800, 100, 10]]\n\n# # Start timer\n# #start = timer()\n\n# # Processes\n# List_of_structures = []\n# for i in list_of_structures:\n# item = [input_array.shape[1]] + i\n# List_of_structures.append(item)\n\n# weights_tensor = []\n# for i in List_of_structures:\n# weights_tensor.append(initialize_random_weights(i))\n\n# We find that paralell iteration of gradient descent algorithm is not faster than successive. :/. this is probably not the case when implemented correct.\n# 3x faster than non-gpu\n\nrun_training_code = False\n\nif run_training_code == True:\n for j in cp.arange(50):\n node_tensor = []\n for i, structure in enumerate(List_of_structures):\n # Forward propagation\n node_tensor.append(propagate(input_array, weights_tensor[i], structure[1:]))\n\n # Backpropagation\n grad_adjustment_vector, iter_error = backpropagate(node_tensor[i], output_array, weights_tensor[i], structure[1:])\n\n for k in np.arange(len(structure[1:])):\n weights_tensor[i][k] -= (grad_adjustment_vector[k] / 5000) #+ gamma*weights_matrix[k]) / 5000\n\n for i, structure in enumerate(List_of_structures):\n final_error = (output_array - node_tensor[i][-1].round()).mean()\n\n\n # Stop timer\n time = timer()-start\n print('total training time', time)\n\n# ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ \n## END EXPERIMENTATION SECTION\n# ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ \n\n\n\n\n# \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \n### COMBINING INTO CLASS OBJECT ###\n# \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \n\n# Helper functions\n# These are the functions required for the class to operate correctly, despite not being class functions\ndef train_cv_split(x_array, y_array, cv_pct):\n '''\n Inputs - Dataset in the form of np array, percentage of dataset you would like to select as cross validation set \\n\n There are two \"dataset\" arguments, data and data2. This is in case you have separate arrays for x and y. They will be sampled with the same indices.\n Outputs - Training set, cross validation set, output format is np array\n '''\n \n idx = cp.random.randint(x_array.shape[0], size= int(cp.around(x_array.shape[0]*cv_pct)) )\n \n mask = cp.ones(x_array.shape[0],dtype=bool) \n mask[idx] = 0\n\n x_array_test = x_array[idx, :]\n x_array_train = x_array[mask, :]\n y_array_test = y_array[idx, :]\n y_array_train = y_array[mask, :]\n\n return x_array_train, x_array_test, y_array_train, y_array_test\n\ndef backpropagate(node_array, output_array, weights_matrix, layer_n_list):\n ''' \n My implementation of a backpropagation algorithm. \n Inputs - \\n\n node_array - list of np arrays, each array (each list element) corresponds to the nodes in each layer, for each training observation. The first element is the input layer, last element is output layer. \\n\n Output_aray - a numpy array corresponding to the y values of each observation \\n\n weights_matrix - A list where the elements are two dimensional numpy arrays of float64s. \\n\n layer_n_list - the vector corresponding to the neural network structure.\n Example- [10,5,3] corresponds to some unknown amount of inputs, 10 nodes in layer 1, 5 in layer 2, and 3 output nodes. \\n \\n\n\n Outputs - \\n\n grad_adjustment_vector - list of numpy arrays containing the amounts that the weights should be adjusted to reduce error in a given iteration of the backprop algorithm \\n\n Output err-r also used in adjusting weights in backprop algorithm\n '''\n \n output_error = node_array[-1] - output_array\n d_vector = [output_error]\n grad_adjustmet_vector = [cp.matmul(output_error.T, node_array[-2])]\n for i in cp.arange(len(layer_n_list)-1):\n output_error = cp.matmul(output_error, weights_matrix[-int(i+1)][:,1:]) * (node_array[-int(i+2)][:,1:]*(1-node_array[-int(i+2)][:,1:]))\n grad_adjustment = cp.matmul(output_error.T, node_array[-int(i+3)])\n d_vector.append(output_error)\n grad_adjustmet_vector.append(grad_adjustment)\n \n grad_adjustmet_vector.reverse()\n\n return grad_adjustmet_vector, d_vector[0]\n\ndef initialize_random_weights(layer_n_list):\n '''\n Input- the vector corresponding to the neural network structure.\n Example- [10,5,3] corresponds to some unknown amount of inputs, 10 nodes in layer 1, 5 in layer 2, and 3 output nodes. \\n\n The last element is always the number of output nodes. \\n \\n\n Output- A list where the elements are two dimensional numpy arrays of float64s. \n '''\n random_choice_params = []\n for i in np.arange(len(layer_n_list)-1):\n adjacent_lengths = layer_n_list[i] + layer_n_list[i+1]\n random_choice_params.append(math.sqrt(6)/(math.sqrt(adjacent_lengths)))\n \n weights_matrix = []\n for n, k in enumerate(random_choice_params):\n weights_array = []\n for i in np.arange(layer_n_list[n+1]):\n x_feature_list = []\n for j in np.arange(layer_n_list[n]):\n x_feature_list.append(random.uniform(-k, k))\n weights_array.append(x_feature_list)\n weights_matrix.append(np.array(weights_array))\n\n for i in np.arange(len(layer_n_list)-2):\n weights_matrix[i+1] = np.concatenate((np.array([[1]]*weights_matrix[i+1].shape[0]), weights_matrix[i+1]), axis=1)\n \n weights_matrix = [cp.asarray(i) for i in weights_matrix]\n\n return weights_matrix\n\ndef sigmoid(x):\n \"\"\"\n Input- one dimensional numpy array\n Output- array of the same shape\n \"\"\"\n return 1/(1+cp.exp(-x))\n\ndef propagate(input_array, weights_matrix, layer_n_list):\n '''\n forward propagation algorithm. \\n\n Inputs - \\n\n input_array - two dimensional numpy array corresponding to x data \\n \n weights_matrix - A list where the elements are two dimensional numpy arrays of float64s. \\n\n layer_n_list- the vector corresponding to the neural network structure.\n Example- [10,5,3] corresponds to some unknown amount of inputs, 10 nodes in layer 1, 5 in layer 2, and 3 output nodes. \\n\n Output - \\n\n node_array - list of np arrays, each array (each list element) corresponds to the nodes in each layer, for each training observation. The first element is the input layer, last element is output layer. \\n\n '''\n node_array = [input_array]\n for i in cp.arange(len(layer_n_list)-1):\n foo = cp.matmul(node_array[int(i)], weights_matrix[int(i)].T)\n foo = sigmoid(foo)\n\n foo = cp.concatenate((cp.array([[1]]*foo.shape[0]), foo), axis=1)\n\n node_array.append(foo)\n\n foo = cp.matmul(node_array[-1], weights_matrix[-1].T)\n foo = sigmoid(foo)\n node_array.append(foo)\n\n return node_array\n\n\nclass neural_network():\n def load_data(self, x_array, y_array):\n x_array = cp.concatenate((cp.array([[1]]*x_array.shape[0]), x_array), axis=1)\n random.Random(4).shuffle(x_array)\n random.Random(4).shuffle(y_array)\n self.n_observations = x_array.shape[1]\n self.x_array = x_array\n self.y_array = y_array\n\n def train_cv_split(self, cv_pct=0.2):\n '''\n Inputs - Dataset in the form of np array, percentage of dataset you would like to select as cross validation set \\n\n There are two \"dataset\" arguments, data and data2. This is in case you have separate arrays for x and y. They will be sampled with the same indices.\n Outputs - Training set, cross validation set, output format is np array\n '''\n \n # Create indices masks for test and training set\n idx = cp.random.randint(self.x_array.shape[0], size=int(round(self.x_array.shape[0]*cv_pct)))\n mask = cp.ones(self.x_array.shape[0], dtype=bool) \n mask[idx] = False\n\n # Split train and test set into folds, since backpropagation efficiency goes as n^5. Optimal size of folds depends on ability to compute in paralell.\n self.train_folds = math.floor(sum(mask)/2500)\n self.train_cutoffs = cp.linspace(0, sum(mask), self.train_folds+1)\n self.test_folds = math.floor(len(idx)/2500)\n self.test_cutoffs = cp.linspace(0, len(idx), self.test_folds+1)\n\n x_train_list = []\n y_train_list = []\n for i in cp.arange(self.train_folds):\n x_train_list.append(self.x_array[mask, :][int(self.train_cutoffs[i]):int(self.train_cutoffs[i+1]), :])\n y_train_list.append(self.y_array[mask, :][int(self.train_cutoffs[i]):int(self.train_cutoffs[i+1]), :])\n\n y_test_list = []\n x_test_list = []\n for i in cp.arange(self.test_folds):\n x_test_list.append(self.y_array[idx, :][self.test_cutoffs[i]:self.test_cutoffs[i+1], :])\n y_test_list.append(self.y_array[idx, :][self.test_cutoffs[i]:self.test_cutoffs[i+1], :])\n\n self.x_array_test = x_test_list\n self.x_array_train = x_train_list\n self.y_array_test = y_test_list\n self.y_array_train = y_train_list\n\n\n def train_net(self, layer_n_list, n_iterations, gamma=0):\n self.n_iterations = n_iterations\n self.layer_n_list = layer_n_list\n start = timer()\n try:\n self.x_array_train\n except AttributeError:\n self.train_cv_split()\n\n layer_N_list = [self.n_observations] + self.layer_n_list\n\n # Procedurally initiate matrix of weights\n weights_matrix = initialize_random_weights(layer_N_list)\n\n # Gradient descent iteration\n for n in cp.arange(self.n_iterations): \n error = []\n for j in cp.arange(self.train_folds):\n # Forward propagation\n node_array = propagate(self.x_array_train[int(j)], weights_matrix, self.layer_n_list)\n\n # Backpropagation\n grad_adjustment_vector, iter_error = backpropagate(node_array, self.y_array_train[int(j)], weights_matrix, self.layer_n_list)\n\n for i in cp.arange(len(self.layer_n_list)):\n weights_matrix[int(i)] -= (grad_adjustment_vector[int(i)] + gamma*weights_matrix[int(i)]) / 5000\n error.append(iter_error.sum())\n\n self.node_array = node_array\n self.weights_matrix = weights_matrix\n self.train_error = abs((self.y_array_train[int(j)] - self.node_array[-1].round()))\n\n print(self.train_error.mean())\n print('time',timer()-start)\n \n def test_net(self):\n x_array_test = [i[0] for i in self.x_array_test]\n y_array_test = [i[0] for i in self.y_array_test]\n\n node_array = propagate(x_array_test, self.weights_matrix, self.layer_n_list)\n self.test_error = abs((y_array_test - node_array[-1].round())).mean()\n\n\n def graph_learning_curve(self, layer_n_list, n_samples = 5, n_iterations = 50, cv_size_min = 0.1, cv_size_max = 0.5, timeit = False):\n '''\n Does not require any prior neural net training or validation, or train/test split\n '''\n if timeit == True:\n start = timer()\n\n cv_sizes = cp.linspace(cv_size_min, cv_size_max, int((cv_size_max - cv_size_min)*20))\n train_error_vector = []\n test_error_vector = []\n for cv_size in cv_sizes:\n train_error = []\n test_error = []\n for i in cp.arange(n_samples):\n self.x_array_train, self.x_array_test, self.y_array_train, self.y_array_test = train_cv_split(self.x_array, self.y_array, cv_pct = cv_size)\n self.train_net(layer_n_list, n_iterations)\n train_error.append(self.train_error)\n self.test_net()\n test_error.append(self.test_error)\n train_error_vector.append(np.mean(train_error))\n test_error_vector.append(np.mean(test_error))\n\n train_error_vector = np.array(train_error_vector)\n test_error_vector = np.array(test_error_vector)\n cv_sizes = np.linspace( cv_size_min, cv_size_max, int((cv_size_max - cv_size_min)*20) )\n\n if timeit == True:\n print('Time to do {} iterations:'.format(int((cv_size_max - cv_size_min)*20)*n_samples), round(timer()-start, 3))\n\n # eventually replace with legend because i am not a fucking moron\n print('The blue line is training error, orange line is test error')\n\n plt.plot(cv_sizes, train_error_vector)\n plt.plot(cv_sizes, test_error_vector)\n plt.show() \n\nnet = neural_network()\nnet.load_data(input_array, output_array)\nnet.train_net([25,10],50)\n\n#net.graph_learning_curve([25, 10], timeit=True)\n \n\n\n\n","sub_path":"paralell_with_cupy.py","file_name":"paralell_with_cupy.py","file_ext":"py","file_size_in_byte":15366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"621860604","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 11 15:23:12 2019\n\n@author: rjlin\n\"\"\"\n\nfrom keras.models import Sequential #用來啟動 NN\nfrom keras.layers import Conv2D # Convolution Operation\nfrom keras.layers import MaxPooling2D # Pooling\nfrom keras.layers import Flatten\nfrom keras.layers import Dense # Fully Connected Networks\nimport preprocess \nfrom sklearn.model_selection import train_test_split\nimport os\nwith open('file_path.txt', 'r') as files:\n file_path = files.readlines()\n\nselections = []\npaths_tag = []\nfor i in file_path:\n path, tag, split_half = i.rstrip().split(',')\n if not tag in selections:\n selections.append(tag)\n paths_tag.append((path, tag, split_half))\n \n#argument\ndata_merge = []\nfor i in paths_tag:\n data = preprocess.read_files_name(i[0], i[1], i[2])\n data_merge += data\n\n#data = preprocess.read_files('data/ace', split_half=True)\n#data2 = preprocess.read_files('data/titan/', split_half=False)\n\n#ace = preprocess.read_files_name('data/ace', lable='ace')\n#titan = preprocess.read_files_name('data/titan', lable='titan')\n#\n#data_merge = ace + titan\ntrain, test = train_test_split(data_merge, test_size=0.1)\n\n\n\nmodel = Sequential() \nmodel.add(Conv2D(32, (7, 7), strides = 3, input_shape = (770, 490, 1), activation = 'relu'))\nmodel.add(MaxPooling2D(pool_size = (2, 2)))\n\nmodel.add(Conv2D(32, (5, 5), activation = 'relu'))\nmodel.add(MaxPooling2D(pool_size = (2, 2)))\n\n# Third convolutional layer\nmodel.add(Conv2D(64, (3, 3), activation = 'relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(output_dim = 128, activation = 'relu'))\nmodel.add(Dense(output_dim = len(selections), activation = 'sigmoid'))\n\nmodel.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])\n\ntrain_gen = preprocess.generator(train, batch_size=20, crop_size=(770, 490), selections=selections, normalize=True)\ntest_gen = preprocess.generator(test, batch_size=20, crop_size=(770, 490), selections=selections, normalize=True)\n\nmodel.fit_generator(generator=train_gen, \n validation_data=test_gen,\n steps_per_epoch=2,\n validation_steps=2,\n epochs = 3\n )\n\nmodel.save('comic_classifer.h5')\nwith open('comic_classifer.lable', 'w') as files:\n files.write(','.join(selections))\nmodel_name = input('please input a model name')\nsafe_name = True\nif model_name+'.h5' in os.listdir('model'):\n safe_name = False\n print('filename conflict')\n if input('key \"f\" for covering the old file') == 'f':\n safe_name = True\nif safe_name:\n model.save('model/%s.h5'%model_name)\n with open('model/%s.lable'%model_name, 'w') as files:\n files.write(','.join(selections))\n print('model save successfully')","sub_path":"classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"473621718","text":"\nfrom starter2 import *\nimport davetools as DT\nreload(DT)\nplt.close('all')\n#data_location = '/scratch1/dcollins/Paper19/Datasets/'\nimport data_locations as dl\nreload(dl)\n#file_list=glob.glob('%s/track_indfix_sixteenframe_core_*.h5'%dl.snapshot_location)\nfile_list=glob.glob('/home/dcollins/scratch/Paper19/all_frames/track_all_frames_*.h5')\n\n#This keeps track of the min and max velocity.\nif 'ext_v' not in dir():\n ext_v=DT.extents() \n ext_r=DT.extents()\n ext_v(nar([-4.29e+01, 3.26e+01]))\n ext_r(nar([2.13e-08, 1.11e+00]))\n print(\"Running Extents\")\n if 0:\n #in case you actually need to compute the extents\n for nfile,fname in enumerate(file_list):\n this_looper=looper.core_looper(directory=dl.enzo_directory)\n trw.load_loop(this_looper,fname)\n if True:\n for frame in this_looper.snaps:\n for core_id in this_looper.snaps[frame]:\n snap = this_looper.snaps[frame][core_id]\n if snap.R_mag.size > 1:\n ext_v( snap.V_radial)\n ext_r( snap.R_mag)\n\n#\n# Set up velocity bins. \n# Force a symetric log in the velocity. (Ask if this isn't clear)\n#\n\nnvel_bins = 10\nnrad_bins = 20\nvel_max = 50 #max signed velocity\nvel_linthresh=0.1 #Between += this, the plot is linear \nNlinear=2 #Number of linear bins\nnlog = (nvel_bins-Nlinear)//2+1\nvba= np.linspace(0, vel_linthresh, Nlinear)[:-1] #the linear portion\nvbb= np.logspace(np.log10(vel_linthresh),np.log10(vel_max),nlog)#the log portion\nvelbins0=np.concatenate([vba,vbb]) #put the linear and log together\nvelbins = np.concatenate([-velbins0[::-1],velbins0[1:] ]) #make it symmetric\nrmin = 0.05*1./128*0.5**4\nrmax = 1\nradbins = np.concatenate([np.zeros(1),np.logspace(np.log10(rmin),np.log10(rmax),nrad_bins)])\nvelhist_global = np.zeros([nvel_bins,nrad_bins])\n\nfor nfile,fname in enumerate(file_list):\n \n #this is a crude way to get the core_id for debug purpose\n #t1 = fname.split(\"/\")[-1]\n #l = len(\"track_indfix_sixteenframe_core_\")\n #this_core = int(t1[l:l+4]) #[fname.index('_'):]\n #this_core=31\n #if this_core not in [12]:#, 31]:\n # continue\n #print(this_core)\n\n #This builds the looper object\n this_looper=looper.core_looper(directory=dl.enzo_directory)\n trw.load_loop(this_looper,fname)\n\n #some short hand for ease of use.\n thtr = this_looper.tr\n all_cores = np.unique(thtr.core_ids)\n core_list=all_cores\n #for making things colorful.\n #which is nice for effect, but better for keeping track of\n #what's going on.\n rm = rainbow_map(len(all_cores)) \n tmap=rainbow_map(len(this_looper.snaps.keys()))\n\n frame_list=sorted(list(this_looper.snaps.keys()))\n if 1:\n #big histogram\n\n #the histogram t fill\n velhist = np.zeros([nvel_bins,nrad_bins])\n\n #the plot tools\n fig=plt.figure(figsize=(4,4))\n axa=fig.subplots(1,1)\n\n for iframe,frame in enumerate(frame_list):\n for core_id in this_looper.snaps[frame]:\n snap = this_looper.snaps[frame][core_id]\n if snap.V_radial is None:\n snap.compute_relative_coords()\n if len(snap.R_mag) < 3:\n continue\n if snap.time == 0:\n print(\"NO ZERO\")\n continue\n\n #makes a 2d histogram, like phase diagrams in yt.\n h, xe, ye = np.histogram2d(snap.R_mag,snap.V_radial, bins=(radbins,velbins))\n h=h.T #the transpose so that data structures line up.\n\n #this is the x and y coordinates of the 2d histogram that we'll\n #plot\n rrr, vvv = np.meshgrid(xe,ye)\n\n #For this code, we'll only plot the cumulative of all \n #histograms.\n velhist += h\n velhist_global += h\n if len(snap.R_mag) < 3:\n continue\n\n #plot the histogram.\n #this is cumbersome, make sure each of these pieces\n #makes sense.\n norm = mpl.colors.LogNorm(vmin=1,vmax=velhist.max())\n cmap=mpl.cm.jet\n cmap.set_under('w')\n p=axa.pcolormesh(rrr,vvv,velhist,norm=norm)\n cbar=fig.colorbar(p)\n\n #plot a scatter plot along with the histogram\n for iframe,frame in enumerate(frame_list):\n for core_id in this_looper.snaps[frame]:\n snap = this_looper.snaps[frame][core_id]\n if len(snap.R_mag) < 3:\n continue\n #rrr, vvv = np.meshgrid(radbins,velbins)\n axa.scatter(snap.R_mag,snap.V_radial,c=tmap(iframe,snap.R_mag.size),s=0.1,label=str(frame))\n\n #this is a dumb bit of code that shortens plot formatting\n DT.axbonk(axa,xscale='log',yscale='linear',xlabel='R_mag',ylabel='V_rel',\n xlim=ext_r, ylim=ext_v)\n #though the dumb bit of code doesn't deal with symlog\n axa.set_yscale('symlog',linthreshy=vel_linthresh)\n axa.set_xscale('symlog',linthreshx=2*rmin)\n outname = 'image_tracks/vel_hist_c%04d.png'%core_id\n print(outname)\n fig.savefig(outname)\n print(\"saved \"+outname)\n plt.close('all')\n \n #now we'll plot the multi-core version\n fig,ax=plt.subplots(1,1)\n norm = mpl.colors.Normalize(vmin=1,vmax=velhist_global.max())\n cmap=mpl.cm.jet\n cmap.set_under('w')\n p=ax.pcolormesh(rrr,vvv,velhist_global,norm=norm)\n DT.axbonk(ax,xscale='log',yscale='linear',xlabel='R_mag',ylabel='V_rel',\n xlim=ext_r, ylim=ext_v)\n ax.set_yscale('symlog',linthreshy=vel_linthresh)\n ax.set_xscale('symlog',linthreshx=2*rmin)\n cbar=fig.colorbar(p)\n outname = 'bigtest.png'\n fig.savefig(outname)\n print(\"saved \"+outname)\n","sub_path":"tools_tracks/UNFINISHED/vel_hist.py","file_name":"vel_hist.py","file_ext":"py","file_size_in_byte":5902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"337782591","text":"# -*- coding: UTF-8 -*-\n\nfrom twisted.application.service import MultiService\nfrom twisted.python import log\nfrom core.items import Items\nfrom core.map import Map\n\n\nclass World(MultiService):\n def startService(self):\n log.msg('Initializing World')\n\n log.msg('Loading Tibia.dat')\n self.items = Items()\n log.msg('%d items loaded' % len(self.items._items))\n\n log.msg('Loading map')\n self.map = Map(self.items)\n self.map.load_map('map.json')\n log.msg('Map loaded: (%dx%d)' % (self.map.width, self.map.height))\n\n MultiService.startService(self)\n\n def stopService(self):\n log.msg('Destroing World')\n MultiService.stopService(self)\n","sub_path":"core/world.py","file_name":"world.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"320867540","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nimport scrapy\nfrom scrapy.exceptions import CloseSpider\nimport sys\nimport logging\nimport urllib\nimport hashlib\nimport os\nimport json\nimport requests\nfrom scrapy.loader import ItemLoader\nfrom amazon_product_page_fetcher.items import Page\nfrom datetime import datetime\nfrom scrapy_selenium import SeleniumRequest\nimport math\nfrom io import BytesIO\nimport base64\nimport configparser\nfrom dotenv import load_dotenv\nfrom pathlib import Path # python3 only\nimport random\n# Selenium Specific & Related Imports\nfrom time import sleep\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.proxy import Proxy\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as ec\nfrom selenium.webdriver.remote.webelement import WebElement\nfrom selenium.webdriver.remote.remote_connection import LOGGER\nfrom scrapy.http import HtmlResponse\nfrom urllib import parse\nimport sentry_sdk\nfrom PIL import Image\nfrom amazon_product_page_fetcher.mattermost import send_message_to_mattermost\nimport threading\ntry:\n import thread\nexcept ImportError:\n import _thread as thread\n \ntry: # use code that works the same in Python 2 and 3\n range, _print = xrange, print\n def print(*args, **kwargs): \n flush = kwargs.pop('flush', False)\n _print(*args, **kwargs)\n if flush:\n kwargs.get('file', sys.stdout).flush() \nexcept NameError:\n pass\n\n# config = configparser.ConfigParser()\n# config.read('scrapy.cfg')\n# project = config['deploy']['project']\n# env_path = Path(f'/envs/{project}') / '.env'\n# load_dotenv(dotenv_path=env_path)\n# print(env_path)\ndef cdquit(fn_name):\n # print to stderr, unbuffered in Python 2.\n print('{0} took too long'.format(fn_name), file=sys.stderr)\n sys.stderr.flush() # Python 3 stderr is likely buffered.\n thread.interrupt_main() # raises KeyboardInterrupt\n \ndef exit_after(s):\n '''\n use as decorator to exit process if \n function takes longer than s seconds\n '''\n def outer(fn):\n def inner(*args, **kwargs):\n timer = threading.Timer(s, cdquit, args=[fn.__name__])\n timer.start()\n try:\n result = fn(*args, **kwargs)\n finally:\n timer.cancel()\n return result\n return inner\n return outer\nLOGGER.setLevel(logging.WARNING)\n\ndef hash_keyword(url):\n clean_url = remove_ref_from_url(url)\n return hashlib.md5(clean_url.encode('utf-8')).hexdigest()\n\ndef remove_ref_from_url(url):\n return url.split('/ref')[0]\n\nclass ProductPageFetcherSpider(scrapy.Spider):\n old_factory = logging.getLogRecordFactory()\n name = 'product_page_fetcher_desktop'\n allowed_domains_dict = {\n 'IN': 'www.amazon.in',\n 'US': 'www.amazon.us',\n 'GLOBAL': 'www.amazon.com'\n }\n allowed_domains = allowed_domains_dict.values()\n custom_settings = {\n #Selenium configurations\n 'SELENIUM_DRIVER_NAME' : os.getenv('SELENIUM_DRIVER_NAME'),\n # 'SELENIUM_DRIVER_NAME' : webdriver.Firefox(),\n 'SELENIUM_DRIVER_ARGUMENTS' : os.getenv('SELENIUM_DRIVER_ARGUMENTS').split('|'), # '--headless' if using chrome instead of firefox\n 'SELENIUM_COMMAND_EXECUTOR' : os.getenv('SELENIUM_COMMAND_EXECUTOR'),\n }\n\n @classmethod\n def from_crawler(cls, crawler, *args, **kwargs):\n sentry_webhook = os.getenv('SENTRY_WEBHOOK')\n sentry_sdk.init(sentry_webhook)\n return cls(\n bot_name=crawler.settings.get('BOT_NAME'),\n *args,\n **kwargs\n )\n \n @classmethod\n def setup_proxy(cls, proxy_server):\n proxy = Proxy({'proxyType': 'MANUAL', 'httpProxy': proxy_server, 'sslProxy': proxy_server})\n\n cls.custom_settings['SELENIUM_PROXY'] = proxy\n\n @classmethod\n def prepare_settings(cls):\n pass\n cls.custom_settings['DOWNLOADER_MIDDLEWARES'] = {\n 'scrapy_selenium.SeleniumMiddleware': 800,\n 'amazon_captcha_solver.AmazonCaptchaDownloaderMiddleware': 900\n }\n\n def __init__(self, bot_name=None, proxy_service='1ds', seeds=None, seed_type=None, task_id=None, pipeline_id=None, amazon=None, spider_settings=None, *args, **kwargs):\n super().__init__(*args, **kwargs)\n if seeds is None or task_id is None:\n sys.exit(0)\n\n if pipeline_id is None:\n sys.exit(0)\n\n if amazon is None or amazon not in ProductPageFetcherSpider.allowed_domains_dict:\n logging.info(\"No specific region is defined. Therefore crawling default www.amazon.com\")\n self.amazon = ProductPageFetcherSpider.allowed_domains_dict.get('IN')\n else:\n logging.info(\"Starting specific crawling of \"+ProductPageFetcherSpider.allowed_domains_dict.get(amazon))\n self.amazon = ProductPageFetcherSpider.allowed_domains_dict.get(amazon)\n\n if spider_settings:\n\n setts_json = json.loads(spider_settings)\n self.urls = {}\n\n for k in setts_json:\n setting = k + \"=\" + setts_json[k]\n ProductPageFetcherSpider.custom_settings['SELENIUM_DRIVER_ARGUMENTS'].append(setting)\n \n self.__class__.prepare_settings()\n self.proxy_service = proxy_service\n self.blocked_urls = []\n self.blocked_seeds = {}\n if proxy_service == '1ds':\n # 1DS proxy setup\n proxy_r = requests.post(os.getenv('PROXY_API_URL'), \n data={\n 'pass': os.getenv('PROXY_API_PASSWORD'), \n 'user': os.getenv('PROXY_API_USER'), \n 'source': self.name, \n 'type': os.getenv('PROXY_API_TYPE')\n })\n\n proxy_details = json.loads(proxy_r.text)\n if proxy_details['status'] == 'ok':\n self.proxyServer = proxy_details['server']\n self.__class__.setup_proxy(self.proxyServer)\n\n elif proxy_service == 'luminati':\n # Luminati proxy setup\n # l_username = os.getenv('LUMINATI_USERNAME')\n # l_password = os.getenv('LUMINATI_PASSWORD')\n # l_port = os.getenv('LUMINATI_PORT')\n # l_session = random.random()\n # self.proxyServer = f'zproxy.lum-superproxy.io:{l_port}'\n # proxy = Proxy({'proxyType': 'MANUAL', 'httpProxy': self.proxyServer, 'sslProxy': self.proxyServer})\n # proxy.socksUsername = f'{l_username}-country-in-session-{l_session}'\n # proxy.socksPassword = l_password\n # self.custom_settings['SELENIUM_PROXY'] = proxy\n self.proxyServer = os.getenv('PROXY')\n self.__class__.setup_proxy(self.proxyServer)\n else:\n self.logger.info('No proxy service defined. Using default proxy')\n \n self.task_id = task_id\n self.job_id = kwargs['_job']\n self.pipeline_id = pipeline_id\n self.seeds = seeds.split('|')\n self.browser = setts_json['user-agent']\n self.bot_name = bot_name\n self.seed_type = seed_type\n self.missed_asins = []\n self.__configure_logger()\n\n if seed_type is None:\n self.logger.info(f'Seed Type can not be : {seed_type}')\n raise CloseSpider()\n \n self.logger.info(f'\\n\\nJob Id: {self.job_id}\\nPipeline Id: {self.pipeline_id}\\nTask Id: {self.task_id}\\n')\n self.logger.info(f'Begin Time: {datetime.now()}')\n self.logger.info(f'Number of ASINs assigned: {len(self.seeds)}')\n self.logger.info(f'Proxy server for the spider is: {self.proxyServer}')\n self.logger.info(f'User Agent for the spider is: {self.browser}')\n job_info = {\n \"asins\": self.seeds,\n \"# of asins\": len(self.seeds),\n \"proxy\": self.proxyServer,\n \"pipeline_id\": self.pipeline_id,\n \"job_id\": self.job_id,\n \"seed_type\": self.seed_type\n }\n message = (f\"#### New Job \\n\"+\"```json\\n\"+json.dumps(job_info, indent=4)+\"\\n```\")\n send_message_to_mattermost(message, self.bot_name)\n logging.getLogger('pika').setLevel(logging.WARN)\n \n def __configure_logger(self):\n \n logger = logging.getLogger(self.name)\n extra = {\n 'job_id': self.job_id,\n 'pipeline_id': self.pipeline_id\n }\n folder_path = f'/scrapyd/logs-internal/{self.bot_name}/{self.name}/'\n if not os.path.exists(folder_path):\n os.makedirs(folder_path)\n # Create handlers\n c_handler = logging.StreamHandler()\n f_handler = logging.FileHandler(f'{folder_path}/{self.pipeline_id}.log')\n c_handler.setLevel(logging.WARNING)\n f_handler.setLevel(logging.INFO)\n \n logging.setLogRecordFactory(self.record_factory)\n # Create formatters and add it to handlers\n c_format = logging.Formatter('%(name)s - %(pipeline_id)s - %(job_id)s - %(levelname)s - %(message)s')\n f_format = logging.Formatter('%(asctime)s - %(pipeline_id)s - %(job_id)s - %(name)s - %(levelname)s - %(message)s')\n c_handler.setFormatter(c_format)\n f_handler.setFormatter(f_format)\n\n # Add handlers to the logger\n logger.addHandler(c_handler)\n logger.addHandler(f_handler)\n\n def record_factory(self, *args, **kwargs):\n \n record = self.__class__.old_factory(*args, **kwargs)\n record.job_id = self.job_id\n record.pipeline_id = self.pipeline_id \n return record\n\n def start_requests(self):\n \n # yield SeleniumRequest(url=\"https://www.amazon.in/\", callback=self.parse_root)\n for index, seed in enumerate(self.seeds):\n sleep(random.randint(3, 15))\n self.logger.info(f'Fetching page for URL/ASIN at {index} : {seed}')\n if self.seed_type == 'asin':\n yield scrapy.Request(url=f'https://{self.amazon}/dp/{seed}', callback=self.parse, cb_kwargs={'asin': seed})\n elif self.seed_type == 'url':\n # yield SeleniumRequest(url=seed, callback=self.parse, screenshot=True)\n yield scrapy.Request(url=seed, callback=self.parse)\n \n def parse_root(self, response):\n print(response.xpath('//title/text()').get())\n\n def parse(self, response, asin=None):\n # driver = response.request.meta['driver']\n # wait = WebDriverWait(driver, 10)\n # if self.check_blocked(driver):\n # captcha_image = response.request.meta['screenshot']\n # buffered_image = BytesIO(captcha_image)\n # base64_image = base64.b64encode(buffered_image.getvalue())\n # payload = {}\n # payload['password'] = \"theSecretKey007\"\n # payload['imageBase64'] = base64_image\n # payload['jobId'] = self.pipeline_id\n # unraveler_r = requests.post(os.getenv('UNRAVELER_QUESTION'), \n # data=payload, \n # headers = {\n # 'content-type': 'application/x-www-form-urlencoded'\n # })\n\n # result = json.loads(unraveler_r.text)\n # try:\n # captcha_answer = self.poll_unraveler_for_answer(result['imageId'])\n # print(captcha_answer)\n # captcha_box = self.get_captcha_input(driver, wait)\n # self.fill_in_captcha(captcha_box, captcha_answer)\n # response = HtmlResponse(\n # driver.current_url,\n # body=str.encode(driver.page_source),\n # encoding='utf-8',\n # request=response.request\n # )\n # except Exception as error:\n # print(error)\n # return\n\n try:\n loader = ItemLoader(item=Page(), response=response)\n except Exception as exception:\n print(exception)\n\n url_hash = hash_keyword(response.request.url)\n\n # try:\n # aplus_element = wait.until(ec.visibility_of_element_located((By.ID, 'aplus')))\n # ActionChains(driver).move_to_element(aplus_element)\n # full_page_ss = response.request.meta['screenshot']\n # ss = self.get_ss_of_element(aplus_element, full_page_ss)\n # except Exception as error:\n # print(error)\n # self.logger.error(\"No A Plus Page\")\n \n self.save_file(response.body.decode('utf-8'), url_hash)\n \n canonical_link = \"NOT_FOUND\"\n canonical_link = response.xpath('//*[@rel=\"canonical\"]/@href').get()\n try:\n canonical_asin = os.path.basename(canonical_link) or \"Not_Found\"\n except Exception as error:\n self.missed_asins.append(response.request.url)\n self.logger.error(error)\n canonical_asin = \"NOT_FOUND\"\n loader.add_value('asin', asin)\n loader.add_value('canonical_asin', canonical_asin)\n loader.add_value('canonical_link', canonical_link)\n loader.add_value('source_url', response.request.url)\n loader.add_value('pages', self.urls[url_hash])\n loader.add_value('crawl_time', {\"$date\": datetime.now().isoformat()})\n loader.add_value('task_id', self.task_id)\n loader._add_value('job_id', self.job_id)\n loader.add_value('pipeline_id', self.pipeline_id)\n loader.add_value('browser', self.browser)\n loader.add_value('renderer', ProductPageFetcherSpider.name.replace('product_page_fetcher_', ''))\n return loader.load_item()\n\n def closed(self, reason):\n self.logger.info(f'Number of ASINs/URLs missed : {len(self.missed_asins)}')\n if len(self.missed_asins) > 0:\n self.logger.info(f'Missed ASINs/URLs are: {self.missed_asins}')\n self.logger.info(f'Spider closed : {reason}')\n # @exit_after(180)\n # def poll_unraveler_for_answer(self, image_id):\n # result = self.check_status(image_id)\n # status = result['status']\n # while status != \"ok\":\n # sleep(5)\n # result = self.check_status(image_id)\n # status = result['status']\n # return result['answer']\n\n # def check_status(self, image_id):\n # unraveler_r = requests.get(f'{os.getenv(\"UNRAVELER_ANSWER\")}/{image_id}')\n # response = json.loads(unraveler_r.text)\n # return response\n\n # def fill_in_captcha(self, captcha_box, answer):\n # try:\n # sleep(1)\n # captcha_box.clear() # Clear the contents\n # sleep(1)\n # captcha_box.send_keys(answer) # Add the keywords\n # sleep(2)\n # captcha_box.send_keys(Keys.RETURN) \n # except Exception as exception:\n # print(exception)\n # raise exception\n \n # def get_captcha_input(self, driver, wait):\n # try:\n # captcha_box = wait.until(ec.visibility_of_element_located(\n # (By.XPATH, '//*[@id=\"captchacharacters\"]')))\n # # CLick the searchbox by \"moving\" to that location\n # sleep(2)\n # ActionChains(driver).move_to_element(\n # captcha_box).click().perform()\n # return captcha_box\n # except Exception as exception:\n # self.logger.error(\n # \"Captcha Input Box not Found on page. No reason to continue.\")\n # raise exception\n\n def get_ss_of_element(self, element: WebDriverWait, full_page_ss):\n x = element.location[\"x\"]\n y = element.location[\"y\"]\n w = element.size[\"width\"]\n h = element.size[\"height\"]\n im = Image.open(BytesIO(full_page_ss))\n left=math.floor(x)\n top=math.floor(y)\n right= x + math.ceil(w)\n bottom= y + math.ceil(h)\n # return im.crop((18, 2165, 1333, 3134))\n return im.crop((left, top, right, bottom))\n # return im\n\n\n def save_file(self, data, url_hash):\n # url_hash = hash_url(response.url)\n # data = data # .body.decode(\"utf-8\")\n file_path = self.file_location(url_hash)\n try:\n with open(file_path, \"w\") as file:\n self.logger.info(f'Saving file at {file_path}')\n file.write(data)\n except IOError:\n self.logger.error(f'Unable to write file at {file_path}')\n\n self.urls[url_hash].append(self.http_url_for_file_path(file_path))\n # if url_hash in self.urls:\n # self.urls[url_hash].append(file_path)\n # else:\n # self.urls[url_hash] = [file_path]\n\n def http_url_for_file_path(self, file_path: str):\n return f\"https://{os.getenv('STORAGE_HOSTNAME')}.storage.1digitalstack.com/\"+file_path.split('/storage/')[1]\n\n def file_location(self, url_hash):\n \n time = datetime.now()\n folder = time.strftime(\"%Y%m%d\")\n folder_path = \"/storage/\"+folder+\"/\"+self.pipeline_id+\"/\"+self.job_id\n if not os.path.exists(folder_path):\n print(\"creating folder\")\n os.makedirs(folder_path)\n\n if not url_hash in self.urls:\n self.urls[url_hash] = []\n file_path = folder_path+\"/\"+url_hash + \\\n \"_\" + str(len(self.urls[url_hash]))\n return file_path\n\n # def next_page_url(self, response):\n # # print(response.body.decode(\"utf-8\"))\n # query = urllib.parse.urlparse(response.xpath(\n # '//*[normalize-space(text()) = \"Next\"]//@href').get()).query\n # # print(urllib.parse.urlparse(response.xpath('//*[normalize-space(text()) = \"Next\"]//@href').get()))\n # if query:\n # return self.base_url + query\n # else:\n # return None\n\n def check_blocked(self, driver):\n # page_title = response.xpath('//title/text()').get()\n page_title = driver.title\n if page_title == \"Robot Check\":\n print(\n \"******************Blocked by Amazon**********************\")\n return True\n return False\n","sub_path":"amazon-product-page-fetcher/amazon-product-page-fetcher/amazon_product_page_fetcher/spiders/product_page_fetcher.py","file_name":"product_page_fetcher.py","file_ext":"py","file_size_in_byte":18230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"455603449","text":"from pprint import pprint\nfrom card import Card\n\nfrom deck import Deck\nfrom stack import Stack\nfrom player import Player\nimport names #remove this when players become real\n\nclass Game:\n\tdef __init__(self, amountOfPlayers):\n\t\tself.deck = Deck()\n\t\tself.deck.shuffle()\n\t\tself.stack = Stack()\n\t\tself.players = []\n\t\tself.started = True\n\n\t\tfor player in range(amountOfPlayers):\n\t\t\tplayerName = names.get_full_name()\n\t\t\tself.players.append(Player(self.stack, playerName, self.deck))\n\n\t#TODO: This method should never show all cards for all players, as cheating would be a piece of cake.\n\tdef toJSON(self):\n\t\treturn {\n\t\t\t'id': 0,\n\t\t\t'started': self.started,\n\t\t\t'players': [p.toJSON() for p in self.players]\n\t\t}\n\n\tdef getPlayerNames(self):\n\t\treturn [p.playerName for p in self.players]\n\n\ndef getPlayerId(currentPlayer, players):\n\tfor index, player in enumerate(players):\n\t\tif currentPlayer.playerName == player.playerName:\n\t\t\treturn index\n\treturn \"alles is naar de kanker als dit gebeurt\"\n\ndef lastPlayer(currentPlayerId, players):\n\tif currentPlayerId + 1 == len(players):\n\t\treturn True\n\telse:\n\t\treturn False\n\treturn \"apocalypse now\"\n\n#TODO: replace this somehow\nif __name__ == '__main__':\n\tdeck = Deck()\n\tdeck.shuffle()\n\tstack = Stack()\n\tplayers = []\n\n\t#ask amount of players\n\twhile True:\n\t\ttry:\n\t\t\tplayersAmount = int(input(\"How many players? \"))\n\t\texcept Exception:\n\t\t\tprint(\"Opbokken gauw.\")\n\t\telse:\n\t\t\tbreak\n\n\t#create players, ask for names\n\tcounter = 1\n\tfor player in range(playersAmount):\n\t\tplayerName = input(\"What's the name of player %s? \" % (counter))\n\t\tplayers.append(Player(stack, playerName, deck))\n\t\tcounter += 1\n\n\tprint('\\n')\n\n\twhile True:\n\t\tindex = 0\n\t\twhile index < len(players):\n\t\t\tprint(players[index].showHand())\n\t\t\tprint('\\n')\n\t\t\twhile True:\n\t\t\t\tplayedId = input(\"%s, which card (id) do you want to play? (or pass) \" % (players[index].playerName))\n\t\t\t\tif playedId == 'pass':\n\t\t\t\t\tplayers[index].passTurn(deck, stack)\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tplayedCard = players[index].hand.cardbyId(players[index], playedId)\n\t\t\t\t\tif players[index].cardisValid(playedCard, stack) and not playedCard == False:\n\t\t\t\t\t\t#Play the card\n\t\t\t\t\t\tprint('\\n')\n\t\t\t\t\t\tplayed = players[index].playCard(playedCard, stack)\n\t\t\t\t\t\tprint(played)\n\t\t\t\t\t\tprint('\\n')\n\t\t\t\t\t\t#Do trickery if it was a trickcard\n\t\t\t\t\t\tif playedCard.trickCard:\n\t\t\t\t\t\t\t#aas\n\t\t\t\t\t\t\tif Card.rankNames[playedCard.rank] == 'Aas':\n\t\t\t\t\t\t\t\tplayers = players[::-1]\n\t\t\t\t\t\t\t\tif lastPlayer(index, players):\n\t\t\t\t\t\t\t\t\tindex = 0\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tindex = getPlayerId(players[index], players) - 1\n\t\t\t\t\t\t\t\tindex = getPlayerId(players[index], players)\n\t\t\t\t\t\t\t#2\n\t\t\t\t\t\t\telif Card.rankNames[playedCard.rank] == '2':\n\t\t\t\t\t\t\t\tif lastPlayer(index, players):\n\t\t\t\t\t\t\t\t\tplayers[0].takeCard(deck, stack, 5)\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tplayers[index + 1].takeCard(deck, stack, 2)\n\t\t\t\t\t\t\t#7\n\t\t\t\t\t\t\telif Card.rankNames[playedCard.rank] == '7':\n\t\t\t\t\t\t\t\tprint(\"%s mag nog een keer\" % (players[index].playerName))\n\t\t\t\t\t\t\t\tindex -= 1\n\t\t\t\t\t\t\t#8\n\t\t\t\t\t\t\telif Card.rankNames[playedCard.rank] == '8':\n\t\t\t\t\t\t\t\tprint(\"%s slaat over\" % (players[index + 1].playerName))\n\t\t\t\t\t\t\t\tindex += 1\n\t\t\t\t\t\t\t#Boer\n\t\t\t\t\t\t\telif Card.rankNames[playedCard.rank] == 'Boer':\n\t\t\t\t\t\t\t\tprint(\"7 blijft kleven\")\n\t\t\t\t\t\t\t#Heer\n\t\t\t\t\t\t\telif Card.rankNames[playedCard.rank] == 'Heer':\n\t\t\t\t\t\t\t\tprint(\"%s mag nog een keer\" % (players[index].playerName))\n\t\t\t\t\t\t\t\tindex -= 1\n\t\t\t\t\t\t\t#Joker\n\t\t\t\t\t\t\telif Card.rankNames[playedCard.rank] == 'Joker':\n\t\t\t\t\t\t\t\tif lastPlayer(index, players):\n\t\t\t\t\t\t\t\t\tplayers[0].takeCard(deck, stack, 5)\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tplayers[index + 1].takeCard(deck, stack, 5)\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(\"\\nWat denken jij?!\")\n\t\t\t\t\t\tprint(\"\\nOp tafel:\\n\"+str(stack.lastPlayedString())+\"\\n\")\n\t\t\t\t\t\tprint(\"\\n\"+players[index].playerName+\"'s hand:\\n\"+players[index].showHand())\n\t\t\t\n\t\t\tindex += 1\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"117207032","text":"\"\"\"\nCore of model `ren`.\n\nauthor: cyrus\ndate: 2018-4-21\n\"\"\"\nimport sys\nsys.path.append('/home/cyrus/Public/mimicry')\n\nfrom black_box.ren.train_and_test import TrainAndTest\n\nFILE = 0x00\nUSER = 0x01\nDATASET = 0x10\nNOTHING = 0x11\nCORR_LOWER_LIMIT = 0.8\n\n\nclass RenActions():\n def __init__(self):\n self.train_and_test = None\n self.result = None\n\n def pre_train(self, path):\n self.train_and_test = TrainAndTest(path)\n self.result = self.train_and_test.run()\n\n def get_pre_train_results(self):\n self.train_and_test.print_pre_train_results()\n\n\nif __name__ == '__main__':\n dataset_path = '/home/cyrus/Public/mimicry/dataset/10-walking/owner'\n\n ren = RenActions()\n ren.pre_train(dataset_path)\n ren.get_pre_train_results()\n","sub_path":"experiment/pcc_exp_1/ren.py","file_name":"ren.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"34349236","text":"import pandas as pd\nimport numpy as np\npd.options.mode.chained_assignment = None\n\ndef get_status(status):\n \"\"\"\n Takes the Status of a visa application\n Returns either Certified of Not Certifed\n Used to create the column CERTIFIED\n \"\"\"\n if status == 'CERTIFIED' or status == 'CERTIFIED-WITHDRAWN':\n return 'certified'\n else:\n return 'denied'\n\ndef case_status(hb):\n \"\"\"\n Takes the hb dataframe.\n Drops records from CASE_STATUS, creates CERTIFIED\n Returns the new hb dataframe\n \"\"\"\n valid_status_values = ['CERTIFIED', 'CERTIFIED-WITHDRAWN', 'DENIED']\n hb = hb[hb.CASE_STATUS.isin(valid_status_values)]\n hb['CERTIFIED'] = hb.CASE_STATUS.apply(get_status)\n return hb\n\n#read in data\nhb = pd.read_csv('Z:/Springboard/H1B_Capstone/data/h1b_kaggle.csv')\n\n#rename missing column header. This is from the data dict website\n#https://www.foreignlaborcert.doleta.gov/docs/Performance_Data/Disclosure/FY15-FY16/H-1B_FY16_Record_Layout.pdf\nhb.rename(columns={'Unnamed: 0': 'CASE_NUMBER'}, inplace = True)\nhb.set_index('CASE_NUMBER', inplace=True)\n\nhb = case_status(hb)\n\n#Convert year to an integer\nhb.YEAR = hb.YEAR.astype(np.int64)\n\n#Split WORKSITE into City and State\nhb['CITY'], hb['STATE'] = hb['WORKSITE'].str.split(', ', 1).str\nhb['CITY'] = hb['CITY'].str.strip()\nhb['STATE'] = hb['STATE'].str.strip()\n\n#log-transform wage into new column\nhb['LOG_WAGE'] = np.log10(hb['PREVAILING_WAGE'])\n\n#drop obviously erroneous records\nhb = hb[hb.PREVAILING_WAGE < 1e+09]\n\nhb.to_csv('Z:/Springboard/H1B_Capstone/data/h1b_clean.csv')\n","sub_path":"H1B_Capstone/python/h1b_cleanup.py","file_name":"h1b_cleanup.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"51965934","text":"from termcolor import colored\n\n\ndef leiaInt(phrase):\n while True:\n num = input(f'{phrase} ')\n if num.isnumeric():\n return num\n else:\n print(colored('ERROR!', 'red'))\n\n\nn = leiaInt('Enter an number: ')\nprint(f'You enter the number: {n}')\n\n\n","sub_path":"exercicosPython/exercises/ex001_114/ex104input.py","file_name":"ex104input.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"171607990","text":"# coding=utf-8\nimport requests\nimport datetime\nimport time\nimport threading\nimport os\n\nurl = \"\"\nr = \"\"\nthreads = []\nnub = 10 # 设置并发线程数\nThinkTime = 1 # 设置思考时间\n\n\nclass url_request():\n times = []\n error = []\n\n def req(self):\n myreq = url_request()\n timestamp = str(int(round(time.time() * 1000)))\n randomno = timestamp[-7:-1]\n h = {\n \"Content-Type\": \"application/json;charset=utf-8\"\n }\n d = [{\n \"projectCode\": \"劳务实名制人员上传对外标准接口\",\n \"teamSysNo\": \"test0001\",\n \"workerName\": \"劳务工\" + timestamp,\n \"idCardNumber\": randomno + \"199008123819\",\n \"workType\": \"水泥工\",\n \"address\": \"住址\",\n \"cellPhone\": \"15372027056\",\n \"grantOrg\": \"发证机关\",\n \"headImage\": \"\",\n \"corpName\": \"新中大\"\n }]\n url = \"http://192.168.23.153/AttendenceService/LrsData/PostYgCraftInfo4HY\"\n print(url)\n r = requests.post(url, headers=h, json=d, verify=False)\n print(r.json())\n f.write(\"\\n\" + str(r.json()))\n ResponseTime = float(r.elapsed.microseconds) / 1000 # 获取响应时间,单位ms\n myreq.times.append(ResponseTime) # 将响应时间写入数组\n if r.status_code != 200:\n myreq.error.append(\"0\")\n print(r.json())\n\n\nif __name__ == '__main__':\n directory = \"C:/Users/lenovo/Desktop/数字工地自动化测试/输出日志记录\"\n os.chdir(directory) # 切换到directory目录\n cwd = os.getcwd() # 获取当前目录即dir目录下\n timenow = time.strftime('%Y-%m-%d', time.localtime()) # 将指定格式的当前时间以字符串输出\n suffix = \".txt\"\n newfile = timenow + suffix\n if not os.path.exists(newfile):\n f = open(newfile, 'w')\n print(newfile)\n f.close()\n print(newfile + \"创建成功\")\n else:\n print(newfile + \"已创建\")\n f = open(newfile, 'r+')\n f.read()\n f.write(\"\\n ——————————————————劳务工外部接口测试日志——————————————————\")\n threads = []\n starttime = datetime.datetime.now()\n print(\"请求开始时间 %s\" % starttime)\n nub = 10 # 设置并发线程数\n ThinkTime = 0.1 # 设置思考时间\n f.write(\"\\n 开始时间:\" + str(starttime) + \"\\n 接口返回为:\")\n myreq = url_request()\n for i in range(1, nub + 1):\n t = threading.Thread(target=myreq.req)\n threads.append(t)\n for t in threads:\n time.sleep(ThinkTime)\n print(\"thread %s\" % t) # 打印线程\n t.setDaemon(True)\n t.start()\n\n t.join() # 线程阻塞\n endtime = datetime.datetime.now()\n print(\"响应结束时间 %s\" % endtime)\n f.write(\"\\n 结束时间:\" + str(endtime))\n time.sleep(3)\n if len(url_request.times) != 0:\n AverageTime = \"{:.3f}\".format(float(sum(url_request.times)) / float(len(url_request.times))) # 计算数组的平均值,保留3位小数\n else:\n AverageTime = 0\n print(\"接口请求平均时间 %s ms\" % AverageTime) # 打印平均响应时间\n usetime = str(endtime - starttime)\n hour = usetime.split(':').pop(0)\n minute = usetime.split(':').pop(1)\n second = usetime.split(':').pop(2)\n totaltime = float(hour) * 60 * 60 + float(minute) * 60 + float(second) # 计算总的思考时间+请求时间\n print(\"设置线程数 %s 个\" % nub) # 打印并发数\n print(\"接口总共请求时间 %s s\" % (totaltime - float(nub * ThinkTime / 1000))) # 打印总共消耗的时间\n print(\"失败的请求接口数量 %s 个\" % url_request.error.count(\"0\")) # 打印错误请求数\n f.write(\"\\n 设置线程数 %s 个\" % nub + \"\\n 接口总共请求时间 %s s\" % (\n totaltime - float(nub * ThinkTime / 1000)) + \"\\n 失败的请求接口数量 %s 个\" % url_request.error.count(\"0\"))\n f.close()\n","sub_path":"i8劳务工相关外部接口测试/劳务工外部上传接口多并发测试.py","file_name":"劳务工外部上传接口多并发测试.py","file_ext":"py","file_size_in_byte":4008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"612899500","text":"#\n# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2019 Intel Corporation\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#\n\nimport os\nimport sys\n\nfrom common.base_model_init import BaseModelInitializer\nfrom common.base_model_init import set_env_var\n\nfrom common.utils.validators import check_positive_number\n\nimport argparse\n\n\nclass ModelInitializer(BaseModelInitializer):\n def run_inference_sanity_checks(self, args, custom_args):\n if not args.input_graph:\n sys.exit(\"Please provide a path to the frozen graph directory\"\n \" via the '--in-graph' flag.\")\n if not args.data_location and self.args.accuracy_only:\n sys.exit(\"Please provide a path to the data directory via the \"\n \"'--data-location' flag.\")\n if args.socket_id == -1 and args.num_cores == -1:\n print(\"***Warning***: Running inference on all cores could degrade\"\n \" performance. Pass a '--socket-id' to specify running on a\"\n \" single socket instead.\\n\")\n\n def __init__(self, args, custom_args, platform_util):\n super(ModelInitializer, self).__init__(args, custom_args, platform_util)\n\n arg_parser = argparse.ArgumentParser(description='Parse additional args')\n\n arg_parser.add_argument(\n \"--input-size\", help=\"Size of the input graph \",\n dest=\"input_size\", default=300, type=check_positive_number)\n arg_parser.add_argument(\"--warmup-steps\", dest='warmup_steps',\n type=check_positive_number, default=200,\n help=\"Number of warmup steps\")\n arg_parser.add_argument(\"--steps\", dest='steps',\n type=check_positive_number, default=800,\n help=\"Number of steps\")\n\n self.additional_args, unknown_args = arg_parser.parse_known_args(custom_args)\n self.run_inference_sanity_checks(self.args, self.custom_args)\n\n # Set KMP env vars, if they haven't already been set\n config_file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"config.json\")\n self.set_kmp_vars(config_file_path)\n\n self.set_num_inter_intra_threads()\n\n set_env_var(\"OMP_NUM_THREADS\", self.args.num_intra_threads)\n\n self.model_dir = os.path.join(self.args.intelai_models, self.args.mode, self.args.precision)\n\n # get benchmark command\n benchmark_script = os.path.join(self.model_dir, \"infer_detections.py\")\n\n # get command with numactl\n self.run_cmd = self.get_command_prefix(self.args.socket_id)\n self.run_cmd += \"{0} {1}\".format(self.python_exe, benchmark_script)\n self.run_cmd += \" --input-graph {0}\".format(self.args.input_graph)\n self.run_cmd += \" --batch-size {0}\".format(args.batch_size)\n self.run_cmd += \" --inter-op-parallelism-threads {0}\".format(self.args.num_inter_threads)\n self.run_cmd += \" --intra-op-parallelism-threads {0}\".format(self.args.num_intra_threads)\n self.run_cmd += \" --input-size {0}\".format(self.additional_args.input_size)\n self.run_cmd += \" --warmup-steps {0}\".format(self.additional_args.warmup_steps)\n self.run_cmd += \" --steps {0}\".format(self.additional_args.steps)\n\n if self.args.accuracy_only:\n self.run_cmd += \" --accuracy-only \"\n self.run_cmd += \" --data-location {0}\".format(self.args.data_location)\n\n def run(self):\n old_python_path = os.environ[\"PYTHONPATH\"]\n benchmarks_path = os.path.join(self.args.model_source_dir, \"../ssd-resnet-benchmarks\")\n os.environ[\"PYTHONPATH\"] = os.path.join(self.args.model_source_dir, \"research\")\n\n # TODO: make it a property in PlatformUtils (platform_util.os_type) to get the host OS.\n # We already do the OS check there to see if it's one that we support.\n if os.environ.get('OS', '') == 'Windows_NT':\n os.environ[\"PYTHONPATH\"] += \";\" + os.path.join(benchmarks_path, \"scripts/tf_cnn_benchmarks\")\n else:\n os.environ[\"PYTHONPATH\"] += \":\" + os.path.join(benchmarks_path, \"scripts/tf_cnn_benchmarks\")\n self.run_command(self.run_cmd)\n os.environ[\"PYTHONPATH\"] = old_python_path\n","sub_path":"benchmarks/object_detection/tensorflow/ssd-resnet34/inference/int8/model_init.py","file_name":"model_init.py","file_ext":"py","file_size_in_byte":4743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"31274288","text":"# 获取用户关注人物信息\nimport requests\nfrom bson import json_util\nimport json\nimport math\nimport time\nfrom db import mdb\n# dbInstance = mdb.dbInstance()\nsinceErrorId = []\nsince_id = ''\ncookies = {\"_T_WM\":\"fdbf8bc44c795c5cda57655e31c304de\",\"ALF\":\"1526014941\",\"SCF\":\"ApRKvktpAcri8KRFdlfeaR8dMo-GQd5NxTEoaTuNtdjmAq-3_higwpSMdrV72mrVn3LFqgAfSSwbcYrXvRQwm1Q.\",\"SUB\":\"_2A253ydKODeRhGeRO4lQQ8yjMzTiIHXVVNf7GrDV6PUJbktAKLUugkW1NUErsJnvjJSKp6jEcynkOR6rIDOZFDDjS\",\"SUBP\":\"0033WrSXqPxfM725Ws9jqgMF55529P9D9WFB2S6d3gIMp73iO8nSlZep5JpX5K-hUgL.Foz71Kqpe0q7SoB2dJLoI7pFdGHLKg8.qgY_C-.t\",\"SUHB\":\"0y0YEigCc5VM7u\",\"H5_INDEX\":\"3\",\"H5_INDEX_TITLE\":\"BlueMadao-II\",\"WEIBOCN_FROM\":\"1110006030\",\"M_WEIBOCN_PARAMS\":\"luicode%3D10000012%26lfid%3D1005052096136064_-_FANS%26fid%3D1076031918106382%26uicode%3D10000011\"}\ndef weiboSubcriptionScrapy(id, sid):\n \"\"\" 抓取微博评论\n :param id: 微博ID\n :param page: 评论翻页页数\n :return:\n \"\"\"\n url = 'https://m.weibo.cn/api/container/getIndex'\n params= {\n 'containerid': id\n }\n if sid != '':\n params = {\n 'containerid': id,\n 'since_id': sid\n }\n try:\n print(params)\n res = requests.get(url, params=params, cookies=cookies)\n content = res.content\n fileHandle = 'followers.json'\n resJson = json.loads(content)\n print(url)\n print(resJson)\n data = processJSON(resJson, sid)\n with open(fileHandle, 'wt', encoding='utf-8') as f:\n json.dump(resJson, f, indent=4, ensure_ascii=False, default=json_util.default)\n since_id = data['sid']\n hasNext = data['hasNext']\n if hasNext:\n time.sleep(3)\n weiboSubcriptionScrapy(id, since_id)\n else:\n print('completed')\n except BaseException as err:\n print('error page process' + str(err))\n\n\n\n\n\ndef processJSON(res, id):\n print(res)\n followersList = []\n if res['ok'] == 1:\n followersList = res['data']['cards']\n hasNext = True\n sid = res['data']['cardlistInfo']['since_id']\n return {\n 'list': followersList,\n 'hasNext': hasNext,\n 'sid': sid\n }\n else:\n return {\n 'list': [],\n 'hasNext': False,\n 'sid': ''\n }\n\n\n\nif __name__ == '__main__':\n id = '231051_-_followersrecomm_-_1662766362'\n weiboSubcriptionScrapy(id, since_id)\n print('sinceErrorId', sinceErrorId)\n","sub_path":"Scrapy/scrapy_weibo/weiboSubscription.py","file_name":"weiboSubscription.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"484125789","text":"import matplotlib.pyplot as plt\nimport tensorflow as tf\nimport numpy as np\nimport os \nfrom skimage import transform\n\n#unused\nvar_list = []\n\nbatch_size = 5\nout_size = 256*256\n\ndata_dir = '../data/'\ninput_dir = data_dir + 'input/'\noutput_dir = data_dir + 'output/'\n\nnum_files = 0\nwhile 1:\n filename = input_dir + 'batch{}.npy'.format(num_files)\n if not os.path.exists(filename):\n break\n num_files += 1\n\n#print(num_files)\nnum_train_files = num_files - 5\n\nbuffer = [None, None]\nbuffer_count = 0\n\ndef next_batch(n, test = False):\n if not test:\n global buffer_count\n if buffer_count == 0:\n buffer_count = 40\n index = np.random.randint(0, num_train_files)\n\n filename = input_dir + 'batch{}.npy'.format(index)\n buffer[0] = np.load(filename).astype(np.float32)\n filename = output_dir + 'batch{}.npy'.format(index)\n buffer[1] = np.load(filename).astype(np.int32)\n\n indices = np.random.choice(buffer[0].shape[0], n, replace=False)\n batch = [buffer[0][indices], buffer[1][indices]]\n '''\n print(batch[0].shape)\n print(batch[1].shape)\n '''\n batch[0] = batch[0].reshape((batch[0].shape[0], -1))\n batch[1] = batch[1].reshape((batch[1].shape[0], -1))\n '''\n plt.subplot(121)\n plt.imshow(i[0], cmap='gray', interpolation='None')\n plt.subplot(122)\n plt.imshow(o[0], cmap='gray', interpolation='None')\n plt.show()\n '''\n buffer_count -= n\n return batch\n else:\n index = np.random.randint(num_train_files, num_files)\n filename = input_dir + 'batch{}.npy'.format(index)\n i = np.load(filename).astype(np.float32)\n filename = output_dir + 'batch{}.npy'.format(index)\n o = np.load(filename).astype(np.int32)\n\n indices = np.random.choice(i.shape[0], n, replace=False)\n batch = [i[indices], o[indices]]\n\n batch[0] = batch[0].reshape((batch[0].shape[0], -1))\n batch[1] = batch[1].reshape((batch[1].shape[0], -1))\n return batch\n\ndef weight_variable(shape):\n initial = tf.truncated_normal(shape, stddev=0.1)\n var = tf.Variable(initial)\n var_list.append(var)\n return var\n\ndef bias_variable(shape):\n initial = tf.constant(0.1, shape=shape)\n var = tf.Variable(initial)\n var_list.append(var)\n return var\n\ndef conv2d(x, W, pad='SAME'):\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding=pad)\n\ndef max_pool(bottom, ks=2, stride=2):\n return tf.nn.max_pool(bottom, ksize=[1, ks, ks, 1],\n strides=[1, stride, stride, 1], padding='SAME')\n\ndef conv_relu(bottom, nin, nout, ks=3, stride=1, pad='SAME'):\n W = weight_variable([ks, ks, nin, nout])\n b = bias_variable([nout])\n conv = conv2d(bottom, W, pad=pad)\n return conv, tf.nn.relu(conv + b)\n\n\n\nsess = tf.InteractiveSession()\n\nx = tf.placeholder(tf.float32, shape=[None, 256*256])\ny_ = tf.placeholder(tf.int32, shape=[None, out_size])\n\nx_image = tf.reshape(x, [-1, 256, 256, 1])\n\n\nconv1_1, relu1_1 = conv_relu(x_image, 1, 64)\npool1 = max_pool(relu1_1)\n\nconv2_1, relu2_1 = conv_relu(pool1, 64, 128)\npool2 = max_pool(relu2_1)\n\nconv3_1, relu3_1 = conv_relu(pool2, 128, 256)\nconv3_2, relu3_2 = conv_relu(relu3_1, 256, 256)\npool3 = max_pool(relu3_1)\n\nconv4_1, relu4_1 = conv_relu(pool3, 256, 512)\npool4 = max_pool(relu4_1)\n\nconv5_1, relu5_1 = conv_relu(pool4, 512, 512)\npool5 = max_pool(relu5_1)\n\n# fully conv\nfc6, relu6 = conv_relu(pool5, 512, 4096, ks=7, pad='VALID')\n\n#Dropout\nkeep_prob = tf.placeholder(tf.float32)\ndrop6 = tf.nn.dropout(relu6, keep_prob)\n\nfc7, relu7 = conv_relu(drop6, 4096, 4096, ks=1)\n\n#Dropout\ndrop7 = tf.nn.dropout(relu7, keep_prob)\n\nscore_fr, relu8 = conv_relu(drop7, 4096, 64, ks=1)\n\n\n'''\n#deconv\nW_deconv = weight_variable([128, 128, 3, 32])\nb_deconv = bias_variable([32])\ny_conv = tf.nn.conv2d_transpose(\n score_fr - b_deconv, \n W_deconv,\n [batch_size, 256, 256, 3],\n #y_.get_shape(),\n [1,128,128,1],\n padding='SAME')\n'''\n\nW_fc = weight_variable([2*2*64, 48*48*3])\nb_fc = bias_variable([48*48*3])\n\ny_last = tf.reshape(tf.matmul(tf.reshape(relu8, [-1, 2*2*64]), W_fc) + b_fc, [-1, 48, 48, 3]) \n\ny_resized = tf.image.resize_nearest_neighbor(y_last, [256, 256])\n\n#skip, y_out = conv_relu(y_resized, 3, 3, ks=16)\n\n\ny_conv = tf.reshape(y_resized, [-1, 3])\n\ny_in = tf.to_int64(tf.reshape(y_, [-1]))\ny_fin = tf.one_hot(y_in, 3, 1., 0.)\n\n\n\n'''\n#fc8, relu8 = conv_relu(y_conv, 3, 3, ks=1)\ny_conv = tf.reshape(y_conv, [-1, 3])\n'''\n\ncross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y_conv, y_fin))\ncross_entropy = tf.Print(cross_entropy, [cross_entropy], \"cross_entropy: \")\n\n\nsquared_error = tf.reduce_sum(tf.squared_difference(y_conv, y_fin))\nsquared_error = tf.Print(squared_error, [squared_error], \"squared_error: \")\n\naccuracy = tf.reduce_mean(tf.div(cross_entropy, tf.reduce_sum(y_fin)))\n\n\n\ntrain_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\n\nsaver = tf.train.Saver()\n\ny_prob = tf.nn.softmax(y_conv)\nprint('y_prob shape: ', y_prob.get_shape())\nprint('y_fin shape: ', y_fin.get_shape())\n\n#sess.run(tf.initialize_all_variables())\n\nSHOW_PLOTS = True\n\nsaver.restore(sess, 'my-model-6999')\n\n\n\n\n\n\n\nfor j in range(100):\n batch = next_batch(batch_size, test = True)\n \n inp = y_fin.eval({y_: batch[1]})\n inp = np.reshape(inp, (batch_size, 256, 256, 3))\n out = y_prob.eval(feed_dict={x:batch[0], keep_prob: 1.})\n out = np.reshape(out, (batch_size, 256, 256, 3))\n \n plt.subplot(121)\n plt.imshow(np.reshape(batch[0][0], [256,256]), cmap='gray', interpolation='None')\n for j in range(3):\n plt.subplot(2, 6, j+4)\n plt.imshow(inp[0, :, :, j], cmap='gray', interpolation='None')\n plt.subplot(2, 6, j+10)\n plt.imshow(out[0, :, :, j], cmap='gray', interpolation='None')\n plt.show()\n\nfor i in range(20000):\n batch = next_batch(batch_size)\n train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})\n\n #print(squared_error.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.}))\n\n if i%500 == 0:\n\n inp = y_fin.eval({y_: batch[1]})\n inp = np.reshape(inp, (batch_size, 256, 256, 3))\n out = y_prob.eval(feed_dict={x:batch[0], keep_prob: 1.})\n print(out)\n out = np.reshape(out, (batch_size, 256, 256, 3))\n \n #print(score_fr.eval({x:batch[0], keep_prob: 1.}))\n #print(y_conv.eval({x:batch[0], keep_prob: 1.}))\n\n if SHOW_PLOTS:\n plt.subplot(121)\n plt.imshow(np.reshape(batch[0][0], [256,256]), cmap='gray', interpolation='None')\n for j in range(3):\n plt.subplot(2, 6, j+4)\n plt.imshow(inp[0, :, :, j], cmap='gray', interpolation='None')\n plt.subplot(2, 6, j+10)\n plt.imshow(out[0, :, :, j], cmap='gray', interpolation='None')\n plt.show()\n \n else:\n print(saver.save(sess, 'my-model', global_step=i))\n\n train_accuracy = accuracy.eval(feed_dict={\n x:batch[0], y_: batch[1], keep_prob: 1.})\n print(\"step {}, training accuracy {}\".format(i, train_accuracy))\n print(\"squared error {}\".format(squared_error.eval({x:batch[0], y_:batch[1], keep_prob: 1.})))\n print(\"sum {}\".format(tf.reduce_sum(y_fin).eval({ y_:batch[1]})))\n'''\nprint(\"test accuracy %g\"%accuracy.eval(feed_dict={\n x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.}))\n'''\n\n\n","sub_path":"med-segm/fully_conv.py","file_name":"fully_conv.py","file_ext":"py","file_size_in_byte":7489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"235680861","text":"class estado:\n def __init__(self):\n self.name = None\n self.proxEstado = None\n self.anteriorEstado = None\n\n def get_proxEstado(self):\n return self.proxEstado\n \n def set_proxEstado(self, prox):\n self.proxEstado = prox\n\n def get_anteriorEstado(self):\n return self.anteriorEstado\n \n def set_anteriorEstado(self, anterior):\n self.anteriorEstado = anterior\n\nclass Automato:\n def __init__(self):\n self.alfabeto = []\n self.transicoes = {}\n self.estados = []\n self.estadoInicial = None\n self.estadosFinais = []\n self.primeiro_estado = None\n self.ultimo_estado = None\n self.quantidade_estados = 0\n \n def verificar_repitidos(self, dados):\n vetor = []\n for i in dados:\n if(i not in vetor):\n vetor.append(i)\n return vetor\n\n def set_alfabeto(self, alfabeto):\n self.alfabeto = self.verificar_repitidos(alfabeto)\n\n def set_estados(self, estados):\n self.estados = self.verificar_repitidos(estados)\n self.estados.sort()\n self.alfabeto.append(\"epsilon\")\n \n def set_estadoInicial(self, estado):\n if estado in self.estados:\n self.estadoInicial = estado\n else:\n print(\"Estado inicial invalido\")\n \n def set_estadosFinais(self, estados):\n estados = self.verificar_repitidos(estados)\n for i in estados:\n if i in self.estados:\n if i not in self.estadosFinais:\n self.estadosFinais.append(i)\n #print(self.estadosFinais)\n \n def verificar_transicoes(self, transicoes):\n estados_transições = []\n for estado in transicoes:\n check_estados = []; estados_transições.append(estado)\n if(estado not in check_estados and estado in self.estados):\n check_estados.append(estado); check_alfabeto = []\n for entrada in transicoes[estado]:\n check_alfabeto.append(entrada)\n if(entrada in self.alfabeto):\n for i in transicoes[estado][entrada]:\n if(i not in self.estados):\n return False\n else:\n return False \n check_alfabeto.sort()\n if(check_alfabeto != self.alfabeto):\n return False \n else:\n return False\n \n estados_transições.sort()\n if(estados_transições != self.estados):\n return False\n return True\n\n def set_transicoes(self, transicoes):\n if(self.verificar_transicoes(transicoes) == True):\n self.transicoes = transicoes\n else:\n print(\"Funções de transições fora do Padrao de um AFND\")\n\n def laco_transicoes(self,simbolo):\n estado = self.primeiro_estado\n aux_inicio = None\n aux_fim = None\n if estado != None:\n controle = False\n while estado.get_proxEstado() != None:\n aux1, aux2 = self.aplicacao_transicoes(simbolo, estado)\n if((aux_inicio and aux_inicio) == None):\n aux_inicio = aux1\n aux_fim = aux2\n else:\n aux_fim.set_proxEstado(aux1)\n if aux1 != None:\n aux1.set_anteriorEstado(aux_fim)\n aux_fim = aux2\n estado = estado.get_proxEstado()\n if(estado == None):\n break\n else: \n aux1, aux2 = self.aplicacao_transicoes(simbolo, estado)\n if((aux1 and aux2) != None):\n if((aux_inicio and aux_fim) == None):\n aux_inicio = aux1\n aux_fim = aux2\n else:\n aux_fim.set_proxEstado(aux1)\n aux1.set_anteriorEstado(aux_fim)\n aux_fim = aux2\n if((aux_inicio and aux_fim) != None):\n estado.set_proxEstado(aux_inicio)\n aux_inicio.set_anteriorEstado(estado)\n self.ultimo_estado = aux_fim\n\n def organicacao_epsilon(self, estado, inicio_fila, fim_fila):\n if((inicio_fila and fim_fila) == None):\n inicio_fila = estado\n fim_fila = estado\n else:\n fim_fila.set_proxEstado(estado)\n estado.set_anteriorEstado(fim_fila)\n estado.set_anteriorEstado(fim_fila)\n fim_fila = estado\n return inicio_fila,fim_fila\n\n\n def transicao_epsilon(self,estado_atual):\n inicio_fila = None\n fim_fila = None\n controle = False\n for i in range(len(self.transicoes[estado_atual][\"epsilon\"])):\n novoEstado = estado()\n novoEstado.name = self.transicoes[estado_atual][\"epsilon\"][i]\n if(i == len(self.transicoes[estado_atual][\"epsilon\"])):\n controle = True\n while(self.transicoes[novoEstado.name][\"epsilon\"] != []):\n guarda_estado = novoEstado.name\n for j in range(len(self.transicoes[novoEstado.name][\"epsilon\"])):\n if(j>0):\n newEstado = estado()\n newEstado.name = self.transicoes[guarda_estado][\"epsilon\"][j]\n inicio_fila, fim_fila = self.organicacao_epsilon(newEstado,inicio_fila,fim_fila)\n else:\n novoEstado.name = self.transicoes[novoEstado.name][\"epsilon\"][j]\n #print(novoEstado.name)\n inicio_fila, fim_fila = self.organicacao_epsilon(novoEstado,inicio_fila,fim_fila)\n self.quantidade_estados += 1\n else:\n if(controle == False):\n inicio_fila, fim_fila = self.organicacao_epsilon(novoEstado,inicio_fila,fim_fila)\n self.quantidade_estados += 1\n return inicio_fila,fim_fila\n \n def aplicacao_transicoes(self, simbolo,estado_atual): \n aux_inicio = None\n aux_fim = None\n estados = estado_atual.name\n\n for i in range(len(self.transicoes[estados][simbolo])):\n if(i == 0):\n estado_atual.name = self.transicoes[estados][simbolo][i]\n inicio_epsilon, fim_epsilon = self.transicao_epsilon(estado_atual.name) \n if((aux_inicio and aux_fim) == None):\n aux_inicio = inicio_epsilon\n aux_fim = fim_epsilon\n else: \n print(inicio_epsilon.name, fim_epsilon.name)\n aux_fim.set_proxEstado(inicio_epsilon)\n inicio_epsilon.set_anteriorEstado(aux_fim)\n aux_fim =fim_epsilon\n else:\n novoEstado = estado()\n novoEstado.name = self.transicoes[estados][simbolo][i]\n inicio_epsilon, fim_epsilon = self.transicao_epsilon(novoEstado.name)\n if((aux_inicio and aux_fim) == None):\n aux_inicio = novoEstado\n aux_fim = novoEstado\n else:\n aux_fim.set_proxEstado(novoEstado)\n novoEstado.set_anteriorEstado(aux_fim)\n aux_fim = novoEstado\n if((inicio_epsilon and fim_epsilon) != None):\n aux_fim.set_proxEstado(inicio_epsilon)\n inicio_epsilon.set_anteriorEstado(aux_fim)\n aux_fim =fim_epsilon\n\n self.quantidade_estados += 1\n if(len(self.transicoes[estados][simbolo]) == 0):\n self.entrada_sem_saida(estado_atual)\n return aux_inicio, aux_fim\n\n def entrada_sem_saida(self, estado):\n if(estado == self.primeiro_estado):\n self.primeiro_estado = self.primeiro_estado.get_proxEstado()\n elif(estado == self.ultimo_estado):\n self.ultimo_estado = self.ultimo_estado.get_anteriorEstado()\n self.ultimo_estado.set_proxEstado(None)\n else:\n estado1 = estado.get_anteriorEstado()\n estado2 = estado.get_proxEstado()\n estado1.set_proxEstado(estado2)\n estado2.set_anteriorEstado(estado1)\n self.quantidade_estados += -1\n\n def set_string(self, string):\n for simbolo in list(set(string)):\n if(simbolo not in self.alfabeto):\n print(\"'\"+ simbolo +\"' nao faz parte do alfabeto\")\n return\n \n if(self.quantidade_estados == 0):\n if(self.estadoInicial == None):\n print(\"Automato não possui estado inicial\")\n return\n novoEstado = estado()\n novoEstado.name = self.estadoInicial\n self.primeiro_estado = novoEstado\n self.ultimo_estado = novoEstado\n self.quantidade_estados += 1\n\n for simbolo in string:\n self.laco_transicoes(simbolo)\n \n estado_atual = self.primeiro_estado\n\n if(estado_atual != None):\n while(estado_atual.get_proxEstado() != None):\n #print(estado_atual.name)\n if(self.verificacao_automato(estado_atual.name) == True):\n self.end()\n return True\n estado_atual = estado_atual.get_proxEstado()\n else:\n #print(estado_atual.name)\n if(self.verificacao_automato(estado_atual.name) == True):\n self.end()\n return True\n else:\n print(\"String Recusada\")\n self.end()\n return False\n else:\n print(\"String Recusada\")\n self.end()\n return False\n \n def verificacao_automato(self, estado):\n if(estado in self.estadosFinais):\n print(\"String Aceita\")\n return True\n\n def end(self):\n self.primeiro_estado = None\n self.ultimo_estado = None\n self.quantidade_estados = 0\n","sub_path":"Item C - AFND to AFN/AFND.py","file_name":"AFND.py","file_ext":"py","file_size_in_byte":10190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"279529920","text":"from urllib.parse import urlencode\n\nfrom tornado.httpclient import AsyncHTTPClient\nfrom tornado.web import RequestHandler\nfrom tornado.web import HTTPError as ServerHTTPError\nfrom tornado.httpclient import HTTPError as ClientHTTPError\nfrom tornado.escape import json_decode\nfrom tornado import gen\n\nfrom blueshed.micro.web.user_mixin import UserMixin\nfrom blueshed.micro.web.cors_mixin import CorsMixin, cors\n\n\nclass RemoteSignInHandler(UserMixin, CorsMixin, RequestHandler):\n '''\n Validates a one-time-password with an auth server and\n puts the result into our access control cookie\n and redirects.\n '''\n\n def initialize(self, service_name, service_secret, auth_url, http_origins=None): # noqa\n self.service_name = service_name\n self.service_secret = service_secret\n self.auth_url = auth_url\n\n # cors options\n self.set_cors_methods('GET,OPTIONS')\n if http_origins:\n self.set_cors_whitelist(http_origins)\n\n def write_error(self, *args, **kwargs):\n '''\n Must override base write error to stop uncaught\n HTTP errors from clearing CORS headers\n '''\n self.write_cors_headers()\n RequestHandler.write_error(self, *args, **kwargs)\n\n def options(self):\n return self.cors_options()\n\n @property\n def auth_headers(self):\n return {\n \"service-name\": self.service_name,\n \"service-secret\": self.service_secret\n }\n\n @cors\n @gen.coroutine\n def get(self):\n # get otp from request\n otp = self.get_argument(\"otp\")\n\n try:\n # make request to auth server\n response = yield AsyncHTTPClient().fetch(\n self.auth_url + '/control/get_user',\n method=\"POST\",\n headers=self.auth_headers,\n body=urlencode({\"user_otp\": otp})\n )\n except ClientHTTPError as error:\n # check content type for json to try and parse result\n if error.response and error.response.headers.get('Content-Type') is 'application/json; charset=UTF-8':\n # decode the response\n content = json_decode(error.response.body)\n\n # catch client otp errors\n if content['status_code'] == 400:\n raise ServerHTTPError(401, reason=content['message'])\n\n # handle all other cases as internal errors\n raise error\n\n else:\n # set client cookie and respond\n content = json_decode(response.body)\n self.set_secure_cookie(self.cookie_name, str(content['result']['id']))\n self.write({\"result\": \"OK\"})\n self.finish()\n","sub_path":"talka2z/auth/handlers/remote_sign_in_handler.py","file_name":"remote_sign_in_handler.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"378359215","text":"# Copyright (c) 2016-2020, Neil Booth\n# Copyright (c) 2017, the ElectrumX authors\n#\n# All rights reserved.\n#\n# See the file \"LICENCE\" for information about the copyright\n# and warranty status of this software.\n\n'''Interface to the blockchain database.'''\n\n\nimport array\nimport ast\nimport os\nimport time\nfrom bisect import bisect_right\nfrom collections import namedtuple\nfrom glob import glob\n\nimport attr\nfrom aiorpcx import run_in_thread, sleep\n\nfrom electrumx.lib import util\nfrom electrumx.lib.hash import hash_to_hex_str, HASHX_LEN\nfrom electrumx.lib.merkle import Merkle, MerkleCache\nfrom electrumx.lib.util import (\n formatted_time, pack_be_uint16, pack_be_uint32, pack_le_uint32,\n unpack_le_uint32, unpack_be_uint32, unpack_le_uint64, base_encode\n)\nfrom electrumx.server.history import History\nfrom electrumx.server.storage import db_class\n\nASSET = namedtuple(\"ASSET\", \"tx_num tx_pos tx_hash height name value\")\nUTXO = namedtuple(\"UTXO\", \"tx_num tx_pos tx_hash height value\")\n\n\n@attr.s(slots=True)\nclass FlushData(object):\n height = attr.ib()\n tx_count = attr.ib()\n headers = attr.ib()\n block_tx_hashes = attr.ib()\n # The following are flushed to the UTXO DB if undo_infos is not None\n undo_infos = attr.ib()\n adds = attr.ib()\n deletes = attr.ib()\n tip = attr.ib()\n # Assets\n asset_adds = attr.ib()\n asset_deletes = attr.ib()\n asset_meta_adds = attr.ib()\n asset_meta_reissues = attr.ib()\n asset_undo_infos = attr.ib()\n asset_meta_undos = attr.ib()\n asset_meta_deletes = attr.ib()\n asset_count = attr.ib()\n\n # Asset Qualifiers\n asset_restricted2qual = attr.ib()\n asset_restricted2qual_del = attr.ib()\n asset_restricted2qual_undo = attr.ib()\n asset_current_associations = attr.ib()\n\n asset_restricted_freezes = attr.ib()\n asset_restricted_freezes_current = attr.ib()\n asset_restricted_freezes_del = attr.ib()\n asset_restricted_freezes_undo = attr.ib()\n\n asset_tag2pub = attr.ib()\n asset_tag2pub_current = attr.ib()\n asset_tag2pub_del = attr.ib()\n asset_tag2pub_undo = attr.ib()\n\n # Broadcasts\n asset_broadcasts = attr.ib()\n asset_broadcasts_undo = attr.ib()\n asset_broadcasts_del = attr.ib()\n\n\nclass DB(object):\n '''Simple wrapper of the backend database for querying.\n\n Performs no DB update, though the DB will be cleaned on opening if\n it was shutdown uncleanly.\n '''\n\n DB_VERSIONS = [6, 7, 8]\n\n class DBError(Exception):\n '''Raised on general DB errors generally indicating corruption.'''\n\n def __init__(self, env):\n self.logger = util.class_logger(__name__, self.__class__.__name__)\n self.env = env\n self.coin = env.coin\n\n self.header_offset = self.coin.static_header_offset\n self.header_len = self.coin.static_header_len\n\n self.logger.info(f'switching current directory to {env.db_dir}')\n os.chdir(env.db_dir)\n\n self.db_class = db_class(self.env.db_engine)\n self.history = History()\n self.utxo_db = None\n self.utxo_flush_count = 0\n self.fs_height = -1\n self.fs_tx_count = 0\n self.fs_asset_count = 0\n self.db_height = -1\n self.db_tx_count = 0\n self.db_asset_count = 0\n self.db_tip = None\n self.tx_counts = None\n self.last_flush = time.time()\n self.last_flush_tx_count = 0\n self.last_flush_asset_count = 0\n self.wall_time = 0\n self.first_sync = True\n self.db_version = -1\n\n self.asset_db = None\n self.asset_info_db = None\n\n self.logger.info(f'using {self.env.db_engine} for DB backend')\n\n # Header merkle cache\n self.merkle = Merkle()\n self.header_mc = MerkleCache(self.merkle, self.fs_block_hashes)\n\n self.headers_file = util.LogicalFile('meta/headers', 2, 16000000)\n self.tx_counts_file = util.LogicalFile('meta/txcounts', 2, 2000000)\n self.hashes_file = util.LogicalFile('meta/hashes', 4, 16000000)\n\n async def _read_tx_counts(self):\n if self.tx_counts is not None:\n return\n # tx_counts[N] has the cumulative number of txs at the end of\n # height N. So tx_counts[0] is 1 - the genesis coinbase\n size = (self.db_height + 1) * 8\n tx_counts = self.tx_counts_file.read(0, size)\n assert len(tx_counts) == size\n self.tx_counts = array.array('Q', tx_counts)\n if self.tx_counts:\n assert self.db_tx_count == self.tx_counts[-1]\n else:\n assert self.db_tx_count == 0\n\n async def _open_dbs(self, for_sync, compacting):\n assert self.utxo_db is None\n assert self.asset_db is None\n assert self.asset_info_db is None\n\n # First UTXO DB\n self.utxo_db = self.db_class('utxo', for_sync)\n if self.utxo_db.is_new:\n self.logger.info('created new database')\n self.logger.info('creating metadata directory')\n os.mkdir('meta')\n with util.open_file('COIN', create=True) as f:\n f.write(f'ElectrumX databases and metadata for '\n f'{self.coin.NAME} {self.coin.NET}'.encode())\n else:\n self.logger.info(f'opened UTXO DB (for sync: {for_sync})')\n self.read_utxo_state()\n\n # Asset DB\n self.asset_db = self.db_class('asset', for_sync)\n self.read_asset_state()\n self.asset_info_db = self.db_class('asset_info', for_sync)\n\n # Then history DB\n self.utxo_flush_count = self.history.open_db(self.db_class, for_sync,\n self.utxo_flush_count,\n compacting)\n self.clear_excess_undo_info()\n\n # Read TX counts (requires meta directory)\n await self._read_tx_counts()\n\n async def open_for_compacting(self):\n await self._open_dbs(True, True)\n\n async def open_for_sync(self):\n '''Open the databases to sync to the daemon.\n\n When syncing we want to reserve a lot of open files for the\n synchronization. When serving clients we want the open files for\n serving network connections.\n '''\n await self._open_dbs(True, False)\n\n async def open_for_serving(self):\n '''Open the databases for serving. If they are already open they are\n closed first.\n '''\n if self.utxo_db:\n self.logger.info('closing DBs to re-open for serving')\n self.utxo_db.close()\n self.asset_db.close()\n self.asset_info_db.close()\n self.history.close_db()\n self.utxo_db = None\n self.asset_db = None\n self.asset_info_db = None\n await self._open_dbs(False, False)\n\n # Header merkle cache\n async def populate_header_merkle_cache(self):\n self.logger.info('populating header merkle cache...')\n length = max(1, self.db_height - self.env.reorg_limit)\n start = time.monotonic()\n await self.header_mc.initialize(length)\n elapsed = time.monotonic() - start\n self.logger.info(f'header merkle cache populated in {elapsed:.1f}s')\n\n async def header_branch_and_root(self, length, height):\n return await self.header_mc.branch_and_root(length, height)\n\n # Flushing\n def assert_flushed(self, flush_data):\n '''Asserts state is fully flushed.'''\n assert flush_data.tx_count == self.fs_tx_count == self.db_tx_count\n assert flush_data.asset_count == self.fs_asset_count == self.db_asset_count\n assert flush_data.height == self.fs_height == self.db_height\n assert flush_data.tip == self.db_tip\n assert not flush_data.headers\n assert not flush_data.block_tx_hashes\n assert not flush_data.adds\n assert not flush_data.deletes\n assert not flush_data.undo_infos\n\n assert not flush_data.asset_adds\n assert not flush_data.asset_deletes\n assert not flush_data.asset_undo_infos\n\n assert not flush_data.asset_meta_adds\n assert not flush_data.asset_meta_reissues\n assert not flush_data.asset_meta_undos\n assert not flush_data.asset_meta_deletes\n\n assert not flush_data.asset_restricted2qual\n assert not flush_data.asset_restricted2qual_del\n assert not flush_data.asset_restricted2qual_undo\n assert not flush_data.asset_current_associations\n\n assert not flush_data.asset_restricted_freezes\n assert not flush_data.asset_restricted_freezes_current\n assert not flush_data.asset_restricted_freezes_del\n assert not flush_data.asset_restricted_freezes_undo\n\n assert not flush_data.asset_tag2pub\n assert not flush_data.asset_tag2pub_del\n assert not flush_data.asset_tag2pub_undo\n assert not flush_data.asset_tag2pub_current\n\n assert not flush_data.asset_broadcasts\n assert not flush_data.asset_broadcasts_undo\n assert not flush_data.asset_broadcasts_del\n\n self.history.assert_flushed()\n\n def flush_dbs(self, flush_data, flush_utxos, estimate_txs_remaining):\n '''Flush out cached state. History is always flushed; UTXOs are\n flushed if flush_utxos.'''\n if flush_data.height == self.db_height:\n self.assert_flushed(flush_data)\n return\n\n start_time = time.time()\n prior_flush = self.last_flush\n tx_delta = flush_data.tx_count - self.last_flush_tx_count\n asset_delta = flush_data.asset_count - self.last_flush_asset_count\n\n # Flush to file system\n self.flush_fs(flush_data)\n\n # Then history\n self.flush_history()\n\n with self.asset_db.write_batch() as batch:\n if flush_utxos:\n self.flush_asset_db(batch, flush_data)\n self.flush_asset_state(batch)\n\n with self.asset_info_db.write_batch() as batch:\n if flush_utxos:\n self.flush_asset_info_db(batch, flush_data)\n\n # Flush state last as it reads the wall time.\n with self.utxo_db.write_batch() as batch:\n if flush_utxos:\n self.flush_utxo_db(batch, flush_data)\n self.flush_state(batch)\n\n # Update and put the wall time again - otherwise we drop the\n # time it took to commit the batch\n self.flush_state(self.utxo_db)\n\n elapsed = self.last_flush - start_time\n self.logger.info(f'flush #{self.history.flush_count:,d} took '\n f'{elapsed:.1f}s. Height {flush_data.height:,d} '\n f'txs: {flush_data.tx_count:,d} ({tx_delta:+,d}) '\n f'assets: {flush_data.asset_count:,d} ({asset_delta:+,d})')\n\n # Catch-up stats\n if self.utxo_db.for_sync:\n flush_interval = self.last_flush - prior_flush\n tx_per_sec_gen = int(flush_data.tx_count / self.wall_time)\n tx_per_sec_last = 1 + int(tx_delta / flush_interval)\n eta = estimate_txs_remaining() / tx_per_sec_last\n self.logger.info(f'tx/sec since genesis: {tx_per_sec_gen:,d}, '\n f'since last flush: {tx_per_sec_last:,d}')\n self.logger.info(f'sync time: {formatted_time(self.wall_time)} '\n f'ETA: {formatted_time(eta)}')\n\n def flush_fs(self, flush_data):\n '''Write headers, tx counts and block tx hashes to the filesystem.\n\n The first height to write is self.fs_height + 1. The FS\n metadata is all append-only, so in a crash we just pick up\n again from the height stored in the DB.\n '''\n prior_tx_count = (self.tx_counts[self.fs_height]\n if self.fs_height >= 0 else 0)\n assert len(flush_data.block_tx_hashes) == len(flush_data.headers)\n assert flush_data.height == self.fs_height + len(flush_data.headers)\n assert flush_data.tx_count == (self.tx_counts[-1] if self.tx_counts\n else 0)\n assert len(self.tx_counts) == flush_data.height + 1\n hashes = b''.join(flush_data.block_tx_hashes)\n flush_data.block_tx_hashes.clear()\n assert len(hashes) % 32 == 0\n assert len(hashes) // 32 == flush_data.tx_count - prior_tx_count\n\n # Write the headers, tx counts, and tx hashes\n start_time = time.monotonic()\n height_start = self.fs_height + 1\n offset = self.header_offset(height_start)\n self.headers_file.write(offset, b''.join(flush_data.headers))\n flush_data.headers.clear()\n\n offset = height_start * self.tx_counts.itemsize\n self.tx_counts_file.write(offset,\n self.tx_counts[height_start:].tobytes())\n offset = prior_tx_count * 32\n self.hashes_file.write(offset, hashes)\n\n self.fs_height = flush_data.height\n self.fs_tx_count = flush_data.tx_count\n self.fs_asset_count = flush_data.asset_count\n\n if self.utxo_db.for_sync:\n elapsed = time.monotonic() - start_time\n self.logger.info(f'flushed filesystem data in {elapsed:.2f}s')\n\n def flush_history(self):\n self.history.flush()\n\n def flush_asset_info_db(self, batch, flush_data: FlushData):\n start_time = time.monotonic()\n adds = len(flush_data.asset_meta_adds)\n reissues = len(flush_data.asset_meta_reissues)\n\n batch_delete = batch.delete\n for key in flush_data.asset_meta_deletes:\n batch_delete(key)\n flush_data.asset_meta_deletes.clear()\n\n batch_put = batch.put\n for key, value in flush_data.asset_meta_reissues.items():\n batch_put(key, value)\n flush_data.asset_meta_reissues.clear()\n\n for key, value in flush_data.asset_meta_adds.items():\n batch_put(key, value)\n flush_data.asset_meta_adds.clear()\n\n self.flush_asset_meta_undos(batch_put, flush_data.asset_meta_undos)\n flush_data.asset_meta_undos.clear()\n\n if self.asset_info_db.for_sync:\n elapsed = time.monotonic() - start_time\n self.logger.info(f'{adds:,d} assets\\' metadata created, '\n f'{reissues:,d} assets\\' metadata reissued, '\n f'{elapsed:.1f}s, committing...')\n\n def flush_asset_db(self, batch, flush_data: FlushData):\n start_time = time.monotonic()\n add_count = len(flush_data.asset_adds)\n spend_count = len(flush_data.asset_deletes) // 2\n\n restricted_assets = len(flush_data.asset_restricted2qual)\n freezes = len(flush_data.asset_restricted_freezes)\n tags = len(flush_data.asset_tag2pub)\n\n broadcasts = len(flush_data.asset_broadcasts)\n\n # Spends\n batch_delete = batch.delete\n for key in sorted(flush_data.asset_deletes):\n batch_delete(key)\n flush_data.asset_deletes.clear()\n\n # Qualifiers\n for key in sorted(flush_data.asset_restricted_freezes_del):\n batch_delete(key)\n flush_data.asset_restricted_freezes_del.clear()\n\n for key in sorted(flush_data.asset_restricted2qual_del):\n batch_delete(key)\n flush_data.asset_restricted2qual_del.clear()\n\n for key in sorted(flush_data.asset_tag2pub_del):\n batch_delete(key)\n flush_data.asset_tag2pub_del.clear()\n\n for key in sorted(flush_data.asset_broadcasts_del):\n batch_delete(b'b' + key)\n flush_data.asset_broadcasts_del.clear()\n\n # New Assets\n batch_put = batch.put\n for key, value in flush_data.asset_adds.items():\n # suffix = tx_idx + tx_num\n # key tx_hash (32), tx_idx (4)\n # value = hashx (11) + tx_num (5) + u64 sat val(8)+ namelen(1) + asset name\n hashX = value[:HASHX_LEN]\n suffix = key[-4:] + value[HASHX_LEN:5+HASHX_LEN]\n batch_put(b'h' + key[:4] + suffix, hashX)\n batch_put(b'u' + hashX + suffix, value[5+HASHX_LEN:])\n flush_data.asset_adds.clear()\n\n # New undo information\n self.flush_undo_infos(batch_put, flush_data.asset_undo_infos)\n flush_data.asset_undo_infos.clear()\n\n # FIXME: For current values, maybe have them in the db if they are true\n # or omit them if they are false. For now, there are not enough qualifiers\n # or restricted assets for this to be a problem.\n\n for key, value in flush_data.asset_tag2pub.items():\n # b'p' h160 -> asset\n # b'a' asset -> h160\n key_parser = util.DataParser(key)\n asset_len, asset = key_parser.read_var_bytes_tuple_bytes()\n h160_len, h160 = key_parser.read_var_bytes_tuple_bytes()\n idx = key_parser.read_bytes(4)\n tx_numb = key_parser.read_bytes(5)\n batch_put(b'p' + h160_len + h160 + idx + tx_numb, asset_len + asset + value)\n batch_put(b'a' + asset_len + asset + idx + tx_numb, h160_len + h160 + value)\n flush_data.asset_tag2pub.clear()\n\n self.flush_t2p_undo_infos(batch_put, flush_data.asset_tag2pub_undo)\n flush_data.asset_tag2pub_undo.clear()\n\n for key, value in flush_data.asset_tag2pub_current.items():\n # b't' h160 -> asset\n # b'Q' asset -> h160\n batch_put(key, value)\n flush_data.asset_tag2pub_current.clear()\n\n for key, value in flush_data.asset_restricted_freezes.items():\n # b'f'\n batch_put(b'f' + key, value)\n flush_data.asset_restricted_freezes.clear()\n\n self.flush_freezes_undo_info(batch_put, flush_data.asset_restricted_freezes_undo)\n flush_data.asset_restricted_freezes_undo.clear()\n\n for key, value in flush_data.asset_restricted_freezes_current.items():\n #b'l'\n batch_put(b'l' + key, value)\n flush_data.asset_restricted_freezes_current.clear()\n\n for key, value in flush_data.asset_restricted2qual.items():\n #b'1' res\n #b'2' qual\n parser = util.DataParser(key)\n restricted_len, restricted_asset = parser.read_var_bytes_tuple_bytes()\n bytes_append = parser.read_bytes(4 + 4 + 5)\n qual_adds, qual_removes = value\n batch_put(\n b'1' + restricted_len + restricted_asset + bytes_append,\n bytes([len(qual_adds)]) + b''.join([bytes([len(qual)]) + qual for qual in qual_adds]) +\n bytes([len(qual_removes)]) + b''.join([bytes([len(qual)]) + qual for qual in qual_removes])\n )\n\n for qual in qual_adds:\n batch_put(\n b'2' + bytes([len(qual)]) + qual + bytes_append,\n b'\\x01' + restricted_len + restricted_asset\n )\n\n for qual in qual_removes:\n batch_put(\n b'2' + bytes([len(qual)]) + qual + bytes_append,\n b'\\0' + restricted_len + restricted_asset\n )\n\n flush_data.asset_restricted2qual.clear()\n\n self.flush_restricted2qual_undo_info(batch_put, flush_data.asset_restricted2qual_undo)\n flush_data.asset_restricted2qual_undo.clear()\n\n for key, value in flush_data.asset_current_associations.items():\n # b'r' res\n # b'c' qual\n batch_put(key, value)\n flush_data.asset_current_associations.clear()\n\n for key, value in flush_data.asset_broadcasts.items():\n batch_put(b'b' + key, value)\n flush_data.asset_broadcasts.clear()\n\n self.flush_asset_broadcast_undos(batch_put, flush_data.asset_broadcasts_undo)\n flush_data.asset_broadcasts_undo.clear()\n\n if self.asset_db.for_sync:\n elapsed = time.monotonic() - start_time\n self.logger.info(f'{add_count:,d} Asset adds, '\n f'{spend_count:,d} spends in, '\n f'{restricted_assets:,d} restricted assets modified, '\n f'{freezes:,d} retricted asset freezes, '\n f'{tags:,d} addresses tagged, '\n f'{broadcasts:,d} messages broadcast, '\n f'{elapsed:.1f}s, committing...')\n\n self.db_asset_count = flush_data.asset_count\n\n def flush_utxo_db(self, batch, flush_data):\n '''Flush the cached DB writes and UTXO set to the batch.'''\n # Care is needed because the writes generated by flushing the\n # UTXO state may have keys in common with our write cache or\n # may be in the DB already.\n start_time = time.monotonic()\n add_count = len(flush_data.adds)\n spend_count = len(flush_data.deletes) // 2\n\n # Spends\n batch_delete = batch.delete\n for key in sorted(flush_data.deletes):\n batch_delete(key)\n flush_data.deletes.clear()\n\n # New UTXOs\n batch_put = batch.put\n for key, value in flush_data.adds.items():\n # suffix = tx_idx + tx_num\n hashX = value[:-13]\n suffix = key[-4:] + value[-13:-8]\n batch_put(b'h' + key[:4] + suffix, hashX)\n batch_put(b'u' + hashX + suffix, value[-8:])\n flush_data.adds.clear()\n\n # New undo information\n self.flush_undo_infos(batch_put, flush_data.undo_infos)\n flush_data.undo_infos.clear()\n\n if self.utxo_db.for_sync:\n block_count = flush_data.height - self.db_height\n tx_count = flush_data.tx_count - self.db_tx_count\n elapsed = time.monotonic() - start_time\n self.logger.info(f'flushed {block_count:,d} blocks with '\n f'{tx_count:,d} txs, {add_count:,d} UTXO adds, '\n f'{spend_count:,d} spends in '\n f'{elapsed:.1f}s, committing...')\n\n self.utxo_flush_count = self.history.flush_count\n self.db_height = flush_data.height\n self.db_tx_count = flush_data.tx_count\n self.db_tip = flush_data.tip\n\n def flush_asset_state(self, batch):\n self.last_flush_asset_count = self.fs_asset_count\n self.write_asset_state(batch)\n\n def flush_state(self, batch):\n '''Flush chain state to the batch.'''\n now = time.time()\n self.wall_time += now - self.last_flush\n self.last_flush = now\n self.last_flush_tx_count = self.fs_tx_count\n self.write_utxo_state(batch)\n\n def flush_backup(self, flush_data, touched):\n '''Like flush_dbs() but when backing up. All UTXOs are flushed.'''\n assert not flush_data.headers\n assert not flush_data.block_tx_hashes\n assert flush_data.height < self.db_height\n self.history.assert_flushed()\n\n start_time = time.time()\n tx_delta = flush_data.tx_count - self.last_flush_tx_count\n asset_delta = flush_data.asset_count - self.last_flush_asset_count\n\n self.backup_fs(flush_data.height, flush_data.tx_count, flush_data.asset_count)\n self.history.backup(touched, flush_data.tx_count)\n with self.utxo_db.write_batch() as batch:\n self.flush_utxo_db(batch, flush_data)\n # Flush state last as it reads the wall time.\n self.flush_state(batch)\n\n with self.asset_db.write_batch() as batch:\n self.flush_asset_db(batch, flush_data)\n self.flush_asset_state(batch)\n\n with self.asset_info_db.write_batch() as batch:\n self.flush_asset_info_db(batch, flush_data)\n\n elapsed = self.last_flush - start_time\n self.logger.info(f'backup flush #{self.history.flush_count:,d} took '\n f'{elapsed:.1f}s. Height {flush_data.height:,d} '\n f'txs: {flush_data.tx_count:,d} ({tx_delta:+,d}) '\n f'assets: {flush_data.asset_count:,d} ({asset_delta:+,d})')\n\n def backup_fs(self, height, tx_count, asset_count):\n '''Back up during a reorg. This just updates our pointers.'''\n self.fs_height = height\n self.fs_tx_count = tx_count\n self.fs_asset_count = asset_count\n # Truncate header_mc: header count is 1 more than the height.\n self.header_mc.truncate(height + 1)\n\n async def raw_header(self, height):\n '''Return the binary header at the given height.'''\n header, n = await self.read_headers(height, 1)\n if n != 1:\n raise IndexError(f'height {height:,d} out of range')\n return header\n\n async def read_headers(self, start_height, count):\n '''Requires start_height >= 0, count >= 0. Reads as many headers as\n are available starting at start_height up to count. This\n would be zero if start_height is beyond self.db_height, for\n example.\n Returns a (binary, n) pair where binary is the concatenated\n binary headers, and n is the count of headers returned.\n '''\n if start_height < 0 or count < 0:\n raise self.DBError(f'{count:,d} headers starting at '\n f'{start_height:,d} not on disk')\n\n def read_headers():\n # Read some from disk\n disk_count = max(0, min(count, self.db_height + 1 - start_height))\n if disk_count:\n offset = self.header_offset(start_height)\n size = self.header_offset(start_height + disk_count) - offset\n return self.headers_file.read(offset, size), disk_count\n return b'', 0\n\n return await run_in_thread(read_headers)\n\n def fs_tx_hash(self, tx_num):\n '''Return a pair (tx_hash, tx_height) for the given tx number.\n\n If the tx_height is not on disk, returns (None, tx_height).'''\n tx_height = bisect_right(self.tx_counts, tx_num)\n if tx_height > self.db_height:\n tx_hash = None\n else:\n tx_hash = self.hashes_file.read(tx_num * 32, 32)\n return tx_hash, tx_height\n\n def fs_tx_hashes_at_blockheight(self, block_height):\n '''Return a list of tx_hashes at given block height,\n in the same order as in the block.\n '''\n if block_height > self.db_height:\n raise self.DBError(f'block {block_height:,d} not on disk (>{self.db_height:,d})')\n assert block_height >= 0\n if block_height > 0:\n first_tx_num = self.tx_counts[block_height - 1]\n else:\n first_tx_num = 0\n num_txs_in_block = self.tx_counts[block_height] - first_tx_num\n tx_hashes = self.hashes_file.read(first_tx_num * 32, num_txs_in_block * 32)\n assert num_txs_in_block == len(tx_hashes) // 32\n return [tx_hashes[idx * 32: (idx+1) * 32] for idx in range(num_txs_in_block)]\n\n async def tx_hashes_at_blockheight(self, block_height):\n return await run_in_thread(self.fs_tx_hashes_at_blockheight, block_height)\n\n async def fs_block_hashes(self, height, count):\n headers_concat, headers_count = await self.read_headers(height, count)\n if headers_count != count:\n raise self.DBError('only got {:,d} headers starting at {:,d}, not '\n '{:,d}'.format(headers_count, height, count))\n offset = 0\n headers = []\n for n in range(count):\n hlen = self.header_len(height + n)\n headers.append(headers_concat[offset:offset + hlen])\n offset += hlen\n\n return [self.coin.header_hash(header) for header in headers]\n\n async def limited_history(self, hashX, *, limit=1000):\n '''Return an unpruned, sorted list of (tx_hash, height) tuples of\n confirmed transactions that touched the address, earliest in\n the blockchain first. Includes both spending and receiving\n transactions. By default returns at most 1000 entries. Set\n limit to None to get them all.\n '''\n def read_history():\n tx_nums = list(self.history.get_txnums(hashX, limit))\n fs_tx_hash = self.fs_tx_hash\n return [fs_tx_hash(tx_num) for tx_num in tx_nums]\n\n while True:\n history = await run_in_thread(read_history)\n if all(hash is not None for hash, height in history):\n return history\n self.logger.warning('limited_history: tx hash not found (reorg?), retrying...')\n await sleep(0.25)\n\n # -- Undo information\n\n def min_undo_height(self, max_height):\n '''Returns a height from which we should store undo info.'''\n return max_height - self.env.reorg_limit + 1\n\n def undo_key_broadcast(self, height):\n return b'B' + pack_be_uint32(height)\n\n def undo_key(self, height):\n '''DB key for undo information at the given height.'''\n return b'U' + pack_be_uint32(height)\n\n def undo_res2qual_key(self, height):\n return b'R' + pack_be_uint32(height)\n\n def undo_freeze_key(self, height):\n return b'F' + pack_be_uint32(height)\n\n def undo_tag_key(self, height):\n return b'T' + pack_be_uint32(height)\n\n def read_asset_broadcast_undo_info(self, height):\n return self.asset_info_db.get(self.undo_key_broadcast(height))\n\n def read_asset_meta_undo_info(self, height):\n return self.asset_info_db.get(self.undo_key(height))\n\n def read_asset_undo_res2qual_key(self, height):\n return self.asset_db.get(self.undo_res2qual_key(height))\n\n def read_asset_undo_freeze_info(self, height):\n return self.asset_db.get(self.undo_freeze_key(height))\n\n def read_asset_undo_tag_info(self, height):\n return self.asset_db.get(self.undo_tag_key(height))\n\n def read_asset_undo_info(self, height):\n return self.asset_db.get(self.undo_key(height))\n\n def read_undo_info(self, height):\n '''Read undo information from a file for the current height.'''\n return self.utxo_db.get(self.undo_key(height))\n\n def flush_asset_broadcast_undos(self, batch_put, undo_infos):\n for undo_info, height in undo_infos:\n if len(undo_info) > 0:\n batch_put(self.undo_key_broadcast(height), b''.join(undo_info))\n\n def flush_asset_meta_undos(self, batch_put, undo_infos):\n for undo_info, height in undo_infos:\n if len(undo_info) > 0:\n batch_put(self.undo_key(height), b''.join(undo_info))\n\n def flush_t2p_undo_infos(self, batch_put, undo_infos):\n for undo_info, height in undo_infos:\n if len(undo_info) > 0:\n batch_put(self.undo_tag_key(height), b''.join(undo_info))\n\n def flush_freezes_undo_info(self, batch_put, undo_infos):\n for undo_info, height in undo_infos:\n if len(undo_info) > 0:\n batch_put(self.undo_freeze_key(height), b''.join(undo_info))\n\n def flush_restricted2qual_undo_info(self, batch_put, undo_infos):\n for undo_info, height in undo_infos:\n if len(undo_info) > 0:\n batch_put(self.undo_res2qual_key(height), b''.join(undo_info))\n\n def flush_undo_infos(self, batch_put, undo_infos):\n '''undo_infos is a list of (undo_info, height) pairs.'''\n for undo_info, height in undo_infos:\n batch_put(self.undo_key(height), b''.join(undo_info))\n\n def raw_block_prefix(self):\n return 'meta/block'\n\n def raw_block_path(self, height):\n return f'{self.raw_block_prefix()}{height:d}'\n\n def read_raw_block(self, height):\n '''Returns a raw block read from disk. Raises FileNotFoundError\n if the block isn't on-disk.'''\n with util.open_file(self.raw_block_path(height)) as f:\n return f.read(-1)\n\n def write_raw_block(self, block, height):\n '''Write a raw block to disk.'''\n with util.open_truncate(self.raw_block_path(height)) as f:\n f.write(block)\n # Delete old blocks to prevent them accumulating\n try:\n del_height = self.min_undo_height(height) - 1\n os.remove(self.raw_block_path(del_height))\n except FileNotFoundError:\n pass\n\n def clear_excess_undo_info(self):\n '''Clear excess undo info. Only most recent N are kept.'''\n prefix = b'U'\n min_height = self.min_undo_height(self.db_height)\n keys = []\n for key, _hist in self.utxo_db.iterator(prefix=prefix):\n height, = unpack_be_uint32(key[-4:])\n if height >= min_height:\n break\n keys.append(key)\n\n if keys:\n with self.utxo_db.write_batch() as batch:\n for key in keys:\n batch.delete(key)\n self.logger.info(f'deleted {len(keys):,d} stale undo entries')\n\n keys = []\n for key, _hist in self.asset_info_db.iterator(prefix=prefix):\n height, = unpack_be_uint32(key[-4:])\n if height >= min_height:\n break\n keys.append(key)\n if keys:\n with self.asset_info_db.write_batch() as batch:\n for key in keys:\n batch.delete(key)\n self.logger.info(f'deleted {len(keys):,d} stale asset meta undo entries')\n\n keys = []\n for key, _hist in self.asset_db.iterator(prefix=prefix):\n height, = unpack_be_uint32(key[-4:])\n if height >= min_height:\n break\n keys.append(key)\n\n for key, _hist in self.asset_db.iterator(prefix=b'R'):\n height, = unpack_be_uint32(key[-4:])\n if height >= min_height:\n break\n keys.append(key)\n\n for key, _hist in self.asset_db.iterator(prefix=b'F'):\n height, = unpack_be_uint32(key[-4:])\n if height >= min_height:\n break\n keys.append(key)\n\n for key, _hist in self.asset_db.iterator(prefix=b'T'):\n height, = unpack_be_uint32(key[-4:])\n if height >= min_height:\n break\n keys.append(key)\n\n for key, _hist in self.asset_db.iterator(prefix=b'B'):\n height, = unpack_be_uint32(key[-4:])\n if height >= min_height:\n break\n keys.append(key)\n\n if keys:\n with self.asset_db.write_batch() as batch:\n for key in keys:\n batch.delete(key)\n self.logger.info(f'deleted {len(keys):,d} stale asset undo entries')\n\n # delete old block files\n prefix = self.raw_block_prefix()\n paths = [path for path in glob(f'{prefix}[0-9]*')\n if len(path) > len(prefix)\n and int(path[len(prefix):]) < min_height]\n if paths:\n for path in paths:\n try:\n os.remove(path)\n except FileNotFoundError:\n pass\n self.logger.info(f'deleted {len(paths):,d} stale block files')\n\n # -- Asset database\n\n def read_asset_state(self):\n state = self.asset_db.get(b'state')\n if not state:\n self.db_asset_count = 0\n else:\n state = ast.literal_eval(state.decode())\n if not isinstance(state, dict):\n raise self.DBError('failed reading state from asset DB')\n self.db_asset_count = state['asset_count']\n\n self.fs_asset_count = self.db_asset_count\n self.last_flush_asset_count = self.fs_asset_count\n\n # -- UTXO database\n\n def read_utxo_state(self):\n state = self.utxo_db.get(b'state')\n if not state:\n self.db_height = -1\n self.db_tx_count = 0\n self.db_tip = b'\\0' * 32\n self.db_version = max(self.DB_VERSIONS)\n self.utxo_flush_count = 0\n self.wall_time = 0\n self.first_sync = True\n else:\n state = ast.literal_eval(state.decode())\n if not isinstance(state, dict):\n raise self.DBError('failed reading state from DB')\n self.db_version = state['db_version']\n if self.db_version not in self.DB_VERSIONS:\n raise self.DBError('your UTXO DB version is {} but this '\n 'software only handles versions {}'\n .format(self.db_version, self.DB_VERSIONS))\n # backwards compat\n genesis_hash = state['genesis']\n if isinstance(genesis_hash, bytes):\n genesis_hash = genesis_hash.decode()\n if genesis_hash != self.coin.GENESIS_HASH:\n raise self.DBError('DB genesis hash {} does not match coin {}'\n .format(genesis_hash,\n self.coin.GENESIS_HASH))\n self.db_height = state['height']\n self.db_tx_count = state['tx_count']\n self.db_tip = state['tip']\n self.utxo_flush_count = state['utxo_flush_count']\n self.wall_time = state['wall_time']\n self.first_sync = state['first_sync']\n\n # These are our state as we move ahead of DB state\n self.fs_height = self.db_height\n self.fs_tx_count = self.db_tx_count\n self.last_flush_tx_count = self.fs_tx_count\n\n # Upgrade DB\n if self.db_version != max(self.DB_VERSIONS):\n self.upgrade_db()\n\n # Log some stats\n self.logger.info('UTXO DB version: {:d}'.format(self.db_version))\n self.logger.info('coin: {}'.format(self.coin.NAME))\n self.logger.info('network: {}'.format(self.coin.NET))\n self.logger.info('height: {:,d}'.format(self.db_height))\n self.logger.info('tip: {}'.format(hash_to_hex_str(self.db_tip)))\n self.logger.info('tx count: {:,d}'.format(self.db_tx_count))\n self.logger.info('VOUT debugging: {}'.format(self.env.write_bad_vouts_to_file))\n if self.utxo_db.for_sync:\n self.logger.info(f'flushing DB cache at {self.env.cache_MB:,d} MB')\n if self.first_sync:\n self.logger.info('sync time so far: {}'\n .format(util.formatted_time(self.wall_time)))\n\n def upgrade_db(self):\n self.logger.info(f'UTXO DB version: {self.db_version}')\n self.logger.info('Upgrading your DB; this can take some time...')\n\n def upgrade_u_prefix(prefix):\n count = 0\n with self.utxo_db.write_batch() as batch:\n batch_delete = batch.delete\n batch_put = batch.put\n # Key: b'u' + address_hashX + tx_idx + tx_num\n for db_key, db_value in self.utxo_db.iterator(prefix=prefix):\n if len(db_key) == 21:\n return\n break\n if self.db_version == 6:\n for db_key, db_value in self.utxo_db.iterator(prefix=prefix):\n count += 1\n batch_delete(db_key)\n batch_put(db_key[:14] + b'\\0\\0' + db_key[14:] + b'\\0', db_value)\n else:\n for db_key, db_value in self.utxo_db.iterator(prefix=prefix):\n count += 1\n batch_delete(db_key)\n batch_put(db_key + b'\\0', db_value)\n return count\n\n last = time.monotonic()\n count = 0\n for cursor in range(65536):\n prefix = b'u' + pack_be_uint16(cursor)\n count += upgrade_u_prefix(prefix)\n now = time.monotonic()\n if now > last + 10:\n last = now\n self.logger.info(f'DB 1 of 3: {count:,d} entries updated, '\n f'{cursor * 100 / 65536:.1f}% complete')\n self.logger.info('DB 1 of 3 upgraded successfully')\n\n def upgrade_h_prefix(prefix):\n count = 0\n with self.utxo_db.write_batch() as batch:\n batch_delete = batch.delete\n batch_put = batch.put\n # Key: b'h' + compressed_tx_hash + tx_idx + tx_num\n for db_key, db_value in self.utxo_db.iterator(prefix=prefix):\n if len(db_key) == 14:\n return\n break\n if self.db_version == 6:\n for db_key, db_value in self.utxo_db.iterator(prefix=prefix):\n count += 1\n batch_delete(db_key)\n batch_put(db_key[:7] + b'\\0\\0' + db_key[7:] + b'\\0', db_value)\n else:\n for db_key, db_value in self.utxo_db.iterator(prefix=prefix):\n count += 1\n batch_delete(db_key)\n batch_put(db_key + b'\\0', db_value)\n return count\n\n last = time.monotonic()\n count = 0\n for cursor in range(65536):\n prefix = b'h' + pack_be_uint16(cursor)\n count += upgrade_h_prefix(prefix)\n now = time.monotonic()\n if now > last + 10:\n last = now\n self.logger.info(f'DB 2 of 3: {count:,d} entries updated, '\n f'{cursor * 100 / 65536:.1f}% complete')\n\n # Upgrade tx_counts file\n size = (self.db_height + 1) * 8\n tx_counts = self.tx_counts_file.read(0, size)\n if len(tx_counts) == (self.db_height + 1) * 4:\n tx_counts = array.array('I', tx_counts)\n tx_counts = array.array('Q', tx_counts)\n self.tx_counts_file.write(0, tx_counts.tobytes())\n\n self.db_version = max(self.DB_VERSIONS)\n with self.utxo_db.write_batch() as batch:\n self.write_utxo_state(batch)\n self.logger.info('DB 2 of 3 upgraded successfully')\n\n def write_asset_state(self, batch):\n state = {\n 'asset_count': self.db_asset_count,\n }\n batch.put(b'state', repr(state).encode())\n\n def write_utxo_state(self, batch):\n '''Write (UTXO) state to the batch.'''\n state = {\n 'genesis': self.coin.GENESIS_HASH,\n 'height': self.db_height,\n 'tx_count': self.db_tx_count,\n 'tip': self.db_tip,\n 'utxo_flush_count': self.utxo_flush_count,\n 'wall_time': self.wall_time,\n 'first_sync': self.first_sync,\n 'db_version': self.db_version,\n }\n batch.put(b'state', repr(state).encode())\n\n def set_flush_count(self, count):\n self.utxo_flush_count = count\n with self.utxo_db.write_batch() as batch:\n self.write_utxo_state(batch)\n\n async def all_assets(self, hashX):\n def read_assets():\n assets = []\n assets_append = assets.append\n prefix = b'u' + hashX\n for db_key, db_value in self.asset_db.iterator(prefix=prefix):\n tx_pos, = unpack_le_uint32(db_key[-9:-5])\n tx_num, = unpack_le_uint64(db_key[-5:] + bytes(3))\n tx_hash, height = self.fs_tx_hash(tx_num)\n value, = unpack_le_uint64(db_value[:8])\n name = db_value[9:].decode('ascii')\n assets_append(ASSET(tx_num, tx_pos, tx_hash, height, name, value))\n return assets\n\n while True:\n assets = await run_in_thread(read_assets)\n if all(asset.tx_hash is not None for asset in assets):\n return assets\n self.logger.warning('all_assets: tx hash not found (reorg?), retrying...')\n await sleep(0.25)\n\n async def all_utxos(self, hashX):\n '''Return all UTXOs for an address sorted in no particular order.'''\n def read_utxos():\n utxos = []\n utxos_append = utxos.append\n # Key: b'u' + address_hashX + tx_idx + tx_num\n # Value: the UTXO value as a 64-bit unsigned integer\n prefix = b'u' + hashX\n for db_key, db_value in self.utxo_db.iterator(prefix=prefix):\n value, = unpack_le_uint64(db_value)\n if value > 0:\n # Values of 0 will only be assets.\n # Get them from all_assets\n tx_pos, = unpack_le_uint32(db_key[-9:-5])\n tx_num, = unpack_le_uint64(db_key[-5:] + bytes(3))\n tx_hash, height = self.fs_tx_hash(tx_num)\n utxos_append(UTXO(tx_num, tx_pos, tx_hash, height, value))\n return utxos\n\n while True:\n utxos = await run_in_thread(read_utxos)\n if all(utxo.tx_hash is not None for utxo in utxos):\n return utxos\n self.logger.warning('all_utxos: tx hash not found (reorg?), retrying...')\n await sleep(0.25)\n\n async def lookup_utxos(self, prevouts):\n '''For each prevout, lookup it up in the DB and return a (hashX,\n value) pair or None if not found.\n\n Used by the mempool code.\n '''\n def lookup_hashXs():\n '''Return (hashX, suffix) pairs, or None if not found,\n for each prevout.\n '''\n def lookup_hashX(tx_hash, tx_idx):\n idx_packed = pack_le_uint32(tx_idx)\n\n # Key: b'h' + compressed_tx_hash + tx_idx + tx_num\n # Value: hashX\n prefix = b'h' + tx_hash[:4] + idx_packed\n\n # Find which entry, if any, the TX_HASH matches.\n for db_key, hashX in self.utxo_db.iterator(prefix=prefix):\n tx_num_packed = db_key[-5:]\n tx_num, = unpack_le_uint64(tx_num_packed + bytes(3))\n fs_hash, _height = self.fs_tx_hash(tx_num)\n if fs_hash == tx_hash:\n return hashX, idx_packed + tx_num_packed\n return None, None\n return [lookup_hashX(*prevout) for prevout in prevouts]\n\n def lookup_utxos(hashX_pairs):\n def lookup_utxo(hashX, suffix):\n if not hashX:\n # This can happen when the daemon is a block ahead\n # of us and has mempool txs spending outputs from\n # that new block\n return None\n # Key: b'u' + address_hashX + tx_idx + tx_num\n # Value: the UTXO value as a 64-bit unsigned integer\n key = b'u' + hashX + suffix\n db_value = self.utxo_db.get(key)\n if not db_value:\n # This can happen if the DB was updated between\n # getting the hashXs and getting the UTXOs\n return None\n value, = unpack_le_uint64(db_value)\n if value == 0:\n return None\n return hashX, value\n return [lookup_utxo(*hashX_pair) for hashX_pair in hashX_pairs]\n\n hashX_pairs = await run_in_thread(lookup_hashXs)\n return [i for i in await run_in_thread(lookup_utxos, hashX_pairs) if i]\n\n # For external use\n async def get_associations_for_qualifier_current(self, asset: bytes):\n def get_current_info():\n ret = {}\n data = self.asset_db.get(b'c' + asset)\n if data is None:\n return ret\n parser = util.DataParser(data)\n for _ in range(parser.read_int()):\n ass = parser.read_var_bytes_as_ascii()\n res_idx, = unpack_le_uint32(parser.read_bytes(4))\n qual_idx, = unpack_le_uint32(parser.read_bytes(4))\n tx_numb = parser.read_bytes(5)\n flag = parser.read_boolean()\n tx_num, = unpack_le_uint64(tx_numb + bytes(3))\n tx_hash, height = self.fs_tx_hash(tx_num)\n ret[ass] = {\n 'associated': flag,\n 'height': height,\n 'txid': hash_to_hex_str(tx_hash),\n 'res_tx_pos': res_idx,\n 'qual_tx_pos': qual_idx,\n }\n return ret\n return await run_in_thread(get_current_info)\n\n async def get_associations_for_qualifier_history(self, asset: bytes):\n def get_asset_history():\n ret = {}\n prefix = b'2' + bytes([len(asset)]) + asset\n for db_key, db_value in self.asset_db.iterator(prefix=prefix):\n res_tx_pos, = unpack_le_uint32(db_key[-13:-9])\n qual_tx_pos, = unpack_le_uint32(db_key[-9:-5])\n tx_num, = unpack_le_uint64(db_key[-5:] + bytes(3))\n tx_hash, height = self.fs_tx_hash(tx_num)\n parser = util.DataParser(db_value)\n\n flag = parser.read_boolean()\n ass = parser.read_var_bytes_as_ascii()\n\n if height in ret.keys():\n ret[height][hash_to_hex_str(tx_hash)] = {\n 'asset': ass,\n 'associated': flag,\n 'res_tx_pos': res_tx_pos,\n 'qual_tx_pos': qual_tx_pos,\n }\n else:\n ret[height] = {\n hash_to_hex_str(tx_hash): {\n 'asset': ass,\n 'associated': flag,\n 'res_tx_pos': res_tx_pos,\n 'qual_tx_pos': qual_tx_pos,\n }\n }\n\n return ret\n return await run_in_thread(get_asset_history)\n\n # For external use\n async def get_associations_for_restricted_current(self, asset: bytes):\n def get_current_info():\n ret = {}\n data = self.asset_db.get(b'r' + asset)\n if data is None:\n return ret\n parser = util.DataParser(data)\n for _ in range(parser.read_int()):\n ass = parser.read_var_bytes_as_ascii()\n res_idx, = unpack_le_uint32(parser.read_bytes(4))\n qual_idx, = unpack_le_uint32(parser.read_bytes(4))\n tx_numb = parser.read_bytes(5)\n flag = parser.read_boolean()\n tx_num, = unpack_le_uint64(tx_numb + bytes(3))\n tx_hash, height = self.fs_tx_hash(tx_num)\n ret[ass] = {\n 'associated': flag,\n 'height': height,\n 'txid': hash_to_hex_str(tx_hash),\n 'res_tx_pos': res_idx,\n 'qual_tx_pos': qual_idx,\n }\n return ret\n return await run_in_thread(get_current_info)\n\n async def get_associations_for_restricted_history(self, asset: bytes):\n def get_asset_history():\n ret = {}\n prefix = b'1' + bytes([len(asset)]) + asset\n for db_key, db_value in self.asset_db.iterator(prefix=prefix):\n res_tx_pos, = unpack_le_uint32(db_key[-13:-9])\n qual_tx_pos, = unpack_le_uint32(db_key[-9:-5])\n tx_num, = unpack_le_uint64(db_key[-5:] + bytes(3))\n tx_hash, height = self.fs_tx_hash(tx_num)\n parser = util.DataParser(db_value)\n\n adds = []\n removes = []\n\n for _ in range(parser.read_int()):\n adds.append(parser.read_var_bytes_as_ascii())\n for _ in range(parser.read_int()):\n removes.append(parser.read_var_bytes_as_ascii())\n\n if height in ret.keys():\n ret[height][hash_to_hex_str(tx_hash)] = {\n 'associations': adds,\n 'removes': removes,\n 'res_tx_pos': res_tx_pos,\n 'qual_tx_pos': qual_tx_pos\n }\n else:\n ret[height] = {\n hash_to_hex_str(tx_hash): {\n 'associations': adds,\n 'removes': removes,\n 'res_tx_pos': res_tx_pos,\n 'qual_tx_pos': qual_tx_pos\n }\n }\n\n return ret\n return await run_in_thread(get_asset_history)\n\n # For external use\n async def is_qualified(self, asset: bytes, hex: bytes):\n def run():\n data = self.asset_db.get(b'Q' + asset)\n if data is None:\n return {}\n parser = util.DataParser(data)\n for _ in range(parser.read_int()):\n h160 = parser.read_var_bytes()\n tx_pos, = unpack_le_uint32(parser.read_bytes(4))\n tx_numb = parser.read_bytes(5)\n flag = parser.read_boolean()\n tx_num, = unpack_le_uint64(tx_numb + bytes(3))\n tx_hash, height = self.fs_tx_hash(tx_num)\n if hex == h160:\n return {\n 'flag': flag,\n 'height': height,\n 'txid': hash_to_hex_str(tx_hash),\n 'tx_pos': tx_pos,\n }\n return {}\n return await run_in_thread(run)\n\n # For external use\n async def get_h160s_associated_with_asset_current(self, asset: bytes):\n def get_current_info():\n ret = {}\n data = self.asset_db.get(b'Q' + asset)\n if data is None:\n return ret\n parser = util.DataParser(data)\n for _ in range(parser.read_int()):\n h160 = parser.read_var_bytes()\n tx_pos, = unpack_le_uint32(parser.read_bytes(4))\n tx_numb = parser.read_bytes(5)\n flag = parser.read_boolean()\n tx_num, = unpack_le_uint64(tx_numb + bytes(3))\n tx_hash, height = self.fs_tx_hash(tx_num)\n ret[h160.hex()] = {\n 'flag': flag,\n 'height': height,\n 'txid': hash_to_hex_str(tx_hash),\n 'tx_pos': tx_pos,\n }\n return ret\n return await run_in_thread(get_current_info)\n\n async def get_h160s_associated_with_asset_history(self, asset: bytes):\n def get_h160_history():\n ret = {}\n prefix = b'a' + bytes([len(asset)]) + asset\n for db_key, db_value in self.asset_db.iterator(prefix=prefix):\n tx_pos, = unpack_le_uint32(db_key[-9:-5])\n tx_num, = unpack_le_uint64(db_key[-5:] + bytes(3))\n tx_hash, height = self.fs_tx_hash(tx_num)\n parser = util.DataParser(db_value)\n h160 = parser.read_var_bytes()\n flag = parser.read_boolean()\n if height in ret.keys():\n ret[height][hash_to_hex_str(tx_hash)] = {\n 'pubkey': h160.hex(),\n 'tx_pos': tx_pos,\n 'flag': flag,\n }\n else:\n ret[height] = {\n hash_to_hex_str(tx_hash): {\n 'pubkey': h160.hex(),\n 'tx_pos': tx_pos,\n 'flag': flag,\n }\n }\n return ret\n\n return await run_in_thread(get_h160_history)\n\n # For external use\n async def get_tags_associated_with_h160_current(self, h160: bytes):\n def get_current_info():\n ret = {}\n data = self.asset_db.get(b't' + h160)\n if data is None:\n return ret\n parser = util.DataParser(data)\n for _ in range(parser.read_int()):\n asset = parser.read_var_bytes_as_ascii()\n tx_pos, = unpack_le_uint32(parser.read_bytes(4))\n tx_numb = parser.read_bytes(5)\n flag = parser.read_boolean()\n tx_num, = unpack_le_uint64(tx_numb + bytes(3))\n tx_hash, height = self.fs_tx_hash(tx_num)\n ret[asset] = {\n 'flag': flag,\n 'height': height,\n 'txid': hash_to_hex_str(tx_hash),\n 'tx_pos': tx_pos,\n }\n return ret\n return await run_in_thread(get_current_info)\n\n async def get_tags_associated_with_h160_history(self, h160: bytes):\n\n def get_h160_history():\n ret = {}\n prefix = b'p' + bytes([len(h160)]) + h160\n for db_key, db_value in self.asset_db.iterator(prefix=prefix):\n tx_pos, = unpack_le_uint32(db_key[-9:-5])\n tx_num, = unpack_le_uint64(db_key[-5:] + bytes(3))\n tx_hash, height = self.fs_tx_hash(tx_num)\n parser = util.DataParser(db_value)\n asset = parser.read_var_bytes_as_ascii()\n flag = parser.read_boolean()\n if height in ret.keys():\n ret[height][hash_to_hex_str(tx_hash)] = {\n 'tag': asset,\n 'tx_pos': tx_pos,\n 'flag': flag,\n }\n else:\n ret[height] = {\n hash_to_hex_str(tx_hash): {\n 'tag': asset,\n 'tx_pos': tx_pos,\n 'flag': flag,\n }\n }\n return ret\n\n return await run_in_thread(get_h160_history)\n\n # For external use\n async def get_frozen_status_of_restricted_current(self, asset: bytes):\n def get_current_info():\n data = self.asset_db.get(b'l' + asset)\n if not data:\n return {}\n parser = util.DataParser(data)\n tx_pos, = unpack_le_uint32(parser.read_bytes(4))\n tx_numb = parser.read_bytes(5)\n flag = parser.read_boolean()\n tx_num, = unpack_le_uint64(tx_numb + bytes(3))\n tx_hash, height = self.fs_tx_hash(tx_num)\n return {\n 'frozen': flag,\n 'height': height,\n 'txid': hash_to_hex_str(tx_hash),\n 'tx_pos': tx_pos,\n }\n\n return await run_in_thread(get_current_info)\n\n async def get_frozen_status_of_restricted_history(self, asset: bytes):\n def get_frozen_history():\n ret = {}\n prefix = b'f' + bytes([len(asset)]) + asset\n for db_key, db_value in self.asset_db.iterator(prefix=prefix):\n tx_pos, = unpack_le_uint32(db_key[-9:-5])\n tx_num, = unpack_le_uint64(db_key[-5:] + bytes(3))\n tx_hash, height = self.fs_tx_hash(tx_num)\n parser = util.DataParser(db_value)\n flag = parser.read_boolean()\n if height in ret.keys():\n ret[height][hash_to_hex_str(tx_hash)] = {\n 'frozen': flag,\n 'tx_pos': tx_pos,\n }\n else:\n ret[height] = {\n hash_to_hex_str(tx_hash): {\n 'frozen': flag,\n 'tx_pos': tx_pos,\n }\n }\n return ret\n\n return await run_in_thread(get_frozen_history)\n\n async def lookup_messages(self, asset_name: bytes):\n def read_messages():\n prefix = b'b' + bytes([len(asset_name)]) + asset_name\n ret_val = {}\n for db_key, db_value in self.asset_db.iterator(prefix=prefix):\n tx_pos, = unpack_le_uint32(db_key[-9:-5])\n tx_num, = unpack_le_uint64(db_key[-5:] + bytes(3))\n tx_hash, height = self.fs_tx_hash(tx_num)\n ret_val[hash_to_hex_str(tx_hash)] = {\n 'data': base_encode(db_value, 58),\n 'height': height,\n 'tx_pos': tx_pos,\n }\n return ret_val\n return await run_in_thread(read_messages)\n\n async def get_assets_with_prefix(self, prefix: bytes):\n def find_assets():\n return [asset.decode('ascii') for asset, _ in self.asset_info_db.iterator(prefix=prefix)]\n return await run_in_thread(find_assets)\n\n async def lookup_asset_meta(self, asset_name):\n def read_assets_meta():\n b = self.asset_info_db.get(asset_name)\n if not b:\n return {}\n data_parser = util.DataParser(b)\n sats_in_circulation = data_parser.read_bytes(8)\n div_amt = data_parser.read_int()\n reissuable = data_parser.read_int()\n has_ipfs = data_parser.read_int()\n to_ret = {\n 'sats_in_circulation': int.from_bytes(sats_in_circulation, 'little', signed=False),\n 'divisions': div_amt,\n 'reissuable': reissuable,\n 'has_ipfs': has_ipfs\n }\n if has_ipfs != 0:\n ipfs_data = data_parser.read_bytes(34)\n to_ret['ipfs'] = base_encode(ipfs_data, 58)\n\n idx = data_parser.read_bytes(4)\n tx_numb = data_parser.read_bytes(5)\n\n tx_pos, = unpack_le_uint32(idx)\n tx_num, = unpack_le_uint64(tx_numb + bytes(3))\n tx_hash, height = self.fs_tx_hash(tx_num)\n\n to_ret['source'] = {\n 'tx_hash': hash_to_hex_str(tx_hash),\n 'tx_pos': tx_pos,\n 'height': height\n }\n\n if data_parser.read_boolean():\n idx_prev = data_parser.read_bytes(4)\n tx_numb_prev = data_parser.read_bytes(5)\n\n tx_pos, = unpack_le_uint32(idx_prev)\n tx_num_prev, = unpack_le_uint64(tx_numb_prev + bytes(3))\n tx_hash, height = self.fs_tx_hash(tx_num_prev)\n to_ret['source_prev'] = {\n 'tx_hash': hash_to_hex_str(tx_hash),\n 'tx_pos': tx_pos,\n 'height': height\n }\n\n return to_ret\n return await run_in_thread(read_assets_meta)\n\n async def lookup_assets(self, prevouts):\n '''For each prevout, lookup it up in the DB and return a (hashX,\n value) pair or None if not found.\n\n Used by the mempool code.\n '''\n def lookup_hashXs():\n '''Return (hashX, suffix) pairs, or None if not found,\n for each prevout.\n '''\n def lookup_hashX(tx_hash, tx_idx):\n idx_packed = pack_le_uint32(tx_idx)\n\n # Key: b'h' + compressed_tx_hash + tx_idx + tx_num\n # Value: hashX\n prefix = b'h' + tx_hash[:4] + idx_packed\n\n # Find which entry, if any, the TX_HASH matches.\n for db_key, hashX in self.asset_db.iterator(prefix=prefix):\n tx_num_packed = db_key[-5:]\n tx_num, = unpack_le_uint64(tx_num_packed + bytes(3))\n fs_hash, _height = self.fs_tx_hash(tx_num)\n if fs_hash == tx_hash:\n return hashX, idx_packed + tx_num_packed\n return None, None\n return [lookup_hashX(*prevout) for prevout in prevouts]\n\n def lookup_assets(hashX_pairs):\n def lookup_asset(hashX, suffix):\n if not hashX:\n # This can happen when the daemon is a block ahead\n # of us and has mempool txs spending outputs from\n # that new block\n return None\n # Key: b'u' + address_hashX + tx_idx + tx_num\n # Value: the UTXO value as a 64-bit unsigned integer\n key = b'u' + hashX + suffix\n db_value = self.asset_db.get(key)\n if not db_value:\n # This can happen if the DB was updated between\n # getting the hashXs and getting the UTXOs\n return None\n\n value, = unpack_le_uint64(db_value[:8])\n name = db_value[9:].decode('ascii')\n\n return hashX, value, name\n return [lookup_asset(*hashX_pair) for hashX_pair in hashX_pairs]\n\n hashX_pairs = await run_in_thread(lookup_hashXs)\n return [i for i in await run_in_thread(lookup_assets, hashX_pairs) if i]","sub_path":"electrumx/server/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":64358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"358033766","text":"import logging\n\nimport arxiv\nimport datetime\nimport json\nimport os\n\nfrom multiprocessing.pool import ThreadPool\nfrom gather import Scraper\nfrom utilities.feedparser import normalize_feedparser_data\n\n\nclass ArXivScraper(Scraper):\n\n def __init__(self, *args, category=None, min_date=None, **kwargs):\n super().__init__(*args, **kwargs)\n self.category = category\n self.min_allowed_date = min_date if min_date is not None else datetime.datetime(1970, 1, 1)\n self.min_allowed_date = datetime.datetime(self.min_allowed_date.year, self.min_allowed_date.month,\n self.min_allowed_date.day, 0, 0, 0)\n\n def scrape(self):\n calls = [\n (self.fetch_results, {'category': self.category, 'forward': True}),\n ]\n if self.min_date > self.min_allowed_date:\n calls.append(\n (self.fetch_results, {'category': self.category, 'forward': False})\n )\n pool = ThreadPool(len(calls))\n results = pool.map_async(lambda x: x[0](**x[1]), calls)\n pool.close()\n pool.join()\n for (found_min_date, found_max_date) in results.get():\n self.min_date = min(self.min_date, found_min_date)\n self.min_date = max(self.min_date, self.min_allowed_date)\n self.max_date = max(self.max_date, found_max_date)\n self.set_state('min_date', self.min_date.strftime(self.datetime_format))\n self.set_state('max_date', self.max_date.strftime(self.datetime_format))\n\n def fetch_results(self, category=None, forward=False):\n query = [\n 'cat:{}'.format(category)\n ]\n sort_by = 'submittedDate'\n\n if forward:\n min_date = self.max_date.strftime('%Y%m%d%H%M')\n query.append('submittedDate:[{} TO 999999999999]'.format(min_date))\n sort_order = 'ascending'\n else:\n max_date = self.min_date.strftime('%Y%m%d%H%M')\n query.append('submittedDate:[0 TO {}]'.format(max_date))\n sort_order = 'descending'\n\n if self.min_date < self.min_allowed_date:\n return self.min_allowed_date, self.max_date\n\n query = ' AND '.join(query)\n results = arxiv.query(\n search_query=query,\n sort_by=sort_by,\n sort_order=sort_order,\n max_results=100\n )\n min_date = self.min_date\n max_date = self.max_date\n\n for result in results:\n published_date = datetime.datetime(*result['published_parsed'][:6])\n min_date = min(min_date, published_date)\n max_date = max(max_date, published_date)\n\n # Write the results to disk\n results = list(map(lambda entry: normalize_feedparser_data(entry, 'rss', 'ArXiv'), results))\n for result in results:\n result['category'] = category\n self.write_to_disk(result)\n\n return min_date, max_date\n\n def write_to_disk(self, result):\n published_date = datetime.datetime(*result['published_parsed'][:6])\n if published_date < self.min_allowed_date:\n return\n del result['published_parsed']\n del result['updated_parsed']\n folder = os.path.join(self.path, published_date.strftime('%Y-%m-%d'))\n if not os.path.exists(folder):\n os.makedirs(folder)\n path = os.path.join(folder, result['id'].split('/')[-1] + '.json')\n with open(path, 'w') as out_file:\n json.dump(result, out_file)\n\n\nif __name__ == '__main__':\n ArXivScraper(path=os.path.join('..', 'data', 'demo'), category='cs.CL',\n min_date=datetime.datetime(2019, 1, 1)).scrape()\n","sub_path":"gather/arxiv_scraper.py","file_name":"arxiv_scraper.py","file_ext":"py","file_size_in_byte":3692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"75704413","text":"def solution(n):\n quota = n//3\n remainder = n%3\n if remainder == 0:\n quota -= 1\n a = solution(quota) if quota != 0 else \"\" \n if remainder == 1 or remainder == 2:\n return \"{}{}\".format(a,remainder)\n elif remainder == 0:\n return \"{}{}\".format(a,4)\n\nprint(solution(3))\n\n \n","sub_path":"Programmers/Programmers_lv2/Programmers_lv2_124 나라의 숫자.py","file_name":"Programmers_lv2_124 나라의 숫자.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"367644015","text":"import json\n\nwith open('homebrew.json') as f: \n# with open('bestiary_new.json') as f: \n text = f.read().split('<|endoftext|>\\n<|startoftext|>\\n')\n text[0] = '\\n'.join(text[0].split('\\n')[1:])\n text[-1] = '\\n'.join(text[-1].split('\\n')[:-1]).replace('<|endoftext|>','')\n\nstart = ['monster_name', 'type', 'cr', 'size', 'alignment', 'speed', 'str', 'dex', 'con', 'int', 'wis', 'cha', 'ac', 'hp']\nnew_text = ''\nfor monster in text: \n m = json.loads(monster)\n keys = list(m.keys())\n end = [x for x in keys if x not in start]\n order = start + end\n if 'cr' not in m: \n m['cr'] = '-'\n if 'alignment' not in m: \n m['alignment'] = ['A'] \n reordered = {k: m[k] for k in order}\n new_text += f'<|startoftext|>\\n{json.dumps(reordered, indent=1)}\\n<|endoftext|>\\n'\nwith open('homebrew_reordered.json', 'w') as f: \n# with open('bestiary_reordered.json', 'w') as f: \n f.write(new_text)\n \n","sub_path":"reorder_json.py","file_name":"reorder_json.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"537045609","text":"import unittest\n\n\ndef reverse_words(message):\n\n\t# Decode the message by reversing the words\n\n\tList = []\n\tstring = ''\n\t\n\tfor i in range(len(message)):\n\t\tif(message[i]!=' '):\n\t\t\tstring = string+message[i]\n\t\telse:\n\t\t\tList.append(string)\n\t\t\tstring = ''\n\n\tList.append(string)\n\n\n\n\tfor i in range(len(List)//2):\n\t\ttemp = List[i]\n\t\tList[i] = List[len(List)-i-1]\n\t\tList[len(List)-i-1] = temp\n\too = 0\n\n\tfor i in List:\n\t\tfor j in i:\n\t\t\tmessage[oo] = j\n\t\t\too += 1\n\t\tif(oo!=len(message)):\n\t\t\tmessage[oo] = ' '\n\t\t\too += 1\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# Tests\n\nclass Test(unittest.TestCase):\n\n\tdef test_one_word(self):\n\t\tmessage = list('vault')\n\t\treverse_words(message)\n\t\texpected = list('vault')\n\t\tself.assertEqual(message, expected)\n\n\tdef test_two_words(self):\n\t\tmessage = list('thief cake')\n\t\treverse_words(message)\n\t\texpected = list('cake thief')\n\t\tself.assertEqual(message, expected)\n\n\tdef test_three_words(self):\n\t\tmessage = list('one another get')\n\t\treverse_words(message)\n\t\texpected = list('get another one')\n\t\tself.assertEqual(message, expected)\n\n\tdef test_multiple_words_same_length(self):\n\t\tmessage = list('rat the ate cat the')\n\t\treverse_words(message)\n\t\texpected = list('the cat ate the rat')\n\t\tself.assertEqual(message, expected)\n\n\tdef test_multiple_words_different_lengths(self):\n\t\tmessage = list('yummy is cake bundt chocolate')\n\t\treverse_words(message)\n\t\texpected = list('chocolate bundt cake is yummy')\n\t\tself.assertEqual(message, expected)\n\n\tdef test_empty_string(self):\n\t\tmessage = list('')\n\t\treverse_words(message)\n\t\texpected = list('')\n\t\tself.assertEqual(message, expected)\n\n\nunittest.main(verbosity=2)","sub_path":"Week-2/Day-3/Programs/ReverseWords.py","file_name":"ReverseWords.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"600286313","text":"#!/usr/bin/env python\n# ROS Imports\nimport rospy\nfrom geometry_msgs.msg import Pose\n\n\nclass GoalPublisher(object):\n def __init__(self):\n self.goal_pub = rospy.Publisher('/teacher/ik_vel/', Pose, queue_size=3)\n self.ee_pose_sub = rospy.Subscriber('/robot/limb/right/end_effector_pose', Pose, self.ee_pose_cb)\n\n self.is_set_target = False\n\n self.mode = input(\"Select Mode (0: safe init, 1 : safe home, 2 : init position, 3: home position 4: user define)\")\n\n\n rate = rospy.Rate(100)\n while not rospy.is_shutdown():\n self.goal_publish()\n rate.sleep()\n\n def goal_publish(self):\n\n if self.mode == 0 :\n if self.is_set_target == False:\n self.control_start_time = rospy.get_rostime().secs + rospy.get_rostime().nsecs*10**-9\n self.target_x = 0.290\n self.target_y = 0.0\n self.target_z = 0.203\n self.is_set_target = True\n self.now = rospy.get_rostime().secs + rospy.get_rostime().nsecs*10**-9\n self.goal_x = self.cubic(self.now, self.control_start_time, self.control_start_time+2.0, self.init_x, self.target_x, 0.0, 0.0)\n self.goal_y = self.cubic(self.now, self.control_start_time, self.control_start_time+2.0, self.init_y, self.target_y, 0.0, 0.0)\n self.goal_z = self.cubic(self.now, self.control_start_time, self.control_start_time+2.0, self.init_z, self.target_z, 0.0, 0.0)\n\n elif self.mode == 1 :\n if self.is_set_target == False:\n self.control_start_time = rospy.get_rostime().secs + rospy.get_rostime().nsecs*10**-9\n self.target_x = 0.138\n self.target_y = 0.0\n self.target_z = 0.239\n self.is_set_target = True\n self.now = rospy.get_rostime().secs + rospy.get_rostime().nsecs*10**-9\n self.goal_x = self.cubic(self.now, self.control_start_time, self.control_start_time+2.0, self.init_x, self.target_x, 0.0, 0.0)\n self.goal_y = self.cubic(self.now, self.control_start_time, self.control_start_time+2.0, self.init_y, self.target_y, 0.0, 0.0)\n self.goal_z = self.cubic(self.now, self.control_start_time, self.control_start_time+2.0, self.init_z, self.target_z, 0.0, 0.0)\n\n elif self.mode == 2:\n self.goal_x = 0.138\n self.goal_y = 0.0\n self.goal_z = 0.239\n\n elif self.mode == 3:\n self.goal_x = 0.290\n self.goal_y = 0.0\n self.goal_z = 0.203\n self.control_start_time = rospy.get_rostime().secs + rospy.get_rostime().nsecs*10**-9\n\n elif self.mode == 4:\n self.goal_x, self.goal_y, self.goal_z = [float(goal) for goal in raw_input(\"Enter goal position x, y, z: \").split()]\n\n \n goal_pose = Pose()\n goal_pose.position.x = self.goal_x\n goal_pose.position.y = self.goal_y\n goal_pose.position.z = self.goal_z \n self.goal_pub.publish(goal_pose)\n\n def ee_pose_cb(self, ee_pose):\n self.init_x = ee_pose.position.x\n self.init_y = ee_pose.position.y\n self.init_z = ee_pose.position.z\n self.init_z = ee_pose.position.z\n self.init_z = ee_pose.position.z\n self.init_z = ee_pose.position.z\n self.init_z = ee_pose.position.z\n\n\n def cubic(self, time,time_0, time_f, x_0, x_f, x_dot_0, x_dot_f):\n x_t = x_0\n\n if (time < time_0):\n x_t = x_0\n\n elif (time > time_f):\n x_t = x_f\n else :\n elapsed_time = time - time_0\n total_time = time_f - time_0\n total_time2 = total_time * total_time\n total_time3 = total_time2 * total_time\n total_x = x_f - x_0\n\n x_t = x_0 + x_dot_0 * elapsed_time \\\n + (3 * total_x / total_time2 \\\n - 2 * x_dot_0 / total_time \\\n - x_dot_f / total_time) \\\n * elapsed_time * elapsed_time \\\n + (-2 * total_x / total_time3 + \\\n (x_dot_0 + x_dot_f) / total_time2) \\\n * elapsed_time * elapsed_time * elapsed_time\n\n return x_t\n\n\ndef main():\n rospy.init_node('goal_publisher')\n\n try:\n gp = GoalPublisher()\n except rospy.ROSInterruptException:\n pass\n\n rospy.spin()\n\nif __name__ == '__main__':\n main()\n","sub_path":"vel_ctrl_ingredients/scripts/sawyer_traj.py","file_name":"sawyer_traj.py","file_ext":"py","file_size_in_byte":4386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"603270570","text":"import requests\n\n__HOST = \"https://rickandmortyapi.com/api\"\n__DOCS = \"https://rickandmortyapi.com/documentation/\"\n\n__all__ = ['get_location_results',\n 'get_location_info',\n 'get_location_single',\n 'get_location_all',\n #'get_location_multi',\n #'location_filter'\n ]\n\ndef get_location_results(page_num=1):\n \"\"\"\n Get 20 locations from the specified page number\n \n Parameters\n ----------\n page_num = int: page to return\n \n Returns\n -------\n json: 20 characters with various fields\n \"\"\"\n endpoint = \"/location\"\n params = {\n \"page\": page_num\n }\n data = requests.get(__HOST + endpoint, params).json()\n return data['results']\n\ndef get_location_info():\n \"\"\"\n Get summary of number of pages and locations available\n \n Parameters\n ----------\n None\n \n Returns\n -------\n json: information about the locations available on the rick and morty API.\n \"\"\"\n endpoint = \"/location\"\n data = requests.get(__HOST + endpoint).json()\n return data['info']\n\ndef get_location_single(id):\n \"\"\"\n Get a location from their ID\n \n Parameters\n ----------\n id = int: id of the location to be returned\n \n Returns\n -------\n json: information about the location\n \"\"\"\n endpoint = f\"/location/{int(id)}\"\n\n data = requests.get(__HOST + endpoint).json()\n return data\n\ndef get_location_all():\n \"\"\"\n Get a list of all the location names from the api\n \n Parameters\n ----------\n None\n \n Returns\n -------\n results = tuple: location id, location names\n \"\"\"\n results = []\n num_of_pages = get_location_info()['pages'] + 1\n\n for i in range(1, num_of_pages):\n locations = get_location_results(i)\n for loc in locations:\n results.append((loc['id'], loc['name']))\n return results\n\n","sub_path":"rick_and_morty/locations.py","file_name":"locations.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"65793303","text":"from flask import Flask,render_template,session,request, redirect, url_for, g\nfrom app import webapp\nimport boto3\nimport datetime\nfrom app.homeui import create_filename\nfrom app.constants import *\nfrom app.photo_info import PhotoInfo\nfrom app.crud import *\n@webapp.route('/post_photo', methods=['GET', 'POST'])\ndef post_photo():\n s3=boto3.client('s3')\n new_file=request.files['postimage']\n new_file.seek(0)\n username=session['current_username']\n full_filename=create_filename(new_file)\n s3.upload_fileobj(new_file,'dongxuren1779a2',full_filename)\n photo_infos = PhotoInfo(username, full_filename, PHOTO_TYPE_SELF,None,None)\n response = update_photo_info(photo_infos)\n\n response_public=select_public_user_info(username)\n response_photo=select_all_photo_info_for_user(username)\n #need modification here\n post_username=response_public[USERNAME]\n post_region=response_public[REGION]\n post_email=response_public[EMAIL]\n post_bio=response_public[DESCRIPTION]\n response_profile=select_profile_photo_info_for_user(username)\n\n profile_location=response_profile[0]\n photo_location=profile_location[PHOTO_LOCATION]\n url_profile=s3.generate_presigned_url('get_object',\n Params={\n 'Bucket':'dongxuren1779a2',\n 'Key':photo_location,\n\n },\n ExpiresIn=3600)\n url_post_list=[]\n for index in response_photo:\n location=index[PHOTO_LOCATION]\n url=s3.generate_presigned_url('get_object',\n Params={\n 'Bucket':'dongxuren1779a2',\n 'Key':location,\n\n },\n ExpiresIn=3600)\n url_post_list.append(url)\n\n return redirect(url_for('load_homepage'))\n #return render_template('home.html',username=post_username,bio=post_bio,email=post_email,region=post_region,url_list=url_post_list,url_profile=url_profile)\n","sub_path":"final_project/app/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"46469992","text":"\"\"\"\nDjango settings for myproject 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# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nimport local_settings\n\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\ngettext = lambda s: s\nPROJECT_PATH = os.path.abspath(os.path.dirname(__file__))\n\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 = local_settings.SECRET_KEY\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = local_settings.DEBUG\n\nTEMPLATE_DEBUG = True\n\nALLOWED_HOSTS = local_settings.ALLOWED_HOSTS\n\n\n# Application definition\n\nINSTALLED_APPS = (\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\n # Django Fiber Apps\n 'mptt',\n 'compressor',\n 'easy_thumbnails',\n 'fiber',\n\n # Additional 3rd party apps\n 'ckeditor',\n 'captcha',\n\n # Project Apps\n 'home', # main site app\n 'projects' # projects app\n #'meetings', # meetings app\n\n)\n\nMIDDLEWARE_CLASSES = (\n 'fiber.middleware.ObfuscateEmailAddressMiddleware', # fiber middleware needs to be listed first\n 'fiber.middleware.AdminPageMiddleware',\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 = 'myproject.urls'\n\nWSGI_APPLICATION = 'reedlab.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, 'reedlab.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/\n\nSTATIC_URL = local_settings.STATIC_URL\nSTATIC_ROOT = local_settings.STATIC_ROOT\nTEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]\n\n# Absolute filesystem path to the directory that will hold user-uploaded files.\n# Example: \"/home/media/media.lawrence.com/media/\"\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash.\n# Examples: \"http://media.lawrence.com/media/\", \"http://example.com/media/\"\nMEDIA_URL = \"/media/\"\n\nCRSF_COOKIE_SECURE = local_settings.CRSF_COOKIE_SECURE\nSESSION_COOKIE_SECURE = local_settings.SESSION_COOKIE_SECURE\n\n##############################\n## Django ckeditor Settings ##\n##############################\nCKEDITOR_UPLOAD_PATH = \"uploads/\"\nCKEDITOR_IMAGE_BACKEND = \"pillow\"\n\n\n###########################\n## Django Fiber Settings ##\n###########################\nimport django.conf.global_settings as DEFAULT_SETTINGS\n\n# Overides Middleware Classes defined above\n# MIDDLEWARE_CLASSES = DEFAULT_SETTINGS.MIDDLEWARE_CLASSES + (\n# 'fiber.middleware.ObfuscateEmailAddressMiddleware',\n# 'fiber.middleware.AdminPageMiddleware',\n# )\n\nTEMPLATE_CONTEXT_PROCESSORS = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (\n 'django.core.context_processors.request',\n)\n\n\n\"\"\"\nAdded to appropriate section above\nINSTALLED_APPS = (\n ...\n 'django.contrib.staticfiles',\n 'mptt',\n 'compressor',\n 'easy_thumbnails',\n 'fiber',\n ...\n)\n\"\"\"\n\n# import os # Already imported above\n# BASE_DIR = os.path.abspath(os.path.dirname(__file__)) # Already defined above\n\n# STATIC_URL = '/static/' # Already defined above\nSTATICFILES_FINDERS = DEFAULT_SETTINGS.STATICFILES_FINDERS + (\n 'compressor.finders.CompressorFinder',\n)\n\n####################################\n## Django Simple Captcha Settings ##\n####################################\nCAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.math_challenge'\nCAPTCHA_NOISE_FUNCTIONS = []\n","sub_path":"myproject/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"611995894","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/ztfy/utils/catalog/index.py\n# Compiled at: 2013-11-19 09:26:44\n__docformat__ = 'restructuredtext'\nimport re\nfrom persistent import Persistent\nfrom BTrees import IFBTree\nfrom zope.index.interfaces import IInjection, IStatistics, IIndexSearch\nfrom zopyx.txng3.core.interfaces import IStorageWithTermFrequency\nfrom zopyx.txng3.core.interfaces.ting import ITingIndex\nfrom zope.catalog.attribute import AttributeIndex\nfrom zope.component import createObject\nfrom zope.container.contained import Contained\nfrom zope.interface import implements\nfrom zopyx.txng3.core import config\nfrom zopyx.txng3.core.index import Index\nfrom hurry.query.query import IndexTerm\n\nclass TextIndexNG(AttributeIndex, Persistent, Contained):\n \"\"\"Adaptation of zopyx.txng3.core for use zope.catalog index\"\"\"\n implements(IInjection, IStatistics, IIndexSearch, ITingIndex)\n\n def __init__(self, field_name=None, interface=None, field_callable=False, use_stemmer=config.defaults['use_stemmer'], dedicated_storage=config.defaults['dedicated_storage'], ranking=config.defaults['ranking'], use_normalizer=config.defaults['use_normalizer'], languages=config.DEFAULT_LANGUAGE, use_stopwords=config.defaults['use_stopwords'], autoexpand_limit=config.defaults['autoexpand_limit'], splitter=config.DEFAULT_SPLITTER, index_unknown_languages=config.defaults['index_unknown_languages'], query_parser=config.DEFAULT_PARSER, lexicon=config.DEFAULT_LEXICON, splitter_additional_chars=config.defaults['splitter_additional_chars'], storage=config.DEFAULT_STORAGE, splitter_casefolding=config.defaults['splitter_casefolding']):\n spaces = re.compile('\\\\s+')\n if ranking:\n util = createObject(storage)\n if not IStorageWithTermFrequency.providedBy(util):\n raise ValueError('This storage cannot be used for ranking')\n _fields = spaces.split(field_name)\n AttributeIndex.__init__(self, _fields[0], interface, field_callable)\n if len(_fields) < 2:\n dedicated_storage = False\n self._index = Index(fields=_fields, languages=spaces.split(languages), use_stemmer=use_stemmer, dedicated_storage=dedicated_storage, ranking=ranking, use_normalizer=use_normalizer, use_stopwords=use_stopwords, storage=storage, autoexpand_limit=autoexpand_limit, splitter=splitter, lexicon=lexicon, index_unknown_languages=index_unknown_languages, query_parser=query_parser, splitter_additional_chars=splitter_additional_chars, splitter_casefolding=splitter_casefolding)\n self.languages = languages\n self.use_stemmer = use_stemmer\n self.dedicated_storage = dedicated_storage\n self.ranking = ranking\n self.use_normalizer = use_normalizer\n self.use_stopwords = use_stopwords\n self.interface = interface\n self.storage = storage\n self.autoexpand_limit = autoexpand_limit\n self.default_field = _fields[0]\n self._fields = _fields\n self.splitter = splitter\n self.lexicon = lexicon\n self.index_unknown_languages = index_unknown_languages\n self.query_parser = query_parser\n self.splitter_additional_chars = splitter_additional_chars\n self.splitter_casefolding = splitter_casefolding\n\n def clear(self):\n self._index.clear()\n\n def documentCount(self):\n \"\"\"See interface IStatistics\"\"\"\n return len(self._index.getStorage(self.default_field))\n\n def wordCount(self):\n \"\"\"See interface IStatistics\"\"\"\n return len(self._index.getLexicon())\n\n def index_doc(self, docid, value):\n \"\"\"See interface IInjection\"\"\"\n self.unindex_doc(docid)\n v = self.interface(value, None)\n if v is not None:\n self._index.index_object(v, docid)\n return\n\n def unindex_doc(self, docid):\n \"\"\"See interface IInjection\"\"\"\n self._index.unindex_object(docid)\n\n def apply(self, query):\n if isinstance(query, dict):\n kw = query\n query = kw['query']\n del kw['query']\n ting_rr = self._index.search(query, **kw)\n return ting_rr.getDocids().keys()\n\n\nclass Text(IndexTerm):\n \"\"\"hurry.query search term\"\"\"\n\n def __init__(self, index_id, text):\n super(Text, self).__init__(index_id)\n self.text = text\n\n def getIndex(self, context=None):\n index = super(Text, self).getIndex(context)\n assert ITingIndex.providedBy(index)\n return index\n\n def apply(self, context=None):\n index = self.getIndex(context)\n return IFBTree.IFSet(index.apply(self.text))","sub_path":"pycfiles/ztfy.utils-0.4.15.1-py2.7/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":4740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"20702630","text":"# -*- coding: utf-8 -*-\n'''\n Created by hushiwei on 2018/7/11\n Desc : tensorflow基础代码---常量变量\n'''\n\nimport tensorflow as tf\n\n# 1. 定义常量矩阵a和矩阵b\na = tf.Variable(initial_value=5, dtype=tf.int32, name='a')\n# a = tf.constant(value=10, dtype=tf.int32)\nb = tf.constant(value=[5, 6, 7, 8], dtype=tf.int32, shape=[2, 2], name='b')\n\nprint(type(a))\nprint(type(b))\n\nprint(a)\nprint(b)\n\ng = tf.placeholder(dtype=tf.int32, shape=[1], name='g1')\n\nf = tf.assign(a, a * 2)\n\n\ninit_op = tf.global_variables_initializer()\n\nwith tf.Session() as session:\n session.run(init_op)\n session.run(f)\n print(session.run(a))\n # print('res:{}'.format(res))\n","sub_path":"BasicLibs/learnTensorFlow/basic/tensorflow-basic01.py","file_name":"tensorflow-basic01.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"95574915","text":"from bs4 import BeautifulSoup\nimport arrow, requests\n\nCOUNTRY_CODE = 'PL'\nsession = requests.session()\n\ndef fetchValue(params):\n\n now = arrow.utcnow()\n end = now.replace(hours=+2)\n start = now.replace(hours=-22)\n periodEnd = end.format('YYYYMMDDHH00')\n periodStart = start.format('YYYYMMDDHH00')\n\n parameters = '&psrType=' + params + '&documentType=A75&processType=A16&in_Domain=10YPL-AREA-----S&periodStart=' + periodStart + '&periodEnd=' + periodEnd\n url = 'https://transparency.entsoe.eu/api?securityToken=7466690c-c66a-4a00-8e21-2cb7d538f380' + parameters\n\n content = session.get(url)\n soup = BeautifulSoup(content.text, \"html.parser\")\n\n last = soup.find_all('point')[-1].find_all('quantity')[-1]\n value = last.contents[0]\n\n return float(value)\n\ndef fetch_PL():\n\n parameters = [\"B01\", \"B02\", \"B03\", \"B04\", \"B05\", \"B06\", \"B10\", \"B11\", \"B12\", \"B19\"]\n output_array = map(fetchValue, parameters)\n\n data = {\n 'countryCode': COUNTRY_CODE,\n 'production': {\n 'wind': output_array[9],\n 'solar': 0,\n 'hydro': output_array[6] + output_array[7] + output_array[8],\n 'biomass': output_array[0],\n 'nuclear': 0,\n 'gas': output_array[2] + output_array[3],\n 'coal': output_array[1] + output_array[4],\n 'oil': output_array[5],\n 'unknown': 0\n }\n }\n\n return data\n\nif __name__ == '__main__':\n print(fetch_PL())\n","sub_path":"feeder/parsers/PL.py","file_name":"PL.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"359596376","text":"import math\nfrom enum import Enum\nimport networkx as nx\n\nfrom mesa import Agent, Model\nfrom mesa.time import RandomActivation\nfrom mesa.datacollection import DataCollector\nfrom mesa.space import NetworkGrid\n\n\nclass State(Enum):\n not_clean = 0\n has_clean = 1\n refuses_clean = 2\n\n\ndef number_state(model, state):\n return sum([1 for a in model.grid.get_all_cell_contents() if a.state is state])\n\n\ndef number_has_clean(model):\n return number_state(model, State.has_clean)\n\n\ndef number_not_clean(model):\n return number_state(model, State.not_clean)\n\n\ndef number_refuses_clean(model):\n return number_state(model, State.refuses_clean)\n\n\nclass Change_Res_Network(Model):\n \"\"\"A virus model with some number of agents\"\"\"\n\n def __init__(\n self,\n num_nodes=1740,\n avg_node_degree=3,\n initial_with_clean=174,\n change_clean_chance=0.03,\n check_frequency=1.0,\n switch_back_chance=0.02,\n gain_resistance_chance=0.0,\n ):\n\n self.num_nodes = num_nodes\n prob = avg_node_degree / self.num_nodes\n self.G = nx.erdos_renyi_graph(n=self.num_nodes, p=prob)\n self.grid = NetworkGrid(self.G)\n self.schedule = RandomActivation(self)\n self.initial_with_clean = (\n initial_with_clean if initial_with_clean <= num_nodes else num_nodes\n )\n self.change_clean_chance = change_clean_chance\n self.check_frequency = check_frequency\n self.switch_back_chance = switch_back_chance\n self.gain_resistance_chance = gain_resistance_chance\n\n self.datacollector = DataCollector(\n {\n \"has_clean\": number_has_clean,\n \"not_clean\": number_not_clean,\n \"refuses_clean\": number_refuses_clean,\n }\n )\n\n # Create agents\n for i, node in enumerate(self.G.nodes()):\n a = VirusAgent(\n i,\n self,\n State.not_clean,\n self.change_clean_chance,\n self.check_frequency,\n self.switch_back_chance,\n self.gain_resistance_chance,\n )\n self.schedule.add(a)\n # Add the agent to the node\n self.grid.place_agent(a, node)\n\n # Infect some nodes\n has_clean_nodes = self.random.sample(self.G.nodes(), self.initial_with_clean)\n for a in self.grid.get_cell_list_contents(has_clean_nodes):\n a.state = State.has_clean\n\n self.running = True\n self.datacollector.collect(self)\n\n def refuses_clean_not_clean_ratio(self):\n try:\n return number_state(self, State.refuses_clean) / number_state(\n self, State.not_clean\n )\n except ZeroDivisionError:\n return math.inf\n\n def step(self):\n self.schedule.step()\n # collect data\n self.datacollector.collect(self)\n\n def run_model(self, n):\n for i in range(n):\n self.step()\n\n\nclass VirusAgent(Agent):\n def __init__(\n self,\n unique_id,\n model,\n initial_state,\n change_clean_chance,\n check_frequency,\n switch_back_chance,\n gain_resistance_chance,\n ):\n super().__init__(unique_id, model)\n\n self.state = initial_state\n\n self.change_clean_chance = change_clean_chance\n self.check_frequency = check_frequency\n self.switch_back_chance = switch_back_chance\n self.gain_resistance_chance = gain_resistance_chance\n\n def try_to_infect_neighbors(self):\n neighbors_nodes = self.model.grid.get_neighbors(self.pos, include_center=False)\n not_clean_neighbors = [\n agent\n for agent in self.model.grid.get_cell_list_contents(neighbors_nodes)\n if agent.state is State.not_clean\n ]\n for a in not_clean_neighbors:\n if self.random.random() < self.change_clean_chance:\n a.state = State.has_clean\n\n def try_gain_resistance(self):\n if self.random.random() < self.gain_resistance_chance:\n self.state = State.refuses_clean\n\n def try_remove_infection(self):\n # Try to remove\n if self.random.random() < self.switch_back_chance:\n # Success\n self.state = State.not_clean\n self.try_gain_resistance()\n else:\n # Failed\n self.state = State.has_clean\n\n def try_check_situation(self):\n if self.random.random() < self.check_frequency:\n # Checking...\n if self.state is State.has_clean:\n self.try_remove_infection()\n\n def step(self):\n if self.state is State.has_clean:\n self.try_to_infect_neighbors()\n self.try_check_situation()\n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"526676619","text":"import socket\n\nserver = \"irc.freenode.net\"\nchannel = \"#jec-dev\"\nbotnick = \"Mybot\"\n\ndef ping(): # responds to server pings\n ircsock.send(\"PONG :pingis\\n\")\n\ndef sendmsg(chan , msg):\n ircsock.send(\"PRIVMSG \"+ chan +\" :\"+ msg +\"\\n\")\n\ndef joinchan(chan):\n ircsock.send(\"JOIN \"+ chan +\"\\n\")\n\ndef hello():\n ircsock.send(\"PRIVMSG \"+ channel +\" :Hello! Welcome to jec-dev! Happy \\\n Hacking! :D\\n\")\n\nircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nircsock.connect((server, 6667)) # Here we connect to the server using the port 6667\nircsock.send(\"USER \"+ botnick +\" \"+ botnick +\" \"+ botnick +\" Test Bot\\n\") # user authentication\nircsock.send(\"NICK \"+ botnick +\"\\n\") # here we actually assign the nick to the bot\n\njoinchan(channel)\n\nwhile 1:\n ircmsg = ircsock.recv(2048)\n ircmsg = ircmsg.strip('\\n\\r') # removing any unnecessary linebreaks.\n print(ircmsg) # server messages\n\n if ircmsg.find(\":Hello \"+ botnick) != -1:\n hello()\n\n if ircmsg.find(\":PING \") != -1:\n ping()\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"178986755","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 20 12:35:17 2017\n\n@author: rstreet\n\"\"\"\nimport os\nimport sys\nfrom astropy.io import fits\nfrom astropy import table\nimport numpy as np\nfrom pyDANDIA import logs\nfrom pyDANDIA import metadata\nfrom pyDANDIA import starfind\nfrom pyDANDIA import pipeline_setup\nfrom pyDANDIA import sky_background\nfrom pyDANDIA import wcs\nfrom pyDANDIA import psf\nfrom pyDANDIA import psf_selection\nfrom pyDANDIA import photometry\nfrom pyDANDIA import phot_db\nfrom pyDANDIA import utilities\nfrom pyDANDIA import config_utils\nfrom pyDANDIA import catalog_utils\nfrom pyDANDIA import calibrate_photometry\nfrom pyDANDIA import image_handling\n\n\nVERSION = 'pyDANDIA_stage3_v1.0.0'\n\ndef run_stage3(setup, **kwargs):\n \"\"\"Driver function for pyDANDIA Stage 3:\n Detailed star find and PSF modeling\n \"\"\"\n\n # Switch to apply Naylor's approach to photometry. Default is False\n use_naylor_phot = False\n\n log = logs.start_stage_log( setup.red_dir, 'stage3', version=VERSION )\n\n log.info('Applying Naylors photometric algorithm? '+repr(use_naylor_phot))\n\n kwargs = get_default_config(kwargs,log)\n for key, value in kwargs.items():\n log.info(str(key)+', '+str(value)+', '+repr(type(value)))\n\n reduction_metadata = metadata.MetaData()\n reduction_metadata.load_all_metadata(metadata_directory=setup.red_dir,\n metadata_name='pyDANDIA_metadata.fits')\n image_red_status = reduction_metadata.fetch_image_status(3)\n\n sane = check_metadata(reduction_metadata,log)\n\n if sane:\n\n meta_pars = extract_parameters_stage3(reduction_metadata,log)\n\n sane = sanity_checks(reduction_metadata,log,meta_pars)\n\n if sane:\n\n ref_structure = image_handling.determine_image_struture(meta_pars['ref_image_path'], log=None)\n\n scidata = image_handling.get_science_image(meta_pars['ref_image_path'], image_structure=ref_structure)\n\n if use_naylor_phot:\n ref_flux = find_reference_flux(detected_sources,log)\n\n ref_star_catalog = catalog_utils.load_ref_star_catalog_from_metadata(reduction_metadata)\n\n sky_model = sky_background.model_sky_background(setup,\n reduction_metadata,log,ref_star_catalog,\n bandpass=meta_pars['bandpass'],\n n_sky_bins=kwargs['n_sky_bins'],\n sky_value=kwargs['sky_value'])\n\n ref_star_catalog = psf_selection.psf_star_selection(setup,\n reduction_metadata,\n log,ref_star_catalog,\n diagnostics=True)\n\n #psf_diameter = reduction_metadata.psf_dimensions[1]['psf_radius'][0]*2.0\n psf_diameter = reduction_metadata.get_psf_radius()*2.0\n log.info('Calculated diameter of PSF = '+str(psf_diameter)+'pix')\n\n (psf_model,psf_status) = psf.build_psf(setup, reduction_metadata,\n log, scidata,\n ref_star_catalog, sky_model,\n psf_diameter,\n diagnostics=True)\n\n if use_naylor_phot:\n ref_star_catalog = photometry.run_psf_photometry_naylor(setup,\n reduction_metadata,\n log,\n ref_star_catalog,\n meta_pars['ref_image_path'],\n psf_model,\n sky_model,\n ref_flux,\n psf_diameter=psf_diameter,\n centroiding=False)\n else:\n ref_star_catalog = photometry.run_psf_photometry(setup,\n reduction_metadata,\n log,\n ref_star_catalog,\n meta_pars['ref_image_path'],\n psf_model,\n sky_model,\n psf_diameter=psf_diameter,\n centroiding=False,\n diagnostics=True)\n\n\n reduction_metadata = store_photometry_in_metadata(reduction_metadata, ref_star_catalog)\n\n reduction_metadata.save_a_layer_to_file(setup.red_dir,\n 'pyDANDIA_metadata.fits',\n 'star_catalog', log=log)\n\n reduction_metadata = calibrate_photometry.calibrate_photometry(setup, reduction_metadata, log,\n **kwargs)\n\n reduction_metadata.create_software_layer(np.array([VERSION,'NONE']),\n log=log)\n\n reduction_metadata.save_a_layer_to_file(setup.red_dir,\n 'pyDANDIA_metadata.fits',\n 'software', log=log)\n\n image_red_status = metadata.set_image_red_status(image_red_status,'1')\n\n reduction_metadata.update_reduction_metadata_reduction_status_dict(image_red_status,\n stage_number=3, log=log)\n reduction_metadata.save_updated_metadata(metadata_directory=setup.red_dir,\n metadata_name='pyDANDIA_metadata.fits')\n\n status = 'OK'\n report = 'Completed successfully'\n\n else:\n status = 'ERROR'\n report = 'Failed sanity checks'\n\n log.info('Stage 3: '+report)\n logs.close_log(log)\n\n return status, report\n\ndef get_default_config(kwargs,log):\n\n default_config = {'n_sky_bins': None, 'sky_value': None,\n 'set_phot_calib': False, 'a0': None, 'a1': None,\n 'use_gaia_phot': False}\n\n kwargs = config_utils.set_default_config(default_config, kwargs, log)\n\n return kwargs\n\ndef check_metadata(reduction_metadata,log):\n \"\"\"Function to verify sufficient information has been extracted from\n the metadata\n\n :param MetaData reduction_metadata: pipeline metadata for this dataset\n\n Returns:\n\n :param boolean status: Status parameter indicating if conditions are OK\n to continue the stage.\n \"\"\"\n\n if 'REF_PATH' not in reduction_metadata.data_architecture[1].keys():\n\n log.info('ERROR: Stage 3 cannot find path to reference image in metadata')\n\n return False\n\n else:\n\n return True\n\ndef sanity_checks(reduction_metadata,log,meta_pars):\n \"\"\"Function to check that stage 3 has all the information that it needs\n from the reduction metadata and reduction products from earlier stages\n before continuing.\n\n :param MetaData reduction_metadata: pipeline metadata for this dataset\n :param logging log: Open reduction log object\n :param dict meta_pars: Essential parameters from the metadata\n\n Returns:\n\n :param boolean status: Status parameter indicating if conditions are OK\n to continue the stage.\n \"\"\"\n\n ref_path = str(reduction_metadata.data_architecture[1]['REF_PATH'][0]) +'/'+ str(reduction_metadata.data_architecture[1]['REF_IMAGE'][0])\n if not os.path.isfile(ref_path):\n # Message reduction_control? Return error code?\n log.info('ERROR: Stage 3 cannot access reference image at '+\\\n ref_path)\n return False\n\n for key, value in meta_pars.items():\n\n if value == None:\n\n log.info('ERROR: Stage 3 cannot access essential metadata parameter '+key)\n\n return False\n\n log.info('Passed stage 3 sanity checks')\n\n return True\n\ndef extract_parameters_stage3(reduction_metadata,log):\n \"\"\"Function to extract the metadata parameters necessary for this stage.\n\n :param MetaData reduction_metadata: pipeline metadata for this dataset\n\n Returns:\n\n :param dict meta_params: Dictionary of parameters and their values\n \"\"\"\n\n meta_pars = {}\n\n try:\n\n meta_pars['ref_image_path'] = str(reduction_metadata.data_architecture[1]['REF_PATH'][0]) +'/'+ str(reduction_metadata.data_architecture[1]['REF_IMAGE'][0])\n meta_pars['ref_image_name'] = str(reduction_metadata.data_architecture[1]['REF_IMAGE'][0])\n\n except AttributeError:\n\n meta_pars['ref_image_path'] = None\n meta_pars['ref_image_name'] = None\n\n idx = np.where(reduction_metadata.images_stats[1]['IM_NAME'].data == reduction_metadata.data_architecture[1]['REF_IMAGE'][0])\n\n if len(idx[0]) > 0:\n\n meta_pars['ref_sky_bkgd'] = reduction_metadata.images_stats[1]['SKY'].data[idx[0][0]]\n\n meta_pars['ref_fwhm'] = reduction_metadata.images_stats[1]['FWHM'].data[idx[0][0]]\n\n meta_pars['bandpass'] = str(reduction_metadata.headers_summary[1]['FILTKEY'].data[idx[0]][0]).replace('p','')\n\n else:\n\n meta_pars['ref_sky_bkgd'] = None\n\n\n\n try:\n\n meta_pars['sky_model_type'] = reduction_metadata.reduction_parameters[1]['BACK_VAR'][0]\n\n except AttributeError:\n\n meta_pars['sky_model_type'] = 'constant'\n\n if len(meta_pars) > 0:\n log.info('Extracted metadata parameters:')\n for key, value in meta_pars.items():\n log.info(key+' = '+str(value))\n\n return meta_pars\n\ndef find_reference_flux(detected_sources,log):\n \"\"\"Function to identify the faintest star in the detected sources\n catalogue. This will be used as the reference flux in the calculation\n of optimized photometry, following the method of Naylor (1997)\n\n Input:\n :param array detected_sources: Array of sources in the frame produced by\n DAOfind\n\n Output:\n :param float ref_flux: Reference flux\n \"\"\"\n\n idx = np.where(detected_sources[:,9] > 0.0)\n\n idx = np.where( detected_sources[idx,9] == detected_sources[idx,9].min() )\n\n ref_flux = detected_sources[idx[0][0],9]\n\n log.info('Measured reference flux of faintest star (used for normalization) = '+\\\n str(ref_flux))\n\n return ref_flux\n\ndef add_reference_image_to_db(setup, reduction_metadata, log=None):\n \"\"\"Function to ingest the reference image and corresponding star catalogue\n to the photometry DB\"\"\"\n\n conn = phot_db.get_connection(dsn=setup.phot_db_path)\n\n ref_image_name = reduction_metadata.data_architecture[1]['REF_IMAGE'].data[0]\n ref_image_dir = reduction_metadata.data_architecture[1]['REF_PATH'].data[0]\n\n idx = np.where(ref_image_name == reduction_metadata.headers_summary[1]['IMAGES'].data)[0][0]\n ref_header = reduction_metadata.headers_summary[1][idx]\n\n query = 'SELECT refimg_name FROM reference_images'\n t = phot_db.query_to_astropy_table(conn, query, args=())\n\n if len(t) == 0 or ref_image_name not in t[0]['refimg_name']:\n\n phot_db.ingest_reference_in_db(conn, setup, ref_header,\n ref_image_dir, ref_image_name,\n ref_header['OBJKEY'], VERSION)\n\n query = 'SELECT refimg_id,refimg_name,current_best FROM reference_images WHERE refimg_name=\"'+ref_image_name+'\"'\n t = phot_db.query_to_astropy_table(conn, query, args=())\n\n ref_db_id = t[0]['refimg_id']\n\n if log!=None:\n log.info('Added reference image to phot_db as entry '+str(ref_db_id))\n\n else:\n\n query = 'SELECT refimg_id,refimg_name FROM reference_images WHERE refimg_name=\"'+ref_image_name+'\"'\n t = phot_db.query_to_astropy_table(conn, query, args=())\n\n ref_db_id = t[0]['refimg_id']\n\n if log!=None:\n log.info('Reference image already in phot_db')\n\n return ref_db_id\n\ndef ingest_stars_to_db(setup, ref_star_catalog, ref_image_name, log=None):\n \"\"\"Function to ingest the detected stars to the photometry database\"\"\"\n\n conn = phot_db.get_connection(dsn=setup.phot_db_path)\n\n query = 'SELECT refimg_id FROM reference_images WHERE refimg_name=\"'+\\\n ref_image_name+'\"'\n t = phot_db.query_to_astropy_table(conn, query, args=())\n\n refimg_id = t['refimg_id'].data[0]\n\n if log!=None:\n log.info('Ingesting stars detected in reference image '+ref_image_name+', refimg_id='+str(refimg_id))\n log.info('Length of ref_star_catalog = '+str(len(ref_star_catalog)))\n\n star_ids = []\n\n for j in range(0,len(ref_star_catalog),1):\n\n star_ids.append( phot_db.feed_to_table( conn, 'Stars', ['ra','dec'],\n [ref_star_catalog[j,3], ref_star_catalog[j,4]] ) )\n\n phot_db.update_table_entry(conn,'stars','reference_images',\n 'star_id',star_ids[-1],refimg_id)\n\n conn.close()\n\n return star_ids\n\ndef ingest_star_catalog_to_db(setup, ref_star_catalog, ref_db_id, star_ids,\n log=None):\n \"\"\"Function to ingest the reference image photometry data for all stars\n detected in this image.\n\n Important: This function only ingests the photometry for a single bandpass,\n and only for instrumental rather than calibrated data, since\n the latter is produced by a different stage of the pipeline.\n\n :param Setup setup: Pipeline setup configuration\n :param np.array ref_star_catalog: Reference image photometry data\n :param int ref_db_id: Primary key of the reference image in the phot_db\n :param list star_ids: List of the DB primary keys of stars in the catalog\n :param Log log: Logger object [optional]\n \"\"\"\n\n conn = phot_db.get_connection(dsn=setup.phot_db_path)\n\n ref_ids = np.zeros(len(ref_star_catalog), dtype='int')\n ref_ids.fill(ref_db_id)\n\n keys = ['reference_mag', 'reference_mag_err',\n 'reference_flux', 'reference_flux_err',\n 'reference_x', 'reference_y']\n\n ref_phot_ids = []\n\n for j in range(0,len(ref_star_catalog),1):\n\n values = [ ref_star_catalog[j,7], ref_star_catalog[j,8],\n ref_star_catalog[j,5], ref_star_catalog[j,6],\n ref_star_catalog[j,1], ref_star_catalog[j,2] ]\n\n ref_phot_ids.append( phot_db.feed_to_table( conn, 'ref_phot',\n keys, values ) )\n\n phot_db.update_table_entry(conn,'ref_phot','reference_images',\n 'ref_phot_id',ref_phot_ids[-1],ref_db_id)\n\n phot_db.update_table_entry(conn,'ref_phot','star_id',\n 'ref_phot_id',ref_phot_ids[-1],star_ids[j])\n\n if log!=None:\n log.info('Ingested '+str(len(ref_phot_ids))+\\\n ' reference image photometry entries into phot_db for reference image '+\\\n str(ref_db_id))\n\n return ref_phot_ids\n\ndef store_photometry_in_metadata(reduction_metadata, ref_star_catalog):\n \"\"\"Function to save the photometry to the metadata star_catalog\"\"\"\n\n reduction_metadata.star_catalog[1]['ref_flux'] = ref_star_catalog[:,5]\n reduction_metadata.star_catalog[1]['ref_flux_error'] = ref_star_catalog[:,6]\n reduction_metadata.star_catalog[1]['ref_mag'] = ref_star_catalog[:,7]\n reduction_metadata.star_catalog[1]['ref_mag_error'] = ref_star_catalog[:,8]\n reduction_metadata.star_catalog[1]['cal_ref_mag'] = ref_star_catalog[:,9]\n reduction_metadata.star_catalog[1]['cal_ref_mag_error'] = ref_star_catalog[:,10]\n reduction_metadata.star_catalog[1]['psf_star'] = ref_star_catalog[:,11]\n reduction_metadata.star_catalog[1]['sky_background'] = ref_star_catalog[:,12]\n reduction_metadata.star_catalog[1]['sky_background_error'] = ref_star_catalog[:,13]\n\n return reduction_metadata\n","sub_path":"pyDANDIA/stage3.py","file_name":"stage3.py","file_ext":"py","file_size_in_byte":16025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"127862846","text":"#!/usr/bin.env python\n#encoding:utf8\nimport sys\nimport os\nimport platform \nimport argparse\nimport textwrap\n\n# 参考\n# https://docs.python.org/zh-cn/3/library/argparse.html\n# https://docs.python.org/3.7/library/difflib.html\n# https://docs.python.org/3.7/library/argparse.html\n\n# TODO: difflib 用于更友好的输出\n# TODO: 测试数据生成\n# TODO: 更多的命令行参数 : 测试次数 , 时间限制等\n# TODO: 增加功能 : 没有对拍程序,只将自己写的程序与标准答案对比\n# TODO:\n\n# 功能\n# 1. 对拍模式 最少需要三个文件 你自己写的源文件 标程 测试数据\n# 1.1 若已存在源程序 将其删除 尝试从源码编译 \n# 1.1.0 优先选择g++ 编译, \n# g++路径用户未事先指定 ==> 直接在命令行执行g++ \n# ==> 若g++不存在,linux下直接报错,windows下尝试使用cl.exe编译\n# ==> 否则,正常编译\n# 否则 ==> 使用用户指定的路径 => 若目标路径存在 => 正常编译\n# => 报错\n \n# 1.2 若已存在标程 将其删除 尝试从源码编译\n# 同1.1.0 \n\n# 1.3 若不存在测试数据 报错\n\n# 2. 验证模式 最少需要三个文件 你自己写的源文件 测试数据 正确答案\n\n# 2.1 若已存在源程序 将其删除 尝试从源码编译 \n# 同1.1.0 \n \n# 2.2 若不存在测试数据 报错\n# 2.3 若不存在正确答案 报错\n\n# NOTE 若指定了 val参数,则将val参数传进.validate函数中并调用.validate函数,否则运行 pai函数\n\n\nstr_desc = textwrap.dedent('''\\\n跨平台对拍程序\\n\n--------------------------------\\n\n Windows平台下无需书写.exe后缀名\\n\n Linux下书写完整程序名\\n\n''')\n\nparser = argparse.ArgumentParser(prog='pai.py', description=str_desc,\n epilog=\"author: bamboohill@outlook.com\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument('my', type=str, nargs='?', default='my', help='自己写的程序')\nparser.add_argument('std', type=str, nargs='?', default='std', help='标准例程')\nparser.add_argument('data', type=str, nargs='?', default='data', help='测试数据')\nparser.add_argument('-v', '--val', '--validate', dest='ans', nargs='?', default='data', help='验证答案')\nargs = parser.parse_args()\n\nclass Pai:\n pass\n\nclass WindowsPai(Pai):\n \n def __init__(self):\n pass\n\n def check_execuable(self, fname):\n if not os.path.exists(fname):\n print(\"(⇀‸↼‶) 找不到可执行文件: {}\".format(fname))\n sys.exit(1)\n\n def exec_std(self):\n ## FIXME 若文件名写了.exe 则不应该再在后面加 .exe 若没写,则程序自动加上后缀 .exe\n os.system('{std}.exe < {data}.in > {std}.out'.format(std=args.std, data=args.data))\n \n def exec_my(self):\n os.system('{my}.exe < {data}.in > {my}.out'.format(my=args.my, data=args.data))\n\n def diff(self, lhs, rhs):\n os.system('fc {lhs} {rhs}'.format(lhs=lhs, rhs=rhs))\n\n # TODO\n def run(self):\n if args.ans:\n print(args.ans)\n print(\"validate\")\n else:\n print('pai')\n self.pai()\n\n def pai(self):\n self.check_execuable('{std}.exe'.format(std=args.std))\n self.check_execuable('{my}.exe'.format(my=args.my))\n\n self.exec_std()\n self.exec_my()\n\n me = '{}.out'.format(args.my)\n std = '{}.out'.format(args.std)\n self.diff(me, std)\n\n def validate(self):\n self.check_execuable('{my}.exe'.format(my=args.my))\n if not os.path.exists('{}.ans'.format(args.my)):\n print('(⇀‸↼‶) 找不到正确答案: {}.ans'.format(args.my))\n sys.exit(1)\n\n os.system('{my}.exe < {my}.in > {my}.out'.format(my=args.my))\n me = '{}.out'.format(args.my)\n ans = '{}.ans'.format(args.my)\n self.diff(me, ans)\n\n\nclass LinuxPai(Pai):\n def pai(self):\n pass\n\nif __name__ == '__main__':\n sys_type = platform.system()\n if sys_type == 'Windows':\n WindowsPai().validate()\n elif sys_type == 'Linux':\n LinuxPai().pai()\n else:\n print('Unknown platform');\n sys.exit(1)","sub_path":"leetcode-en/py/pai.py","file_name":"pai.py","file_ext":"py","file_size_in_byte":4472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"142186273","text":"import pandas as pd\n\n\ndata = pd.read_csv('scored_196.csv')\n# THRESHOLD = 0.4 # ----->>>>>> change this according to your preference\n\ndata = data.sort_values(by=['patientId'])\n\n# data.to_csv(\"scored_195_sort.csv\", index=False)\n\ndf_pneu = pd.read_csv('has_pneu.csv')\n\ndf_pneu = df_pneu.sort_values(by=['patientId'])\n\nnew_strings = list()\n\nl = 0\n\nfor line in data['PredictionString']:\n # print(df_pneu['patientId'][0])\n if type(line) is str:\n tokens = line.split(' ')\n new_line = \"\"\n for k in range(int(len(tokens)/5)):\n # if float(tokens[k * 5]) >= THRESHOLD:\n x, y, w, h = float(tokens[k*5+1]), float(tokens[k*5+2]), float(tokens[k*5+3]), float(tokens[k*5+4])\n if (df_pneu['has_pneu'][l] == 1) or w >= 250 or h >= 250:\n for i in range(k * 5, k * 5 + 5):\n new_line += tokens[i] + \" \"\n new_strings.append(new_line)\n else:\n new_strings.append(\"\")\n\n l += 1\n\nnew_file = pd.DataFrame({'patientId': data['patientId'], 'PredictionString': new_strings})\nnew_file.to_csv('scored_180_no_small_boxes_conf.csv', index=False)\n","sub_path":"change_csv.py","file_name":"change_csv.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"240102754","text":"class Node:\r\n\r\n\tdef __init__(self,value):\r\n\t\tself.value = value\r\n\t\tself.next = None\r\n\r\nclass LinkedList:\r\n\r\n\tdef __init__(self):\r\n\t\tself.head = None\r\n\r\n\tdef cs2c(self): # function to convert a singly linked list to circular\r\n\t\ttemp = self.head\r\n\t\tc = 0 \r\n\t\twhile(temp):\r\n\t\t\tc += 1\r\n\t\t\ttemp = temp.next\r\n\t\ttemp = self.head\r\n\t\tfor i in range(int(c)-1):\r\n\t\t\ttemp = temp.next\r\n\t\ttemp.next = self.head\r\n\r\n\t\t# Printing the linked list\r\n\t\ttemp = self.head\r\n\t\tc = 0\r\n\t\twhile(temp and c < 18): # this will print linked list twi e as there are 9 elements in the linked list.\r\n\t\t\tprint(temp.value)\r\n\t\t\ttemp = temp.next\r\n\t\t\tc += 1\r\n\r\n\r\n# defining elements of linked list\r\nLinkedListObj = LinkedList() # creating object of linked list\r\nLinkedListObj.head = Node(1) # defining head\r\nfirst_node = Node(2) # second element in linked list\r\nsecond_node = Node(3) \r\nthird_node = Node(4)\r\nforth_node = Node(99)\r\nfifth_node = Node(3)\r\nsixth_node = Node(44)\r\nseventh_node = Node(2)\r\neight_node = Node(7)\r\nninth_node = Node(77)\r\n\r\n# linking linked list0\r\nLinkedListObj.head.next = first_node \r\nfirst_node.next = second_node\r\nsecond_node.next = third_node\r\nthird_node.next = forth_node\r\nforth_node.next = fifth_node\r\nfifth_node.next = sixth_node\r\nsixth_node.next = seventh_node\r\nseventh_node.next = eight_node\r\neight_node.next = ninth_node\r\n\r\nLinkedListObj.cs2c()","sub_path":"Singly_to_Circular_LinkedList_Conversion.py","file_name":"Singly_to_Circular_LinkedList_Conversion.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"42591378","text":"# Licensed Materials - Property of IBM\n# 5725I71-CC011829\n# (C) Copyright IBM Corp. 2015, 2020. All Rights Reserved.\n# US Government Users Restricted Rights - Use, duplication or\n# disclosure restricted by GSA ADP Schedule Contract with IBM Corp.\n\n__author__ = 'IBM'\n\nfrom flask import Flask\nfrom qpylib import qpylib\n\n\n# Flask application factory.\ndef create_app():\n # Create a Flask instance.\n qflask = Flask(__name__)\n\n # Retrieve QRadar app id.\n qradar_app_id = qpylib.get_app_id()\n\n # Create unique session cookie name for this app.\n qflask.config['SESSION_COOKIE_NAME'] = 'session_{0}'.format(qradar_app_id)\n\n # Hide server details in endpoint responses.\n # pylint: disable=unused-variable\n @qflask.after_request\n def obscure_server_header(resp):\n resp.headers['Server'] = 'QRadar App {0}'.format(qradar_app_id)\n return resp\n\n # Register q_url_for function for use with Jinja2 templates.\n qflask.add_template_global(qpylib.q_url_for, 'q_url_for')\n\n # Initialize logging.\n qpylib.create_log()\n\n # To enable app health checking, the QRadar App Framework\n # requires every Flask app to define a /debug endpoint.\n # The endpoint function should contain a trivial implementation\n # that returns a simple confirmation response message.\n @qflask.route('/debug')\n def debug():\n return 'Pong!'\n\n # Import additional endpoints.\n # For more information see:\n # https://flask.palletsprojects.com/en/1.1.x/tutorial/views\n from . import views\n qflask.register_blueprint(views.viewsbp)\n\n return qflask\n","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"233023305","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/Products/Zpydoc/tests/zcheck.py\n# Compiled at: 2011-09-28 02:31:46\n__version__ = '0.2.0'\nimport os, sys\nif __name__ == '__main__':\n execfile(os.path.join(sys.path[0], 'framework.py'))\nimport warnings\nwarnings.simplefilter('ignore', DeprecationWarning, append=1)\nfrom Testing import ZopeTestCase\nfrom Testing.ZopeTestCase import _print\nZopeTestCase.installProduct('PlacelessTranslationService')\nZopeTestCase.installProduct('ZChecker')\nfrom Products.CMFPlone.tests import PloneTestCase\n\nclass TestSkins(PloneTestCase.PloneTestCase):\n\n def afterSetUp(self):\n factory = self.portal.manage_addProduct['ZChecker']\n factory.manage_addZChecker('zchecker')\n self.verbose = '-q' not in sys.argv\n\n def testSkins(self):\n \"\"\"Runs the ZChecker on skins\"\"\"\n dirs = self.portal.portal_skins.objectValues()\n for dir in dirs:\n if self._skinpath(dir) in ('portal_skins/zpydoc', ):\n results = self.portal.zchecker.checkObjects(dir.objectValues())\n for result in results:\n self._report(result)\n\n if self.verbose:\n _print('\\n')\n\n def testZMI(self):\n \"\"\" WAM trying this ...\"\"\"\n pass\n\n def _report(self, result):\n msg = result['msg']\n obj = result['obj']\n if msg:\n if self.verbose:\n _print('\\n')\n _print('------\\n%s\\n' % self._skinpath(obj))\n for line in msg:\n _print('%s\\n' % line)\n\n if self.verbose:\n _print('.')\n\n def _skinpath(self, obj):\n path = obj.absolute_url(1)\n path = path.split('/')\n return ('/').join(path[1:])\n\n\nif __name__ == '__main__':\n TestRunner(verbosity=0).run(test_suite())","sub_path":"pycfiles/Products.Zpydoc-4.0.1-py2.6/zcheck.py","file_name":"zcheck.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"559763610","text":"# Copyright (c) 2017 Niklas Rosenstein\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\ntry:\n require\nexcept NameError:\n from . import git\nelse:\n git = require('./git')\n\nfrom datetime import datetime, timezone, timedelta\nfrom collections import namedtuple\nimport errno\nimport os\nimport time\nimport sys\n\nnow = datetime.now\ntime_fmt = '%d/%b/%Y:%H:%M:%S %z'\nCheckinData = namedtuple('CheckinData', 'name time')\nCheckoutData = namedtuple('CheckoutData', 'name begin end interval message')\n\n\ndef makedirs(path):\n if not os.path.isdir(path):\n os.makedirs(path)\n\ndef now():\n tz = timezone(timedelta(hours=-time.timezone/3600))\n return datetime.now().replace(tzinfo=tz)\n\ndef strftime(time, fmt=None):\n return time.strftime(fmt or time_fmt)\n\ndef strptime(value, fmt=None):\n return datetime.strptime(value, fmt or time_fmt)\n\ndef splittimedelta(tdelta, components='DHMS'):\n l = {'D': 86400, 'H': 3600, 'M': 60, 'S': 1}\n r = []\n rem = int(tdelta.total_seconds())\n for k in components:\n d, rem = divmod(rem, l[k])\n r.append(d)\n return r\n\ndef parse_time(value):\n \"\"\"\n Parses a time string in multiple possible variants.\n \"\"\"\n\n formats = [\n time_fmt,\n '%H:%M',\n '%H:%M:%S',\n '%H-%M',\n '%H-%M-%S',\n '%d/%H:%M',\n '%d/%H:%M:%S',\n '%m/%d/%H:%M',\n '%m/%d/%H:%M:%S'\n ]\n for fmt in formats:\n try:\n return datetime.strptime(value, fmt)\n except ValueError:\n pass\n raise ValueError('invalid time string: {!r}'.format(value))\n\nclass NoCheckinAvailable(Exception):\n pass\n\ndef get_checkin_file(fatal=True):\n return os.path.join(git.dir(fatal=fatal), 'timetable', 'checkin')\n\ndef set_checkin(name, time=None):\n time = time or now()\n filename = get_checkin_file()\n makedirs(os.path.dirname(filename))\n with open(filename, 'w') as fp:\n fp.write('{}\\n{}\\n'.format(name, strftime(time)))\n return CheckinData(name, time)\n\ndef get_checkin():\n filename = get_checkin_file()\n if not os.path.isfile(filename):\n raise NoCheckinAvailable(filename)\n with open(filename) as fp:\n name = fp.readline().rstrip()\n time = fp.readline().rstrip()\n time = strptime(time)\n if not name or fp.read().strip():\n raise ValueError('invalid check-in file at {!r}'.format(filename))\n return CheckinData(name, time)\n\ndef rem_checkin():\n filename = get_checkin_file()\n try:\n os.remove(filename)\n except OSError as exc:\n if exc.errno != errno.ENOENT:\n raise\n\ndef add_checkout(name, begin, end, message=None):\n interval = end - begin\n if not message:\n message = 'Checkout ' + str(interval)\n\n # Read the contents of the timetable file for this user.\n filename = name + '.tsv'\n try:\n contents = git.show('git-timetable:' + filename)\n except git.DoesNotExist:\n contents = ''\n\n # Add an entry to the file.\n if not contents.endswith('\\n'):\n contents += '\\n'\n contents += '{}\\t{}\\t{}\\n'.format(strftime(begin), strftime(end), message or '')\n\n # Create a commit to add the line to the timetable.\n commit = git.Commit()\n commit.head('git-timetable', message)\n commit.add_file_contents(contents, filename)\n\n git.fast_import(commit.getvalue(), date_format='raw', quiet=True)\n return CheckoutData(name, begin, end, interval, message)\n","sub_path":"git_timetable/timetable.py","file_name":"timetable.py","file_ext":"py","file_size_in_byte":4217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"604595854","text":"# greaseweazle/image/scp.py\n#\n# Written & released by Keir Fraser \n#\n# This is free and unencumbered software released into the public domain.\n# See the file COPYING for more details, or visit .\n\nimport struct, functools\n\nfrom greaseweazle import error\nfrom greaseweazle.flux import Flux\n\nclass SCPOpts:\n \"\"\"legacy_ss: Set to True to generate (incorrect) legacy single-sided\n SCP image.\n \"\"\"\n def __init__(self):\n self.legacy_ss = False\n\nclass SCP:\n\n # 40MHz\n sample_freq = 40000000\n\n def __init__(self, start_cyl, nr_sides):\n self.opts = SCPOpts()\n self.nr_sides = nr_sides\n self.nr_revs = None\n self.track_list = [(None,None)] * (start_cyl*2)\n\n\n @classmethod\n def to_file(cls, start_cyl, nr_sides):\n scp = cls(start_cyl, nr_sides)\n return scp\n\n\n @classmethod\n def from_file(cls, dat):\n\n header = struct.unpack(\"<3s9BI\", dat[0:16])\n (sig, _, _, nr_revs, _, _, flags, _, single_sided, _, _) = header\n error.check(sig == b\"SCP\", \"SCP: Bad signature\")\n\n index_cued = flags & 1 or nr_revs == 1\n if not index_cued:\n nr_revs -= 1\n \n # Some tools generate a short TLUT. We handle this by truncating the\n # TLUT at the first Track Data Header.\n trk_offs = struct.unpack(\"<168I\", dat[16:0x2b0])\n for i in range(168):\n try:\n off = trk_offs[i]\n except IndexError:\n break\n if off == 0 or off >= 0x2b0:\n continue\n off = off//4 - 4\n error.check(off >= 0, \"SCP: Bad Track Table\")\n trk_offs = trk_offs[:off]\n\n scp = cls(0, 2)\n scp.nr_revs = nr_revs\n\n for trknr in range(len(trk_offs)):\n \n trk_off = trk_offs[trknr]\n if trk_off == 0:\n scp.track_list.append((None, None))\n continue\n\n # Parse the SCP track header and extract the flux data.\n thdr = dat[trk_off:trk_off+4+12*nr_revs]\n sig, tnr = struct.unpack(\"<3sB\", thdr[:4])\n error.check(sig == b\"TRK\", \"SCP: Missing track signature\")\n error.check(tnr == trknr, \"SCP: Wrong track number in header\")\n _off = 12 if index_cued else 24 # skip first partial rev\n s_off, = struct.unpack(\"= len(self.track_list):\n return None\n tdh, dat = self.track_list[off]\n if dat is None:\n return None\n\n index_list = []\n while tdh:\n ticks, _, _ = struct.unpack(\"<3I\", tdh[:12])\n index_list.append(ticks)\n tdh = tdh[12:]\n \n # Decode the SCP flux data into a simple list of flux times.\n flux_list = []\n val = 0\n for i in range(0, len(dat), 2):\n x = dat[i]*256 + dat[i+1]\n if x == 0:\n val += 65536\n continue\n flux_list.append(val + x)\n val = 0\n\n return Flux(index_list, flux_list, SCP.sample_freq)\n\n\n def append_track(self, track):\n \"\"\"Converts @track into a Supercard Pro Track and appends it to\n the current image-in-progress.\n \"\"\"\n\n def _append(self, tdh, dat):\n self.track_list.append((tdh, dat))\n if self.nr_sides == 1:\n self.track_list.append((None, None))\n\n flux = track.flux()\n\n nr_revs = len(flux.index_list)\n if not self.nr_revs:\n self.nr_revs = nr_revs\n else:\n assert self.nr_revs == nr_revs\n \n factor = SCP.sample_freq / flux.sample_freq\n\n tdh, dat = bytearray(), bytearray()\n len_at_index = rev = 0\n to_index = flux.index_list[0]\n rem = 0.0\n\n for x in flux.list:\n\n # Does the next flux interval cross the index mark?\n while to_index < x:\n # Append to the TDH for the previous full revolution\n tdh += struct.pack(\"= nr_revs:\n # We're done: We simply discard any surplus flux samples\n _append(self, tdh, dat)\n return\n to_index += flux.index_list[rev]\n\n # Process the current flux sample into SCP \"bitcell\" format\n to_index -= x\n y = x * factor + rem\n val = int(round(y))\n if (val & 65535) == 0:\n val += 1\n rem = y - val\n while val >= 65536:\n dat.append(0)\n dat.append(0)\n val -= 65536\n dat.append(val>>8)\n dat.append(val&255)\n\n # Header for last track(s) in case we ran out of flux timings.\n while rev < nr_revs:\n tdh += struct.pack(\"= 200.00):\n\tprint(round(pd, 2))\n\nelse:\n\tprint(round(preco, 2))","sub_path":"5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/222/users/4066/codes/1643_869.py","file_name":"1643_869.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"384040607","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef question1_6():\n num = 100\n rVals = np.linspace(1.e-5, 0.025, num=num)\n timeVals = np.logspace(0.1, 1.75, num=5)\n\n plt.style.use('/home/will/Projects/MCLS_CSU/MCLS_Res/GeneralTools/Visualization/matplotlibStyleSheets/MCLSPoster')\n fig, ax = plt.subplots(nrows=2, ncols=1)\n\n for i in range(len(timeVals)):\n yVals = _fun1_6(rVals, timeVals[i])\n dYVals = _dFun1_6(rVals, timeVals[i])\n ax[0].plot(rVals, yVals)\n maxY = max(yVals)\n maxX = rVals[np.argwhere(yVals==maxY)[0,0]]\n ax[0].annotate('{}s'.format(np.round(timeVals[i],2)), xy=(maxX, maxY-25))\n\n ax[1].plot(rVals, dYVals)\n maxY = max(dYVals)\n maxX = rVals[np.argwhere(dYVals == maxY)[0, 0]]\n if i <= 2:\n ax[1].annotate('{}s'.format(np.round(timeVals[i],2)), xy=(maxX, maxY))\n ax[0].grid()\n ax[1].grid()\n ax[1].set_xlabel('r (m)', fontsize=16)\n ax[0].set_ylabel(r'$V_{\\theta} (m/s)$', fontsize=16)\n ax[1].set_ylabel(r'$\\omega_{3} (s^{-1})$', fontsize=16)\n ax[0].set_xlim(0, 0.025)\n ax[1].set_xlim(0, max(rVals))\n plt.show()\n return\n\ndef _fun1_6(rVals, time, constant=1., nu=1e-6):\n term1 = np.exp(-(rVals**2)/(4.*nu*time))\n val = (constant/rVals)*(1. - term1)\n return val\n\ndef _dFun1_6(rVals, time, constant=1., nu=1e-6):\n term1 = np.exp(-(rVals ** 2) / (4. * nu * time))\n term2 = constant/(2.*nu*time)\n val = term1*term2\n return val\n\nif __name__=='__main__':\n question1_6()","sub_path":"ViscousFlow/Homework1/Homework1.py","file_name":"Homework1.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"183625792","text":"\"\"\"pause.py\nexample of a pause screen scene.\n\"\"\"\n\nimport logging\nfrom pygame import Surface\n\nfrom crashlib.scene import Scene, command\nfrom crashlib.config import Config\nfrom crashlib.resources import ResourceManager\n\nCURTAIN_COLOR = (0, 0, 0)\nCURTAIN_ALPHA = 150\nTEXT_COLOR = (255, 255, 0)\n\nclass PauseScene(Scene):\n def __init__(self, director, paused_scene):\n super().__init__(director, 'pause')\n self.paused_scene = paused_scene\n self.curtain_surface = Surface((Config.window_w, Config.window_h))\n self.curtain_surface.fill(CURTAIN_COLOR)\n self.curtain_surface.set_alpha(CURTAIN_ALPHA)\n self.font = ResourceManager.load_font('ttf/Roboto-Medium.ttf', 'roboto')\n\n def on_update(self):\n pass\n\n def on_draw(self, screen):\n self.paused_scene.on_draw(screen) # render the paused scene as 'background'\n screen.blit(self.curtain_surface, (0, 0)) # add a semi-transparent layer\n # draw the pause menu here\n # ...\n self.font.render_to(screen, (50, 50), \"The game is in PAUSE\", TEXT_COLOR, size=20)\n\n@command(PauseScene, 'pause_back')\ndef back(scene):\n scene.director.change_scene(scene.paused_scene)\n","sub_path":"src/pause.py","file_name":"pause.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"273428031","text":"from flask import (\n Blueprint, flash, g, redirect, render_template, request, url_for, json\n)\nfrom werkzeug.exceptions import abort\nfrom flask import Markup\n#from flaskr.auth import login_required\n#from flaskr.db import get_db\n\nbp = Blueprint('cbs', __name__)\n\n#convert sentence into array \ndef convertToArray(sentence): \n\t#return sentence.split()\n\treturn list(sentence)\n\n#convert array to string\ndef convertToString(keywords):\n\tstr = \"\"\n\tfor keyword in keywords:\n\t\tstr += keyword + ' '\n\treturn str\t\n\n\n@bp.route('/')\ndef index():\n \n sentence = \"Hello Road?, Is this, the emergency hotline?.. I would like to report that there \" + \"is a heavy traffic due to a collision... between MitsubishiV.02 & mazda3 car \" + \"along District 11th Kamuning road. \" \n jap_sentence = \"こんにちは道路、これは緊急ホットラインですか?第11地区カムニン道路沿いの 三菱とマツダ3両が 衝突して渋 滞しているとのことです。\"\n keywords = [\"三菱\",\"トラフィック\",\"マツダ\",\"衝突\",\"道路\"]\n #keywords = [\"Mitsubishi\",\"traffic\", \"Mazda\", \"Collision\", \"road\"]\n\n sentence_array = convertToArray(jap_sentence)\n print(sentence_array)\n\n #=== FRO ENGLISH WORDS ====\n #check if keywords are present in the realtime sentence.\n # for n, word in enumerate(sentence_array):\n # for keyword in keywords:\n # if keyword.upper() == word.upper() or word.upper().find(keyword.upper()) > -1:\n # sentence_array[n] = \"\"+word+\"\"\n \n #=== FOR JAPANESE ===\n for n, word in enumerate(sentence_array):\n for keyword in keywords:\n if word in keyword:\n \t print(word +\"->\"+ keyword)\n \t sentence_array[n] = \"\"+word+\"\"\n \n data = {'name':'ben', 'info':'sample data', 'content': Markup(\"\".join(sentence_array))}\n data2 = {'sentence':jap_sentence, 'keywords': convertToString(keywords).strip()}\n\n return render_template('cbs/index.html', data=data, data2=data2)\n\n","sub_path":"CBSMain/cbs.py","file_name":"cbs.py","file_ext":"py","file_size_in_byte":2065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"431701621","text":"import re\n\nfrom django import forms\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.contrib.admin.widgets import AdminTextInputWidget, AdminTextareaWidget\n\nfrom mailer.models import Message, make_message\n\n\nclass MessageForm(forms.ModelForm):\n from_email = forms.CharField(widget=AdminTextInputWidget())\n to = forms.CharField(widget=AdminTextInputWidget())\n subject = forms.CharField(widget=AdminTextInputWidget())\n body = forms.CharField(widget=AdminTextareaWidget)\n body_html = forms.CharField(required=False, widget=AdminTextareaWidget)\n\n def __init__(self, *args, **kwargs):\n instance = kwargs.get('instance')\n if instance:\n if not kwargs.get('initial'):\n kwargs['initial'] = {}\n kwargs['initial']['from_email'] = instance.from_address\n kwargs['initial']['to'] = instance.to_addresses\n kwargs['initial']['subject'] = instance.subject\n kwargs['initial']['body'] = instance.body\n kwargs['initial']['body_html'] = instance.body_html\n return super(MessageForm, self).__init__(*args, **kwargs)\n\n def save(self, commit=True):\n instance = super(MessageForm, self).save(commit=False)\n instance = make_message(db_msg=instance,\n from_email=self.cleaned_data['from_email'],\n to=re.split(\", *\", self.cleaned_data['to']),\n subject=self.cleaned_data['subject'],\n body=self.cleaned_data['body'])\n\n body_html = self.cleaned_data['body_html']\n if body_html:\n email = instance.email\n email = EmailMultiAlternatives(email.subject, email.body, email.from_email, email.to)\n email.attach_alternative(body_html, \"text/html\")\n instance.email = email\n\n if commit:\n instance.save()\n return instance\n\n class Meta:\n model = Message\n fields = ('from_email', 'to', 'subject', 'body', 'body_html', 'when_added', 'priority')\n","sub_path":"mailer/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"16137289","text":"import textract\nfrom FileReader import *\nfrom flask import *\nfrom werkzeug import secure_filename\nimport pyrebase\nimport sys\nimport os\napp = Flask(__name__)\napp.config['UPLOAD_FOLDER'] = './static/images/'\napp.secret_key = 'some_secret'\nconfig = {\n \"apiKey\": \"AIzaSyBNeqANlaGZOcRX0aT_i1YfDbiCpTgfHqI\",\n \"authDomain\": \"flickering-fire-3792.firebaseapp.com\",\n \"databaseURL\": \"https://flickering-fire-3792.firebaseio.com\",\n \"projectId\": \"flickering-fire-3792\",\n \"storageBucket\": \"flickering-fire-3792.appspot.com\",\n \"messagingSenderId\": \"189921954509\"\n}\nfirebase = pyrebase.initialize_app(config)\n\n@app.route('/', methods=['GET','POST'])\ndef start():\n try:\n _ = session[\"user\"]\n except Exception as e:\n session[\"user\"] = None\n session[\"result\"] = None\n return render_template('index.html')\n\n@app.route('/login', methods=['GET','POST'])\ndef login():\n if request.method == 'POST':\n username = request.form['username']\n password = request.form['password']\n try:\n session[\"user\"] = firebase.auth().sign_in_with_email_and_password(username, password)\n return redirect('/admin')\n except Exception as e:\n message = str(e)\n index = message.find(\"\\\"message\\\": \\\"\")\n end = message.find(\"\\\"\", index+12)\n print(index, end)\n error = message[index+12 : end]\n return render_template('login.html', error=error)\n else:\n if not session[\"user\"]: \n return render_template('login.html', error=\"\")\n else:\n return redirect('/admin')\n\n@app.route('/logout')\ndef logout():\n session[\"user\"] = None\n return redirect('/login')\n\n@app.route('/popular')\ndef popular():\n session[\"user\"] = None\n return render_template('popular.html', error=\"\")\n\n@app.route('/admin')\ndef admin():\n try:\n _ = session[\"user\"]\n except Exception as e:\n session[\"user\"] = None\n\n if session[\"user\"] is None:\n # For testing only\n # user = \"Test\"\n # return redirect('/admin')\n # Actual line\n return redirect('/login')\n else:\n db = firebase.database()\n labels = [label.val() for label in db.child(\"Labels\").get().each()]\n return render_template('admin.html', labels=labels)\n\n@app.route('/reset-password', methods=[\"POST\"])\ndef reset():\n email = request.form[\"username\"]\n try:\n firebase.auth().send_password_reset_email(email)\n flash(\"Password reset email sent!\")\n except Exception as e:\n message = str(e)\n index = message.find(\"\\\"message\\\": \\\"\")\n end = message.find(\"\\\"\", index+12)\n print(index, end)\n error = message[index+12 : end]\n flash(error)\n return redirect('/login')\n\n\n\n\n@app.route('/main')\ndef main():\n try:\n _ = session[\"result\"]\n except Exception as e:\n session[\"result\"] = None\n\n return render_template('main.html')\n\n@app.route('/result', methods=['GET', 'POST'])\ndef analyze():\n if request.method == 'POST':\n data = request.form['text']\n if data == \"\":\n return redirect('/main')\n iconlist = FileReader.textSplit(data)\n\n db = firebase.database()\n labels = [label.val() for label in db.child(\"Labels\").get().each()]\n for text, labelid in iconlist.items():\n iconlist[text] = labels[labelid]\n\n out = open(\"static/output.txt\", \"w+\")\n for k in iconlist.keys():\n out.write(\"\\n\" + iconlist[k][\"name\"] + \"\\n\" + \"\\n\" + k + \"\\n\" + \"\\n\" + \"----------\" + \"\\n\" + \"\\n\")\n out.close()\n\n\n session[\"result\"] = iconlist\n return render_template('result.html', result=iconlist)\n else:\n if session[\"result\"]:\n return render_template('result.html', result=session[\"result\"])\n else:\n return redirect('/main')\n\n\n@app.route('/result-file', methods=['GET','POST'])\ndef analyzefile():\n if request.method == 'POST':\n f = request.files['file']\n \n text = textract.process(f.filename)\n\n iconlist = FileReader.fileSplit(text.decode('utf-8'))\n\n db = firebase.database()\n labels = [label.val() for label in db.child(\"Labels\").get().each()]\n for text, labelid in iconlist.items():\n iconlist[text] = labels[labelid]\n\n out = open(\"static/output.txt\", \"w+\")\n for k in iconlist.keys():\n out.write(\"\\n\" + iconlist[k][\"name\"] + \"\\n\" + \"\\n\" + k + \"\\n\" + \"\\n\" + \"----------\" + \"\\n\" + \"\\n\")\n out.close()\n\n session[\"result\"] = iconlist\n return render_template('result.html', result=iconlist)\n else:\n if session[\"result\"]:\n return render_template('result.html', result=session[\"result\"])\n else:\n return redirect('/main')\n \n@app.route('/report-main', methods=['POST'])\ndef report_main():\n label = request.form['label']\n text = request.form['text']\n report(label, text)\n return redirect('/main')\n\n@app.route('/report-result', methods=['POST'])\ndef report_result():\n label = request.form['label']\n text = request.form['text']\n report(label, text)\n if session[\"result\"]:\n return render_template('result.html', result=session[\"result\"])\n else:\n return redirect('/main')\n\n\ndef report(label, text):\n db = firebase.database()\n db.child(\"Reports\").push({\"category\":label, \"text\":text, \"resolved\":False})\n\n\n\n@app.route('/userFeedback')\ndef feedback():\n try:\n _ = session[\"user\"]\n except Exception as e:\n session[\"user\"] = None\n\n if session[\"user\"] is None:\n # For testing only\n # user = \"Test\"\n # return redirect('/userFeedback')\n # Actual line\n return redirect('/login')\n else:\n db = firebase.database()\n reports = []\n for key, report in [(item.key(), item.val()) for item in db.child('Reports').get().each()]:\n reports.append((key, report[\"category\"], report[\"text\"], report[\"resolved\"]))\n return render_template('userFeedback.html', reports=reports)\n\n@app.route('/edit-icon', methods=[\"POST\"])\ndef editicon():\n name = request.form[\"name\"]\n url = request.form[\"url\"]\n desc = request.form[\"desc\"]\n index = request.form[\"index\"]\n\n if not url.endswith(\".png\") and not url.endswith(\".jpg\"):\n url = url + \".png\"\n\n data = {\n \"Labels/\"+index: {\n \"name\" : name,\n \"imgurl\" : url,\n \"description\" : desc\n }\n }\n firebase.database().update(data)\n return redirect(\"/admin\")\n\n\n@app.route('/add-admin', methods=['POST'])\ndef add_admin():\n email = request.form['email']\n password = request.form['password']\n try:\n firebase.auth().create_user_with_email_and_password(email, password)\n flash(\"Account added successfully!\")\n except Exception as e:\n message = str(e)\n index = message.find(\"\\\"message\\\": \\\"\")\n end = message.find(\"\\\"\", index+12)\n print(index, end)\n error = message[index+12 : end]\n flash(error)\n\n return redirect('/admin')\n\n@app.route('/resolve', methods=['POST'])\ndef resolve():\n issueid = request.form['id']\n status = request.form['status']\n print(status)\n if not issueid:\n flash(\"No issue selected!\")\n else:\n try:\n db = firebase.database()\n db.child(\"Reports\").child(issueid).update({\"resolved\": status != \"True\"})\n except Exception as e:\n message = str(e)\n index = message.find(\"\\\"message\\\": \\\"\")\n end = message.find(\"\\\"\", index+12)\n print(index, end)\n error = message[index+12 : end]\n flash(error)\n\n return redirect('/userFeedback')\n\n@app.route('/add-image', methods=[\"POST\"])\ndef upload_image():\n try:\n f = request.files['image']\n f.save(os.path.join(app.config['UPLOAD_FOLDER'],secure_filename(f.filename)))\n flash(\"Image Uploaded Successfully\")\n except Exception as e:\n flash(str(e))\n return redirect('/admin')\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"178133407","text":"#!/usr/bin/env python\nimport csv\nimport sqlite3\n\nconnection = sqlite3.connect('db.sqlite3')\nconnection.text_factory = str\ncursor = connection.cursor()\n\ncsvfile = open('versionlist.csv', 'rb')\ncreader = csv.reader(csvfile, delimiter=',', quotechar='|')\n\nfor t in creader:\n if t[1] != '':\n cursor.execute('INSERT INTO charts_issue_versions (issue_id, version_id) VALUES (?,?)', (t[0], t[1]) )\n\n\ncsvfile.close()\nconnection.commit()\nconnection.close()\n","sub_path":"importerVersion.py","file_name":"importerVersion.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"520749784","text":"from twium.models import User, Status, Notify\n\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\n\n\ndef tweet_parser(tweet_item: BeautifulSoup):\n try:\n text = tweet_item.find('p', class_='tweet-text').text.replace('\\n', '\\\\n')\n except:\n return None\n\n user = User(\n name=tweet_item.attrs['data-name'],\n screen_name=tweet_item.attrs['data-screen-name'],\n user_id=int(tweet_item.attrs['data-user-id'])\n )\n tweet = Status(\n status_id=int(tweet_item.attrs['data-tweet-id']),\n text=text, user=user\n )\n return tweet\n\n\ndef activity_parser(activity_item: BeautifulSoup):\n user_items = activity_item.find_all('a', class_='js-profile-popup-actionable')\n users = []\n for user_item in user_items:\n s = User(\n name=user_item.attrs['title'],\n screen_name=user_item.attrs['href'][1:],\n user_id=int(user_item.attrs['data-user-id'])\n )\n users.append(s)\n\n tweet_item = activity_item.find('div', class_='QuoteTweet-innerContainer')\n tweet_user = User(\n name=tweet_item.find('b', class_='QuoteTweet-fullname').text,\n screen_name=tweet_item.attrs['data-screen-name'],\n user_id=int(tweet_item.attrs['data-user-id'])\n )\n tweet = Status(\n text=tweet_item.find('div', class_='QuoteTweet-text').text,\n status_id=int(tweet_item.attrs['data-item-id']),\n user=tweet_user\n )\n\n notify = Notify(\n activity_type=activity_item.attrs['data-component-context'],\n users=users,\n tweet=tweet\n )\n return notify\n\n\ndef driver2soup(driver: webdriver):\n return BeautifulSoup(driver.page_source, 'html.parser')\n","sub_path":"twium/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"167466477","text":"import logging.config\nfrom logging.handlers import SysLogHandler\nimport sys\n\ntry:\n from logging.config import dictConfig\nexcept ImportError: # pragma: nocover\n from logutils.dictconfig import dictConfig\n\n\nclass ColoredStreamHandler(logging.StreamHandler):\n\n _color_map = {\n logging.DEBUG: '37',\n logging.INFO: '1;39',\n logging.WARN: '96',\n logging.ERROR: '91',\n logging.CRITICAL: '1;91',\n }\n\n def format(self, record):\n lines = logging.StreamHandler.format(self, record)\n color = self._color_map.get(record.levelno, '39')\n lines = ''.join([\n '\\033[0;%sm%s\\033[0m' % (color, line)\n for line in lines.splitlines(True)\n ])\n return lines\n\n\nclass MultilineFormatter(logging.Formatter):\n def format(self, record):\n s = logging.Formatter.format(self, record)\n if '\\n' not in s:\n return s\n\n lines = s.splitlines()\n d = record.__dict__.copy()\n for i, line in enumerate(lines[1:]):\n record.message = line\n lines[1 + i] = self._fmt % record.__dict__\n record.__dict__ = d\n\n return '\\n'.join(lines)\n\n\nclass LastnameFilter(logging.Filter):\n root, _, _ = __name__.partition('.')\n\n def filter(self, record):\n record.lastname = record.name\n if record.name.startswith(self.root + '.'):\n _, record.lastname = record.name.rsplit('.', 1)\n # Always log, we are just enriching records.\n return 1\n\n\nHANDLERS = {\n 'file': {\n '()': 'logging.FileHandler',\n 'mode': 'a',\n 'formatter': 'dated_syslog',\n },\n 'syslog': {\n '()': 'logging.handlers.SysLogHandler',\n 'formatter': 'syslog',\n },\n 'stderr': {\n '()': 'logging.StreamHandler',\n 'formatter': 'minimal',\n },\n}\n\n\ndef setup_logging(**kw):\n logging_config = generate_logging_config(**kw)\n dictConfig(logging_config)\n\n\ndef configure_debug(logging_config, core, debug):\n # If --debug or DEBUG=1, apply DEBUG to all core loggers\n if debug in (True, '__debug__'):\n debug = core\n\n if hasattr(debug, 'split'):\n debug = filter(None, debug.split(','))\n\n # Now apply debug level.\n if debug:\n for loggername in debug:\n logger = logging_config['loggers'].setdefault(loggername, {})\n logger['level'] = 'DEBUG'\n\n\ndef generate_logging_config(\n level=None, destination=None, facility='local0',\n method='stderr', debug=None, **kw):\n\n core = LastnameFilter.root\n\n if level is None:\n level = 'DEBUG' if debug else 'INFO'\n\n if debug is None:\n debug = level == 'DEBUG'\n\n facility = SysLogHandler.facility_names[facility]\n HANDLERS['syslog']['facility'] = facility\n HANDLERS['syslog']['address'] = destination\n HANDLERS['file']['filename'] = destination\n\n fmt = 'verbose' if debug or level == 'DEBUG' else 'minimal'\n\n HANDLERS['stderr']['formatter'] = fmt\n if sys.stderr.isatty():\n HANDLERS['stderr']['()'] = __name__ + '.ColoredStreamHandler'\n\n minimal_fmt = '%(levelname)5.5s: %(message)s'\n verbose_fmt = (\n '%(asctime)s [%(process)5d] [%(lastname)-16.16s] ' + minimal_fmt\n )\n syslog_fmt = (\n core + \"[%(process)d]: \"\n \"[%(lastname)s] %(levelname)s: %(message)s\"\n )\n\n logging_config = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'lastname': {\n '()': __name__ + '.LastnameFilter',\n }\n },\n 'formatters': {\n 'dated_syslog': {\n '()': __name__ + '.MultilineFormatter',\n 'format': '%(asctime)s ' + syslog_fmt,\n },\n 'minimal': {\n '()': __name__ + '.MultilineFormatter',\n 'format': minimal_fmt,\n },\n 'syslog': {\n '()': __name__ + '.MultilineFormatter',\n 'format': syslog_fmt,\n },\n 'verbose': {\n '()': __name__ + '.MultilineFormatter',\n 'format': verbose_fmt,\n },\n },\n 'handlers': {\n 'configured': dict(\n HANDLERS[method],\n filters=['lastname'],\n ),\n },\n 'root': {\n 'level': 'INFO',\n # Avoid instanciate all handlers, especially syslog which open\n # /dev/log\n 'handlers': ['configured'],\n },\n 'loggers': {},\n }\n\n # Apply level to temboard loggers only\n logging_config['loggers'][core] = dict(level=level)\n\n configure_debug(logging_config, core, debug)\n return logging_config\n","sub_path":"log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":4699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"356586420","text":"\"\"\"\nStore here local functions to parse, obtain, compose operations for database details.\n\n\"\"\"\nimport datetime\nimport logging\nfrom django.db.models import Q\nfrom django.utils import timezone\nfrom octo_tku_patterns.models import TestLast, TestHistory, TestCases\n\nlog = logging.getLogger(\"octo.octologger\")\n\n\nclass PatternsDjangoModelRaw:\n\n @staticmethod\n def sel_history_by_latest_all(date_to, date_from, addm_name):\n \"\"\"\n Select last N days test records for pattern:\n :param addm_name:\n :param date_from:\n :param date_to:\n :return:\n \"\"\"\n query = \"\"\"SELECT octo_test_history.id,\n octo_test_history.time_spent_test,\n octo_test_history.test_py_path,\n octo_test_history.test_date_time\n FROM octopus_dev_copy.octo_test_history\n WHERE octo_test_history.test_date_time BETWEEN '{date_from}' AND '{date_to}'\n AND octo_test_history.addm_name = '{addm_name}'\n GROUP BY day(octo_test_history.test_date_time), octo_test_history.test_py_path\n ORDER BY octo_test_history.test_py_path;\n \"\"\".format(date_from=date_from,\n date_to=date_to,\n addm_name=addm_name,\n )\n log.debug(\"Using query: \\n%s\", query)\n history_recs = TestHistory.objects.raw(query)\n return history_recs\n\n\nclass PatternsDjangoTableOper:\n\n @staticmethod\n def release_db_date():\n \"\"\" Just generate time window from last month 26th till today +1 day\n Because p4 would not show all today changes\n\n Start dates:\n - main \"2017-09-25\"\n - ship \"2017-10-12\"\n \"\"\"\n # TODO: Here update dates also!\n import datetime\n date_time_now = datetime.datetime.now()\n\n # CURRENT day date\n last_day = date_time_now + datetime.timedelta(days=1)\n tomorrow = last_day.strftime('%Y-%m-%d')\n\n # 25th date of previous month:\n first_day_month = datetime.date.today().replace(day=1)\n lastMonth = first_day_month - datetime.timedelta(days=6)\n last_month_release = lastMonth.strftime('%Y-%m-%d')\n\n release_window = dict(\n today = tomorrow,\n start_date = last_month_release)\n\n return release_window\n\n # TODO: CHANGE EVERYWHERE where is relation to this\n @staticmethod\n def sel_tests_dynamical(**kwargs):\n \"\"\"\n Based on options from kwargs - select patterns for test routine.\n Possible options:\n\n - include: list of pattern folder names should be selected anyway;\n - exclude: list of pattern folder names should NOT be selected anyway;\n - last_days: datetime window converted from int of last days changes to select patterns;\n - date_from: datetime str from what date to start;\n - date_to: if set - the latest date of changes, if not - use tomorrow date\n - branch: tkn_main or tkn_ship or both if none\n - user: user_adprod name - to choose only those patterns;\n - change: str - number of p4 change\n - library: CORE, CLOUD etc\n\n :param kwargs:\n :return:\n \"\"\"\n from django.utils import timezone\n import datetime\n sel_opts = kwargs.get('sel_opts', {})\n\n now = datetime.datetime.now(tz=timezone.utc)\n tomorrow = now + datetime.timedelta(days=1)\n\n # switch-case:\n selectables = dict(\n # sel_k = sel_v\n # Experimental options:\n pattern_folder_name='pattern_folder_name__in',\n # Dynamical options:\n last_days='change_time__range',\n date_from='change_time__range',\n # Strict options:\n exclude='pattern_folder_name__in',\n branch='tkn_branch__exact',\n user='change_user__exact',\n change='change__exact',\n library='pattern_library__exact',\n )\n\n # log.debug(\"<=Django Model intra_select=> Select sel_opts %s\", sel_opts)\n\n # Select everything valid for test:\n all_patterns = TestCases.objects.filter(test_type__exact='tku_patterns')\n\n def intra_select(queryset, option_key, option_value):\n sel_k = selectables.get(option_key)\n select_d = {sel_k: option_value}\n\n # # NOT Work fine, NOT excluding by pattern's folder\n # TODO: Exclude by checking if pattern is member of \"Excluded\" group.\n if option_key == 'exclude':\n # log.debug(\"<=Django Model intra_select=> Select exclude: %s\", select_d)\n intra_filtered = queryset.exclude(**select_d)\n\n # Select from last N-days, till today(tomorrow)\n elif option_key == 'last_days':\n date_from = now - datetime.timedelta(days=int(option_value))\n # log.debug(\"<=Django Model intra_select=> Select for the last %s days. %s %s\", option_value, date_from, tomorrow)\n select_d.update(change_time__range=[date_from, tomorrow])\n # log.debug(\"<=Django Model intra_select=> Select last_days: %s\", select_d)\n intra_filtered = queryset.filter(**select_d)\n\n # Select from strict date till today(tomorrow)\n elif option_key == 'date_from':\n date_from = datetime.datetime.strptime(option_value, '%Y-%m-%d').replace(tzinfo=timezone.utc)\n # log.debug(\"<=Django Model intra_select=> Select date_from %s %s to %s\", option_value, date_from, tomorrow)\n select_d.update(change_time__range=[date_from, tomorrow])\n # log.debug(\"<=Django Model intra_select=> Select date_from: %s\", select_d)\n intra_filtered = queryset.filter(**select_d)\n\n # All other strict options:\n else:\n # log.debug(\"<=Django Model intra_select=> Select %s: %s\", sel_k, select_d)\n intra_filtered = queryset.filter(**select_d)\n\n return intra_filtered\n\n for opt_k, opt_v in sel_opts.items():\n # When key value is present and not None\n if opt_v:\n # log.info(\"<=Django Model=> Using this option: %s value is %s\", opt_k, opt_v)\n all_patterns = intra_select(all_patterns, opt_k, opt_v)\n else:\n # log.info(\"<=Django Model=> Skipping this option: %s value is %s\", opt_k, opt_v)\n pass\n\n # log.debug(\"<=Django Model intra_select=> sel_tests_dynamical() \"\n # \"selected len: %s \"\n # \"history_recs.query: \\n%s\", all_patterns.count(), all_patterns.query)\n\n # log.debug(\"sel_tests_dynamical queryset explain \\n%s\", all_patterns.explain())\n return all_patterns\n\n @staticmethod\n def sel_dynamical(model, **kwargs):\n \"\"\"\n Based on options from kwargs - select patterns for test routine.\n Possible options:\n\n - include: list of pattern folder names should be selected anyway;\n - exclude: list of pattern folder names should NOT be selected anyway;\n - last_days: datetime window converted from int of last days changes to select patterns;\n - date_from: datetime str from what date to start;\n - date_to: if set - the latest date of changes, if not - use tomorrow date\n - branch: tkn_main or tkn_ship or both if none\n - user: user_adprod name - to choose only those patterns;\n - change: str - number of p4 change\n - library: CORE, CLOUD etc\n\n :param model:\n :param kwargs:\n :return:\n \"\"\"\n sel_opts = kwargs.get('sel_opts', {})\n\n now = datetime.datetime.now(tz=timezone.utc)\n tomorrow = now + datetime.timedelta(days=1)\n\n # switch-case:\n selectables = dict(\n test_type='test_type__exact',\n tkn_branch='tkn_branch__exact',\n change_user='change_user__exact',\n change_review='change_review__contains',\n change_ticket='change_ticket__exact',\n pattern_library='pattern_library__exact',\n pattern_folder_name='pattern_folder_name__exact',\n pattern_folder_names='pattern_folder_name__in', # list()\n change='change__exact',\n # Test related:\n addm_name='addm_name__exact',\n addm_group='addm_group__exact',\n addm_v_int='addm_v_int__exact',\n addm_host='addm_host__exact',\n addm_ip='addm_ip__exact',\n # Dynamical options:\n last_days='change_time__range',\n date_from='change_time__range',\n # Strict options:\n exclude='pattern_folder_name__in', # list()\n\n # For single test.py record sorting:\n test_py_path='test_py_path__exact',\n # For single test item sorting:\n tst_name='tst_name__exact',\n tst_class='tst_class__exact',\n )\n # log.debug(\"<=Django Model intra_select=> Select sel_opts %s\", sel_opts)\n all_qs = model.objects.all()\n\n def intra_select(queryset, option_key, option_value):\n sel_k = selectables.get(option_key)\n select_d = {sel_k: option_value}\n\n if option_key == 'exclude':\n # log.debug(\"<=Django Model intra_select=> Select exclude: %s\", select_d)\n intra_qs = queryset.exclude(**select_d)\n\n # Select from last N-days, till today(tomorrow)\n elif option_key == 'last_days':\n date_from = now - datetime.timedelta(days=int(option_value))\n # log.debug(\"<=Django Model intra_select=> Select for the last %s days. %s %s\", option_value, date_from, tomorrow)\n select_d.update(change_time__range=[date_from, tomorrow])\n # log.debug(\"<=Django Model intra_select=> Select last_days: %s\", select_d)\n intra_qs = queryset.filter(**select_d)\n\n # Select from strict date till today(tomorrow)\n elif option_key == 'date_from':\n date_from = datetime.datetime.strptime(option_value, '%Y-%m-%d').replace(tzinfo=timezone.utc)\n # log.debug(\"<=Django Model intra_select=> Select date_from %s %s to %s\", option_value, date_from, tomorrow)\n select_d.update(change_time__range=[date_from, tomorrow])\n # log.debug(\"<=Django Model intra_select=> Select date_from: %s\", select_d)\n intra_qs = queryset.filter(**select_d)\n elif option_key == 'tst_status':\n # log.debug(\"Going to sort selected tests with status '%s' only.\", option_value)\n if option_value == 'pass':\n # log.debug(\"use: pass_only\")\n intra_qs = queryset.filter(~Q(tst_status__iregex='FAIL$') & ~Q(tst_status__iregex='ERROR$'))\n elif option_value == 'fail':\n # log.debug(\"use: fail_only\")\n intra_qs = queryset.filter(Q(tst_status__iregex='FAIL$')| Q(tst_status__iregex='unexpected') | Q(tst_status__iregex='Warning'))\n elif option_value == 'notpass':\n # log.debug(\"use: not_pass_only\")\n intra_qs = queryset.filter(\n Q(tst_status__iregex='FAIL$') | Q(tst_status__iregex='ERROR$') | Q(tst_status__iregex='unexpected') | Q(tst_status__iregex='Warning'))\n elif option_value == 'error':\n # log.debug(\"use: error_only\")\n intra_qs = queryset.filter(tst_status__iregex='ERROR$')\n elif option_value == 'skip':\n # log.debug(\"use: skip_only\")\n intra_qs = queryset.filter(\n Q(tst_status__iregex='skipped') | Q(tst_status__iregex='expected failure'))\n else:\n log.warning(\"Unknown option_value '%s' for '%s' Do not select - return as is.\", option_value, option_key)\n intra_qs = queryset\n\n # All other strict options:\n else:\n # log.debug(\"<=Django Model intra_select=> Select %s: %s\", sel_k, select_d)\n intra_qs = queryset.filter(**select_d)\n\n return intra_qs\n\n for opt_k, opt_v in sel_opts.items():\n # When key value is present and not None\n if opt_v:\n # log.info(\"<=Django Model=> Using this option: %s value is %s\", opt_k, opt_v)\n all_qs = intra_select(all_qs, opt_k, opt_v)\n else:\n # log.info(\"<=Django Model=> Skipping this option: %s value is %s\", opt_k, opt_v)\n pass\n # log.debug(\"<=Django Model sel_dynamical=> sel_dynamical() \"\n # \"selected len: %s \"\n # \"sel_dynamical.query: \\n%s\", all_qs.count(), all_qs.query)\n #\n # log.debug(\"sel_dynamical queryset explain \\n%s\", all_qs.explain())\n return all_qs\n\n\nclass PatternsDjangoTableOperDel:\n\n \"\"\"\n Routine to delete logs older than 400 days.\n DELETE FROM `octopus_dev_copy`.`octo_test_history`\n WHERE test_date_time < DATE_SUB(NOW(),INTERVAL 400 DAY);\n \"\"\"\n\n @staticmethod\n def delete_old_solo_test_logs(query_args):\n test_item_deleted = 'None'\n try:\n if query_args.get('tst_class') and query_args.get('tst_name'):\n test_item_deleted = TestLast.objects.filter(\n tkn_branch__exact = query_args['branch'],\n pattern_library__exact = query_args['pattern_library'],\n pattern_folder_name__exact = query_args['pattern_folder'],\n tst_name__exact = query_args['tst_name'],\n tst_class__exact = query_args['tst_class']\n ).delete()\n else:\n test_item_deleted = TestLast.objects.filter(\n tkn_branch__exact = query_args['branch'],\n pattern_library__exact = query_args['pattern_library'],\n pattern_folder_name__exact = query_args['pattern_folder'],\n )\n except Exception as e:\n log.error(\"<=DjangoTableOperDel=> delete_old_solo_test_logs Error: %s\", e)\n return test_item_deleted\n","sub_path":"octo_tku_patterns/table_oper.py","file_name":"table_oper.py","file_ext":"py","file_size_in_byte":14417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"382350404","text":"from __future__ import print_function\n\n### Need to make sure these libraries can be loaded! ###\nimport os,sys,subprocess,urllib,requests,getopt,pickle\nimport math,random\nimport xyplotter,webbrowser\nimport myfeedforward6 as myfeedforward\n\n\n#\n# This program is just like tutorial3.py except a function is used to generate the html rather than a webbsite.\n#\n# To run \n#\n# python tutorial5.py\n#\n#\n# This code is assuming that your python is a python 2.7 and that you have the above libraries available on your system. \n# I'm pretty sure only the requests library is not in default installation.\n#\n# One you get it to run, try changing the name of the feifilename to see if you can read in different data sets.\n#\n\n\n#feifilename = \"h2-aimd.fei\"\n#feifilename = \"tequil-2018-3-2-12.fei\"\n#feifilename = \"tequil-2018-3-9-8.fei\"\n\n#### going to read a URL ####\n#feifilename = \"https://arrows.emsl.pnnl.gov/api/eric_view/raw=we31869:/media/Seagate2/Projects/ForJim/Position-Specific-Isotopes/1M/Pyruvate/AIMD/tequil-2018-3-2-12.fei\"\n#feifilename = \"https://arrows.emsl.pnnl.gov/api/eric_view/raw=we31869:/media/Seagate2/Projects/BES/Mackinawite/Cascade-hopper/udimer-fes.fei\"\n#feifilename = \"/Users/bylaska/Codes/ML_Potentials/CO2/perm2/co2.fei\"\n#feifilename = \"https://arrows.emsl.pnnl.gov/api/eric_view/raw=we31869:/media/Seagate2/Projects/ForRaymond/perm/co2-2019-30-19-12.fei\"\n\n#feifilename = \"https://bitbucket.org/ebylaska/ml_potentials/raw/7afb9bece4d7a8f2a0a500970a0dea639cc75f47/ML_Potentials/CO2/perm2/co2.fei\"\n\n\nfeifilename = \"co2.fei\"\n\n\n\n\n#### simple functions to check if string is a number ####\ndef evalnum(s):\n try:\n return int(s)\n except ValueError:\n return float(s)\n\ndef isevalnum(s):\n try:\n x = evalnum(s)\n return True\n except:\n return False\n\n\n\n#################################\n# #\n# read_fei_urlfile #\n# #\n#################################\n#\n# This function reads an nwchem .fei file frame by frame.\n# Note that urlfilename can either be a filename or a url link to a .fei file\n#\ndef read_fei_urlfile(urlfilename):\n \"\"\"Lazy function (generator) to read a fei_file \n frame by frame.\"\"\"\n #tobohr = 1.0/0.529177\n tobohr = 1.0 #fei file is in atomic units\n\n if \"http\" in urlfilename:\n rr = requests.get(urlfilename.strip())\n xyzdata = rr.text.split('\\n')\n else:\n with open(urlfilename,'r') as ff: \n xyzdata = ff.read().strip().split('\\n')\n\n nion = int(xyzdata[0])\n nlines = nion+5\n nframes = int(len(xyzdata)/nlines)\n print(\"NION=\",nion,\" nframes=\",nframes)\n print(\"nlines=\",nlines,\" len(xyzdata)=\",len(xyzdata))\n\n framecounter = 0\n while (framecounterymax): ymax = y\n if (yymax): ymax = y0[i]\n if (y0[i]\\n\"\n msg4 += '''\n \n \n \n
%s
\n
\n \n ''' % (xlabel)\n\n msg4 += \"\\n\"\n\n return msg4\n\n\n\n\n####################### main program ##############################\n\n### started from scratch - build up path from l=0 ###\nplot = xyplotter.xyplotter(0.0,0.0,1.0,1.0, \"Scaled Energies Plot\",2)\n\n\n##### Read in fei file lazilly and do a simple print out of the data ####\nnframes = 0\n\nemin = +99999.99\nemax = -99999.99\nenergies = []\n\nd1min = +999999.9\nd1max = -999999.9\ndist1 = []\n\nd2min = +999999.9\nd2max = -999999.9\ndist2 = []\n\nd3min = +999999.9\nd3max = -999999.9\ndist3 = []\nfor (symbols,rions,fions,energy) in read_fei_urlfile(feifilename):\n energies.append(energy)\n if (energyemax): emax = energy\n\n x12 = rions[0] - rions[3]\n y12 = rions[1] - rions[4]\n z12 = rions[2] - rions[5]\n r12 = math.sqrt(x12*x12 + y12*y12 + z12*z12)\n dist1.append(r12)\n if (r12d1max): d1max = r12\n\n x23 = rions[3] - rions[6]\n y23 = rions[4] - rions[7]\n z23 = rions[5] - rions[8]\n r23 = math.sqrt(x23*x23 + y23*y23 + z23*z23)\n dist2.append(r23)\n if (r23d2max): d2max = r23\n\n x13 = rions[0] - rions[6]\n y13 = rions[1] - rions[7]\n z13 = rions[2] - rions[8]\n r13 = math.sqrt(x13*x13 + y13*y13 + z13*z13)\n dist3.append(r13)\n if (r13d3max): d3max = r13\n\n nframes += 1\n\n#es = (e-emin)/(emax-emin)\n#x = ((xmax+xmin) + xs*(xmax-xmin))*0.5\n#xs = (2*x - (xmax+xmin))/(xmax-xmin)\n#\n#define scaled coordinates ###\nfor i in range(nframes):\n energies[i] = (energies[i]-emin)/(emax-emin)\n dist1[i] = (2*dist1[i] - (d1max+d1min))/(d1max-d1min)\n dist2[i] = (2*dist2[i] - (d2max+d2min))/(d2max-d2min)\n dist3[i] = (2*dist3[i] - (d3max+d3min))/(d3max-d3min)\n\nnframes0 = nframes-500\n\n\nalpha0 = 0.01\nalpha = 0.0001\nbeta1 = 0.9\nbeta2 = 0.999\neps = 1e-8\n\nbeta = 2.0\n#sigmoid = lambda x: 1.0/(1.0+math.exp(-x))\n#sigmoidp = lambda x: math.exp(-x)/(1.0+math.exp(-x))**2\n#sigmoidpp = lambda x: math.exp(-x)*(math.exp(-x)-1.0)/(1.0+math.exp(-x))**3\nap = 1.0\nxp = 4.5\nbp = 3.0\npenalty = lambda x: ap*(0.5*(math.tanh(bp*(x-xp)) - math.tanh(bp*(x+xp))) + 1.0)\npenaltyp = lambda x: ap*0.5*bp*( (1/math.cosh(bp*(x-xp)))**2 - (1.0/math.cosh(bp*(x+xp)))**2)\n\nsigmoid = lambda x: 0.5*(math.tanh(beta*x)+1.0)\nsigmoidp = lambda x: 0.5*beta*(1.0/math.cosh(beta*x))**2\nsigmoidpp = lambda x: 0.5*(-2.0)*beta*beta*math.tanh(beta*x)*(1.0/math.sech(beta*x))**2\nxmoid1 = lambda x: x\nxmoidp1 = lambda x: 1.0\nxmoidpp1 = lambda x: 0.0\n\n#bias = [[0.01],[0.01],[0.001],[0.0001],[0.00001],[0.0000001]]\nbias = [[0.01],[0.01],[0.001]]\nbias = []\nmachine = myfeedforward.MyFeedForward([3,60,120,1],[xmoid1,sigmoid,sigmoid,xmoid1],[xmoidp1,sigmoidp,sigmoidp,xmoidp1],[xmoidpp1,sigmoidpp,sigmoidpp,xmoidpp1])\n\nif os.path.isfile(\"tutorial6.weights\"):\n with open(\"tutorial6.weights\",'rb') as ff:\n weights = pickle.loads(ff.read())\nelse:\n weights = machine.initial_w()\n for i in range(len(weights)):\n weights[i] *= 1.0\n\nnw = len(weights)\n\nprint(\"weights=\",weights)\nprint(\"nw=\",nw)\nm = [0.0]*len(weights)\nv = [0.0]*len(weights)\nbeta1t = 1.0\nbeta2t = 1.0\nprint(\"nframes=\",nframes)\n\n\n\n###plot the relative energies using Turtle graphics###\nplot_pathenergy(plot,energies[nframes0:],machine,weights,dist1[nframes0:],dist2[nframes0:],dist3[nframes0:])\n\nenter0 = input(\" -- start simulation --- \")\n\nerror = 999999.9\nii = 0\nfor i in range(1000000):\n\n es = energies[ii]\n xs = dist1[ii]\n ys = dist2[ii]\n us = dist3[ii]\n ii = ((ii+1)%nframes0)\n \n gg = machine.w_energy_gradient([xs,ys,us],[es],weights)\n error0 = error\n error = gg[0]\n g1 = gg[1]\n\n #for j in range(nw):\n # error += penalty(weights[j])\n # g1[j] += penaltyp(weights[j])\n\n\n beta1t *= beta1\n beta2t *= beta2\n alphat = alpha*math.sqrt(1.0-beta2t)/(1.0-beta1t)\n for j in range(nw):\n m[j] = beta1*m[j] + (1.0-beta1)*g1[j]\n v[j] = beta2*v[j] + (1.0-beta2)*g1[j]*g1[j]\n weights[j] -= alphat*m[j]/(math.sqrt(v[j]) + eps)\n\n if ((i%20000)==0):\n es1 = machine.evaluate([xs,ys,us],weights)[0]\n print(\"%10d %10.3f %10.3f %10.3f %10.3f %10.3f || %12.6f\" % (i,xs,ys,us,es,es1,error))\n plot_pathenergy(plot,energies[nframes0:],machine,weights,dist1[nframes0:],dist2[nframes0:],dist3[nframes0:])\n\n with open(\"tutorial6.weights\",'wb') as ff:\n ff.write(pickle.dumps(weights))\n\n###plot the relative energies using html ###\n\n###wait for return so that plot can be seen###\nx = input(\"--Press return to finish--\")\nprint(\"yeh - writing weeights\")\n\nwith open(\"tutorial6.weights\",'wb') as ff:\n ff.write(pickle.dumps(weights))\n\n","sub_path":"Tutorial/tutorial6.py","file_name":"tutorial6.py","file_ext":"py","file_size_in_byte":11164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"364568325","text":"import unittest\nfrom copy import copy\nimport ROOT\nROOT.PyConfig.IgnoreCommandLineOptions = True\n\n\nclass TestLayer(unittest.TestCase):\n def setUp(self):\n self.egammaLayerRecalibTool = ROOT.egammaLayerRecalibTool\n self.output_file = ROOT.TFile(\"test_output.root\", \"recreate\")\n\n def tearDown(self):\n self.output_file.Close()\n\n def iscrack(self, eta):\n aeta = abs(eta)\n return 1.37 <= aeta <= 1.55\n\n def example_inputs(self):\n inputs = ROOT.StdCalibrationInputs()\n inputs.E0raw = 10.\n inputs.E1raw = 20.\n inputs.E2raw = 30.\n inputs.E3raw = 40.\n inputs.R = 0.\n inputs.phi = 0.;\n return inputs\n\n def test_init(self):\n tool = self.egammaLayerRecalibTool('2012')\n tool = self.egammaLayerRecalibTool('2012_alt')\n tool = self.egammaLayerRecalibTool('2011_alt')\n tool = self.egammaLayerRecalibTool('2012_with_layer2')\n tool = self.egammaLayerRecalibTool('2011_with_layer2')\n tool = self.egammaLayerRecalibTool('2012_alt_with_layer2')\n tool = self.egammaLayerRecalibTool('2011_alt_with_layer2')\n tool = self.egammaLayerRecalibTool('2012_up')\n tool = self.egammaLayerRecalibTool('2012_down')\n tool = self.egammaLayerRecalibTool('2012_errup')\n tool = self.egammaLayerRecalibTool('2012_errdown')\n tool = self.egammaLayerRecalibTool('2012_ps_up')\n tool = self.egammaLayerRecalibTool('2012_ps_down')\n tool = self.egammaLayerRecalibTool('2012_ps_errup')\n tool = self.egammaLayerRecalibTool('2012_ps_errdown')\n tool = self.egammaLayerRecalibTool('2012_layer1_up')\n tool = self.egammaLayerRecalibTool('2012_layer1_down')\n tool = self.egammaLayerRecalibTool('2012_layer1_errup')\n tool = self.egammaLayerRecalibTool('2012_layer1_errdown')\n tool = self.egammaLayerRecalibTool('2011')\n tool = self.egammaLayerRecalibTool('2010')\n\n\n# def test_wrong_init(self):\n# self.assertRaises(SystemExit, lambda: ROOT.egammaLayerRecalibTool('wrong_tune'))\n# with self.assertRaises(SystemExit) as cm:\n# ROOT.egammaLayerRecalibTool('wrong_tune')\n\n def test_manual_scale(self):\n return \n tool = self.egammaLayerRecalibTool('')\n\n modifier = ROOT.ScaleE0(ROOT.InputModifier.ZEROBASED)\n amounter = ROOT.GetAmountFixed(0.01)\n tool.add_scale(modifier, amounter)\n\n inputs = self.example_inputs()\n\n tool.scale_inputs(inputs)\n self.assertAlmostEqual(inputs.E0raw,\n self.example_inputs().E0raw * (1 + 0.01), places=5)\n self.assertAlmostEqual(inputs.E1raw, self.example_inputs().E1raw)\n\n modifier2 = ROOT.ScaleE1(ROOT.InputModifier.ZEROBASED)\n histo = ROOT.TH1F(\"h\", \"h\", 100, -2.5, 2.5)\n histo.Fill(0.03, 0.05)\n amounter2 = ROOT.GetAmountHisto1D(histo)\n tool.add_scale(modifier2, amounter2)\n\n inputs.eta = -0.03\n tool.scale_inputs(inputs)\n self.assertAlmostEqual(inputs.E1raw,\n self.example_inputs().E1raw, places=5)\n self.assertAlmostEqual(inputs.E0raw,\n self.example_inputs().E0raw* (1 + 0.01) * (1 + 0.01), places=5)\n\n inputs = self.example_inputs()\n inputs.eta = 0.03\n tool.scale_inputs(inputs)\n self.assertAlmostEqual(inputs.E1raw,\n self.example_inputs().E1raw * (1. + 0.05), places=5)\n self.assertAlmostEqual(inputs.E0raw,\n self.example_inputs().E0raw * (1. + 0.01), places=5)\n\n def test_scale(self):\n tool = self.egammaLayerRecalibTool('test1')\n inputs = self.example_inputs()\n inputs.eta = 2.\n\n tool.scale_inputs(inputs)\n self.assertAlmostEqual(inputs.E1raw,\n self.example_inputs().E1raw * (1. + 0.01), places=5)\n self.assertAlmostEqual(inputs.E0raw,\n self.example_inputs().E0raw * (1 + 0.1), places=5)\n\n inputs = self.example_inputs()\n inputs.eta = -2.\n tool.scale_inputs(inputs)\n self.assertAlmostEqual(inputs.E1raw,\n self.example_inputs().E1raw * (1. + 0.01), places=5)\n self.assertAlmostEqual(inputs.E0raw,\n self.example_inputs().E0raw * (1 - 0.1), places=5)\n\n\n def test_scaleps2(self):\n tool = self.egammaLayerRecalibTool('ps_2012_v3')\n f = ROOT.TFile(\"$ROOTCOREDIR/data/egammaLayerRecalibTool/egammaLayerRecalibTunes.root\")\n histo_ps_tot_error = f.Get(\"hPS_2012\")\n\n for i in xrange(100):\n inputs = self.example_inputs()\n inputs.eta = i * 0.05 - 2.5\n bin = histo_ps_tot_error.FindBin(inputs.eta)\n amount = histo_ps_tot_error.GetBinContent(bin)\n tool.scale_inputs(inputs)\n self.assertAlmostEqual(inputs.E0raw,\n self.example_inputs().E0raw / amount, places=5)\n\n\n def test_null(self):\n tool = self.egammaLayerRecalibTool('')\n\n modifier1 = ROOT.ScaleE0(ROOT.InputModifier.ZEROBASED)\n modifier2 = ROOT.ScaleE1(ROOT.InputModifier.ONEBASED)\n amounter1 = ROOT.GetAmountFixed(0)\n amounter2 = ROOT.GetAmountFixed(1)\n\n tool.add_scale(modifier1, amounter1)\n tool.add_scale(modifier2, amounter2)\n\n for i in xrange(100):\n inputs = self.example_inputs()\n inputs.eta = i * 0.05 - 2.5\n tool.scale_inputs(inputs)\n self.assertAlmostEqual(inputs.E0raw, self.example_inputs().E0raw)\n self.assertAlmostEqual(inputs.E1raw, self.example_inputs().E1raw)\n\n\n def test_psHV(self):\n tool = self.egammaLayerRecalibTool('ps_HV1')\n\n for i in xrange(100):\n eta = i * 0.05 - 2.5\n inputs = self.example_inputs()\n inputs.eta = eta\n inputs.RunNumber = 200803\n tool.scale_inputs(inputs)\n self.assertAlmostEqual(inputs.E1raw, self.example_inputs().E1raw)\n self.assertAlmostEqual(inputs.E2raw, self.example_inputs().E2raw)\n self.assertAlmostEqual(inputs.eta, eta, 4)\n\n for i in xrange(100):\n eta = i * 0.05 - 2.5\n inputs = self.example_inputs()\n inputs.eta = eta\n inputs.RunNumber = 212810\n tool.scale_inputs(inputs)\n if eta > 1.5:\n self.assertAlmostEqual(inputs.E0raw, self.example_inputs().E0raw)\n\n \n def test_layer1(self):\n tool = self.egammaLayerRecalibTool('layer1_1')\n\n for i in xrange(100):\n inputs = self.example_inputs()\n inputs.eta = i * 0.05 - 2.5\n\n alpha = 0.97 if (abs(inputs.eta) < 1.425) else 1\n\n tool.scale_inputs(inputs)\n\n self.assertAlmostEqual(inputs.E0raw, self.example_inputs().E0raw, 5)\n self.assertAlmostEqual(inputs.E1raw, self.example_inputs().E1raw / alpha, 5)\n\n\n def test_layer1_2010_v5(self):\n tool = self.egammaLayerRecalibTool('layer1_2010_v5')\n\n f = ROOT.TFile(\"$ROOTCOREDIR/data/egammaLayerRecalibTool/egammaLayerRecalibTunes.root\")\n histo = f.Get(\"hE1E2ave_2010\")\n etas = [histo.GetBinCenter(i) for i in range(histo.GetNbinsX())]\n\n for eta in etas:\n inputs = self.example_inputs()\n inputs.eta = eta\n bin = histo.FindFixBin(eta)\n amount = histo.GetBinContent(bin)\n\n if amount == 0:\n continue\n\n tool.scale_inputs(inputs)\n\n self.assertAlmostEqual(inputs.E0raw, self.example_inputs().E0raw, 5)\n self.assertAlmostEqual(inputs.E1raw, self.example_inputs().E1raw / amount, 5)\n\n\n def oldtest_multi_modifier(self):\n tool = self.egammaLayerRecalibTool('layer1_2')\n tool.add_scale('ps_1')\n f = ROOT.TFile(\"$ROOTCOREDIR/data/egammaLayerRecalibTool/EnergyRescalerData.root\")\n histo_ps_tot_error = f.Get(\"Scales/2011/alphaPSmod_b12Fit_errTot\")\n\n for i in xrange(100):\n inputs = self.example_inputs()\n inputs.eta = i * 0.05 - 2.5\n\n bin = histo_ps_tot_error.FindBin(inputs.eta)\n amount = histo_ps_tot_error.GetBinContent(bin)\n\n alpha = 0.97 if (abs(inputs.eta) < 1.425) else 1.05\n\n tool.scale_inputs(inputs)\n self.assertAlmostEqual(inputs.E0raw, self.example_inputs().E0raw / amount, places=5)\n self.assertAlmostEqual(inputs.E1raw, self.example_inputs().E1raw / alpha, 5)\n\n def test_values(self):\n tool = self.egammaLayerRecalibTool('layer1_2')\n for i in xrange(100):\n inputs = self.example_inputs()\n inputs.eta = i * 0.05 - 2.5\n\n original_inputs = copy(inputs)\n\n k = tool.values(inputs)\n tool.scale_inputs(inputs)\n self.assertAlmostEqual(k.E1raw, inputs.E1raw / original_inputs.E1raw)\n\n def test_scale_and_values(self):\n tool = self.egammaLayerRecalibTool('layer1_2')\n for i in xrange(100):\n inputs = self.example_inputs()\n inputs.eta = i * 0.05 - 2.5\n\n original_inputs = copy(inputs)\n\n k = tool.scale_and_values(inputs)\n self.assertAlmostEqual(k.E1raw, inputs.E1raw / original_inputs.E1raw) \n\n\n def test_plot(self):\n self.plot_tune(self.egammaLayerRecalibTool('2012'), '2012.png')\n self.plot_tune(self.egammaLayerRecalibTool('2011'), '2011.png')\n self.plot_tune(self.egammaLayerRecalibTool('2010'), '2010.png')\n self.plot_tune(self.egammaLayerRecalibTool('2012_with_layer2'), '2012_with_layer2.png')\n self.plot_tune(self.egammaLayerRecalibTool('2011_with_layer2'), '2011_with_layer2.png')\n self.plot_tune(self.egammaLayerRecalibTool('2010_with_layer2'), '2010_with_layer2.png')\n self.plot_tune(self.egammaLayerRecalibTool('2012_alt'), '2012_alt.png')\n self.plot_tune(self.egammaLayerRecalibTool('2011_alt'), '2011_alt.png')\n self.plot_tune(self.egammaLayerRecalibTool('2012_alt_with_layer2'), '2012_alt_with_layer2.png')\n self.plot_tune(self.egammaLayerRecalibTool('2011_alt_with_layer2'), '2011_alt_with_layer2.png')\n\n self.plot_tune(self.egammaLayerRecalibTool('layer1_2012_v5'), 'layer1_2012_v5.png')\n self.plot_tune(self.egammaLayerRecalibTool('ps_2012_v3'), 'ps_2012_v3.png')\n self.plot_tune(self.egammaLayerRecalibTool('ps_HV1'), 'ps_HV1.png')\n self.plot_tune(self.egammaLayerRecalibTool('layer2_2012_v5'), 'layer2_2012_v5.png')\n self.plot_tune(self.egammaLayerRecalibTool('layer2_2011_v5'), 'layer2_2011_v5.png')\n self.plot_tune(self.egammaLayerRecalibTool('layer2_2010_v5'), 'layer2_2010_v5.png')\n\n\n def test_plot_error(self):\n self.plot_tune_error(self.egammaLayerRecalibTool('2012'), \"error_2012.png\")\n self.plot_tune_error(self.egammaLayerRecalibTool('2011'), \"error_2011.png\")\n self.plot_tune_error(self.egammaLayerRecalibTool('2010'), \"error_2010.png\")\n self.plot_tune_error(self.egammaLayerRecalibTool('2012_with_layer2'), \"error_2012_with_layer2.png\")\n self.plot_tune_error(self.egammaLayerRecalibTool('2011_with_layer2'), \"error_2011_with_layer2.png\")\n self.plot_tune_error(self.egammaLayerRecalibTool('2012_alt'), \"error_2012_alt.png\")\n self.plot_tune_error(self.egammaLayerRecalibTool('2011_alt'), \"error_2011_alt.png\")\n self.plot_tune_error(self.egammaLayerRecalibTool('2012_alt_with_layer2'), \"error_alt_2012_with_layer2.png\")\n self.plot_tune_error(self.egammaLayerRecalibTool('2011_alt_with_layer2'), \"error_alt_2011_with_layer2.png\")\n\n \n\n def test_plot2d(self):\n self.plot_tune2d(self.egammaLayerRecalibTool('ps_HV1'), \"ps_HV1_2d_period0.png\", run_number = 204931)\n self.plot_tune2d(self.egammaLayerRecalibTool('ps_HV1'), \"ps_HV1_2d_period1.png\", run_number = 204932)\n self.plot_tune2d(self.egammaLayerRecalibTool('ps_HV1'), \"ps_HV1_2d_period2.png\", run_number = 205112)\n self.plot_tune2d(self.egammaLayerRecalibTool('ps_HV1'), \"ps_HV1_2d_period3.png\", run_number = 211670)\n self.plot_tune2d(self.egammaLayerRecalibTool('ps_HV1'), \"ps_HV1_2d_period4.png\", run_number = 212619)\n self.plot_tune2d(self.egammaLayerRecalibTool('ps_HV1'), \"ps_HV1_2d_period5.png\", run_number = 212809)\n\n self.plot_tune2d(self.egammaLayerRecalibTool('2012'), \"2012_2d_period0.png\", run_number = 204931)\n self.plot_tune2d(self.egammaLayerRecalibTool('2012'), \"2012_2d_period1.png\", run_number = 204932)\n self.plot_tune2d(self.egammaLayerRecalibTool('2012'), \"2012_2d_period2.png\", run_number = 205112)\n self.plot_tune2d(self.egammaLayerRecalibTool('2012'), \"2012_2d_period3.png\", run_number = 211670)\n self.plot_tune2d(self.egammaLayerRecalibTool('2012'), \"2012_2d_period4.png\", run_number = 212619)\n self.plot_tune2d(self.egammaLayerRecalibTool('2012'), \"2012_2d_period5.png\", run_number = 212809)\n\n self.plot_tune2d(self.egammaLayerRecalibTool('2012'), \"2012_2d.png\")\n self.plot_tune2d(self.egammaLayerRecalibTool('layer1_1'), \"layer1_1_2d.png\")\n self.plot_tune2d(self.egammaLayerRecalibTool('layer1_2'), \"layer1_2_2d.png\")\n\n \n\n def test_compare(self):\n self.plot_tune((self.egammaLayerRecalibTool('2012'),\n self.egammaLayerRecalibTool('2012_up'),\n self.egammaLayerRecalibTool('2012_down')),\n \"2012_all_up_down.png\",\n (\"central\", \"up\", \"down\"))\n\n self.plot_tune((self.egammaLayerRecalibTool('2012'),\n self.egammaLayerRecalibTool('2012_layer1_up'),\n self.egammaLayerRecalibTool('2012_layer1_down')),\n \"2012_layer1_up_down.png\",\n (\"central\", \"up\", \"down\"))\n\n self.plot_tune((self.egammaLayerRecalibTool('2012'),\n self.egammaLayerRecalibTool('2012_ps_up'),\n self.egammaLayerRecalibTool('2012_ps_down')),\n \"2012_ps_up_down.png\",\n (\"central\", \"up\", \"down\"))\n\n self.plot_tune((self.egammaLayerRecalibTool('2012_errup'),\n self.egammaLayerRecalibTool('2012_errdown')),\n \"2012_all_errup_down.png\",\n (\"errorup\", \"errordown\"))\n\n self.plot_tune((self.egammaLayerRecalibTool('layer2_2012_v5_errup'),\n self.egammaLayerRecalibTool('layer2_2012_v5_errdown')),\n \"2012_layer2_errup_down.png\",\n (\"errorup\", \"errordown\"))\n\n def test_overflow(self):\n tool = self.egammaLayerRecalibTool('')\n modifier = ROOT.ScaleE0(ROOT.InputModifier.ONEBASED)\n histo = ROOT.TH1F(\"h\", \"h\", 100, -1, 1)\n for i in range(100): histo.SetBinContent(i + 1, 2)\n amounter = ROOT.GetAmountHisto1D(histo)\n tool.add_scale(modifier, amounter)\n \n for i in xrange(100):\n inputs = self.example_inputs()\n inputs.eta = i * 0.05 - 2.5\n tool.scale_inputs(inputs)\n if (inputs.eta >= -1 and inputs.eta < 1):\n self.assertEqual(inputs.E0raw, self.example_inputs().E0raw * 2.)\n else:\n self.assertEqual(inputs.E0raw, self.example_inputs().E0raw)\n\n def plot_tune(self, tools, canvas_name, names=None):\n canvas = ROOT.TCanvas(canvas_name, canvas_name)\n canvas.Divide(2, 2)\n canvas.mem = []\n\n legend = None\n if names:\n legend = ROOT.TLegend(0.2, 0.5, 0.4, 0.8)\n\n if type(tools) is not tuple:\n tools = (tools, )\n legend_names = names or [\"\"] * len(tools)\n\n for itool, (tool, name) in enumerate(zip(tools, legend_names)):\n\n h0 = ROOT.TGraph()\n h1 = ROOT.TGraph()\n h2 = ROOT.TGraph()\n h3 = ROOT.TGraph()\n\n for i in xrange(100):\n inputs = self.example_inputs()\n inputs.RunNumber = 0\n inputs.eta = i * 0.05 - 2.5\n inputs.E0raw = 1\n inputs.E1raw = 1\n inputs.E2raw = 1\n inputs.E3raw = 1\n\n tool.scale_inputs(inputs)\n\n h0.SetPoint(i, inputs.eta, inputs.E0raw)\n h1.SetPoint(i, inputs.eta, inputs.E1raw)\n h2.SetPoint(i, inputs.eta, inputs.E2raw)\n h3.SetPoint(i, inputs.eta, inputs.E3raw)\n\n grs = (h0, h1, h2, h3)\n for ig, g in enumerate(grs):\n canvas.cd(ig + 1)\n g.SetTitle(name)\n g.SetLineColor(itool + 1)\n g.SetMarkerColor(itool + 1)\n g.GetXaxis().SetTitle(\"#eta\")\n g.GetYaxis().SetTitle(\"(E_{%d})-corrected / E_{%d}-non-corrected\" % (ig, ig))\n g.SetFillStyle(0)\n g.GetYaxis().SetTitleOffset(1.5)\n g.Draw(\"APL\" if not itool else \"PLsame\")\n if ig == 3 and legend:\n legend.AddEntry(g)\n canvas.mem.append(g)\n if legend:\n canvas.cd(3)\n legend.Draw()\n canvas.SaveAs(canvas_name)\n self.output_file.cd()\n canvas.Write()\n\n\n def plot_tune_error(self, tools, canvas_name, names=None):\n canvas = ROOT.TCanvas(canvas_name, canvas_name)\n canvas.Divide(2, 2)\n canvas.mem = []\n\n legend = None\n if names:\n legend = ROOT.TLegend(0.2, 0.5, 0.4, 0.8)\n\n if type(tools) is not tuple:\n tools = (tools, )\n legend_names = names or [\"\"] * len(tools)\n\n for itool, (tool, name) in enumerate(zip(tools, legend_names)):\n\n h0 = ROOT.TGraph()\n h1 = ROOT.TGraph()\n h2 = ROOT.TGraph()\n h3 = ROOT.TGraph()\n\n for i in xrange(100):\n inputs = self.example_inputs()\n inputs.RunNumber = 0\n inputs.eta = i * 0.05 - 2.5\n inputs.E0raw = 1\n inputs.E1raw = 1\n inputs.E2raw = 1\n inputs.E3raw = 1\n\n errors = tool.rel_error(inputs)\n\n h0.SetPoint(i, inputs.eta, errors.E0raw)\n h1.SetPoint(i, inputs.eta, errors.E1raw)\n h2.SetPoint(i, inputs.eta, errors.E2raw)\n h3.SetPoint(i, inputs.eta, errors.E3raw)\n\n grs = (h0, h1, h2, h3)\n for ig, g in enumerate(grs):\n canvas.cd(ig + 1)\n g.SetTitle(name)\n g.SetLineColor(itool + 1)\n g.SetMarkerColor(itool + 1)\n g.GetXaxis().SetTitle(\"#eta\")\n g.GetYaxis().SetTitle(\"rel error on energy\")\n g.SetFillStyle(0)\n g.GetYaxis().SetTitleOffset(1.5)\n g.Draw(\"APL\" if not itool else \"PLsame\")\n if ig == 3 and legend:\n legend.AddEntry(g)\n canvas.mem.append(g)\n if legend:\n canvas.cd(3)\n legend.Draw()\n canvas.SaveAs(canvas_name)\n self.output_file.cd()\n canvas.Write()\n\n\n def plot_tune2d(self, tool, canvas_name, run_number=0):\n canvas = ROOT.TCanvas()\n canvas.Divide(2, 2)\n nbins_eta = 100\n nbins_phi = 100\n h0 = ROOT.TH2F(\"h0\", \"h0\", nbins_eta, -2.5, 2.5, nbins_phi, -3.1415, 3.1415)\n h1 = ROOT.TH2F(\"h1\", \"h1\", nbins_eta, -2.5, 2.5, nbins_phi, -3.1415, 3.1415)\n h2 = ROOT.TH2F(\"h2\", \"h2\", nbins_eta, -2.5, 2.5, nbins_phi, -3.1415, 3.1415)\n h3 = ROOT.TH2F(\"h3\", \"h3\", nbins_eta, -2.5, 2.5, nbins_phi, -3.1415, 3.1415)\n\n for iphi in xrange(nbins_phi):\n inputs = self.example_inputs()\n inputs.RunNumber = run_number\n for ieta in xrange(nbins_eta):\n inputs.eta = h0.GetXaxis().GetBinCenter(ieta)\n inputs.phi = h0.GetYaxis().GetBinCenter(iphi)\n inputs.E0raw = 1.\n inputs.E1raw = 1.\n inputs.E2raw = 1.\n inputs.E3raw = 1.\n\n tool.scale_inputs(inputs)\n\n h0.SetBinContent(ieta, iphi, inputs.E0raw)\n h1.SetBinContent(ieta, iphi, inputs.E1raw)\n h2.SetBinContent(ieta, iphi, inputs.E2raw)\n h3.SetBinContent(ieta, iphi, inputs.E3raw)\n \n grs = (h0, h1, h2, h3)\n\n for i, g in enumerate(grs):\n canvas.cd(i + 1)\n g.GetXaxis().SetTitle(\"#eta\")\n g.GetYaxis().SetTitle(\"#phi\")\n g.SetTitle(\"(E_{%d})-corrected / E_{%d}-non-corrected\" % (i, i))\n g.SetContour(999)\n g.GetZaxis().SetRangeUser(0.93,\n 1.07)\n# g.GetZaxis().SetRangeUser(0.97, 1.03)\n# g.GetZaxis().SetRangeUser(0.985, 1.0105) # mimic Guillaume ranges\n g.SetStats(0)\n g.Draw(\"colz\")\n\n canvas.SaveAs(canvas_name)\n\n def testMaartenNumbers(self):\n tool = self.egammaLayerRecalibTool('')\n modifier = ROOT.ScaleE0(ROOT.InputModifier.ONEBASED_ALPHA) # correction = 1 / alpha_ps = k\n amounter = ROOT.GetAmountFixed(1.05, 0.1) # alpha_ps = 1.05, alpha_ps_abs_err = 0.1\n # corrected-energy = non-corrected-energy * 1 / alpha_ps\n tool.add_scale(modifier, amounter)\n\n inputs = self.example_inputs()\n k = tool.values(inputs) # multiplicative corrections: corrected-energy = k * non-corrected-energy\n err = tool.rel_error(inputs) # error on multiplicative corrections\n self.assertAlmostEqual(k.E0raw, 1 / 1.05, 6) # k is equal to 1 / 1.05 up to 6 digits\n self.assertAlmostEqual(err.E0raw, 0.1 / 1.05**2) # error on k is: alpha_ps_abs_err / alpha_ps ** 2\n\nif __name__ == '__main__':\n ROOT.gROOT.ProcessLine(\".x $ROOTCOREDIR/scripts/load_packages.C\")\n ROOT.gStyle.SetCanvasDefH(800)\n ROOT.gStyle.SetCanvasDefW(800)\n ROOT.gStyle.SetPadTickX(1)\n ROOT.gStyle.SetPadTickY(1)\n\n unittest.main()\n","sub_path":"workarea/AthAnalysisBase/RootCoreBin/python/egammaLayerRecalibTool/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":22210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"140051644","text":"import flask\nfrom flask import jsonify\nfrom flask import request\n\napp = flask.Flask(__name__)\napp.config[\"DEBUG\"] = True\napp.config[\"JSON_AS_ASCII\"] = False\n\n# test data\ntpe = {\n \"id\": 0,\n \"city_name\": \"台北\",\n \"country_name\": \"台灣\",\n \"is_capital\": True,\n \"location\": {\n \"longitude\": 121.569649,\n \"latitude\": 25.036786\n }\n}\nnyc = {\n \"id\": 1,\n \"city_name\": \"紐約\",\n \"country_name\": \"美國\",\n \"is_capital\": False,\n \"location\": {\n \"longitude\": -74.004364,\n \"latitude\": 40.710405\n }\n}\nldn = {\n \"id\": 2,\n \"city_name\": \"倫敦\",\n \"country_name\": \"英國\",\n \"is_capital\": True,\n \"location\": {\n \"longitude\": -0.114089,\n \"latitude\": 51.507497\n }\n}\n\ncities = [tpe, nyc, ldn]\n\n\n@app.route('/', methods=['GET'])\ndef home():\n return \"

Hello Flask!

\"\n\n\n@app.route('/cities/all', methods=['GET'])\ndef cities_all():\n return jsonify(cities)\n\n@app.route('/cities', methods=['GET'])\ndef city_name():\n if 'city_name' in request.args:\n city_name = request.args['city_name']\n else:\n return \"Error: No city_name provided. Please specify a city_name.\"\n results = []\n\n for city in cities:\n if city['city_name'] == city_name:\n results.append(city)\n\n return jsonify(results)\n\napp.run()\n","sub_path":"slides/10801/雲端數據運算與分析/flask/GetDatabyName.py","file_name":"GetDatabyName.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"40443241","text":"import json\nimport h5py\nimport numpy as np\nimport random\n\nLIKE = 1\nDISLIKE = 0\n\n\nTRAIN = 1\nVAL = 2\nTEST = 3\n\npath_general = 'datasets/' # 'datasets/'\npath_dataset_orig = 'original/'\npath_dataset_eq = 'augm_eq/'\npath_dataset_ineq = 'augm_weigths/'\npath_dataset_tot_eq = 'dataset_equal/'\n\npath_features = 'data/features.h5'\npath_userIds = 'data/userIds.h5'\npath_restIds = 'data/restIds.h5'\npath_labels = 'labels/labels.h5'\n\ndataset_orig = 'dataset_original'\ndataset_eq = 'dataset_augm_eq'\ndataset_weight = 'dataset_augm_weigths'\n\ntrain_path = 'train/'\nval_path = 'val/'\ntest_path = 'test/'\n\n\ndef get_path(particion, path_dataset):\n\n if particion == TRAIN:\n final_path_features = path_general + path_dataset + train_path + path_features\n final_path_userIds = path_general + path_dataset + train_path + path_userIds\n final_path_restIds = path_general + path_dataset + train_path + path_restIds\n final_path_labels = path_general + path_dataset + train_path + path_labels\n elif particion == VAL:\n final_path_features = path_general + path_dataset + val_path + path_features\n final_path_userIds = path_general + path_dataset + val_path + path_userIds\n final_path_restIds = path_general + path_dataset + val_path + path_restIds\n final_path_labels = path_general + path_dataset + val_path + path_labels\n else:\n final_path_features = path_general + path_dataset + test_path + path_features\n final_path_userIds = path_general + path_dataset + test_path + path_userIds\n final_path_restIds = path_general + path_dataset + test_path + path_restIds\n final_path_labels = path_general + path_dataset + test_path + path_labels\n \n #print('FINAL PATHS!!!!')\n #print(final_path_features)\n #print(final_path_userIds)\n #print(final_path_restIds)\n #print(final_path_labels)\n return final_path_features, final_path_userIds, final_path_restIds, final_path_labels\n\n\ndef set_path_dataset(dataset):\n path_dataset = ''\n if dataset == dataset_orig:\n path_dataset = path_dataset_orig\n elif dataset == dataset_eq:\n path_dataset = path_dataset_eq\n elif dataset_eq == dataset_weight:\n path_dataset = path_dataset_ineq\n else:\n path_dataset = path_dataset_tot_eq\n return path_dataset\n\n\ndef load_data(particion, dataset):\n path_dataset = set_path_dataset(dataset)\n #print(path_dataset)\n path_features, path_userIds, path_restIds, path_labels = get_path(particion, path_dataset)\n #print(path_features)\n #print(path_labels)\n h5f_features = h5py.File(path_features, 'r')\n h5f_userIds = h5py.File(path_userIds, 'r')\n h5f_restIds = h5py.File(path_restIds, 'r')\n h5f_labels = h5py.File(path_labels, 'r')\n\n #print(h5f_features.keys())\n #print(h5f_features.values())\n features_string = h5f_features[dataset]\n userIds_string = h5f_userIds[dataset]\n restIds_string = h5f_restIds[dataset]\n labels_string = h5f_labels[dataset]\n\n features = np.array(features_string)\n userIds = np.array(userIds_string)\n restsIds = np.array(restIds_string)\n labels = np.array(labels_string)\n\n h5f_features.close()\n h5f_userIds.close()\n h5f_restIds.close()\n h5f_labels.close()\n data = list(zip(features, userIds, restsIds, labels))\n random.shuffle(data)\n features, userIds, restsIds, labels = zip(*data)\n return features, userIds, restsIds, labels\n ","sub_path":"src/crear_datasets_autoencoder/load_data_pkls.py","file_name":"load_data_pkls.py","file_ext":"py","file_size_in_byte":3438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"415907573","text":"class Solar_Panel:\n\n TECHNOLOGY = [\"mono-Si\", \"multi-Si\"] # \"CdTe\"]\n\n MANUFACTURING_ENERGY = {\"mono-Si\": 5476.100, # IN MEGAJOULES [MJ]\n \"multi-Si\": 4676.100}\n # \"CdTe\": 3749.16}\n\n DISPOSAL_KG = {\"Si\": 0.1602} # IN KILOGRAMS [Kg]\n # \"CdTe\": 0.0487}\n\n DENSITY_KG_WP = {\"Si\": 0.102}\n # \"CdTe\": 0.202}\n\n EFFICIENCY = {\"mono-Si\": 17, # DEFINED AS [Kwp / m2]\n \"multi-Si\": 12.30}\n \n # \"CdTe\": 10.90}\n EFFICIENCY_W = {\"mono-Si\": 80,\n \"multi-Si\": 80}\n\n WH2MJ = 3600 * 10 ** (- 6) # CONVERSION FROM WH TO MJ\n LIFETIME = 43.73\n\n default_data = {\n 'technology': None,\n 'surface': 0, # squared meters\n 'irradiance': 0, # daily irradiance in Mj\n 's_hours': 0,\n 'lifetime': 0, # years\n 'efficiency': 0,\n 'kwp': 0,\n 'efficiency_w': 0, # wear-out efficiency\n 'weight': 0, # kg\n 'e_manufacturing': None,\n 'disposal': None,\n 'e_produced': None,\n }\n\n def __init__(self, data=default_data):\n self.technology = data.get('technology')\n self.surface = data.get('surface')\n self.irradiance = data.get('irradiance')\n self.s_hours = data.get('s_hours')\n self.lifetime = data.get('lifetime')\n self.efficiency = data.get('efficiency')\n self.kwp = data.get('kwp')\n self.efficiency_w = data.get('efficiency_w')\n self.weight = data.get('weight')\n \n self.solar_panel_validation()\n\n# Lifetime, Efficiency and Efficiency_w if equal to 0 will be replaced with common parameters\n self.complete_fields()\n self.compute_e_manufacturing()\n self.compute_disposal()\n self.daily_energy_produced()\n\n def solar_panel_validation(self):\n validation_status = {}\n validation_status['technology'] = self.technology in self.TECHNOLOGY\n validation_status['surface'] = self.surface > 0.0\n validation_status['irradiance'] = self.irradiance > 0.0\n validation_status['s_hours'] = (self.s_hours > 0.0 and self.s_hours < 24)\n validation_status['lifetime'] = self.lifetime >= 0.0\n validation_status['efficiency'] = (self.efficiency >= 0.0 and self.efficiency <= 100.0)\n validation_status['kwp'] = self.kwp >= 0\n validation_status['efficiency_w'] = (self.efficiency_w >= 0.0 and self.efficiency_w <= 100.0)\n validation_status['weight'] = self.weight >= 0\n if all(value for value in validation_status.values()):\n return True\n else:\n raise SolarPanelError(validation_status)\n\n def compute_e_manufacturing(self):\n self.e_manufacturing = self.surface *\\\n self.MANUFACTURING_ENERGY[self.technology]\n\n def compute_disposal(self):\n t = 'Si'\n eff = self.efficiency / 100\n if self.weight == 0:\n self.disposal = eff * self.surface * (10**3) *\\\n self.DENSITY_KG_WP[t] * self.DISPOSAL_KG[t]\n else:\n self.disposal = self.weight * self.DISPOSAL_KG[t]\n\n def daily_energy_produced(self):\n eff = self.efficiency / 100\n self.e_produced = self.surface * self.irradiance * eff *\\\n (10**3) * self.WH2MJ\n\n def complete_fields(self):\n self.auto_set_eff() if self.efficiency is 0 else self.efficiency\n self.auto_set_lifetime() if self.lifetime is 0 else self.lifetime\n self.auto_set_eff_w() if self.efficiency_w is 0 else self.efficiency_w\n\n def auto_set_eff(self):\n self.efficiency = self.EFFICIENCY[self.technology]\n self.kwp = self.efficiency * self.surface\n\n def auto_set_lifetime(self):\n self.lifetime = self.LIFETIME\n\n def auto_set_eff_w(self):\n self.efficiency_w = self.EFFICIENCY[self.technology]\n\n\nclass SolarPanelError(Exception):\n def __init__(self, message):\n self.message = message","sub_path":"iot_green_calculator/solar_panel.py","file_name":"solar_panel.py","file_ext":"py","file_size_in_byte":4160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"256721069","text":"\"\"\"\nThis file is part of the OpenProtein project.\n\nFor license information, please see the LICENSE file in the root directory.\n\"\"\"\nimport math\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport openprotein\nfrom preprocessing import process_raw_data\nfrom training import train_model\nfrom torch.nn.utils.rnn import pad_sequence\n\nfrom util import get_backbone_positions_from_angles, contruct_dataloader_from_disk, initial_pos_from_aa_string, pass_messages, write_out, calc_avg_drmsd_over_minibatch\n\nANGLE_ARR = torch.tensor([[-120, 140, -370], [0, 120, -150], [25, -120, 150]]).float()\n\ndef run_experiment(parser, use_gpu):\n # parse experiment specific command line arguments\n parser.add_argument('--learning-rate', dest='learning_rate', type=float,\n default=0.01, help='Learning rate to use during training.')\n\n parser.add_argument('--input-file', dest='input_file', type=str,\n default='data/preprocessed/protein_net_testfile.txt.hdf5')\n\n args, _unknown = parser.parse_known_args()\n\n # pre-process data\n process_raw_data(use_gpu, force_pre_processing_overwrite=False)\n\n # run experiment\n training_file = args.input_file\n validation_file = args.input_file\n\n model = MyModel(21, use_gpu=use_gpu) # embed size = 21\n\n train_loader = contruct_dataloader_from_disk(training_file, args.minibatch_size)\n validation_loader = contruct_dataloader_from_disk(validation_file, args.minibatch_size)\n\n train_model_path = train_model(data_set_identifier=\"TRAIN\",\n model=model,\n train_loader=train_loader,\n validation_loader=validation_loader,\n learning_rate=args.learning_rate,\n minibatch_size=args.minibatch_size,\n eval_interval=args.eval_interval,\n hide_ui=args.hide_ui,\n use_gpu=use_gpu,\n minimum_updates=args.minimum_updates)\n\n print(\"Completed training, trained model stored at:\")\n print(train_model_path)\n\nclass MyModel(openprotein.BaseModel):\n def __init__(self, embedding_size, use_gpu):\n super(MyModel, self).__init__(use_gpu, embedding_size)\n self.use_gpu = use_gpu\n #RMSD layer\n self.recurrent_steps = 2\n self.hidden_size = 50\n self.msg_output_size = 50\n self.output_size = 9 # 3 dimensions * 3 coordinates for each aa\n self.f_to_hid = nn.Linear((embedding_size * 2 + 9), self.hidden_size, bias=True)\n self.hid_to_pos = nn.Linear(self.hidden_size, self.msg_output_size, bias=True)\n # (last state + orginal state)\n self.linear_transform = nn.Linear(embedding_size + 9 + self.msg_output_size, 9, bias=True)\n #Angles layer\n self.number_angles = 3\n self.input_to_angles = nn.Linear(embedding_size, self.number_angles)\n\n def apply_message_function(self, aa_features):\n # aa_features: msg_count * 2 * feature_count\n aa_features_transformed = torch.cat(\n (\n aa_features[:, 0, 0:21],\n aa_features[:, 1, 0:21],\n aa_features[:, 0, 21:30] - aa_features[:, 1, 21:30]\n ), dim=1)\n return self.hid_to_pos(self.f_to_hid(aa_features_transformed))\n\n def initial_pos_from_aa_string(batch_aa_string, use_gpu):\n arr_of_angles = []\n batch_sizes = []\n for aa_string in batch_aa_string:\n length_of_protein = aa_string.size(0)\n angles = torch.stack([-120 * torch.ones(length_of_protein),\n 140 * torch.ones(length_of_protein),\n -370 * torch.ones(length_of_protein)]).transpose(0, 1)\n arr_of_angles.append(angles)\n batch_sizes.append(length_of_protein)\n\n padded = pad_sequence(arr_of_angles).transpose(0, 1)\n return get_backbone_positions_from_angles(padded, batch_sizes, use_gpu)\n\n def pass_messages(aa_features, message_transformation, use_gpu):\n # aa_features (#aa, #features) - each row represents the amino acid type\n # (embedding) and the positions of the backbone atoms\n # message_transformation: (-1 * 2 * feature_size) -> (-1 * output message size)\n feature_size = aa_features.size(1)\n aa_count = aa_features.size(0)\n\n arange2d = torch.arange(aa_count).repeat(aa_count).view((aa_count, aa_count))\n\n diagonal_matrix = (arange2d == arange2d.transpose(0, 1)).int()\n\n eye = diagonal_matrix.view(-1).expand(2, feature_size, -1) \\\n .transpose(1, 2).transpose(0, 1)\n\n eye_inverted = torch.ones(eye.size(), dtype=torch.uint8) - eye\n if use_gpu:\n eye_inverted = eye_inverted.cuda()\n features_repeated = aa_features.repeat((aa_count, 1)).view((aa_count, aa_count, feature_size))\n # (aa_count^2 - aa_count) x 2 x aa_features (all pairs except for reflexive connections)\n aa_messages = torch.stack((features_repeated.transpose(0, 1), features_repeated)) \\\n .transpose(0, 1).transpose(1, 2).view(-1, 2, feature_size)\n\n eye_inverted_location = eye_inverted.view(-1).nonzero().squeeze(1)\n\n aa_msg_pairs = aa_messages \\\n .reshape(-1).gather(0, eye_inverted_location).view(-1, 2, feature_size)\n\n transformed = message_transformation(aa_msg_pairs).view(aa_count, aa_count - 1, -1)\n transformed_sum = transformed.sum(dim=1) # aa_count x output message size\n return transformed_sum\n\n def _get_network_emissions(self, original_aa_string):\n #RMSD\n backbone_atoms_padded, batch_sizes_backbone = initial_pos_from_aa_string(original_aa_string, self.use_gpu)\n embedding_padded = self.embed(original_aa_string)\n\n if self.use_gpu:\n backbone_atoms_padded = backbone_atoms_padded.cuda()\n\n for _ in range(self.recurrent_steps):\n combined_features = torch.cat(\n (embedding_padded, backbone_atoms_padded),\n dim=2\n ).transpose(0, 1)\n\n features_transformed = []\n\n for aa_features in combined_features.split(1, dim=0):\n msg = pass_messages(aa_features.squeeze(0),\n self.apply_message_function,\n self.use_gpu) # aa_count * output size\n features_transformed.append(self.linear_transform(\n torch.cat((aa_features.squeeze(0), msg), dim=1)))\n\n backbone_atoms_padded_clone = torch.stack(features_transformed).transpose(0, 1)\n\n backbone_atoms_padded = backbone_atoms_padded_clone\n\n #return [], backbone_atoms_padded, batch_sizes_backbone\n\n #ANGLES\n\n batch_sizes = list([a.size() for a in original_aa_string])\n\n #embedded_input = self.embed(original_aa_string)\n emissions_padded = self.input_to_angles(embedding_padded)\n\n probabilities = torch.softmax(emissions_padded.transpose(0, 1), 2)\n\n output_angles = torch.matmul(probabilities, ANGLE_ARR).transpose(0, 1)\n\n return output_angles, backbone_atoms_padded, batch_sizes_backbone\n","sub_path":"experiments/my_model/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"415404334","text":"#!/usr/bin/env python3\n\"\"\"Image differencing on the broodnest photos.\n\nIterate over all photos and compute the distance between\nconsecutive images, output the information as a CSV file\ncontaining in each row the times and filenames for both images,\nthe hive and RPi number and the difference score.\n\nEuclidean distance or absolute difference are implemented.\n\"\"\"\n# Basic libraries\n# import os\n# import glob\nimport time\nimport logging\nimport argparse\nimport platform\nfrom pathlib import Path\nfrom datetime import datetime, timedelta\n\n# Third-party libraries\nimport pytz\nimport pandas as pd\nimport numpy as np\n# OpenCV, we have to load V3 for full list of algorithms\n# https://docs.opencv.org/3.4\n# NOTE: OpenCV 3.2 works on Ubuntu 18.04\nimport cv2 as cv\n\n# Own libraries\nimport iohelp as ioh\n\n# SETTINGS\nPOSTFIX = None\nDEPENDENCIES = [\n Path(\"iohelp.py\"),\n # Path(\"iohelp/iohelp_tk.py\"),\n # Path(\"iohelp/ioplot.py\"),\n]\n# Path to raw files and output folder of generated images\n# PATH_RAW = Path.cwd() / 'img'\n# PATH_OUT = Path.cwd() / 'out'\n# PATH_PHOTOS = Path(\n# \"/media/holzfigure/Data/NAS/NAS_incoming_data/Hiveopolis/\"\n# \"broodnest_obs/hive1\"\n# )\nPATH_PHOTOS = Path(\n \"/media/holzfigure/Data/local_stuff/Hiveopolis/broodnests/sample_folders\"\n)\n# PATH_OUT = Path(\n# \"/media/holzfigure/Data/NAS/NAS_incoming_data/Hiveopolis/\" +\n# \"broodnest_activity/csv\"\n# )\nPATH_OUT = Path(\n \"/media/holzfigure/Data/local_stuff/Hiveopolis/broodnests\"\n)\n# Filename e.g.: pi1_hive1broodn_15_8_0_0_4.jpg\nINFILE_PATTERN = \"raw_hive*_rpi*-utc.jpg\"\n# Foldername e.g.: Photos_of_Pi1_1_9_2019\n# Foldername e.g.: Photos_of_Pi1_heating_1_11_2019\nINFOLDER_PATTERN = \"hive*_rpi*_day-*/\"\nOUTCSV_PREFIX = \"act\"\nOUTRAW_PREFIX = \"raw\"\n\n# 1676802\nFILESIZE_THRESHOLD = 500000\nDIFF_THRESHOLD = 14 # Filter out noise from the difference image\n\nPRINT_MODULUS = 1000\n\n# Maximal seconds accepted between images:\nTOLERANCE_TIMEDELTA = timedelta(seconds=20)\n\nLOCAL_TZ = pytz.timezone(\"Etc/UTC\")\n# LOCAL_TZ = pytz.timezone(\"Europe/Vienna\")\nTIME_FMT = \"%y%m%d-%H%M%S-utc\"\nSTART_TIME_FMT = \"%y%m%d-%H%M%S\"\nEND_TIME_FMT = \"%H%M%S-utc\"\n# TIME_TARGET_FMT = \"%y%m%d-%H\"\n# DAY_FMT = \"day-%y%m%d\"\n# TIME_INFILE_FMT = \"%d_%m_%H_%M_%S.jpg\"\nTIME_INFOLDER_TAG = \"day-\"\nTIME_INFOLDER_FMT = \"%y%m%d\"\nTIME_INFILE_TAG = \"-utc\"\nTIME_INFILE_FMT = \"%y%m%d-%H%M%S-utc.jpg\"\n\n# Argument parsing\nparser = argparse.ArgumentParser(\n description=(\"Extract the broodnest from colony photos.\"))\nparser.add_argument(\"-d\", \"--debug\", action=\"store_true\",\n help=\"debug mode\")\nparser.add_argument(\"-i\", \"--interactive\", action=\"store_true\",\n help=\"popup dialog to select files or folders\")\nparser.add_argument(\"-e\", \"--euclid\", action=\"store_true\",\n help=(\"compute Euclidean distance between images \"\n \"(default: Manhattan distance)\"))\nparser.add_argument(\"-f\", \"--firstidx\", type=int,\n default=0,\n help=(\"file index from where to start \" +\n \"(default: %(default)s)\"))\nparser.add_argument(\"--export\", action=\"store_true\",\n help=\"export the difference images\")\n# xgroup = parser.add_mutually_exclusive_group()\n# xgroup.add_argument(\"-\", \"--windowtime\", type=int,\n# parser.add_argument(\"-w\", \"--windowtime\", nargs=\"?\", type=int,\n# const=DEF_TIME_WINDOW_MINUTES,\n# default=None,\n# help=(\"set time-window [min] \" +\n# \"(default: %(default)s, \" +\n# \"constant: %(const)s)\"))\n# ARGS = vars(parser.parse_args())\nARGS = parser.parse_args()\n# del(parser)\n\n\ndef initialize_io(dir_in=PATH_PHOTOS, dir_out=PATH_OUT,\n deps=DEPENDENCIES,\n postfix=POSTFIX, args=ARGS):\n \"\"\"Set up IO-directories and files and logging.\"\"\"\n # Determine input head folder\n # if args.interactive or not os.path.isdir(dir_ini):\n if args.interactive or not dir_in.is_dir():\n dir_in = ioh.select_directory(\n title=\"Input folder containing rpn-snapshot*.csv files\",\n # filetypes=[(\"RPN-log-CSV\", \"rpn-log_rpn*.csv\")],\n dir_ini=dir_in)\n\n if not dir_in or not dir_in.is_dir():\n print((\"No proper input directory: '{}', \"\n \"returning 'None'.\".format(dir_in)))\n # Leave script\n # sys.exit(1)\n raise SystemExit(1)\n return None\n\n # Determine output folder\n # Set output level\n # TODO: Remove out_level here?\n out_level = 1 # possibly changed later!\n # if args.interactive or not os.path.isdir(dir_out):\n if args.interactive or not dir_out.is_dir():\n dir_out = ioh.select_directory(\n title=\"output folder\",\n dir_ini=dir_in)\n\n if not dir_out or not dir_out.is_dir():\n print((\"no proper output directory: {}, \"\n \"creating a sibling \" +\n \"to input-directory {}\").format(\n dir_out, dir_in))\n dir_out = dir_in\n out_level = -1\n\n # Set up environment (with holzhelp)\n # hostname = socket.gethostname()\n # NOTE: We want only the name, this also works,\n # if __file__ returns a full path AND if not\n # thisfile = os.path.basename(__file__)\n thisfile = Path(__file__).name\n dir_out, thisname = ioh.setup_environment(\n thisfile,\n dir_targ=dir_out,\n level=out_level,\n new_dir=True,\n postfix_dir=postfix,\n daystamp=True,\n dependencies=deps,\n )\n ioh.setup_logging(thisname, args, dir_log=dir_out / \"log\")\n dir_out = Path(dir_out)\n logging.info(f\"input from {dir_in}, output to {dir_out}\")\n\n # Display Python version and system info\n # TODO: Move this into holzhelp when doing overhaul\n logging.info(f\"Python {platform.python_version()} \" +\n f\"on {platform.uname()}\")\n # osys = platform.system()\n # if osys.lower() == \"windows\":\n # os_ver = platform.win32_ver()[1]\n # else:\n # # os_ver = platform.linux_distribution() # NOTE: Deprecated!\n # import distro\n # os_ver = distro.linux_distribution()\n\n # Display versions of used third-party libraries\n logging.info(f\"pytz version: {pytz.__version__}\")\n # logging.info(\"matplotlib version: {}\".format(matplotlib.__version__))\n # logging.info(f\"matplotlib version: {matplotlib.__version__}\")\n logging.info(f\"numpy version: {np.__version__}\")\n logging.info(f\"pandas version: {pd.__version__}\")\n # logging.info(f\"networkx version: {nx.__version__}\")\n logging.info(f\"OpenCV version: {cv.__version__}\")\n\n return dir_in, dir_out\n\n\ndef parse_filename(filename, time_fmt=TIME_INFILE_FMT):\n \"\"\"Parse Hive and RPi number and UTC time from filename.\n\n Filename e.g.: raw_hive1_rpi1_190801-000002-utc.jpg\n \"\"\"\n # Split the name up into its \"blocks\"\n prefix, hive_str, rpi_str, t_str = filename.split(\"_\")\n\n # Parse Hive and RPi number\n hive = int(hive_str[-1])\n rpi = int(rpi_str[-1])\n\n # Parse timestring into a datetime object\n dt_naive = datetime.strptime(t_str, time_fmt)\n dt_utc = pytz.utc.localize(dt_naive)\n\n # # Get datetime object of the day at midnight\n # dt_day = dt_utc.replace(\n # hour=0, minute=0, second=0, microsecond=0)\n\n return hive, rpi, dt_utc # , dt_day\n\n\ndef compute_difference(img1, img2, path_out,\n euclid=ARGS.euclid,\n export=ARGS.export,\n time_fmt=TIME_FMT,\n ):\n \"\"\"Compute difference between two images.\n\n def euclid(img1,img2):\n absdiff = cv.absdiff(img1, img2).astype(np.float)\n return np.sqrt(np.sum(absdiff**2))\n\n def manhattan(img1,img2):\n return np.sum(cv.absdiff(img1,img2))\n\n def time_it(img1, img2, n=10):\n t0=time.time()\n for i in range(n):\n diff = euclid(img1, img2)\n t1=time.time()\n for i in range(n):\n diff = manhattan(img1, img2)\n t2=time.time()\n print(f\"{n} euclid took {t1 - t0} secs, manhatten {t2 - t1}\")\n\n >>> time_it(img1, img2, 1000)\n 1000 euclid took 19.7092 secs, manhatten 2.6678\n\n >>> 19.7092 / 2.6679\n 7.3875\n\n euclid takes about 7.5 times as long..\n\n Useful links:\n\n https://stackoverflow.com/questions/56183201/\n detect-and-visualize-differences-between-two-images-with-opencv-python/\n 56193442\n\n https://stackoverflow.com/questions/27035672/\n cv-extract-differences-between-two-images/27036614#27036614\n \"\"\"\n # Get absolute differences for each pixel as UINT8 array\n # TODO: Turn grayscale first?\n # No! Then read them in as grayscale in the first place!\n # gray1 = cv.cvtColor(img1, cv.COLOR_BGR2GRAY)\n absdiff = cv.absdiff(img1, img2)\n # NOTE: Image is still 3 channel BGR\n\n if export:\n t_str = datetime.utcnow().strftime(time_fmt)\n ffn = path_out / f\"diff_{t_str}.png\"\n cv.imwrite(str(ffn), absdiff)\n\n # TODO: Threshold absdiff to remove JPEG noise?\n\n if euclid:\n # Euclidean Distance\n # diff = np.sqrt(np.sum(np.power(absdiff, 2)))\n diff = np.sqrt(np.sum(absdiff.astype(np.float)**2))\n else:\n # Manhattan Distance\n diff = np.sum(absdiff)\n #\n # # Manhattan Distance\n # diff_man = np.sum(absdiff)\n # # Euclidean Distance\n # diff_euc = np.sqrt(np.sum(absdiff.astype(np.float)**2))\n\n # TODO: Normalize by time difference?\n # No, if you wanna do it, do it later!(?)\n # TODO: Return both distances\n\n return diff\n\n\ndef export_csv(rows, row_cols, path_out, hive, rpi, method,\n time_fmt=TIME_FMT,\n prefix=OUTCSV_PREFIX,\n ):\n \"\"\"Write the image difference to CSV.\n\n row_cols = [\n \"time1\", \"time2\", \"activity\", \"file1\", \"file2\"\n ]\n \"\"\"\n # Initial DataFrame\n df = pd.DataFrame(rows, columns=row_cols)\n\n # Derived columns (duration, central time)\n dur_td = df[\"time2\"] - df[\"time1\"]\n time_c = df[\"time1\"] + (dur_td / 2)\n dur_s = dur_td.dt.total_seconds()\n # Add to DataFrame\n df[\"time_central\"] = time_c\n df[\"duration\"] = dur_s\n\n # Reshape the array\n df.set_index(\"time_central\", drop=True, inplace=True)\n df = df[[\"duration\", \"activity\", \"time1\", \"time2\", \"file1\", \"file2\"]]\n\n # Parse first and last times\n t0 = df[\"time1\"].iloc[0]\n t1 = df[\"time2\"].iloc[-1]\n # Check whether the last image was from the next day\n tx = (\n t0.replace(hour=0, minute=0, second=0, microsecond=0) +\n timedelta(days=1)\n )\n if t1 >= tx:\n t1 = (\n t1.replace(hour=23, minute=59, second=59, microsecond=0) -\n timedelta(days=1)\n )\n\n # Set up output folder\n dir_out = path_out / f\"csv/hive{hive}/rpi{rpi}\"\n if not dir_out.is_dir():\n dir_out.mkdir(parents=True)\n logging.info(f\"Created folder '{dir_out}'\")\n\n # Build filename\n day_str = t0.strftime(\"%y%m%d\")\n t0_str = t0.strftime(\"%H%M%S\")\n t1_str = t1.strftime(\"%H%M%S\")\n fn = (\n f\"{prefix}_hive{hive}_rpi{rpi}_\"\n f\"{day_str}_{t0_str}-{t1_str}-utc_{method.lower()}.csv\"\n )\n ffn = ioh.safename((dir_out / fn), \"file\")\n\n # Export CSV\n df.to_csv(\n ffn,\n # index_label=\"time\",\n # date_format=time_fmt,\n )\n logging.info(f\"Exported df shaped {df.shape} to {ffn}\")\n\n return None\n\n\ndef main(\n file_pattern=INFILE_PATTERN,\n # folder_pattern=INFOLDER_PATTERN,\n tol_td=TOLERANCE_TIMEDELTA,\n fsize_thresh=FILESIZE_THRESHOLD,\n print_modulus=PRINT_MODULUS,\n args=ARGS,\n):\n \"\"\"Compute difference between cosecutive images and output CSVs.\"\"\"\n # Initialize IO-directories and setup logging\n path_photos, path_out = initialize_io()\n\n path_diffs = path_out / \"diff_imgs\"\n if args.export:\n # Folder not needed otherwise, but variable needs to be passed\n if not path_diffs.is_dir():\n path_diffs.mkdir()\n logging.info(f\"Created folder '{path_diffs}'\")\n\n # Find matching files\n # NOTE: This can take potentially long\n # A folderwise sorting would be much faster\n t0 = time.time()\n filelist = sorted(path_photos.rglob(file_pattern))\n dur = time.time() - t0\n\n n_files = len(filelist)\n logging.info(f\"Found {n_files} matching files in '{path_photos}' \"\n f\"(took {dur:.4} seconds)\")\n\n # Trim list according to given first_idx\n # if args.firstidx is not None:\n if args.firstidx > 0:\n filelist = filelist[args.firstidx:]\n n_files = len(filelist)\n logging.info(f\"Trimmed filelist to {n_files} files\")\n\n # Log differencing method employed\n if args.euclid:\n method = \"Euclidean\"\n else:\n method = \"Manhattan\"\n logging.info(f\"Computing {method} distance between images\")\n\n # Initialize containers\n row_cols = [\n \"time1\", \"time2\", \"activity\", \"file1\", \"file2\"\n ]\n rows = []\n\n # Begin clocking\n t0 = time.time()\n\n # Parse first file\n file = filelist[0]\n # c_dir1 = c_file.parent\n hive, rpi, dt = parse_filename(file.name)\n # img = cv.imread(file, cv2.IMREAD_GRAYSCALE)\n img = cv.imread(str(file))\n logging.info(f\"Beginning with Hive{hive}, RPi{rpi}, \"\n f\"photo '{file}' taken {dt}\")\n\n try:\n for i in range(n_files - 1):\n next_file = filelist[i + 1]\n\n if next_file.stat().st_size > fsize_thresh:\n next_hive, next_rpi, next_dt = parse_filename(\n next_file.name)\n\n # next_img = cv.imread(file, cv2.IMREAD_GRAYSCALE)\n next_img = cv.imread(str(next_file))\n logging.debug(f\"Read image {next_file.name}\")\n\n # Check whether next file can be compared to the current file\n # if (hive == next_hive) and (rpi == next_rpi) and ...\n if (rpi == next_rpi) and ((next_dt - dt) < tol_td):\n\n diff = compute_difference(img, next_img, path_diffs)\n\n # Make row and append\n # row_cols = [\"time1\", \"time2\", \"activity\",\n # \"file1\", \"file2\"]\n row = [dt, next_dt, diff, file.name, next_file.name]\n rows.append(row)\n\n # if next_day > day:\n if (next_dt.day != dt.day) or (next_dt.month != dt.month):\n\n # Export rows as CSV and empty row list\n if len(rows) > 0:\n logging.info(\"Day change, \"\n f\"exporting {len(rows)} rows to CSV\")\n export_csv(rows, row_cols, path_out,\n hive, rpi, method)\n rows = []\n\n else:\n logging.info(\n \"Photos not comparable: \"\n f\"file1: {file.name}, file2: {next_file.name}, \"\n \"switching to next series\"\n )\n # Export rows as CSV and empty row list\n if len(rows) > 0:\n logging.info(f\"Exporting {len(rows)} rows to CSV\")\n export_csv(rows, row_cols, path_out,\n hive, rpi, method)\n rows = []\n\n if (i + 1) % print_modulus == 0:\n logging.info(f\"{i + 1}/{n_files} \"\n f\"({100 * (i + 1) / n_files:.3}%) in \"\n f\"{(time.time() - t0) / 60.0:.3} minutes \"\n f\"(last file: {next_file.name})\")\n else:\n logging.warning(f\"File {next_file.name} is too small: \"\n f\"{next_file.stat().st_size} < {fsize_thresh}\"\n f\"Skipping file.\")\n next_file = filelist[i] # reset to previous file\n\n # Reset current photo data\n file, dt, img = next_file, next_dt, next_img\n hive, rpi = next_hive, next_rpi\n\n except KeyboardInterrupt:\n logging.info(\"Manually interrupted script\")\n\n finally:\n if len(rows) > 0:\n logging.info(f\"Exporting {len(rows)} rows to CSV\")\n export_csv(rows, row_cols, path_out, hive, rpi, method)\n\n logging.info(\"Done.\")\n\n\nif __name__ == \"__main__\":\n main() # (args)\n","sub_path":"bee_activity.py","file_name":"bee_activity.py","file_ext":"py","file_size_in_byte":16629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"651162959","text":"import requests\nimport ssl\nimport time\nimport hashlib\nimport json as js\nimport os\nfrom datetime import datetime\nfrom urllib import parse\nimport xml.etree.ElementTree as ET\n\ndef dict2list(dic:dict):\n ''' 将字典转化为列表 '''\n keys = dic.keys()\n vals = dic.values()\n lst = [(key, val) for key, val in zip(keys, vals)]\n return lst\n\ndef curlmd5(src):\n m = hashlib.md5()\n m.update(src.encode('UTF-8'))\n return m.hexdigest()\n\n\ndef get_data(url = 'http://api.cngrid.org/v2/show/cngrid/realtimeInfo'):\n ssl._create_default_https_context = ssl._create_unverified_context\n values = {'username': 'xulubuaa', 'password': 'xulu416','appid':'opus','remember':'true'}\n s = requests.Session()\n r = s.post(\"https://api.cngrid.org/v2/users/login\",values,verify=False)\n root = ET.fromstring(r.text)\n logdic = {}\n for child in root:\n logdic[child.tag] = child.text\n\n #签名算法的计算\n params = {}\n millis = int(round(time.time() * 1000))\n params['timestamp'] = str(millis)\n md5dic_sort = sorted(dict2list(params), key=lambda x:x[0], reverse=False)\n md_str = \"\"\n for i in md5dic_sort:\n md_str= md_str+i[0]+'='+i[1]\n md_str+=logdic['md5secret']\n HTTP_METHOD = \"GET\"\n md_str = HTTP_METHOD+url+md_str\n md5 = curlmd5(md_str)\n params['md5sum'] = str(md5)\n params_data = parse.urlencode(params).encode('utf-8') # 提交类型不能为str,需要为byte类型\n headers = {'Accept': 'application/json', 'Content-Type': 'application/json','User-Agent':\"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36\"}\n\n r = s.get(url, params=params_data,headers=headers,verify=False)\n return r.json()\n","sub_path":"realtime/catalog/getdata.py","file_name":"getdata.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"1458049","text":"\"\"\" verision #2 wherein I'm adjusting all the indices in the for loops to try and make them compatible\nwith how python starts numbering 0 to n-1 for n numbers\"\"\"\n\n\nimport numpy as np #for matrix operations\nimport math\n\ndef knapsack(items, c, k):\n\n #sort based on price\n sorted_items = np.sort(items,order='price')\n prices=sorted_items['price']\n \n \n for i in range(len(prices)):\n prices[i]=int(math.ceil(prices[i]))\n\n \n #discard all items with weight larger than wmax \n remove=[]\n for j in range(k-1,len(sorted_items)): #k to current n\n wmax = sum(prices[0:k]) + prices[j] #note: upper bound k is NOT inclusive, goes to k-1\n if wmax > c:\n remove.append(j)\n \n filt_items=np.delete(sorted_items,range(max(remove),len(sorted_items)),0) \n prices2=filt_items['price']\n \n n=len(filt_items) #number of items post-removal of ones that are too big\n \n #calculate weightsum of the first k items of the sorted list\t\n v=int(sum(prices2[0:k+1:1]))\n \n #initialize g as an n by c matrix (?), sigma as...nothing?\n g = np.zeros([n,c])\n #sigma=np.zeros([n,1])\n sigma = np.zeros([c,1])\n \n #copied the balcardssp algorithm more-or-less verbatim, no clue what's going on tho:\n for weightsum in range(v+1,c):\n g[k,weightsum]=0\n g[k,v]=k+1\n for weightsum in range(int(v+prices2[k+1]),c):\n #sigma.insert(weightsum,1)\n sigma[weightsum]=1\n for weightsum in range (c+1,int(c+prices2[k])):\n temp_keep=[]\n for j in range(n):\n if prices2[j]sigma[weightsum2]:\n for h in range(int(sigma[weightsum2]),int(g[b-1,weightsum]-1)):\n weightsum3=int(weightsum2-prices2[h])\n g[b,weightsum3]=max(g[b,weightsum3],h)\n #sigma.insert(weightsum2,g[b-1,weightsum])\n sigma[weightsum2]=g[b-1,weightsum]\n \n np.savetxt(\"test_results_1.csv\", g, delimiter=\",\")\n np.savetxt(\"test_results_2.csv\", sigma, delimiter=\",\")\n\n\n\n#now apply the knapsack function to imported data\n\ncsv = np.genfromtxt ('dummy_list_subset2.csv', delimiter=\",\", dtype=None, names=['name',\n 'club','pos','price','value'])\n\nknapsack(csv,30,10) #alter values here during testing\n","sub_path":"draft2_knapsack.py","file_name":"draft2_knapsack.py","file_ext":"py","file_size_in_byte":2850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"576858587","text":"import unittest\nfrom unittest import TestCase\n\ndef det(matrice):\n\n dep = len(matrice)\n if dep > 2:\n i = 1\n t = 0\n sumdet = 0\n while t <= dep-1:\n hold={}\n vx = 1\n while vx <= dep-1:\n m = 0\n hold[vx] = []\n while m <= dep-1:\n if m == t:\n u = 0\n else:\n hold[vx].append(matrice[vx][m])\n m += 1\n vx += 1\n ech=[hold[x] for x in hold]\n sumdet = sumdet + i * (matrice [ 0][ t]) * (det(ech))\n i = i*(-1)\n t +=1\n return sumdet\n else:\n return (matrice[0][0] * matrice[1][1] - matrice [0][1] * matrice [1][0])\n\n\nclass TestDet(TestCase):\n\n def testdet2x2(self):\n self.assertEqual(det([[3,2], [2,3]]), 5)\n\n def testdet3X3(self):\n self.assertEqual(det([[1, 4, 3], [2, 1, 2], [2, 4, 1]]), 19)\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"week6/question4.py","file_name":"question4.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"77822081","text":"import os\nimport tornado.web\nfrom application import BaseHandler\nfrom sqlalchemy import *\nfrom data.db import *\n\n\"\"\"This StoryHandler requests the db for a certain 'story', then \nreturns the db text regarding that story. Used for blog posts\"\"\"\nclass StoryHandler(BaseHandler):\n\tdef get(self, story):\n\t\ttry:\n\t\t\tstory = session.query(Story).get(story)\n\t\t\tif not story:\n\t\t\t\tself.write(\"this story doesn't exist\")\n\t\t\t\traise\n\t\t\t\treturn\n\n\t\t\tself.write(story)\n\t\t\tself.write(\"wowowowowo\")\n\n\t\texcept:\n\t\t\tself.write(-1)\n\t\t\tprint(\"Story failed\")\n\t\t\traise","sub_path":"handlers/storyhandler.py","file_name":"storyhandler.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"608359681","text":"#encoding UTF-8\n#Autor: Leonardo Castillejos Vite\n#Descripción: Un programa que lee los litros usados,los kilometros recorridos y lo kilometros a recorrer e imprime el\n# rendimiento en km/l y mi/gal\n\ndef calcularRendimientoKm (kmRecorridos, litrosUsados):\n redimientoInter = kmRecorridos/litrosUsados\n return redimientoInter\n\ndef calcularRendimientoMil (kmRecorridos, litrosUsados):\n milRecorridos = kmRecorridos * 0.621371\n gallRecorridos = litrosUsados * 0.264\n rendimientoImp = milRecorridos/gallRecorridos\n return rendimientoImp\n\ndef calcularGasAUsar (kilometrosARecorrer, rendimientoInter):\n gasolinaUsada = kilometrosARecorrer / rendimientoInter\n return gasolinaUsada\n\ndef main():\n kmRe = int(input(\"Teclea el número de km recorridos: \"))\n gasUsa = int(input(\"Teclea el número de litros de gasolina usados: \"))\n print(\"\")\n print(\"Si recorres %d kms con %d litros de gasolina, el rendimiento es:\" % (kmRe, gasUsa))\n rendimientoInter = calcularRendimientoKm(kmRe, gasUsa )\n rendimientoImp = calcularRendimientoMil(kmRe, gasUsa)\n print(\"%.2f km/l\" % (rendimientoInter))\n print(\"%.2f mi/gal\" % (rendimientoImp))\n print(\"\")\n kmARecorrer = int(input(\"¿Cuántos kilómetros vas a recorrer? \"))\n gasAUtilizar = calcularGasAUsar(kmARecorrer, rendimientoInter)\n print(\"\")\n print(\"Para recorrer %d km. necesitas %.2f litros de gasolina\" % (kmARecorrer, gasAUtilizar))\n\n\n\n\nmain()\n","sub_path":"RendimientodeAutos.py","file_name":"RendimientodeAutos.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"267052522","text":"# -*- coding: utf-8\n\n\"\"\"\n@File : t_multi_cal.py\n@Author : Zitong Lu\n@Contact : zitonglu1996@gmail.com\n@License : MIT License\n\"\"\"\n\nimport numpy as np\nimport unittest\nfrom pyctrsa.ctrdm.multi_cal import ctrdms_cal\n\nclass test_multi_cal(unittest.TestCase):\n\n def test_ctrdms_cal(self):\n\n data = np.random.rand(10, 8, 16, 20)\n CTRDMs = ctrdms_cal(data, chl_opt=1, time_win=10, time_step=5)\n self.assertEqual(CTRDMs.shape[0], 8)\n self.assertEqual(len(CTRDMs.shape), 6)\n\n CTRDMs = ctrdms_cal(data, chl_opt=0, time_win=10, time_step=5)\n self.assertEqual(CTRDMs.shape[0], 8)\n self.assertEqual(len(CTRDMs.shape), 5)\n","sub_path":"test/t_multi_cal.py","file_name":"t_multi_cal.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"389218997","text":"import time\nimport multiprocessing\n\n\ndef calc_square(numbers):\n for n in numbers:\n time.sleep(2)\n print('square %s' % (n*n))\n\n\ndef calc_cube(numbers):\n for n in numbers:\n time.sleep(2)\n print('cube %s' % (n*n*n))\n\n\nnumber_list = [1, 2, 3, 4, 5, 6]\n\np1 = multiprocessing.Process(target=calc_square, args=(number_list,))\np2 = multiprocessing.Process(target=calc_cube, args=(number_list,))\n\np1.start()\np2.start()\n\np1.join()\np2.join()\n\nprint('Done!')\n\n","sub_path":"19_multiprocessing_demo_1.py","file_name":"19_multiprocessing_demo_1.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"126957","text":"import abc\nimport logging\nimport os\nimport random\n\nfrom LAC import LAC\n\nfrom . import utils\nfrom .callbacks import (CallbackWrapper, EntropyCallback, IDFCallback,\n NgramsCallback)\n\n\ndef read_input_files(input_files, callback=None, log_steps=1000):\n if isinstance(input_files, str):\n input_files = [input_files]\n num = 0\n for f in input_files:\n if not os.path.exists(f):\n logging.warning('File %s does not exist.', f)\n continue\n with open(f, mode='rt', encoding='utf8') as fin:\n for line in fin:\n line = line.rstrip('\\n')\n if not line:\n continue\n if callback:\n callback(line)\n num += 1\n if num % log_steps == 0:\n logging.info('Finished to process %d lines.', num)\n logging.info('Finished to process %d lines in total of file: %s', num, f)\n logging.info('Finished to process %d lines in total of all files.', num)\n logging.info('Done!')\n\n\nclass AbstractStrategy:\n\n def __init__(self, tokenizer, callbacks=None, **kwargs):\n self.tokenizer = tokenizer\n self.callback = CallbackWrapper(callbacks=callbacks)\n\n def fit(self, input_doc_files, N=4, **kwargs):\n\n def read_line(line):\n # callbacks process doc begin\n self.callback.on_process_doc_begin()\n tokens = self.tokenizer.tokenize(line, **kwargs)\n # callbacks process tokens\n self.callback.update_tokens(tokens, **kwargs)\n # callbacks process ngrams\n for n in range(1, N + 1):\n for (start, end), window in utils.ngrams(tokens, n=n):\n self.callback.update_ngrams(start, end, window, n, **kwargs)\n # callbacks process doc end\n self.callback.on_process_doc_end()\n\n read_input_files(input_doc_files, callback=read_line, log_steps=kwargs.get('log_steps', 1000))\n\n def select_frequent_phrases(self, **kwargs):\n raise NotImplementedError()\n\n def build_phrase_pool(self, quality_phrases, frequent_phrases, **kwargs):\n raise NotImplementedError()\n\n def compose_training_data(self, pos_pool, neg_pool, **kwargs):\n raise NotImplementedError()\n\n def adjust_phrase_pool(self, pos_pool, neg_pool, classifier, epoch, **kwargs):\n raise NotImplementedError()\n\n def build_input_features(self, phrase, **kwargs):\n raise NotImplementedError()\n\n\ndef default_phrase_filter_fn(phrase, count):\n if any(phrase.endswith(x) for x in ['仅', '中']):\n return True\n return False\n\n\nclass Strategy(AbstractStrategy):\n\n def __init__(self, tokenizer, N=4, epsilon=0.0, **kwargs):\n self.ngrams_callback = NgramsCallback(n=N, epsilon=epsilon)\n self.idf_callback = IDFCallback(epsilon=epsilon)\n self.entropy_callback = EntropyCallback(epsilon=epsilon)\n callbacks = [self.ngrams_callback, self.idf_callback, self.entropy_callback]\n super().__init__(tokenizer=tokenizer, callbacks=callbacks, **kwargs)\n\n self.phrase_filter_fn = kwargs.get('phrase_filter_fn', default_phrase_filter_fn)\n self.phrase_max_count = kwargs.get('phrase_max_count', 1000)\n self.phrase_min_length = kwargs.get('phrase_min_length', 3)\n self.phrase_min_unigram_length = kwargs.get('phrase_min_unigram_length', 3)\n self.phrase_min_freq = kwargs.get('phrase_min_freq', 5)\n self.phrase_drop_stopwords = kwargs.get('phrase_drop_stopwords', True)\n self.phrase_drop_verbs = kwargs.get('phrase_drop_verbs', True)\n if self.phrase_drop_verbs:\n self.lac = LAC()\n self.prob_threshold = kwargs.get('prob_threshold', 0.45)\n self.prob_threshold_schedule_factor = kwargs.get('prob_threshold_schedule_factor', 1.0)\n self.prob_topk = kwargs.get('prob_topk', 10)\n self.min_delta = kwargs.get('min_delta', 3)\n\n self.features_cache = {}\n\n def select_frequent_phrases(self, **kwargs):\n candidates = []\n for n in range(1, self.ngrams_callback.N + 1):\n counter = self.ngrams_callback.ngrams_freq[n]\n for phrase, count in counter.items():\n _phrase = ''.join(phrase.split(' '))\n if self._filter_phrase(_phrase, count, **kwargs):\n continue\n candidates.append((phrase, count))\n\n if self.phrase_drop_verbs:\n candidates = self._drop_verbs(candidates)\n candidates = sorted(candidates, key=lambda x: x[1], reverse=True)\n return [x[0] for x in candidates[:self.phrase_max_count]]\n\n def _filter_phrase(self, phrase, count, **kwargs):\n if len(phrase) < self.phrase_min_length:\n return True\n if count < self.phrase_min_freq:\n return True\n if self.phrase_drop_stopwords and any(utils.STOPWORDS.contains(x) for x in phrase):\n return True\n if self.phrase_filter_fn(phrase, count):\n return True\n return False\n\n def _drop_verbs(self, candidates):\n predictions = []\n for i in range(0, len(candidates), 100):\n # batch_count = [x[1] for x in candidates[i:i+100]]\n batch_texts = [x[0] for x in candidates[i:i+100]]\n batch_preds = self.lac.run(batch_texts)\n predictions.extend(batch_preds)\n filtered_candidates = []\n for i in range(len(predictions)):\n _, pos_tags = predictions[i]\n if any(pos in ['v', 'vn', 'vd'] for pos in pos_tags):\n continue\n filtered_candidates.append(candidates[i])\n return filtered_candidates\n\n def build_phrase_pool(self, quality_phrases, frequent_phrases, **kwargs):\n pos_pool, neg_pool = [], []\n for p in frequent_phrases:\n _p = ''.join(p.split(' '))\n # unigrams are positve phrase\n if _p in self.ngrams_callback.ngrams_freq[1] and len(_p) > self.phrase_min_unigram_length:\n pos_pool.append(p)\n continue\n if _p in quality_phrases:\n if len(p) > self.phrase_min_unigram_length:\n pos_pool.append(p)\n else:\n neg_pool.append(p)\n return pos_pool, neg_pool\n\n def compose_training_data(self, pos_pool, neg_pool, **kwargs):\n x, y = [], []\n examples = []\n for p in pos_pool:\n examples.append((self.build_input_features(p), 1))\n for p in neg_pool:\n examples.append((self.build_input_features(p), 0))\n # shuffle\n random.shuffle(examples)\n for _x, _y in examples:\n x.append(_x)\n y.append(_y)\n return x, y\n\n def adjust_phrase_pool(self, pos_pool, neg_pool, classifier, epoch, **kwargs):\n new_pos_pool, new_neg_pool = [], []\n new_pos_pool.extend(pos_pool)\n\n input_features = [self.build_input_features(x) for x in neg_pool]\n pos_probs = [prob[1] for prob in classifier.predict_proba(input_features)]\n pairs = [(p, prob) for p, prob in zip(neg_pool, pos_probs)]\n pairs = sorted(pairs, key=lambda x: x[1], reverse=True)\n print(pairs[:10])\n\n threshold = self._schedule_threshold(epoch, **kwargs)\n logging.info('\\t using threshold: %f', threshold)\n\n for idx, (p, prob) in enumerate(pairs):\n if prob > threshold:\n new_pos_pool.append(p)\n continue\n new_neg_pool.append(p)\n\n stop = True if len(new_pos_pool) - len(pos_pool) < self.min_delta else False\n return new_pos_pool, new_neg_pool, stop\n\n def _schedule_threshold(self, epoch, **kwargs):\n threshold = min(self.prob_threshold * self.prob_threshold_schedule_factor**epoch, 0.95)\n return threshold\n\n def build_input_features(self, phrase, **kwargs):\n\n def _convert_to_inputs(features):\n example = []\n for k in ['unigram', 'freq', 'doc_freq', 'idf', 'pmi', 'le', 're']:\n example.append(features[k])\n return example\n\n if phrase in self.features_cache:\n features = self.features_cache[phrase]\n return _convert_to_inputs(features)\n\n ngrams = phrase.split(' ')\n counter = self.ngrams_callback.ngrams_freq[len(ngrams)]\n freq = counter[''.join(ngrams)] / sum(counter.values())\n doc_freq = self.idf_callback.doc_freq_of(phrase)\n idf = self.idf_callback.idf_of(phrase)\n pmi = self.ngrams_callback.pmi_of(phrase)\n left_entropy = self.entropy_callback.left_entropy_of(phrase)\n right_entropy = self.entropy_callback.right_entropy_of(phrase)\n features = {\n 'unigram': 1 if len(ngrams) == 1 else 0,\n 'freq': freq,\n 'doc_freq': doc_freq,\n 'idf': idf,\n 'pmi': pmi,\n 'le': left_entropy,\n 're': right_entropy,\n }\n self.features_cache[phrase] = features\n return _convert_to_inputs(features)\n","sub_path":"autophrasex/strategy.py","file_name":"strategy.py","file_ext":"py","file_size_in_byte":9077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"150254433","text":"'''Trains a simple convnet on the MNIST dataset.\nGets to 99.25% test accuracy after 12 epochs\n(there is still a lot of margin for parameter tuning).\n16 seconds per epoch on a GRID K520 GPU.\n'''\n\nfrom __future__ import print_function\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.utils import plot_model\nfrom keras import backend as K\nfrom keras.utils import to_categorical\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\nimport datetime\n\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\n\nbatch_size = 64\nnum_classes = 2\nepochs = 120\n\n\ndef matrix_to_image(data, num, flag):\n min_max_scaler = MinMaxScaler(feature_range=(0, 255))\n data = min_max_scaler.fit_transform(data)\n pic = Image.fromarray(data.astype(np.uint8))\n if flag:\n pic.save('../pic/image/tad/%s.eps' % num, format='eps', dpi=1000)\n else:\n pic.save('../pic/image/no_tad/%s.eps' % (int(num) - 2208), format='eps', dpi=1000)\n\n\ndef load_data(feature=\"../cache/feature_21D_hg18_0506.xls\"):\n df_y = pd.read_excel(feature, header=None, sheetname='y').fillna(0)\n df_n = pd.read_excel(feature, header=None, sheetname='n').fillna(0)\n df = df_y.append(df_n)\n row = [i for i in range(df.shape[0])]\n index = [i for i in range(4, df.shape[1])]\n data = np.empty((df.shape[0], 1, img_rows, img_cols), dtype=\"float32\")\n for current_row in row:\n tmp_data = np.asarray(df.iloc[current_row, index], dtype=float)\n current_data = np.reshape(tmp_data, [9, 21])\n if current_row >= 2208:\n flag = 0\n else:\n flag = 1\n # matrix_to_image(current_data, current_row, flag=flag)\n data[current_row, :] = current_data\n target = df.iloc[:, 3]\n x_train, x_test, y_train, y_test = train_test_split(data, target, train_size=0.7, random_state=49)\n return (x_train, y_train), (x_test, y_test)\n\n\nimg_rows, img_cols = 9, 21\n\n(x_train, y_train), (x_test, y_test) = load_data()\n\nif K.image_data_format() == 'channels_first':\n x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)\n x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)\n input_shape = (1, img_rows, img_cols)\nelse:\n x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)\n x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)\n input_shape = (img_rows, img_cols, 1)\n\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\n\n# convert class vectors to binary class matrices\ny_train = to_categorical(y_train, num_classes)\ny_test = to_categorical(y_test, num_classes)\n\nmodel = Sequential()\nmodel.add(Conv2D(64, kernel_size=2, activation='tanh', input_shape=input_shape))\nmodel.add(Conv2D(64, 2, activation='relu'))\nmodel.add(Dropout(0.25))\nmodel.add(Conv2D(64, 2, activation='relu'))\nmodel.add(Dropout(0.25))\nmodel.add(Conv2D(64, 2, activation='relu'))\nmodel.add(Dropout(0.25))\nmodel.add(Conv2D(64, 2, activation='relu'))\nmodel.add(Dropout(0.25))\nmodel.add(Conv2D(64, 2, activation='relu'))\nmodel.add(Dropout(0.25))\nmodel.add(Conv2D(64, 2, activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))\n# model.add(Dropout(0.25))\nmodel.add(Dense(num_classes, activation='softmax'))\n\nmodel.summary()\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n# plot_model(model, to_file=\"../pic/cnn.png\")\nhistory = model.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=epochs,\n verbose=1,\n validation_data=(x_test, y_test))\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\npixel = plt.gcf()\npixel.savefig(\"../pic/cnn_acc_%s_%s_%s_drop.eps\" % (epochs, batch_size, datetime.datetime.now().strftime('%Y%m%d%H%M')),\n format='eps',\n dpi=1000)\nplt.close()\n# plt.show()\n# summarize history for loss\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\n\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\npixel = plt.gcf()\npixel.savefig(\n \"../pic/cnn_loss_%s_%s_%s_drop.eps\" % (epochs, batch_size, datetime.datetime.now().strftime('%Y%m%d%H%M')),\n format='eps',\n dpi=1000)\n# plt.show()\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])\n","sub_path":"src/cnn_01.py","file_name":"cnn_01.py","file_ext":"py","file_size_in_byte":4856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"520872953","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n__author__ = 'Josh Maine'\n__copyright__ = '''Copyright (C) 2013-2014 Josh \"blacktop\" Maine\n This file is part of Malice - https://github.com/blacktop/malice\n See the file 'docs/LICENSE' for copying permission.'''\n\nimport ConfigParser\nimport hashlib\nimport logging\n\nfrom dateutil import parser\nfrom flask import Config, current_app, flash, g\n\nimport modules\nfrom api.metascan_api import MetaScan\nfrom app.malice.worker.av.avast.scanner import avast_engine\nfrom app.malice.worker.av.avg import scanner as avg_engine\nfrom app.malice.worker.av.avira.scanner import avira_engine\nfrom app.malice.worker.av.bitdefender.scanner import bitdefender_engine\nfrom app.malice.worker.av.clamav.scanner import clamav_engine\nfrom app.malice.worker.av.eset.scanner import eset_engine\nfrom app.malice.worker.av.kaspersky.scanner import kaspersky_engine\nfrom app.malice.worker.av.sophos.scanner import sophos_engine\nfrom app.malice.worker.file.exe.pe import pe\nfrom app.malice.worker.file.exif import exif\nfrom app.malice.worker.file.trid import trid\nfrom app.malice.worker.intel.bit9 import batch_query_bit9, single_query_bit9\nfrom app.malice.worker.intel.virustotal import (batch_query_virustotal,\n single_query_virustotal)\nfrom lib.common.config import Config\nfrom lib.common.constants import MALICE_ROOT\nfrom lib.common.exceptions import MaliceDependencyError\nfrom lib.common.out import *\nfrom lib.core.database import db_insert, is_hash_in_db\nfrom lib.scanworker.file import PickleableFileSample\nfrom modules import av, file, intel\n\n# from app.malice.worker.av.f_prot import scanner as f_prot_engine\n# from app.malice.worker.file.doc.pdf import pdfparser, pdfid\n\ntry:\n import rethinkdb as r\nexcept ImportError:\n raise MaliceDependencyError(\"Unable to import rethinkdb.\"\n \"(install with `pip install rethinkdb`)\")\ntry:\n from redis import Redis\n from rq import Queue\n from rq.decorators import job\nexcept ImportError:\n raise MaliceDependencyError(\"Unable to import redis.\"\n \"(install with `pip install redis`)\")\n\nq = Queue('low', connection=Redis())\n\nconf_path = os.path.normpath(os.path.join(MALICE_ROOT, \"conf\", \"config.cfg\"))\nconfig = ConfigParser.ConfigParser()\nconfig.read(conf_path)\n\nlog = logging.getLogger(__name__)\n\n\nclass ScanManager(object):\n \"\"\"Handle Malice scan events.\"\"\"\n\n def __init__(self):\n conf_path = os.path.join(MALICE_ROOT, \"conf\", \"av.conf\")\n if not os.path.exists(conf_path):\n log.error(\"Configuration file av.conf not found\".format(conf_path))\n self.av_options = False\n return\n\n self.av_options = Config(conf_path)\n\n conf_path = os.path.join(MALICE_ROOT, \"conf\", \"intel.conf\")\n if not os.path.exists(conf_path):\n log.error(\"Configuration file intel.conf not found\".format(conf_path))\n self.intel_options = False\n return\n\n self.intel_options = Config(conf_path)\n\n conf_path = os.path.join(MALICE_ROOT, \"conf\", \"file.conf\")\n if not os.path.exists(conf_path):\n log.error(\"Configuration file file.conf not found\".format(conf_path))\n self.file_options = False\n return\n\n self.file_options = Config(conf_path)\n\n def run(self, file_stream, sample):\n results = {}\n\n # Exit if options were not loaded.\n if not self.av_options:\n return\n if not self.intel_options:\n return\n if not self.file_options:\n return\n\n print(\"<< Now Scanning file: {} >>>>>>>>>>>>>>>>>>>>>>>>>>>>\".format(sample['filename']))\n # vol = VolatilityAPI(self.memfile, self.osprofile)\n\n # TODO: improve the load of scan functions.\n # AntiVirus Engines >>>>>>>>>>>>>>>>>>>>>>>\n print_info(\"Scanning with AV workers now.\")\n\n if self.av_options.avast.enabled:\n results[av.avast.name] = av.avast.scan()\n if self.av_options.avg.enabled:\n results[avg.name] = avg.scan()\n if self.av_options.avira.enabled:\n results[avira.name] = avira.scan()\n if self.av_options.bitdefender.enabled:\n results[bitdefender.name] = bitdefender.scan()\n if self.av_options.clamav.enabled:\n results[clamav.name] = clamav.scan()\n if self.av_options.comodo.enabled:\n results[comodo.name] = comodo.scan()\n if self.av_options.eset.enabled:\n results[eset.name] = eset.scan()\n if self.av_options.fprot.enabled:\n results[fprot.name] = fprot.scan()\n if self.av_options.kaspersky.enabled:\n results[kaspersky.name] = kaspersky.scan()\n if self.av_options.metascan.enabled:\n results[metascan.name] = metascan.scan(ip=self.av_options.metascan.ip,\n port=self.av_options.metascan.port,\n key=self.av_options.metascan.key)\n if self.av_options.panda.enabled:\n results[panda.name] = panda.scan()\n if self.av_options.sophos.enabled:\n results[sophos.name] = sophos.scan()\n if self.av_options.symantec.enabled:\n results[symantec.name] = symantec.scan()\n if self.av_options.yara.enabled:\n results[yara.name] = yara.scan()\n\n print_success(\"Malice AV scan Complete.\")\n\n # Intel Engines >>>>>>>>>>>>>>>>>>>>>>>>>>>>\n print_info(\"Searching for Intel now.\")\n\n if self.intel_options.bit9.enabled:\n results[bit9.name] = bit9.query()\n if self.intel_options.virustotal.enabled:\n results[virustotal.name] = virustotal.query()\n if self.intel_options.shadowserver.enabled:\n results[shadowserver.name] = shadowserver.query()\n if self.intel_options.teamcymru.enabled:\n results[teamcymru.name] = teamcymru.query()\n if self.intel_options.malwr.enabled:\n results[malwr.name] = malwr.query()\n if self.intel_options.anibus.enabled:\n results[anibus.name] = anibus.query()\n if self.intel_options.totalhash.enabled:\n results[totalhash.name] = totalhash.query()\n if self.intel_options.domaintools.enabled:\n results[domaintools.name] = domaintools.query()\n if self.intel_options.opendns.enabled:\n results[opendns.name] = opendns.query()\n if self.intel_options.urlquery.enabled:\n results[urlquery.name] = urlquery.query()\n\n print_success(\"Intel Search Complete.\")\n\n # File Analysis Engines >>>>>>>>>>>>>>>>>>>>>>\n print_info(\"Performing file analysis now.\")\n\n if self.file_options.office.enabled:\n results[office.name] = office.analyze()\n if self.file_options.pdf.enabled:\n results[pdf.name] = pdf.analyze()\n if self.file_options.elf.enabled:\n results[elf.name] = elf.analyze()\n if self.file_options.pe.enabled:\n results[pe.name] = pe.analyze()\n if self.file_options.dotnet.enabled:\n results[dotnet.name] = dotnet.analyze()\n if self.file_options.macho.enabled:\n results[macho.name] = macho.analyze()\n if self.file_options.java.enabled:\n results[java.name] = java.analyze()\n if self.file_options.android.enabled:\n results[android.name] = android.analyze()\n if self.file_options.javascript.enabled:\n results[javascript.name] = javascript.analyze()\n if self.file_options.swf.enabled:\n results[swf.name] = swf.analyze()\n if self.file_options.php.enabled:\n results[php.name] = php.analyze()\n if self.file_options.html.enabled:\n results[html.name] = html.analyze()\n if self.file_options.trid.enabled:\n results[trid.name] = trid.analyze()\n if self.file_options.exif.enabled:\n results[exif.name] = exif.analyze()\n if self.file_options.yara.enabled:\n results[yara.name] = yara.analyze()\n\n print_success(\"File Analysis Complete.\")\n\n return results\n\nsm = ScanManager()\n\n# TODO : Make it so that it will scan with every available worker instead of having to do it explicitly\ndef scan_upload(file_stream, sample):\n # job = q.enqueue(run_workers, file_stream)\n # print job.result\n print(\"<< Now Scanning file: {} >>>>>>>>>>>>>>>>>>>>>>>>>>>>\".format(sample['filename']))\n # print_info(\"Scanning with MetaScan now.\")\n # if run_metascan(file_stream, sample['md5']):\n # print_success(\"MetaScan Complete.\")\n #: Run the AV workers on the file.\n print_info(\"Scanning with AV workers now.\")\n if run_workers(file_stream):\n print_success(\"Malice AV scan Complete.\")\n print_info(\"Performing file analysis now.\")\n print_item(\"Scanning with EXIF now.\", 1)\n exif_scan(file_stream, sample['md5'])\n print_item(\"Scanning with TrID now.\", 1)\n trid_scan(file_stream, sample['md5'])\n if file_is_pe(file_stream):\n #: Run PE Analysis\n print_item(\"Scanning with PE Analysis now.\", 1)\n pe_scan(file_stream, sample['md5'])\n if file_is_pdf(file_stream):\n #: Run PDF Analysis\n pdfparser_scan(file_stream, sample['md5'])\n pdfid_scan(file_stream, sample['md5'])\n #: Run Intel workers\n print_item(\"Searching for Intel now.\", 1)\n single_hash_search(sample['md5'])\n print_success(\"File Analysis Complete.\")\n found = is_hash_in_db(sample['md5'])\n return found['user_uploads'][-1]['detection_ratio']\n\n\ndef single_hash_search(this_hash):\n found = is_hash_in_db(this_hash)\n if not found:\n #: Run all Intel Workers on hash\n # TODO: Make these async with .delay(this_hash)\n single_query_bit9(this_hash)\n single_query_virustotal(this_hash)\n return is_hash_in_db(this_hash)\n else: #: Fill in the blanks\n if 'Bit9' not in list(found.keys()):\n single_query_bit9(this_hash)\n if 'VirusTotal' not in list(found.keys()):\n single_query_virustotal(this_hash)\n if found:\n # TODO: handle case where all fields are filled out (session not updating on first submission)\n r.table('sessions').insert(found).run(g.rdb_sess_conn)\n return found\n else:\n return False\n\n\ndef batch_search_hash(hash_list):\n new_hash_list = []\n search_results = []\n #: Check DB for hashes, if found do not query API\n for a_hash in hash_list:\n found = is_hash_in_db(a_hash)\n if found:\n search_results.append(found)\n r.table('sessions').insert(found).run(g.rdb_sess_conn)\n else:\n new_hash_list.append(a_hash)\n\n if new_hash_list:\n batch_query_bit9(new_hash_list)\n # batch_query_bit9.delay(new_hash_list)\n batch_query_virustotal(new_hash_list)\n for a_new_hash in new_hash_list:\n found = is_hash_in_db(a_new_hash)\n if found:\n search_results.append(found)\n return search_results\n else:\n return search_results\n\n\ndef scan_to_dict(scan, av):\n return dict(av=av, digest=scan.digest, infected=scan.infected, infected_string=scan.infected_string,\n metadata=scan.metadata, timestamp=r.now())\n\n\n# def scan_to_dict(scan, av):\n# return dict(av=av, digest=scan.digest, infected=scan.infected, infected_string=scan.infected_string,\n# metadata=scan.metadata, timestamp=r.now())\n\n\ndef avast_scan(this_file):\n my_avast_engine_engine = avast_engine()\n result = my_avast_engine_engine.scan(PickleableFileSample.string_factory(this_file))\n file_md5_hash = hashlib.md5(this_file).hexdigest().upper()\n found = is_hash_in_db(file_md5_hash)\n if found:\n found['user_uploads'][-1].setdefault('av_results', []).append(scan_to_dict(result, 'Avast'))\n if result.infected:\n found['user_uploads'][-1]['detection_ratio']['infected'] += 1\n found['user_uploads'][-1]['detection_ratio']['count'] += 1\n data = found\n else:\n data = dict(md5=file_md5_hash)\n data['user_uploads'][-1].setdefault('av_results', []).append(scan_to_dict(result, 'Avast'))\n db_insert(data)\n return data\n\n\ndef avg_scan(this_file):\n my_avg = avg_engine.AVG(this_file)\n result = my_avg.scan()\n # result = my_avg.scan(PickleableFileSample.string_factory(file))\n if 'error' in result[1]:\n flash(result[1]['error'], 'error')\n else:\n file_md5_hash = hashlib.md5(this_file).hexdigest().upper()\n found = is_hash_in_db(file_md5_hash)\n if found:\n found['user_uploads'][-1].setdefault('av_results', []).append(result[1])\n if result[1]['infected']:\n found['user_uploads'][-1]['detection_ratio']['infected'] += 1\n found['user_uploads'][-1]['detection_ratio']['count'] += 1\n data = found\n else:\n data = dict(md5=file_md5_hash)\n data['user_uploads'][-1].setdefault('av_results', []).append(result[1])\n db_insert(data)\n return data\n\n\n# TODO: metadata contains a element (description) that I should append or replace the infected string with\n# TODO: [^cont.] i.e. 'Contains code of the Eicar-Test-Signature virus' vs. 'Eicar-Test-Signature'\ndef avira_scan(file):\n my_avira_engine = avira_engine()\n result = my_avira_engine.scan(PickleableFileSample.string_factory(file))\n file_md5_hash = hashlib.md5(file).hexdigest().upper()\n found = is_hash_in_db(file_md5_hash)\n if found:\n found['user_uploads'][-1].setdefault('av_results', []).append(scan_to_dict(result, 'Avira'))\n if result.infected:\n found['user_uploads'][-1]['detection_ratio']['infected'] += 1\n found['user_uploads'][-1]['detection_ratio']['count'] += 1\n data = found\n else:\n data = dict(md5=file_md5_hash)\n data['user_uploads'][-1].setdefault('av_results', []).append(scan_to_dict(result, 'Avira'))\n db_insert(data)\n return data\n\n\ndef eset_scan(this_file):\n my_eset_engine = eset_engine()\n result = my_eset_engine.scan(PickleableFileSample.string_factory(this_file))\n file_md5_hash = hashlib.md5(this_file).hexdigest().upper()\n found = is_hash_in_db(file_md5_hash)\n if found:\n found['user_uploads'][-1].setdefault('av_results', []).append(scan_to_dict(result, 'ESET-NOD32'))\n if result.infected:\n found['user_uploads'][-1]['detection_ratio']['infected'] += 1\n found['user_uploads'][-1]['detection_ratio']['count'] += 1\n data = found\n else:\n data = dict(md5=file_md5_hash)\n data['user_uploads'][-1].setdefault('av_results', []).append(scan_to_dict(result, 'ESET-NOD32'))\n db_insert(data)\n return data\n\n\ndef bitdefender_scan(this_file):\n bitdefender = bitdefender_engine()\n result = bitdefender.scan(PickleableFileSample.string_factory(this_file))\n file_md5_hash = hashlib.md5(this_file).hexdigest().upper()\n found = is_hash_in_db(file_md5_hash)\n if found:\n found['user_uploads'][-1].setdefault('av_results', []).append(scan_to_dict(result, 'BitDefender'))\n if result.infected:\n found['user_uploads'][-1]['detection_ratio']['infected'] += 1\n found['user_uploads'][-1]['detection_ratio']['count'] += 1\n data = found\n else:\n data = dict(md5=file_md5_hash)\n data['user_uploads'][-1].setdefault('av_results', []).append(scan_to_dict(result, 'BitDefender'))\n db_insert(data)\n return data\n\n\ndef clamav_scan(this_file):\n my_clamav_engine = clamav_engine()\n results = my_clamav_engine.scan(PickleableFileSample.string_factory(this_file))\n file_md5_hash = hashlib.md5(this_file).hexdigest().upper()\n found = is_hash_in_db(file_md5_hash)\n if found:\n found['user_uploads'][-1].setdefault('av_results', []).append(scan_to_dict(results, 'ClamAV'))\n if results.infected:\n found['user_uploads'][-1]['detection_ratio']['infected'] += 1\n found['user_uploads'][-1]['detection_ratio']['count'] += 1\n data = found\n else:\n data = dict(md5=file_md5_hash)\n data['user_uploads'][-1].setdefault('av_results', []).append(scan_to_dict(results, 'ClamAV'))\n db_insert(data)\n return data\n\n\ndef f_prot_scan(this_file):\n pass\n # my_f_prot = f_prot_engine.F_PROT(this_file)\n # result = my_f_prot.scan()\n # result = my_avg.scan(PickleableFileSample.string_factory(file))\n # file_md5_hash = hashlib.md5(this_file).hexdigest().upper()\n # found = is_hash_in_db(file_md5_hash)\n # if found:\n # found['user_uploads'][-1].setdefault('av_results', []).append(scan_to_dict(result, 'AVG'))\n # if result.infected:\n # found['user_uploads'][-1]['detection_ratio']['infected'] += 1\n # found['user_uploads'][-1]['detection_ratio']['count'] += 1\n # data = found\n # else:\n # data = dict(md5=file_md5_hash)\n # data['user_uploads'][-1].setdefault('av_results', []).append(scan_to_dict(result, 'AVG'))\n # db_insert(data)\n # return data\n\n\ndef kaspersky_scan(this_file):\n my_kaspersky_engine = kaspersky_engine()\n results = my_kaspersky_engine.scan(PickleableFileSample.string_factory(this_file))\n file_md5_hash = hashlib.md5(this_file).hexdigest().upper()\n found = is_hash_in_db(file_md5_hash)\n if found:\n found['user_uploads'][-1].setdefault('av_results', []).append(scan_to_dict(results, 'Kaspersky'))\n if results.infected:\n found['user_uploads'][-1]['detection_ratio']['infected'] += 1\n found['user_uploads'][-1]['detection_ratio']['count'] += 1\n data = found\n else:\n data = dict(md5=file_md5_hash)\n data['user_uploads'][-1].setdefault('av_results', []).append(scan_to_dict(results, 'Kaspersky'))\n db_insert(data)\n return data\n\n\ndef sophos_scan(this_file):\n my_sophos = sophos_engine()\n results = my_sophos.scan(PickleableFileSample.string_factory(this_file))\n file_md5_hash = hashlib.md5(this_file).hexdigest().upper()\n found = is_hash_in_db(file_md5_hash)\n if found:\n found['user_uploads'][-1].setdefault('av_results', []).append(scan_to_dict(results, 'Sophos'))\n if results.infected:\n found['user_uploads'][-1]['detection_ratio']['infected'] += 1\n found['user_uploads'][-1]['detection_ratio']['count'] += 1\n data = found\n else:\n data = dict(md5=file_md5_hash)\n data['user_uploads'][-1].setdefault('av_results', []).append(scan_to_dict(results, 'Sophos'))\n db_insert(data)\n return data\n\n\ndef exif_scan(file_stream, file_md5):\n this_exif = exif.Exif(file_stream)\n if this_exif:\n key, exif_results = this_exif.scan()\n found = is_hash_in_db(file_md5)\n if found:\n found[key] = exif_results\n data = found\n else:\n data = dict(md5=file_md5)\n data[key] = exif_results\n db_insert(data)\n return data\n else:\n print_error(\"EXIF Analysis Failed.\")\n\n\ndef trid_scan(file_stream, file_md5):\n this_trid = trid.TrID(file_stream)\n if this_trid:\n key, trid_results = this_trid.scan()\n found = is_hash_in_db(file_md5)\n if found:\n found[key] = trid_results\n data = found\n else:\n data = dict(md5=file_md5)\n data[key] = trid_results\n db_insert(data)\n return data\n else:\n print_error(\"TrID Analysis Failed.\")\n\n\ndef pe_scan(this_file, file_md5):\n this_pe = pe.PE(this_file)\n if this_pe.pe:\n key, pe_results = this_pe.scan()\n found = is_hash_in_db(file_md5)\n if found:\n found[key] = pe_results\n data = found\n else:\n data = dict(md5=file_md5)\n data[key] = pe_results\n db_insert(data)\n return data\n else:\n print_error(\"PE Analysis Failed - This file might not be a PE Executable.\")\n\n\ndef file_is_pdf(this_file):\n return False\n\n\ndef file_is_pe(this_file):\n return True\n\n\ndef pdfparser_scan(this_file, file_md5):\n pass\n # this_pdf = pdfparser.PdfParser(this_file)\n # if this_pdf:\n # key, pe_results = this_pdf.scan()\n # found = is_hash_in_db(file_md5)\n # if found:\n # found[key] = pe_results\n # data = found\n # else:\n # data = dict(md5=file_md5)\n # data[key] = pe_results\n # db_insert(data)\n # return data\n # else:\n # pass\n\n\ndef pdfid_scan(this_file, file_md5):\n pass\n # this_pdfid = pdfid.PDFiD(this_file)\n # if this_pdfid:\n # key, pdfid_results = this_pdfid.scan()\n # found = is_hash_in_db(file_md5)\n # if found:\n # found[key] = pdfid_results\n # data = found\n # else:\n # data = dict(md5=file_md5)\n # data[key] = pdfid_results\n # db_insert(data)\n # return data\n # else:\n # pass\n\n\ndef run_metascan(this_file, file_md5):\n # TODO : remove these hardcoded creds\n if config.has_section('Metascan'):\n meta_scan = MetaScan(ip=config.get('Metascan', 'IP'), port=config.get('Metascan', 'Port'))\n else:\n meta_scan = MetaScan(ip='127.0.0.1', port='8008')\n if meta_scan.connected:\n results = meta_scan.scan_file_stream_and_get_results(this_file)\n if results.status_code != 200:\n print_error(\"MetaScan can not be reached.\")\n return None\n metascan_results = results.json()\n #: Calculate AV Detection Ratio\n detection_ratio = dict(infected=0, count=0)\n for av in metascan_results[u'scan_results'][u'scan_details']:\n metascan_results[u'scan_results'][u'scan_details'][av][u'def_time'] \\\n = parser.parse(metascan_results[u'scan_results'][u'scan_details'][av][u'def_time'])\n detection_ratio['count'] += 1\n if metascan_results[u'scan_results'][u'scan_details'][av]['scan_result_i'] == 1:\n detection_ratio['infected'] += 1\n found = is_hash_in_db(file_md5)\n if found:\n found['user_uploads'][-1].setdefault('metascan_results', []).append(metascan_results)\n found['user_uploads'][-1]['detection_ratio']['infected'] += detection_ratio['infected']\n found['user_uploads'][-1]['detection_ratio']['count'] += detection_ratio['count']\n data = found\n else:\n data = dict(md5=file_md5)\n data['user_uploads'][-1].setdefault('metascan_results', []).append(metascan_results)\n db_insert(data)\n return metascan_results\n else:\n return None\n\n\n@job('low', connection=Redis(), timeout=50)\ndef run_workers(file_stream):\n # TODO : Automate this so it will scan all registered engines\n # get_file_details(file_stream)\n # pe_info_results = pe_scan(file_stream)\n # print_item(\"Scanning with Avast.\", 1)\n # avast_scan(file_stream)\n print_item(\"Scanning with AVG.\", 1)\n avg_scan(file_stream)\n # print_item(\"Scanning with F-PROT.\", 1)\n # f_prot_scan(file_stream)\n # print_item(\"Scanning with Avira.\", 1)\n # avira_scan(file_stream)\n # print_item(\"Scanning with BitDefender.\", 1)\n # bitdefender_scan(file_stream)\n print_item(\"Scanning with ClamAV.\", 1)\n clamav_scan(file_stream)\n # print_item(\"Scanning with ESET.\", 1)\n # eset_scan(file_stream)\n # print_item(\"Scanning with Kaspersky.\", 1)\n # kaspersky_scan(file_stream)\n # print_item(\"Scanning with Sophos.\", 1)\n # sophos_scan(file_stream)\n return True\n","sub_path":"app/malice/scans.py","file_name":"scans.py","file_ext":"py","file_size_in_byte":24144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"181825957","text":"import numpy as np\nimport time\nimport sys\n\nSIZE = 10\n\nl1 = range(SIZE)\nl1 = list(range(SIZE))\nprint(\"python list l1: \", l1)\nprint(l1 + l1)\n\nsys.exit()\n\nl2 = range(SIZE)\n\na1 = np.arange(SIZE)\nprint(\"numpy array a1: \", a1)\na2 = np.arange(SIZE)\n\n#python list\nstart = time.time()\nresult = [(x+y) for x,y in zip(l1, l2)]\nprint(\"python list took: \", (time.time() - start) *1000)\nprint(\"resultado lista: \" + str(result))\n#result = l1 + l2\n\n#numpy array\nstart = time.time()\nresult = a1 + a2\nprint(\"numpy list took: \", (time.time() - start) *1000)\nprint(\"resultado array: \" + str(result))\n","sub_path":"scripts/PythonListVSNumpyArray.py","file_name":"PythonListVSNumpyArray.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"579303727","text":"import math\n\nn = int(input())\n\nsoinsu = []\n\nc = n\nif (c % 2 == 0):\n while True:\n soinsu.append(2)\n c = c // 2\n if ( c % 2 != 0):\n break\n\nlen = int(math.sqrt(c)) + 1\nfor i in range (3,len,2):\n while True:\n if ( c % i != 0):\n break\n soinsu.append(i)\n c = c // i\n if ( c == 1):\n break\nif ( c != 1):\n soinsu.append(c)\n\nd = n\nfor i in set(soinsu):\n d = d * (1-(1/i))\nprint (int(d))","sub_path":"NTL/NTL_1_D.py","file_name":"NTL_1_D.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"591835570","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# File: mnist.py\n# Author: Qian Ge \n\nimport os\nimport gzip\nimport struct\nimport numpy as np \nfrom src.utils.dataflow import get_rng\n\n\ndef identity(im):\n return im\n\nclass MNISTData(object):\n \"\"\" class for MNIST dataflow\n\n To access the data of mini-batch, first get data of all the channels\n through batch_data = MNISTData.next_batch_dict()\n then use corresponding key to get label or image through\n batch_data[key].\n \"\"\"\n def __init__(self, name, data_dir='',\n n_use_label=None, n_use_sample=None, pf=identity):\n \"\"\"\n Args:\n name (str): name of data to be read (['train', 'test', 'val'])\n data_dir (str): directory of MNIST data\n n_use_label (int): number of labels to be used\n n_use_sample (int): number of samples to be used\n pf: pre-process function for image data\n \"\"\"\n assert os.path.isdir(data_dir)\n self._data_dir = data_dir\n self._pf = pf\n self.rng = get_rng(self)\n\n self._load_files(name, n_use_label, n_use_sample)\n self._image_id = 0\n\n def _load_files(self, name, n_use_label, n_use_sample):\n if name == 'train':\n image_name = 'train-images-idx3-ubyte.gz'\n label_name = 'train-labels-idx1-ubyte.gz'\n else:\n image_name = 't10k-images-idx3-ubyte.gz'\n label_name = 't10k-labels-idx1-ubyte.gz'\n\n image_path = os.path.join(self._data_dir, image_name)\n label_path = os.path.join(self._data_dir, label_name)\n\n with gzip.open(label_path) as f:\n magic = struct.unpack('>I', f.read(4))\n if magic[0] != 2049:\n raise Exception('Invalid file: unexpected magic number.')\n n_label = struct.unpack('>I', f.read(4))\n label_list = np.fromstring(f.read(n_label[0]), dtype = np.uint8)\n\n with gzip.open(image_path) as f:\n magic = struct.unpack('>I', f.read(4))\n if magic[0] != 2051:\n raise Exception('Invalid file: unexpected magic number.')\n n_im, rows, cols = struct.unpack('>III', f.read(12))\n image_list = np.fromstring(\n f.read(n_im * rows * cols), dtype = np.uint8)\n image_list = np.reshape(image_list, (n_im, rows, cols, 1))\n im_list = []\n if n_use_sample is not None and n_use_sample < len(label_list):\n remain_sample = n_use_sample // 10 * 10\n left_sample = n_use_sample - remain_sample\n keep_sign = [0 for i in range(10)]\n data_idx = 0\n new_label_list = []\n for idx, im in enumerate(image_list):\n\n if remain_sample > 0:\n if keep_sign[label_list[idx]] < (n_use_sample // 10):\n keep_sign[label_list[idx]] += 1\n im_list.append(self._pf(im))\n new_label_list.append(label_list[idx])\n remain_sample -= 1\n else:\n break\n im_list.extend(image_list[idx:idx + left_sample])\n new_label_list.extend(label_list[idx:idx + left_sample])\n label_list = new_label_list\n\n else:\n for im in image_list:\n im_list.append(self._pf(im))\n\n self.im_list = np.array(im_list)\n self.label_list = np.array(label_list)\n\n if n_use_label is not None and n_use_label < self.size():\n remain_sample = n_use_label // 10 * 10\n left_sample = n_use_label - remain_sample\n keep_sign = [0 for i in range(10)]\n data_idx = 0\n while remain_sample > 0:\n if keep_sign[self.label_list[data_idx]] < (n_use_label // 10):\n keep_sign[self.label_list[data_idx]] += 1\n remain_sample -= 1\n else:\n self.label_list[data_idx] = 10\n data_idx += 1\n\n self.label_list[data_idx + left_sample:] = 10\n self._suffle_files()\n\n def _suffle_files(self):\n idxs = np.arange(self.size())\n\n self.rng.shuffle(idxs)\n self.im_list = self.im_list[idxs]\n self.label_list = self.label_list[idxs]\n\n def size(self):\n return self.im_list.shape[0]\n\n def next_im_generator(self):\n for im, label in zip(self.im_list, self.label_list):\n # if label == 0:\n yield im\n\n def occlude_pair_generator(self, pf_im=identity, pf_occlude=identity):\n for idx, (im, label) in enumerate(zip(self.im_list, self.label_list)):\n # print(idx)\n occlude_im = np.copy(im)\n # occlude_im[:14,...] = 0\n # occlude_im[:, 14:, :] = 0\n edge_ind = np.where(occlude_im > 0)\n\n pick_id = np.random.randint(0, edge_ind[0].shape[0])\n gap_center = (edge_ind[0][pick_id], edge_ind[1][pick_id])\n\n occlude_im[gap_center[0] - 7: gap_center[0] + 7,\n gap_center[1] - 7: gap_center[1] + 7] = 0\n\n yield pf_im(im), pf_occlude(occlude_im)\n\n\n # def next_batch(self):\n # assert self._batch_size <= self.size(), \\\n # \"batch_size {} cannot be larger than data size {}\".\\\n # format(self._batch_size, self.size())\n # start = self._image_id\n # self._image_id += self._batch_size\n # end = self._image_id\n # batch_files = self.im_list[start:end]\n # batch_label = self.label_list[start:end]\n\n # if self._image_id + self._batch_size > self.size():\n # self._epochs_completed += 1\n # self._image_id = 0\n # self._suffle_files()\n # return [batch_files, batch_label]\n","sub_path":"src/dataflow/mnist.py","file_name":"mnist.py","file_ext":"py","file_size_in_byte":5896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"42570845","text":"import datetime as dt\nimport unittest\n\nfrom AShareData import set_global_config\nfrom AShareData.PortfolioAnalysis import ASharePortfolioAnalysis\n\n\nclass MyTestCase(unittest.TestCase):\n def setUp(self):\n set_global_config('config.json')\n self.portfolio_analysis = ASharePortfolioAnalysis()\n self.data_reader = self.portfolio_analysis.data_reader\n\n def test_summary_statistics(self):\n start_date = dt.date(2008, 1, 1)\n end_date = dt.date(2020, 1, 1)\n price = self.data_reader.get_factor('股票日行情', '收盘价', start_date=start_date, end_date=end_date)\n self.portfolio_analysis.summary_statistics(price)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/portfolio_test.py","file_name":"portfolio_test.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"386480485","text":"#!/usr/bin/env python3\n#-------------------------------------------------------------------------------\n# Author: Lukasz Janyst \n# Date: 14.06.2017\n#-------------------------------------------------------------------------------\n\nimport argparse\nimport math\nimport sys\nimport os\n\nimport tensorflow as tf\nimport numpy as np\n\nfrom fcnvgg import FCNVGG\nimport utils\nfrom tqdm import tqdm\nfrom apmetrics import APMetrics\nimport shutil\n\n#-------------------------------------------------------------------------------\n# Parse the commandline\n#-------------------------------------------------------------------------------\nparser = argparse.ArgumentParser(description='Train the FCN')\nparser.add_argument('--name', default='test',\n help='project name')\nparser.add_argument('--data-source', default='kitti',\n help='data source')\nparser.add_argument('--data-dir', default='/home/levin/workspace/carnd/semantic_segmentation/data',\n help='data directory')\nparser.add_argument('--vgg-dir', default='/home/levin/workspace/carnd/semantic_segmentation/data/vgg',\n help='directory for the VGG-16 model')\nparser.add_argument('--epochs', type=int, default=30,\n help='number of training epochs')\nparser.add_argument('--batch-size', type=int, default=20,\n help='batch size')\nparser.add_argument('--tensorboard-dir', default=\"tb\",\n help='name of the tensorboard data directory')\nparser.add_argument('--checkpoint-interval', type=int, default=10,\n help='checkpoint interval')\nargs = parser.parse_args()\n\n\n\ntry:\n print('[i] Creating directory {}...'.format(args.name))\n if os.path.exists(args.name):\n shutil.rmtree(args.name) \n os.makedirs(args.name)\n if os.path.exists(args.tensorboard_dir):\n shutil.rmtree(args.tensorboard_dir)\nexcept (IOError) as e:\n print('[!]', str(e))\n sys.exit(1)\n\n\n\n\n \nclass TrainModel(object):\n def __init__(self):\n return\n def __disp_config(self):\n print('[i] Project name: ', args.name)\n print('[i] Data source: ', args.data_source)\n print('[i] Data directory: ', args.data_dir)\n print('[i] VGG directory: ', args.vgg_dir)\n print('[i] # epochs: ', args.epochs)\n print('[i] Batch size: ', args.batch_size)\n print('[i] Tensorboard directory:', args.tensorboard_dir)\n print('[i] Checkpoint interval: ', args.checkpoint_interval)\n return\n def __load_data_source(self):\n \n print('load data source...')\n try:\n source_module = __import__('source_'+args.data_source)\n source = getattr(source_module, 'get_source')()\n source.load_data(args.data_dir, 0.1)\n print('[i] # training samples: ', source.num_training)\n print('[i] # validation samples: ', source.num_validation)\n print('[i] # classes: ', source.num_classes)\n print('[i] Image size: ', source.image_size)\n return source\n except (ImportError, AttributeError, RuntimeError) as e:\n print('[!] Unable to load data source:', str(e))\n sys.exit(1)\n return\n \n \n def run(self):\n self.__disp_config()\n source = self.__load_data_source()\n #-------------------------------------------------------------------------------\n # Create the network\n #-------------------------------------------------------------------------------\n with tf.Session() as sess:\n print('[i] Creating the model...')\n net = FCNVGG(sess, source.num_classes)\n net.build_from_vgg(args.vgg_dir, source.num_classes, progress_hook='tqdm')\n \n net.get_optimizer(net.labels)\n net.add_summary_nodes(args.tensorboard_dir)\n \n validation_imgs = tf.placeholder(tf.float32, shape=[None, None, None, 3])\n validation_img_summary_op = tf.summary.image('validation_img',validation_imgs)\n train_img_summary_op = tf.summary.image('train_img',validation_imgs)\n saver = tf.train.Saver(max_to_keep=100)\n \n \n \n print('[i] Training...')\n \n \n utils.initialize_uninitialized_variables(sess)\n n_train_batches = int(math.ceil(source.num_training/args.batch_size))\n \n cur_step = 0\n step_num = n_train_batches * args.epochs\n \n for e in range(args.epochs):\n \n train_generator = source.train_generator(args.batch_size)\n \n \n for x, y in train_generator:\n cur_step += 1\n feed = {net.image_input: x,\n net.labels: y,\n net.keep_prob: 0.5,\n net.is_training: True}\n \n sess.run(net.reset_iou_op)\n summary, _, loss_batch, _,label_mapper, img_classes,f1,accuracy = sess.run([net.merged, net.update_iou_op, \n net.loss, net.optimizer,net.label_mapper, \n net.classes,net.f1,net.accuracy], feed_dict=feed)\n net.train_writer.add_summary(summary, cur_step)\n iou, summary = sess.run([net.metric_iou__op, net.merged_update])\n net.train_writer.add_summary(summary, cur_step)\n print(\"step {}:{}/{}: loss={}, iou={}, f1={}, acc={}\".format(e+1, cur_step, step_num, loss_batch, iou,f1,accuracy))\n #output trainig input image\n if (cur_step) % 10 == 0:\n val_imgs = x[:1,:,:,:]\n val_img_labels = img_classes[:1, :, :]\n val_img_labels_gt = label_mapper[:1, :, :]\n imgs_inferred = utils.draw_labels_batch(val_imgs, val_img_labels, source.label_colors)\n imgs_gt = utils.draw_labels_batch(val_imgs, val_img_labels_gt, source.label_colors)\n val_imgs = utils.convert_rgb_batch(val_imgs)\n all_imgs = np.concatenate([val_imgs, imgs_gt, imgs_inferred], axis = 0)\n\n summary = sess.run(train_img_summary_op,\n feed_dict={validation_imgs: all_imgs}) \n net.train_writer.add_summary(summary, cur_step)\n #monitor inference on valiaton data\n if (cur_step) % 10 == 0:\n val_generator = source.valid_generator(args.batch_size)\n #jut try out one batch\n x, y = next(val_generator)\n feed = {net.image_input: x,\n net.labels: y,\n net.keep_prob: 1.0,\n net.is_training: False}\n \n sess.run(net.reset_iou_op)\n summary, _, loss_batch,label_mapper, img_classes,f1,accuracy = sess.run([net.merged, net.update_iou_op, \n net.loss, net.label_mapper, net.classes,net.f1,net.accuracy], feed_dict=feed)\n net.val_writer.add_summary(summary, cur_step)\n iou, summary = sess.run([net.metric_iou__op, net.merged_update])\n net.val_writer.add_summary(summary, cur_step)\n print(\"#####validation: step {}/{}: loss={}, iou={}, f1={}, acc={}#####\".format(cur_step, step_num, loss_batch, iou,f1,accuracy))\n \n val_imgs = x[:1,:,:,:]\n val_img_labels = img_classes[:1, :, :]\n val_img_labels_gt = label_mapper[:1, :, :]\n imgs_inferred = utils.draw_labels_batch(val_imgs, val_img_labels, source.label_colors)\n imgs_gt = utils.draw_labels_batch(val_imgs, val_img_labels_gt, source.label_colors)\n val_imgs = utils.convert_rgb_batch(val_imgs)\n all_imgs = np.concatenate([val_imgs, imgs_gt, imgs_inferred], axis = 0)\n\n summary = sess.run(validation_img_summary_op,\n feed_dict={validation_imgs: all_imgs}) \n net.val_writer.add_summary(summary, cur_step)\n \n if (e+1) % args.checkpoint_interval == 0:\n checkpoint = '{}/e{}.ckpt'.format(args.name, e+1)\n saver.save(sess, checkpoint)\n print('Checkpoint saved:', checkpoint)\n \n \n \n \n return\n \nif __name__ == \"__main__\": \n obj= TrainModel()\n obj.run()\n \n","sub_path":"fcn/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"594296000","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n\r\nimport argparse\r\nfrom colorama import Fore\r\nimport json\r\nfrom pprint import pprint, pformat\r\nimport socket\r\nimport sys\r\nfrom prettytable import PrettyTable\r\nimport socket\r\n\r\nfrom pprint import pprint, pformat\r\n\r\nimport requests\r\nfrom requests.auth import HTTPBasicAuth, HTTPDigestAuth\r\n\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument(\"--env\", choices=[\"pro-editrack\", \"pro-fisicas\", \"pro1\", \"pro2\"], default=\"pro1\")\r\nparser.add_argument(\"--output\", choices=[\"table\"], default=\"table\")\r\nparser.add_argument('--include-indralog-urls', dest=\"include_indralog_urls\", action='store_true')\r\nparser.add_argument('--dump-apache-conf', dest=\"dump_apache_conf\", action='store_true')\r\nargs = parser.parse_args()\r\n\r\n\r\njboss_admin_user = \"production\"\r\njboss_admin_pass = \"pr0d5ct10n!:PR0\"\r\n\r\nif args.env == \"pro1\":\r\n jboss_management_url = \"http://192.168.123.131:9990/management\"\r\n hosts = [\"baratheon\", \"greyjoy\"]\r\nelif args.env == \"pro2\":\r\n jboss_management_url = \"http://192.168.123.62:9990/management\"\r\n hosts = [\"stark\", \"targaryen\"]\r\nelif args.env == \"pro-editrack\":\r\n jboss_management_url = \"http://192.168.123.72:9990/management\"\r\n hosts = [\"tico\", \"velma\"]\r\nelif args.env == \"pro-fisicas\":\r\n jboss_management_url = \"http://172.28.237.39:9990/management\"\r\n hosts = [\"indjbosspro01\", \"indjbosspro02\"]\r\n\r\nserver_groups_data = {}\r\n\r\npayload = {\r\n \"operation\": \"read-children-resources\",\r\n \"child-type\": \"host\",\r\n}\r\n\r\nservers_data = []\r\n\r\n# Obtener los hosts registrados\r\nr = requests.post(jboss_management_url, auth=HTTPDigestAuth(jboss_admin_user, jboss_admin_pass), data=json.dumps(payload), headers={\"Content-Type\": \"application/json\"})\r\n\r\ndata_json = None\r\ntry:\r\n data_json = r.json()\r\nexcept Exception as ex:\r\n print(\"{0}Error al obtener los datos (JSON no válido): {1}.{2}\".format(Fore.RED, str(ex), Fore.RESET))\r\n sys.exit(1)\r\n\r\nif not data_json or data_json.get(\"error\"):\r\n\r\n error = \"\"\r\n if data_json.get(\"error\"):\r\n error = data_json.get(\"error\")\r\n else:\r\n error = str(data_json)\r\n print(\"{0}Error al obtener las colas: {1}.{2}\".format(Fore.RED, error, Fore.RESET))\r\n\r\n sys.exit(1)\r\n\r\n\r\nresult = data_json.get(\"result\", {})\r\nfor host_name in sorted(result.keys()):\r\n\r\n # Para cada host, obtener la información de cada servidor\r\n server_configs = result.get(host_name, {}).get(\"server-config\", {})\r\n if server_configs:\r\n\r\n # Guess dns hostname\r\n dns_host_name = requests.post(\r\n jboss_management_url,\r\n auth=HTTPDigestAuth(jboss_admin_user, jboss_admin_pass),\r\n data=json.dumps({\r\n \"address\": [\r\n \"host\", host_name,\r\n \"core-service\", \"host-environment\",\r\n ],\r\n \"operation\": \"read-resource\",\r\n \"include-runtime\": True,\r\n }),\r\n headers={\"Content-Type\": \"application/json\"}\r\n ).json().get(\"result\").get(\"qualified-host-name\")\r\n\r\n for server_name in sorted(server_configs.keys()):\r\n\r\n payload = {\r\n \"operation\": \"read-resource\",\r\n \"include-runtime\": True,\r\n \"address\": [\r\n \"host\", host_name,\r\n \"server-config\", server_name,\r\n ],\r\n }\r\n server_data = requests.post(jboss_management_url, auth=HTTPDigestAuth(jboss_admin_user, jboss_admin_pass), data=json.dumps(payload), headers={\"Content-Type\": \"application/json\"}).json()[\"result\"]\r\n servers_data.append({\r\n \"host\": host_name,\r\n \"dnshostname\": dns_host_name,\r\n \"server\": server_name,\r\n \"group\": server_data.get(\"group\"),\r\n \"status\": server_data.get(\"status\"),\r\n \"offset\": server_data.get(\"socket-binding-port-offset\", 0),\r\n \"auto-start\": server_data.get(\"auto-start\"),\r\n })\r\n\r\n if host_name in hosts:\r\n hosts.remove(host_name)\r\n\r\n\r\nif args.dump_apache_conf:\r\n\r\n for server_data in servers_data:\r\n service_ip = socket.gethostbyname(server_data[\"dnshostname\"])\r\n print(\"\"\"\r\n ServerName jboss-{server}.{env}\r\n ProxyPass /IndraLog ajp://{service_ip}:{ajp_offset}/IndraLog\r\n ProxyPassReverse /IndraLog ajp://10.36.166.21:{ajp_offset}/IndraLog\r\n\"\"\".format(server=server_data[\"server\"], env=args.env, service_ip=service_ip, ajp_offset=server_data[\"offset\"]+8009))\r\n\r\nelse:\r\n\r\n cols = [\"Host\", \"Grupo\", \"Servidor\", \"Estado\", \"Auto-inicio\", \"Offset\", \"Puerto HTTP\", \"Puerto AJP\"]\r\n if args.include_indralog_urls:\r\n cols.append(\"IndraLOG URL\")\r\n\r\n t = PrettyTable(cols)\r\n t.align = \"l\"\r\n t.align[\"Offset\"] = \"r\"\r\n t.align[\"Puerto HTTP\"] = \"r\"\r\n t.align[\"Puerto AJP\"] = \"r\"\r\n for server_data in servers_data:\r\n\r\n if server_data[\"status\"] == \"STARTED\":\r\n status = \"{0}{1}{2}\".format(Fore.GREEN, \"Iniciado\", Fore.RESET)\r\n elif server_data[\"status\"] == \"STARTING\":\r\n status = \"{0}{1}{2}\".format(Fore.YELLOW, \"Arrancando\", Fore.RESET)\r\n elif server_data[\"status\"] == \"STOPPING\":\r\n status = \"{0}{1}{2}\".format(Fore.MAGENTA, \"Parando\", Fore.RESET)\r\n elif server_data[\"status\"] == \"STOPPED\":\r\n status = \"{0}{1}{2}\".format(Fore.RED, \"Parado\", Fore.RESET)\r\n elif server_data[\"status\"] == \"FAILED\":\r\n status = \"{0}{1}{2}\".format(Fore.RED, \"FALLO\", Fore.RESET)\r\n elif server_data[\"status\"] == \"DISABLED\":\r\n status = \"{0}{1}{2}\".format(Fore.BLUE, \"Deshabilitado\", Fore.RESET)\r\n else:\r\n status = \"{0}{1}{2}\".format(Fore.RED, server_data[\"status\"], Fore.RESET)\r\n\r\n data = [\r\n server_data[\"host\"],\r\n server_data[\"group\"],\r\n server_data[\"server\"],\r\n status,\r\n \"{0}{1}{2}\".format(Fore.GREEN if server_data[\"auto-start\"] else Fore.RED, \"Sí\" if server_data[\"auto-start\"] else \"No\", Fore.RESET),\r\n server_data[\"offset\"],\r\n server_data[\"offset\"] + 8080,\r\n server_data[\"offset\"] + 8009,\r\n ]\r\n if args.include_indralog_urls:\r\n data.append(\"http://jboss-{server}.{env}\".format(server=server_data[\"server\"], env=args.env))\r\n t.add_row(data)\r\n\r\n # Mostrar los hosts no encontrados\r\n for host in hosts:\r\n data = [\r\n \"{0}{1}{2}\".format(Fore.RED, host, Fore.RESET),\r\n \"-\",\r\n \"-\",\r\n \"{0}{1}{2}\".format(Fore.RED, \"Parado\", Fore.RESET),\r\n \"-\",\r\n \"-\",\r\n \"-\",\r\n \"-\",\r\n ]\r\n if args.include_indralog_urls:\r\n data.append(\"-\")\r\n t.add_row(data)\r\n\r\n print(t)\r\n","sub_path":"check_running_servers.py","file_name":"check_running_servers.py","file_ext":"py","file_size_in_byte":6801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"73827544","text":"from control.models import *\nfrom django import forms\nfrom decimal import Decimal\nfrom django.db.models import Sum\n\n\nclass RegionForm(forms.ModelForm):\n class Meta:\n model = Region\n fields = ['name']\n\n def __init__(self, form_update=False, *args, **kwargs):\n super(RegionForm, self).__init__(*args, **kwargs)\n self.form_update = form_update\n\n def clean(self):\n if not self.form_update:\n form_data = self.cleaned_data\n name = form_data.get(\"name\", None)\n if Region.objects.filter(name=name).exists():\n self._errors['name'] = \"This region exists\"\n\n def save(self, *args, **kwargs):\n region = super(RegionForm, self).save(*args, **kwargs)\n region.name = self.cleaned_data['name'].capitalize()\n region.save()\n return region\n\n\nclass BranchForm(forms.ModelForm):\n \"\"\"BranchForm definition.\"\"\"\n\n class Meta:\n model = Branch\n fields = [\n 'name',\n 'region',\n 'phone_number',\n 'street'\n ]\n\n def __init__(self, *args, **kwargs):\n super(BranchForm, self).__init__(*args, **kwargs)\n self.fields['region'].empty_label = \"Choose branch region\"\n\n def save(self, *args, **kwargs):\n branch = super(BranchForm, self).save(*args, **kwargs)\n branch.name = self.cleaned_data['name'].capitalize()\n branch.street = self.cleaned_data['street'].capitalize()\n branch.save()\n return branch\n\n\nclass AssetForm(forms.ModelForm):\n \"\"\"Form definition for Asset.\"\"\"\n\n class Meta:\n \"\"\"Meta definition for Assetform.\"\"\"\n\n model = Asset\n fields = [\n 'name',\n 'asset_number',\n 'condition',\n 'branch',\n 'description'\n ]\n\n def __init__(self, *args, **kwargs):\n super(AssetForm, self).__init__(*args, **kwargs)\n self.fields['name'].required = True\n self.fields['asset_number'].required = False\n self.fields['condition'].required = True\n self.fields['branch'].required = True\n self.fields['branch'].empty_label = \"Choose asset branch\"\n self.fields['description'].required = False\n\n def save(self, *args, **kwargs):\n asset = super(AssetForm, self).save(*args, **kwargs)\n asset.name = self.cleaned_data['name'].capitalize()\n asset.save()\n return asset\n\n\nclass UserTypeForm(forms.ModelForm):\n \"\"\"Form definition for UserType.\"\"\"\n\n class Meta:\n \"\"\"Meta definition for UserTypeform.\"\"\"\n\n model = UserType\n fields = ['name']\n\n def save(self, *args, **kwargs):\n utype = super(UserTypeForm, self).save(*args, **kwargs)\n utype.name = self.cleaned_data['name'].capitalize()\n utype.save()\n return utype\n\n\nclass AccountForm(forms.ModelForm):\n \"\"\"Form definition for Account.\"\"\"\n\n class Meta:\n \"\"\"Meta definition for Accountform.\"\"\"\n model = Account\n fields = ['name', 'number', 'branch','opening_balance']\n\n def __init__(self, form_update=False, *args, **kwargs):\n super(AccountForm, self).__init__(*args, **kwargs)\n self.fields['branch'].empty_label = \"Choose branch\"\n self.form_update = form_update\n self.fields['opening_balance'].required = False\n\n def clean(self):\n if not self.form_update:\n form_data = self.cleaned_data\n number = form_data.get(\"number\", None)\n if Account.objects.filter(number=number).exists():\n self._errors['number'] = \"This Account number exists\"\n\n def save(self, *args, **kwargs):\n account = super(AccountForm, self).save(*args, **kwargs)\n account.name = self.cleaned_data['name'].upper()\n account.number = self.cleaned_data['number']\n account.branch = self.cleaned_data['branch']\n account.opening_balance = self.cleaned_data['opening_balance']\n account.save()\n return account\n\n\nclass NotePadForm(forms.ModelForm):\n class Meta:\n model = NotePad\n fields = ['title', 'description', 'created_by', 'priority']\n\n def save(self, *args, **kwargs):\n notepad = super(NotePadForm, self).save(*args, **kwargs)\n notepad.title = self.cleaned_data['title'].upper()\n notepad.description = self.cleaned_data['description']\n notepad.created_by = self.cleaned_data['created_by']\n notepad.priority = self.cleaned_data['priority']\n notepad.save()\n return notepad\n\n\nPAYMENT_TYPE = (\n (\"Bank\", \"Bank\"),\n (\"Cash In Hand\", \"Cash In Hand\")\n)\n\n\nclass SalaryForm(forms.Form):\n payment_type = forms.ChoiceField(\n choices=PAYMENT_TYPE, initial=(\"Bank\", \"Bank\"))\n bank = forms.ModelChoiceField(queryset=Account.objects.filter(is_active=True), empty_label=None)\n\n def __init__(self, form_update=False, *args, **kwargs):\n super(SalaryForm, self).__init__(*args, **kwargs)\n self.fields['bank'].required = False\n self.fields['payment_type'].required = True\n\n\nclass AccountTransanctionForm(forms.ModelForm):\n class Meta:\n model = AccountTransaction\n fields = [\n 'amount',\n 'transanction_type',\n ]\n\n\nclass AccountTransferForm(forms.Form):\n amount = forms.DecimalField(min_value=1, required=True)\n to_account = forms.ModelChoiceField(queryset=Account.objects.filter(is_active=True))\n\n\n def __init__(self, account, *args, **kwargs):\n from control.account_calculations import total_account_amount\n super(AccountTransferForm, self).__init__(*args, **kwargs)\n self.account = account\n self.fields['to_account'].queryset = Account.objects.filter(is_active=True).exclude(id=self.account)\n self.fields['to_account'].empty_label = \"Choose Account to transfer\"\n self.fields['amount'].max_value = total_account_amount(self.account)\n\n def clean(self):\n form_data = self.cleaned_data\n amount = form_data.get(\"amount\", None)\n if amount:\n from control.account_calculations import total_account_amount\n if total_account_amount(self.account) < amount:\n self._errors['amount'] = \"Your balance is not enough!\"\n\nclass CashCollectionTransferForm(forms.Form):\n payment_method = forms.ModelChoiceField(queryset=Account.objects.filter(is_active=True))\n amount = forms.DecimalField()\n description = forms.CharField(widget=forms.Textarea())\n\n \n def __init__(self, *args, **kwargs):\n super(CashCollectionTransferForm, self).__init__(*args, **kwargs)\n self.fields['payment_method'].empty_label = \"Choose Account\"\n \n def clean(self):\n form_data = self.cleaned_data\n amount = form_data.get(\"amount\", None)\n from control.account_calculations import get_today_total_cash_amount,get_total_cash_on_hand\n if amount:\n if get_total_cash_on_hand() < amount:\n self._errors['amount'] = \"Your balance is not enough!\"\n\n\nclass AttendenceForm(forms.Form):\n attend = forms.BooleanField()\n time_in = forms.CharField()\n comment = forms.CharField(max_length=500)\n\n def __init__(self, *args, **kwargs):\n super(AttendenceForm, self).__init__(*args, **kwargs)\n self.fields['attend'].required = False\n self.fields['time_in'].required = False\n self.fields['comment'].required = False\n","sub_path":"control/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":7413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"95194339","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\n\r\nfrom mcpi.minecraft import Minecraft\r\n\r\nmc =Minecraft.create()\r\nx,y,z=mc.player.getTilePos()\r\n\r\ntry:\r\n block=int(input(\"你想要放尛方塊呢??\"))\r\n mc.setBlock(x,y,z,block)\r\nexcept:\r\n mc.postToChat(\"只能輸入數字啦(〝皿〞#)\")","sub_path":"talkbot.py","file_name":"talkbot.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"360829705","text":"# %%-----------------------------------------------------------------------\n# Loading required packages\nimport os, csv # For handling directories\nimport matplotlib\nmatplotlib.use('Agg')\n\nimport matplotlib.backends.backend_pdf\nimport matplotlib.pyplot as plt\nimport numpy as np # For storing data as numpy arrays\nimport pandas as pd\nimport timeit\nfrom pycm import *\nfrom mlxtend.evaluate import confusion_matrix\nfrom mlxtend.plotting import plot_confusion_matrix\n\n# %%-----------------------------------------------------------------------\n\n# importing torch packages\nimport torch\nimport torch.nn as nn\nimport torchvision.transforms as transforms\nfrom PIL import Image # For handling the images\nfrom sklearn.model_selection import train_test_split\nfrom torch.utils.data import Dataset\n\n# added code to unzip the data files in data folder\n\nif (not os.path.exists(\"./data\")):\n os.system(\"mkdir data\")\nos.system(\"tar -xf leapGestRecog.tar.gz -C ./data\")\n\n\n# This class to transform the data, so that it can be loaded to test Loader\nclass DatasetProcessing(Dataset):\n \"\"\"\n This function is used to initialise the class variables - transform, data, target\n\n \"\"\"\n\n def __init__(self, data, target, transform=None): #used to initialise the class variables - transform, data, target\n self.transform = transform\n self.data = data.reshape((-1, 120, 320)).astype(np.uint8)[:, :, :, None]\n self.target = torch.from_numpy(target).float() # needs to be in torch.LongTensor dtype\n\n def __getitem__(self, index): #used to retrieve the X and y index value and return it\n return self.transform(self.data[index]), self.target[index]\n\n def __len__(self): #returns the length of the data\n return len(list(self.data))\n\n\n# specify the model class\nclass CNN(nn.Module):\n '''\n Here we are using CNN model with three conv layers with maxpool\n and relu as transfer/activation function\n for fully connected layer again we have used relu activation function\n '''\n\n def __init__(self):\n super(CNN, self).__init__()\n self.layer1 = nn.Sequential(\n nn.Conv2d(1, 32, kernel_size=5, stride=2),\n nn.BatchNorm2d(32),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2))\n self.layer2 = nn.Sequential(\n nn.Conv2d(32, 64, kernel_size=3, stride=2),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2))\n self.layer3 = nn.Sequential(\n nn.Conv2d(64, 64, kernel_size=3, stride=2),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2))\n self.classifier = nn.Sequential(\n nn.Linear(256, 128),\n nn.ReLU(),\n nn.Linear(128, 10)\n )\n\n def forward(self, x):\n out = self.layer1(x)\n out = self.layer2(out)\n out = self.layer3(out)\n out = out.view(out.size(0), -1)\n out = self.classifier(out)\n return out\n\n\n\n# Train the Model\n\ndef train(model, device, train_loader, optimizer, criterion, epoch):\n model.train()\n loss_list = []\n for i, (images, labels) in enumerate(train_loader):\n images = images.to(device)\n labels = labels.to(device)\n labels = labels.long()\n labels = labels.view(-1, len(labels))[0]\n optimizer.zero_grad()\n outputs = model(images)\n outputs = outputs.float()\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n loss_list.append(loss.item())\n if i % 10 == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, i * len(images), len(train_loader.dataset),\n 100. * i / len(train_loader), loss.item()))\n # Save the model checkpoint\n torch.save(model.state_dict(), '../model/model_trained.pth')\n\n return loss_list\n\n # plt.plot(loss_list)\n # plt.show()\n\n# Validate the model\n\ndef validate(model, device, validate_loader, criterion, epoch):\n model.eval()\n loss_list = []\n with torch.no_grad():\n for i, (images, labels) in enumerate(validate_loader):\n images = images.to(device)\n labels = labels.to(device)\n labels = labels.long()\n labels = labels.view(-1, len(labels))[0]\n outputs = model(images)\n outputs = outputs.float()\n loss = criterion(outputs, labels)\n loss_list.append(loss.item())\n if i % 10 == 0:\n print('Validation Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, i * len(images), len(validate_loader.dataset),\n 100. * i / len(validate_loader), loss.item()))\n\n return loss_list\n\n\ndef main():\n # specify device and choose gpu if it's available\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n print('Using device:', device)\n\n lookup = dict()\n reverselookup = dict()\n count = 0\n for j in os.listdir('./data/leapGestRecog/00/'):\n if not j.startswith('.'): # If running this code locally, this is to\n # ensure you aren't reading in hidden folders\n lookup[j] = count\n reverselookup[count] = j\n count = count + 1\n print(lookup)\n\n classes = (lookup.keys())\n\n x_data = []\n label_data = []\n imagecount = 0 # total Image count\n for i in range(0, 10): # Loop over the ten top-level folders\n for j in os.listdir('./data/leapGestRecog/0' + str(i) + '/'):\n if not j.startswith('.'): # Again avoid hidden folders\n count = 0 # To tally images of a given gesture\n # loop over the images\n # read in and convert to greyscale\n for k in os.listdir('./data/leapGestRecog/0' + str(i) + '/' + j + '/'):\n img = Image.open('./data/leapGestRecog/0' +\n str(i) + '/' + j + '/' + k).convert('L')\n img = img.resize((320, 120))\n arr = np.array(img)\n x_data.append(arr)\n count = count + 1\n\n y_values = np.full((count, 1), lookup[j])\n label_data.append(y_values)\n imagecount = imagecount + count\n\n x_data = np.array(x_data, dtype='float32')\n label_data = np.array(label_data)\n label_data = label_data.reshape(imagecount, 1) # Reshape to be the correct size\n\n # check the shape of train data\n print(\"Total Data shape\", x_data.shape)\n print(\"Total labels shape\", label_data)\n\n # divide the data into train, validation and test\n x_train, x_valid_test, y_train, y_valid_test = train_test_split(x_data, label_data, test_size=0.3)\n x_validate, x_test, y_validate, y_test = train_test_split(x_valid_test, y_valid_test, test_size=0.5)\n\n # check the shape of train data\n print(\"Train Data shape=\", x_train.shape)\n print(\"Train Labels shape=\", y_train.shape)\n\n # check the shape of validation data\n print(\"Validation data shape=\", x_validate.shape)\n print(\"Validation labels shape=\", y_validate.shape)\n\n # check the shape of test data\n print(\"Test data shape=\", x_test.shape)\n print(\"Test data label=\", y_test.shape)\n\n\n batch_size_list = [64]\n\n results = {}\n resultsDF = []\n f1DF = []\n\n for BATCH_SIZE in batch_size_list:\n\n # specify the transformation\n transform = transforms.Compose(\n [transforms.ToPILImage(), transforms.ToTensor(), transforms.Normalize(mean=(0.5,), std=(0.5,))])\n # perform the pre-processing on train data\n data_train = DatasetProcessing(x_train, y_train, transform)\n # load the train data\n train_loader = torch.utils.data.DataLoader(data_train, batch_size=BATCH_SIZE, shuffle=True, num_workers=4)\n\n # specify the transformation\n transform = transforms.Compose(\n [transforms.ToPILImage(), transforms.ToTensor(), transforms.Normalize(mean=(0.5,), std=(0.5,))])\n data_validate = DatasetProcessing(x_validate, y_validate, transform)\n validate_loader = torch.utils.data.DataLoader(data_validate, batch_size=BATCH_SIZE, shuffle=True, num_workers=4)\n\n # specify the transformation\n transform = transforms.Compose(\n [transforms.ToPILImage(), transforms.ToTensor(), transforms.Normalize(mean=(0.5,), std=(0.5,))])\n data_test = DatasetProcessing(x_test, y_test, transform)\n test_loader = torch.utils.data.DataLoader(data_test, batch_size=BATCH_SIZE, shuffle=True, num_workers=4)\n\n # specify the number of epochs and learning rate\n learning_rate_list = [0.001]\n optimizer_functions_list = ['Adam']\n\n for LEARNING_RATE in learning_rate_list:\n\n for OPTIMIZER in optimizer_functions_list:\n # create instance of model\n model = CNN().to(device)\n criterion = nn.CrossEntropyLoss()\n\n if OPTIMIZER == 'SGD':\n optimizer = torch.optim.SGD(model.parameters(), lr=LEARNING_RATE)\n elif OPTIMIZER == 'ASGD':\n optimizer = torch.optim.ASGD(model.parameters(), lr=LEARNING_RATE)\n elif OPTIMIZER == 'Adam':\n optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE)\n elif OPTIMIZER == 'Adagrad':\n optimizer = torch.optim.Adagrad(model.parameters(), lr=LEARNING_RATE)\n elif OPTIMIZER == 'Adadelta':\n optimizer = torch.optim.Adadelta(model.parameters(), lr=LEARNING_RATE)\n elif OPTIMIZER == 'RMSProp':\n optimizer = torch.optim.RMSprop(model.parameters(), lr=LEARNING_RATE)\n\n number_epochs_list = [2]\n\n for NUM_EPOCHS in number_epochs_list:\n training_loss = []\n validation_loss = []\n mean_training_loss = []\n mean_validation_loss = []\n\n for epoch in range(1, NUM_EPOCHS + 1):\n start = timeit.default_timer()\n train_loss = train(model, device, train_loader, optimizer, criterion, epoch)\n stop = timeit.default_timer()\n val_loss = validate(model, device, validate_loader, criterion, epoch)\n training_loss = training_loss + train_loss\n validation_loss = validation_loss + val_loss\n mean_training_loss = mean_training_loss + [np.mean(train_loss)]\n mean_validation_loss = mean_validation_loss + [np.mean(val_loss)]\n accuracy, testing_loss, cm, cm1 = test(model, device, test_loader, criterion, epoch)\n\n fig1 = plt.figure(figsize=(12, 8))\n plt.plot(training_loss)\n plt.plot(validation_loss)\n plt.xlabel(\"batch samples\", fontsize=20)\n plt.ylabel(\"loss\", fontsize=20)\n plt.legend(['training loss', 'validation loss'], loc='upper right', fontsize=20)\n plt.title(\"batch-wise training and validation loss for batch size=\" + str(BATCH_SIZE)\n + \", lr=\" + str(LEARNING_RATE) +\n \", optimizer=\" + str(OPTIMIZER) + \", num_epochs=\" + str(NUM_EPOCHS), fontsize=15)\n # plt.show()\n fig1.savefig(\"batchwise_training_validation_loss_\" + str(BATCH_SIZE) + \"_\" + str(LEARNING_RATE) +\n \"_\" + str(OPTIMIZER) + \"_\" + str(NUM_EPOCHS) + \".png\")\n\n fig2 = plt.figure(figsize=(12, 8))\n plt.plot(mean_training_loss)\n plt.plot(mean_validation_loss)\n plt.xlabel(\"epochs\", fontsize=20)\n plt.ylabel(\"mean loss\", fontsize=20)\n plt.legend(['mean training loss', 'mean validation loss'], loc='upper right', fontsize=20)\n # plt.show()\n plt.title(\"epoch-wise mean training and validation loss for batch size=\" + str(BATCH_SIZE) +\n \", lr=\" + str(LEARNING_RATE) +\n \", optimizer=\" + str(OPTIMIZER) + \", num_epochs=\" + str(NUM_EPOCHS), fontsize=15)\n fig2.savefig(\n \"epochwise_mean_training_validation_loss_\" + str(BATCH_SIZE) + \"_\" + str(LEARNING_RATE) +\n \"_\" + str(OPTIMIZER) + \"_\" + str(NUM_EPOCHS) + \".png\")\n\n fig3 = plt.figure(figsize=(12, 8))\n plt.plot(training_loss)\n plt.xlabel(\"batch samples\", fontsize=20)\n plt.ylabel(\"loss\", fontsize=20)\n plt.legend(['testing loss'], loc='upper right', fontsize=20)\n plt.title(\"testing loss for batch size=\" + str(BATCH_SIZE)\n + \", lr=\" + str(LEARNING_RATE) +\n \", optimizer=\" + str(OPTIMIZER) + \", num_epochs=\" + str(NUM_EPOCHS), fontsize=15)\n # plt.show()\n fig3.savefig(\"testing_loss_\" + str(BATCH_SIZE) + \"_\" + str(LEARNING_RATE) +\n \"_\" + str(OPTIMIZER) + \"_\" + str(NUM_EPOCHS) + \".png\")\n\n fig4, ax = plot_confusion_matrix(conf_mat=cm)\n # plt.show()\n\n print(type(cm1.F1))\n print(\"f1\", cm1.F1)\n\n fig4.savefig(\"confusion_matrix_\" + str(BATCH_SIZE) + \"_\" + str(LEARNING_RATE) +\n \"_\" + str(OPTIMIZER) + \"_\" + str(NUM_EPOCHS) + \".png\")\n\n results[(BATCH_SIZE, LEARNING_RATE, OPTIMIZER, NUM_EPOCHS)] = (\n round(stop - start, 2), round(accuracy, 2))\n\n print(results)\n\n pdf = matplotlib.backends.backend_pdf.PdfPages(\"output.pdf\")\n for fig in range(1, plt.gcf().number + 1): ## will open an empty extra figure\n pdf.savefig(fig)\n pdf.close()\n\n df = pd.DataFrame(list(results.items()))\n df_parameters = pd.DataFrame(df.iloc[:, 0].tolist(),\n columns=['batch_size', 'learning_rate', 'optimizer_method',\n 'num_epochs'])\n df_obs = pd.DataFrame(df.iloc[:, 1].tolist(), columns=['time', 'accuracy'])\n df_final = pd.concat([df_parameters, df_obs], axis=1)\n\n df_final.to_csv(\"df_final.csv\")\n\n df_f1 = pd.DataFrame(list(cm1.F1.items()), columns=['labels', 'f1_score'])\n\n resultsDF.append(df_final)\n f1DF.append(df_f1)\n\n df_results = pd.concat(resultsDF)\n\n df_results = df_results.drop_duplicates(keep='first', inplace=False)\n df_results.to_csv(\"results.csv\")\n\n df_f1_results = pd.concat(f1DF)\n df_f1_results.to_csv(\"f1_score_results.csv\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"model/train_model.py","file_name":"train_model.py","file_ext":"py","file_size_in_byte":15280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"419057516","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nimport torch\nfrom torchvision import transforms\nfrom torch.autograd import Variable\nfrom torchvision import datasets\n\n\ntest_transforms = transforms.Compose([transforms.Resize(64), transforms.ToTensor(),transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ])\nto_pil = transforms.ToPILImage()\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nmodel=torch.load('./cricket-model-Alexnet-1.pth',map_location={'cuda:0': 'cpu'})\ndata_dir = './trainc'\n\n\ndef get_random_images(num):\n data = datasets.ImageFolder(data_dir, transform=test_transforms)\n classes = data.classes\n indices = list(range(len(data)))\n np.random.shuffle(indices)\n idx = indices[:num]\n from torch.utils.data.sampler import SubsetRandomSampler\n sampler = SubsetRandomSampler(idx)\n loader = torch.utils.data.DataLoader(data, \n sampler=sampler, batch_size=num)\n dataiter = iter(loader)\n images, labels = dataiter.next()\n return images, labels, classes\n\n\ndef predict_image(image):\n\timage_tensor = test_transforms(image).float()\n\timage_tensor = image_tensor.unsqueeze_(0)\n\tinput = Variable(image_tensor)\n\toutput = model(input)\n\tindex = output.data.cpu().numpy().argmax()\n\treturn index\n\nlp,ln,rp,rn = 0,0,0,0\nimages, labels, classes = get_random_images(1000)\nfor ii in range(len(images)):\n image = to_pil(images[ii])\n index = predict_image(image)\n res = int(labels[ii]) == index\n if res == True:\n if index == 0:\n lp=lp+1\n if index == 1:\n rp=rp+1\n else:\n if index == 0:\n ln=ln+1\n if index == 1:\n rn=rn+1\n\n\nprint(lp,ln,rp,rn)\nprint(f'Accuracy = {((lp+rp)/(lp+rp+ln+rn))*100}')\nprint(f'False positive = {((ln)/(lp+rp+ln+rn))*100}')\n\n\n\n","sub_path":"Test_the_Alex.py","file_name":"Test_the_Alex.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"177874385","text":"# Definition for a binary tree node\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n # @param num, a list of integers\n # @return a tree node\n def sortedArrayToBST(self, num):\n length = len(num)\n if length == 1:\n return TreeNode(num[0])\n elif length == 0:\n return None\n else:\n mid = length / 2\n node = TreeNode(num[mid])\n node.left = self.sortedArrayToBST(num[:mid])\n node.right = self.sortedArrayToBST(num[mid + 1:]) \n return node\n\nif __name__ == \"__main__\":\n ins = Solution()\n num = [1,2,3,4,5,6,7,8,9]\n\n node = ins.sortedArrayToBST(num)\n input()","sub_path":"Python/LeetCode/LeetCode/sortedArrayToBST.py","file_name":"sortedArrayToBST.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"559341831","text":"#!/usr/bin/python\r\n\r\n\"\"\"\r\nAuthor: S M Al Mahi\r\nCS5793: Artificial Intelligence II\r\nAssignment 4: Part 2 K Means\r\n\"\"\"\r\n\r\nfrom __future__ import print_function\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef mnist_data(fname):\r\n \"\"\"\r\n Read data from MNIST file\r\n :param fname: MNIST file path\r\n :return: MNIST data\r\n :rtype: np.ndarray\r\n \"\"\"\r\n with open(fname, 'rb') as training_images_file:\r\n training_images = training_images_file.read()\r\n training_images = bytearray(training_images)\r\n training_images = training_images[16:]\r\n training_images = np.array(training_images, dtype=\"float64\")\r\n data_size = training_images.shape[0]\r\n image_size = 28 * 28\r\n num_of_img = int(data_size / image_size)\r\n # figure, axes = plt.subplots(nrows=10, ncols=10)\r\n # ind = 1\r\n # print(training_images.shape, image_size, num_of_img)\r\n # for axis in axes.flat:\r\n # axis.imshow(training_images[(ind-1) * image_size: ind * image_size].reshape(28, 28), cmap='bone')\r\n # axis.set_axis_off()\r\n # ind += 1\r\n # plt.show()\r\n return training_images.reshape((num_of_img, image_size))\r\n\r\n\r\ndef mnist_labels(fname):\r\n \"\"\"\r\n Read labels from MNIST file\r\n :param fname: MNIST file path\r\n :return: MNIST labels in shape (N, 1)\r\n :rtype: np.ndarray\r\n \"\"\"\r\n with open(fname, 'rb') as training_label_file:\r\n training_labels = training_label_file.read()\r\n training_labels = bytearray(training_labels)\r\n training_labels = training_labels[8:]\r\n training_labels = np.array(training_labels)\r\n num_of_labels = training_labels.shape[0]\r\n return training_labels.reshape(num_of_labels, 1)\r\n\r\n\r\ndef init_mu(x, y, K):\r\n N = x.shape[0]\r\n M = x[0].shape[0]\r\n mu = np.zeros(shape=(K, M))\r\n for i in range(K):\r\n mu[i] = x[np.random.randint(low=0, high=N)]\r\n done = [False for i in range(K)]\r\n ind = np.random.randint(low=0, high=N, size=N)\r\n np.random.shuffle(ind)\r\n x = x[ind]\r\n y = y[ind]\r\n for i in range(N):\r\n min_d = np.inf\r\n min_k = -1\r\n for k in range(K):\r\n if np.linalg.norm(mu[k] - x[i]) < min_d:\r\n min_d = np.linalg.norm(mu[k] - x[i])\r\n min_k = k\r\n if min_k == -1: continue\r\n if not done[min_k]:\r\n mu[min_k] = x[i]\r\n done[min_k] = True\r\n if sum(done) == K:\r\n break\r\n return mu\r\n\r\n\r\ndef init_cheat_mu(x, y, K):\r\n N = x.shape[0]\r\n M = x[0].shape[0]\r\n mu = np.zeros(shape=(K, M))\r\n taken = np.zeros(N, dtype='bool')\r\n\r\n ind = np.random.randint(low=0, high=N, size=N)\r\n np.random.shuffle(ind)\r\n x = x[ind]\r\n y = y[ind]\r\n for i in range(K):\r\n for j in range(y.shape[0]):\r\n if i == y[j] and not taken[j]:\r\n mu[i] = x[j]\r\n taken[j] = True\r\n break\r\n return mu\r\n\r\n\r\ndef k_means(K, x, mu):\r\n \"\"\"\r\n :type x: np.ndarray\r\n :type mu: np.ndarray\r\n :rtype Z: np.ndarray\r\n :rtype Z: np.ndarray\r\n \"\"\"\r\n print(\"K Means:\")\r\n N = x.shape[0]\r\n limit = 100\r\n Z = np.zeros(shape=(N, K))\r\n for t in range(limit):\r\n changed = False\r\n for i in range(N):\r\n min_d = np.inf\r\n min_k = 0\r\n for k in range(K):\r\n d = np.linalg.norm(mu[k] - x[i])\r\n if d < min_d:\r\n min_d = d\r\n min_k = k\r\n if Z[i, min_k] != 1.:\r\n Z[i, :] = 0.\r\n Z[i, min_k] = 1.\r\n changed = True\r\n\r\n if not changed:\r\n break\r\n\r\n cost = 0.\r\n for k in range(K):\r\n ind = np.where(Z[:, k] == 1.)[0]\r\n # slow code because of vstack\r\n # cluster = x[ind[0]]\r\n # for i in range(1, len(ind)):\r\n # cluster = np.vstack((cluster, x[ind[i]]))\r\n cluster = np.zeros(x[0].shape)\r\n for i in range(len(ind)):\r\n cluster += x[ind[i]]\r\n mu[k] = cluster / float(len(ind))\r\n\r\n for i in range(cluster.shape[0]):\r\n cost += np.linalg.norm(mu[k]-cluster[i])\r\n print(\"#{} cost={}\".format(t, cost))\r\n\r\n return Z, mu\r\n\r\n\r\nif __name__ == \"__main__\":\r\n x = mnist_data('t10k-images-idx3-ubyte.idx3-ubyte')\r\n y = mnist_labels('t10k-labels-idx1-ubyte.idx1-ubyte')\r\n y_hat = np.zeros(y.shape)\r\n N = x.shape[0]\r\n M = x[0].shape[0]\r\n K = 10\r\n Z = np.zeros(shape=(N, K))\r\n\r\n # init mu\r\n mu1 = x[np.random.randint(low=0, high=N, size=K)]\r\n mu2 = init_mu(x, y, K)\r\n mu3 = init_cheat_mu(x, y, K)\r\n\r\n figure, axes = plt.subplots(nrows=5, ncols=2)\r\n ind = 1\r\n for axis in axes.flat:\r\n axis.imshow(mu1[ind-1, :].reshape(28, 28), cmap='bone')\r\n axis.set_axis_off()\r\n ind += 1\r\n plt.suptitle(\"centroid for randomly chosen $\\mu$\")\r\n plt.savefig(\"kmeans1.png\", format='png')\r\n plt.show()\r\n\r\n figure, axes = plt.subplots(nrows=5, ncols=2)\r\n ind = 1\r\n for axis in axes.flat:\r\n axis.imshow(mu2[ind-1, :].reshape(28, 28), cmap='bone')\r\n axis.set_axis_off()\r\n ind += 1\r\n plt.suptitle(\"centroid chosen by K-means++\")\r\n plt.savefig(\"kmeans2.png\", format='png')\r\n plt.show()\r\n\r\n figure, axes = plt.subplots(nrows=5, ncols=2)\r\n ind = 1\r\n for axis in axes.flat:\r\n axis.imshow(mu3[ind-1, :].reshape(28, 28), cmap='bone')\r\n axis.set_axis_off()\r\n ind += 1\r\n plt.suptitle(\"centroid chosen by seeing label\")\r\n plt.savefig(\"kmeans3.png\", format='png')\r\n plt.show()\r\n\r\n\r\n\r\n Z1, m1 =k_means(K, x, mu1)\r\n\r\n figure, axes = plt.subplots(nrows=5, ncols=2)\r\n ind = 1\r\n for axis in axes.flat:\r\n axis.imshow(m1[ind-1].reshape(28, 28), cmap='bone')\r\n axis.set_axis_off()\r\n ind += 1\r\n plt.suptitle(\"K-means centroid for randomly chosen $\\mu$\")\r\n plt.savefig(\"kmeans4.png\", format='png')\r\n plt.show()\r\n\r\n Z2, m2 =k_means(K, x, mu2)\r\n figure, axes = plt.subplots(nrows=5, ncols=2)\r\n ind = 1\r\n for axis in axes.flat:\r\n axis.imshow(m2[ind-1].reshape(28, 28), cmap='bone')\r\n axis.set_axis_off()\r\n ind += 1\r\n plt.suptitle(\"K-means centroid chosen by K-means++\")\r\n plt.savefig(\"kmeans5.png\", format='png')\r\n plt.show()\r\n\r\n Z3, m3 =k_means(K, x, mu3)\r\n\r\n figure, axes = plt.subplots(nrows=5, ncols=2)\r\n ind = 1\r\n for axis in axes.flat:\r\n axis.imshow(m3[ind-1].reshape(28, 28), cmap='bone')\r\n axis.set_axis_off()\r\n ind += 1\r\n plt.suptitle(\"K-means centroid chosen by seeing label\")\r\n plt.savefig(\"kmeans6.png\", format='png')\r\n plt.show()\r\n\r\n Z4, m4 =k_means(3, x, mu2)\r\n ind0 = np.asarray(np.where(Z4[:, 0] == 1), dtype='int')[0]\r\n ind1 = np.asarray(np.where(Z4[:, 1] == 1), dtype='int')[0]\r\n ind2 = np.asarray(np.where(Z4[:, 2] == 1), dtype='int')[0]\r\n\r\n np.random.shuffle(ind0)\r\n np.random.shuffle(ind1)\r\n np.random.shuffle(ind2)\r\n\r\n figure, axes = plt.subplots(nrows=3, ncols=10)\r\n axes.flat[0].imshow(m4[0].reshape(28, 28), cmap='bone')\r\n axes.flat[0].set_xticks([])\r\n axes.flat[0].set_yticks([])\r\n axes.flat[0].set_title(\"Means\")\r\n axes.flat[0].set_ylabel(\"k=0\", rotation='horizontal')\r\n for i in range(1, 10, 1):\r\n axes.flat[i].imshow(x[ind0[i]].reshape(28, 28), cmap='bone')\r\n axes.flat[i].set_axis_off()\r\n axes.flat[10].imshow(m4[1].reshape(28, 28), cmap='bone')\r\n axes.flat[10].set_axis_off()\r\n axes.flat[10].set_title(\"k=1\", loc='left')\r\n for i in range(11, 20, 1):\r\n axes.flat[i].imshow(x[ind1[i-11]].reshape(28, 28), cmap='bone')\r\n axes.flat[i].set_axis_off()\r\n axes.flat[20].imshow(m4[2].reshape(28, 28), cmap='bone')\r\n axes.flat[20].set_axis_off()\r\n axes.flat[20].set_title(\"k=2\")\r\n for i in range(21, 30, 1):\r\n axes.flat[i].imshow(x[ind2[i-21]].reshape(28, 28), cmap='bone')\r\n axes.flat[i].set_axis_off()\r\n plt.suptitle(\"centroid chosen by seting K = 3\")\r\n plt.savefig(\"kmeans7.png\", format='png')\r\n plt.show()","sub_path":"assn4_kmenas_mahi.py","file_name":"assn4_kmenas_mahi.py","file_ext":"py","file_size_in_byte":8107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"218330901","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('portaldata', '0005_defaults_added'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='conducted_classes',\n name='date',\n field=models.DateField(default=datetime.date(2015, 11, 15)),\n ),\n ]\n","sub_path":"attendence/portaldata/migrations/0006_auto_20151115_1213.py","file_name":"0006_auto_20151115_1213.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"195982548","text":"from __future__ import absolute_import\n\nimport uuid\n\nimport mock\n\nfrom .helper import SolveBioTestCase\nfrom solvebio.test.client_mocks import fake_object_create, fake_object_save\nfrom solvebio.test.client_mocks import fake_dataset_create\n\n\nclass ObjectTests(SolveBioTestCase):\n\n def test_object_paths(self):\n vaults = self.client.Vault.all()\n for vault in vaults:\n for file_ in list(vault.ls().solve_objects())[:5]:\n o_path, _ = self.client.Object.validate_full_path(\n file_.full_path)\n self.assertEqual(o_path, file_.full_path)\n\n # assert path is gettable\n self.client.Object.get_by_full_path(o_path)\n\n with self.assertRaises(Exception):\n self.client.Object.get_by_full_path('what/is/this')\n\n def test_object_output(self):\n\n case = 'acme:myVault/uploads_folder'\n expected = 'acme:myVault:/uploads_folder'\n p, path_dict = self.client.Object.validate_full_path(case)\n\n self.assertEqual(p, expected)\n self.assertEqual(path_dict['full_path'], expected)\n self.assertEqual(path_dict['path'], '/uploads_folder')\n self.assertEqual(path_dict['parent_path'], '/')\n self.assertEqual(path_dict['parent_full_path'], 'acme:myVault:/')\n self.assertEqual(path_dict['filename'], 'uploads_folder')\n self.assertEqual(path_dict['domain'], 'acme')\n self.assertEqual(path_dict['vault'], 'myVault')\n self.assertEqual(path_dict['vault_full_path'], 'acme:myVault')\n\n def test_object_path_cases(self):\n\n user = self.client.User.retrieve()\n domain = user.account.domain\n user_vault = '{0}:user-{1}'.format(domain, user.id)\n test_cases = [\n ['acme:myVault:/uploads_folder', 'acme:myVault:/uploads_folder'],\n ['acme:myVault/folder1/project: ABCD',\n 'acme:myVault:/folder1/project: ABCD'],\n ['myVault/folder1/project: ABCD',\n '{0}:myVault:/folder1/project: ABCD'.format(domain)],\n ['myVault:/uploads_folder', '{0}:myVault:/uploads_folder'.format(domain)], # noqa\n # New full path formats\n ['~/uploads_folder', '{0}:/uploads_folder'.format(user_vault)],\n ['~/', '{0}:/'.format(user_vault)],\n ['myVault/uploads_folder', '{0}:myVault:/uploads_folder'.format(domain)], # noqa\n ['acme:myVault/uploads_folder', 'acme:myVault:/uploads_folder'],\n ]\n for case, expected in test_cases:\n p, _ = self.client.Object.validate_full_path(case)\n self.assertEqual(p, expected)\n\n error_test_cases = [\n '',\n '/hello',\n 'myVault',\n 'oops:myDomain:myVault',\n '{0}:myVault'.format(domain),\n 'acme:myVault'\n ]\n for case in error_test_cases:\n with self.assertRaises(Exception):\n v, v_paths = self.client.Object.validate_full_path(case)\n\n def test_object_path_cases_with_overrides(self):\n user = self.client.User.retrieve()\n domain = user.account.domain\n user_vault = '{0}:user-{1}'.format(domain, user.id)\n\n test_cases = [\n 'acme:myVault:/folder',\n 'myVault:/folder',\n 'myVault/folder',\n '/folder',\n ]\n\n for case in test_cases:\n p, _ = self.client.Object.validate_full_path(case, vault='foobar')\n expected = '{0}:foobar:/folder'.format(domain)\n self.assertEqual(p, expected)\n\n p, _ = self.client.Object.validate_full_path(case, vault='foo:bar')\n expected = 'foo:bar:/folder'\n self.assertEqual(p, expected)\n\n p, _ = self.client.Object.validate_full_path(\n case, vault='foo:bar', path='/baz')\n expected = 'foo:bar:/baz'\n self.assertEqual(p, expected)\n\n p, _ = self.client.Object.validate_full_path(\n case, vault='foo:bar', path='/baz/bon')\n expected = 'foo:bar:/baz/bon'\n self.assertEqual(p, expected)\n\n # Test cases where just the path changes\n case = 'acme:myVault:/folder'\n p, _ = self.client.Object.validate_full_path(case, path='foo/bar/baz')\n expected = 'acme:myVault:/foo/bar/baz'\n self.assertEqual(p, expected)\n\n case = '~/folder'\n p, _ = self.client.Object.validate_full_path(case, path='foo/bar/baz')\n expected = '{0}:/foo/bar/baz'.format(user_vault)\n self.assertEqual(p, expected)\n\n @mock.patch('solvebio.resource.Object.create')\n def test_object_has_tag(self, ObjectMock):\n ObjectMock.side_effect = fake_object_create\n\n tags = [\"foo\", \"bar\", \"BIZ\"]\n obj = self.client.Object.create(name='blah', tags=tags)\n self.assertEqual(obj.tags, tags)\n self.assertTrue(obj.has_tag(\"FOO\"))\n self.assertTrue(obj.has_tag(\"foo\"))\n self.assertTrue(obj.has_tag(\"BAr\"))\n self.assertTrue(obj.has_tag(\"BAr\"))\n self.assertTrue(obj.has_tag(\"biz\"))\n self.assertFalse(obj.has_tag(\"BAz\"))\n self.assertFalse(obj.has_tag(\"baz\"))\n\n obj = self.client.Object.create(name='blah_untagged')\n self.assertEqual(obj.tags, [])\n self.assertFalse(obj.has_tag(\"foo\"))\n\n @mock.patch('solvebio.resource.Dataset.create')\n @mock.patch('solvebio.resource.Object.create')\n def test_object_dataset_getattr(self, ObjectCreate, DatasetCreate):\n ObjectCreate.side_effect = fake_object_create\n DatasetCreate.side_effect = fake_dataset_create\n\n valid_attrs = [\n 'query', 'lookup', 'beacon',\n 'import_file', 'export', 'migrate',\n 'fields', 'template', 'imports', 'commits',\n 'activity', 'saved_queries'\n ]\n\n ds = self.client.Dataset.create(name='foo')\n ds_obj = self.client.Object.create(name='foo_dataset',\n object_type='dataset')\n file_ = self.client.Object.create(name='foo_file',\n object_type='file')\n folder_ = self.client.Object.create(name='foo_folder',\n object_type='folder')\n for attr in valid_attrs:\n self.assertTrue(getattr(ds, attr))\n self.assertTrue(getattr(ds_obj, attr))\n with self.assertRaises(AttributeError):\n getattr(file_, attr)\n with self.assertRaises(AttributeError):\n getattr(folder_, attr)\n\n # Test that any old attr doesnt work\n fake_attr = 'foobar'\n for obj in [file_, folder_, ds, ds_obj]:\n with self.assertRaises(AttributeError):\n getattr(obj, fake_attr)\n\n @mock.patch('solvebio.resource.Object.create')\n @mock.patch('solvebio.resource.Object.save')\n def test_object_remove_tag(self, ObjectCreate, ObjectSave):\n ObjectCreate.side_effect = fake_object_create\n ObjectSave.side_effect = fake_object_save\n\n tags = ['tag1', 'tag2', 'tag3']\n file_ = self.client.Object.create(filename='foo_file',\n object_type='file',\n tags=tags)\n for tag in tags:\n self.assertTrue(file_.has_tag(tag))\n\n tags_for_removal = ['tag1', 'tag2']\n file_.tag(tags=tags_for_removal, remove=True, apply_save=True)\n\n # test that given tags are removed\n for tag in tags_for_removal:\n self.assertFalse(file_.has_tag(tag))\n\n updated_tags = [tag for tag in tags if tag not in tags_for_removal]\n\n # test that tags which have not been removed are still there\n for tag in updated_tags:\n self.assertTrue(file_.has_tag(tag))\n\n @mock.patch('solvebio.resource.Object.create')\n @mock.patch('solvebio.resource.Object.save')\n def test_object_untag(self, ObjectCreate, ObjectSave):\n ObjectCreate.side_effect = fake_object_create\n ObjectSave.side_effect = fake_object_save\n\n tags = ['tag1', 'tag2', 'tag3']\n file_ = self.client.Object.create(filename='foo_file',\n object_type='file',\n tags=tags)\n for tag in tags:\n self.assertTrue(file_.has_tag(tag))\n\n tags_for_untagging = ['tag1', 'tag2']\n file_.untag(tags=tags_for_untagging, apply_save=True)\n\n # test that given tags are untagged\n for tag in tags_for_untagging:\n self.assertFalse(file_.has_tag(tag))\n\n updated_tags = [tag for tag in tags if tag not in tags_for_untagging]\n\n # test that tags which have not been untagged are still there\n for tag in updated_tags:\n self.assertTrue(file_.has_tag(tag))\n\n @mock.patch('solvebio.resource.Object.create')\n @mock.patch('solvebio.resource.Object.save')\n def test_object_add_tag_non_iterable_or_string(self, ObjectCreate, ObjectSave):\n ObjectCreate.side_effect = fake_object_create\n ObjectSave.side_effect = fake_object_save\n\n # test that a string is added propery\n tags = 'tag1'\n file_ = self.client.Object.create(filename='foo_file',\n object_type='file')\n file_.tag(tags)\n self.assertTrue(file_.has_tag(tags))\n\n # test that non iterable (e.g. integer) added properly\n tags = 1\n file_.tag(tags)\n self.assertTrue(file_.has_tag(tags))\n\n def test_object_set_metadata(self):\n folder = self.client.Object.\\\n get_or_create_by_full_path('~/{}'.format(uuid.uuid4()), object_type='folder')\n metadata = folder.metadata\n\n metadata['foo_1'] = 'bar_1'\n folder.save()\n\n # Test that item has been set successfully\n self.assertTrue(metadata.get('foo_1') == 'bar_1')\n\n metadata = {'foo_2': 'bar_2'}\n self.assertTrue(metadata.get('foo_2') == 'bar_2')\n\n # Test that direct assignement overrides SolveBio object type with the given dictionary\n self.assertTrue(len(metadata) == 1 and\n metadata.pop('foo_2') == 'bar_2' and\n len(metadata) == 0)\n\n folder.delete(force=True)\n\n def test_object_set_metadata_empty_dict_list(self):\n folder = self.client.Object. \\\n get_or_create_by_full_path('~/{}'.format(uuid.uuid4()), object_type='folder')\n\n folder.metadata['foo'] = 'bar'\n folder.save()\n\n folder.metadata = {}\n folder.save()\n\n # Test that 'metadata' is an empty dict\n self.assertTrue(folder.metadata == {})\n\n folder.metadata = []\n folder.save()\n\n # Test that 'metadata' is an empty list\n self.assertTrue(folder.metadata == [])\n\n folder.delete(force=True)\n","sub_path":"solvebio/test/test_object.py","file_name":"test_object.py","file_ext":"py","file_size_in_byte":10882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"376714335","text":"import time\nimport unittest\n\nfrom selenium.common import exceptions\n\nfrom SI.Report.Click_on_xaxis_and_yaxis import Graph_values\nfrom SI.Report.check_block_per_district_csv_download import blocklevel_csv\nfrom SI.Report.check_blockwise_graph import blockwise_graph\nfrom SI.Report.check_clusterwise_graph import clusterwise_graph\nfrom SI.Report.check_districtwise_graph import districtwise_graph\n\nfrom SI.Report.check_graph_present_on_school_infra import check_with_graph\nfrom SI.Report.check_homebtn import home_button\nfrom SI.Report.check_table_data_metrics import download_report\nfrom SI.Report.check_table_present_on_schoolinfra import check_with_table\nfrom SI.Report.check_tabledata_by_selecting_districts import districtwise_tabledata\n\nfrom SI.Report.check_with_hyperlink import Hyperlink\nfrom SI.Report.click_on_Report_from_scinfra import check_schoolinfra_report\nfrom SI.Report.click_on_district_and_click_download import download_districtwise\nfrom SI.Report.click_on_district_block_cluster_home import check_home\nfrom SI.Report.click_on_table_and_check_with_orderof_values import check_order_of_tabledata\n\nfrom SI.Report.download_blockwise_csv import donwload_blockwise_csv\nfrom SI.Report.download_districtwise_csv import download_district_wise_csv\nfrom SI.Report.navigate_to_SI_report import si_report\nfrom SI.Report.navigate_to_dashboard import check_dashboard\nfrom SI.Report.navigate_to_schoolinfra_and_click_on_logout import schoolinfra_logout\n\nfrom reuse_func import GetData\n\n\nclass cQube_SI_Report(unittest.TestCase):\n\n @classmethod\n def setUpClass(self):\n self.data = GetData()\n self.driver = self.data.get_driver()\n self.data.open_cqube_appln(self.driver)\n self.data.login_cqube(self.driver)\n self.data.navigate_to_school_infrastructure()\n self.data.page_loading(self.driver)\n\n def test_blockwise_from_selectbox(self):\n print(\"check blockwise records..\")\n b =blocklevel_csv(self.driver)\n res = b.test_each_district()\n self.assertEqual(0,res,msg=\"some files are not downloaded\")\n\n def test_graph(self):\n print(\"check graph functinality\")\n b = check_with_graph(self.driver)\n res = b.test_graph()\n self.assertIn(\"myChart\", self.driver.page_source, msg=\"Does not exist\")\n\n def test_home(self):\n print(\"check home button is working or not\")\n b =home_button(self.driver)\n res = b.test_home()\n self.assertTrue(res, msg = \"Home button not working \")\n\n def test_download_district_wise(self):\n print(\"downloading districtwise csv file\")\n b =download_report(self.driver)\n path =b.test_schools()\n self.assertTrue(path, msg=\"File is not downloaded\")\n b.remove_csv()\n\n\n def test_check_hyperlinks(self):\n print(\"check with hyperlinks\")\n hyperlinks = Hyperlink(self.driver)\n result1, result2, choose_dist = hyperlinks.click_on_hyperlinks()\n if result1 == False and result2 == False and choose_dist == \"Choose a District \":\n print(\"hyperlinks are working\")\n else:\n raise self.failureException(\"hyperlinks are not working\")\n self.data.page_loading(self.driver)\n\n def test_tabledata(self):\n print(\"checking table contains records or not\")\n b = check_with_table(self.driver)\n res = b.test_graph_and_table_present_on_school_infra()\n try:\n tablehead = self.driver.find_element_by_tag_name(\"table\")\n self.data.page_loading(self.driver)\n return tablehead.is_displayed()\n except exceptions.NoSuchElementException:\n print(\"Table is present \")\n self.assertTrue(res,msg=\"Table is not exist\")\n self.data.page_loading(self.driver)\n\n\n\n def test_tabledata_districtwise(self):\n print(\"districtwise table records..\")\n b =districtwise_tabledata(self.driver)\n res = b.test_table_data()\n if res != 0:\n raise self.failureException('Data not found on table')\n\n def test_districtwise_csv(self):\n print(\"districtwise csv file downloading..\")\n b = download_districtwise(self.driver)\n res = b.test_donwload()\n self.assertTrue(res,msg=\"districtwise file is not downloaded\")\n b.remove_csv()\n\n time.sleep(3)\n\n def test_cluster_home(self):\n print(\"going to cluster level and clicking on home icon\")\n b = check_home(self.driver)\n self.data.page_loading(self.driver)\n res = b.test_home()\n if \"school-infrastructure\" in self.driver.current_url:\n print(\"School infra report page\")\n else:\n print(\"school infra page not loaded\")\n time.sleep(2)\n\n\n def test_donwload_options(self):\n print(\"download report select box contais options or not\")\n b =Hyperlink(self.driver)\n res = b.click_on_hyperlinks()\n\n\n\n def test_school_report(self):\n print(\"school wise records validation \")\n b=check_schoolinfra_report(self.driver)\n res = b.test_report()\n self.assertEqual(\"menu\",res,msg=\"Dashboard is not exists!\")\n\n\n def test_check_orderwise(self):\n print(\"check order of table records..\")\n b =check_order_of_tabledata(self.driver)\n print(\"Table record order wise..\")\n res = b.test_tablevalue()\n\n\n def test_plotvalue(self):\n print(\"checking x and y axis values\")\n b =Graph_values(self.driver)\n res = b.test_plots()\n\n\n def test_donwload_blockwise(self):\n print(\"Downloading blockwise csv file\")\n b = donwload_blockwise_csv(self.driver)\n res =b.test_block()\n self.assertTrue(res, msg = \"File is not downloaded\")\n b.remove_csv()\n self.data.page_loading(self.driver)\n\n def test_download_districtwise(self):\n print(\"Downloading Districtwise csv file\")\n b = download_district_wise_csv(self.driver)\n res = b.test_districtwise()\n self.assertTrue(res, msg = \"File is not downloaded\")\n b.remove_file()\n\n\n def test_schoolreport(self):\n print(\"school infrastructure report options in dashboard \")\n b = si_report(self.driver)\n res =b.test_url()\n self.assertNotIn(\" School infrastructure for: \",self.driver.page_source,msg=\"School infrastructure report not exist \")\n\n def test_dashboard(self):\n print(\"check with dashboard\")\n b =check_dashboard(self.driver)\n res =b.test_menulist()\n\n def test_logout(self):\n print(\"checking logout functionality is working or not \")\n b=schoolinfra_logout(self.driver)\n res = b.test_logout()\n self.assertNotIn(\" School Infrastructure report for: \",self.driver.page_source,msg=\"School infrastructure report not exist \")\n self.assertEqual(\"Log in to cQube\",self.driver.title,msg=\"logout is not working \")\n self.data.login_cqube(self.driver)\n self.data.navigate_to_school_infrastructure()\n self.data.page_loading(self.driver)\n\n def test_districtwise_graph(self):\n b = districtwise_graph(self.driver)\n res = b.test_districtwise_graph()\n if \"myChart\" in self.driver.page_source:\n print(\"School infra Scattor plot is working fine\")\n else:\n print(\"School infra plot is not exist..\")\n self.data.page_loading(self.driver)\n\n\n def test_blockwise_graph(self):\n b = blockwise_graph(self.driver)\n res = b.test_blockwise_graph()\n if \"myChart\" in self.driver.page_source:\n print(\"School infra Scattor plot is working fine\")\n else:\n print(\"School infra plot is not exist..\")\n self.data.page_loading(self.driver)\n\n\n def test_clusterwise_graph(self):\n b = clusterwise_graph(self.driver)\n res = b.test_clusterwise_graph()\n if \"myChart\" in self.driver.page_source:\n print(\"school infra Scattor plot is working fine\")\n else:\n print(\"School infra plot plot is not exist..\")\n self.data.page_loading(self.driver)\n\n\n @classmethod\n def tearDownClass(cls):\n cls.driver.close()\n","sub_path":"tests/src/SI/Report/School_report_functional_testing.py","file_name":"School_report_functional_testing.py","file_ext":"py","file_size_in_byte":8117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"448805636","text":"#!/usr/bin/env python\nimport sys\nif sys.version_info[0] >= 3:\n import PySimpleGUI as sg\nelse:\n import PySimpleGUI27 as sg\nimport hashlib\nfrom sys import exit as exit\nimport cv2\n\nimport numpy as np\nimport rtsp\n\n\nimport math\n#from sklearn import neighbors\nimport os\nimport os.path\n#import pickle\nfrom PIL import Image, ImageDraw\n#import face_recognition\n#from face_recognition.face_recognition_cli import image_files_in_folder\n\n###1)\ndef get_images_from_video(video_name, time_F):\n video_images = []\n #vc = cv2.VideoCapture(video_name)\n vc = cv2.VideoCapture(\"rtsp://192.168.16.207:8554/h264\")\n c = 1\n if vc.isOpened(): #decide if to open the video\n rval, video_frame = vc.read()\n else:\n rval = False\n\n while rval: #capture the video til finish\n rval, video_frame = vc.read()\n if(c % time_F == 0): #capture per several times\n video_images.append(video_frame)\n c = c + 1\n vc.release()\n\n return video_images\n###2)\ndef play_the_video():\n # Create a VideoCapture object and read from input file\n # If the input is the camera, pass 0 instead of the video file name\n #cap = cv2.VideoCapture('e611fd4c9fa38992dfcd1b419b67b529.mp4')\n cap = cv2.VideoCapture(\"rtsp://192.168.16.207:8554/h264\")\n\n # Check if camera opened successfully\n if (cap.isOpened()== False):\n print(\"Error opening video stream or file\")\n\n # Read until video is completed\n while(cap.isOpened()):\n # Capture frame-by-frame\n ret, frame = cap.read()\n if ret == True:\n # Display the resulting frame\n cv2.imshow('Frame',frame)\n # Press Q on keyboard to exit\n if cv2.waitKey(25) & 0xFF == ord('q'):\n break\n # Break the loop\n else:\n break\n\n # When everything done, release the video capture object\n cap.release()\n\n###3)\ndef slice_and_play_the_video():\n # Set video images\n time_F = 5#time_F decrease, capture more\n video_name = 'tom_cruise.mp4' #name of video \n #read the video and transform to picture\n video_images = get_images_from_video(video_name, time_F)\n #print(video_images)\n\n #show all the captured pictures\n for i in range(0, len(video_images)):\n cv2.imshow('windows', video_images[i]) \n \n cv2.waitKey(100)\n\n # Closes all the frames\n #cv2.destroyAllWindows()\n\n###4)\ndef Destroy_All_Windows():\n cv2.destroyAllWindows()\n\n\n\n\n###5)\ndef test1():\n client = rtsp.Client(rtsp_server_uri = 'rtsp://192.168.16.207:8554/h264')\n client.preview()\n #client.read().show()\n client.close()\n\n###6)\ndef test2():\n\n\n #with rtsp.Client('rtsp://192.168.16.207:8554/h264') as client:\n # client.preview()\n client = rtsp.Client(rtsp_server_uri = 'rtsp://192.168.16.207:8554/h264')\n client.read().show()\n # 讀取圖檔\n #img = cv2.imread(, cv2.IMREAD_GRAYSCALE)\n # 查看資料型態\n #print(type(img))\n # 檢查一下這個 NumPy 陣列的大小\n #print(img.shape)\n\ndef cafe_test():\n #vcap = cv.VideoCapture(\"rtsp://10.38.5.145/ufirststream\")\n #vcap = cv2.VideoCapture(\"rtsp://192.168.43.82:8554/h264\")\n vcap = cv2.VideoCapture(\"rtsp://192.168.16.207:8554/h264\")\n while(1):\n ret, frame = vcap.read()\n cv2.imshow('VIDEO', frame)\n cv2.waitKey(1)\n \ndef skin():\n camera = cv2.VideoCapture(0)\n\n # determine upper and lower HSV limits for (my) skin tones\n lower = np.array([0, 100, 0], dtype=\"uint8\")\n upper = np.array([50,255,255], dtype=\"uint8\")\n\n while (True):\n ret, frame = camera.read()\n if not ret:\n continue\n # switch to HSV\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n # find mask of pixels within HSV range\n skinMask = cv2.inRange(hsv, lower, upper)\n # denoise\n skinMask = cv2.GaussianBlur(skinMask, (9, 9), 0)\n # kernel for morphology operation\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (4, 4))\n # CLOSE (dilate / erode)\n skinMask = cv2.morphologyEx(skinMask, cv2.MORPH_CLOSE, kernel, iterations = 3)\n # denoise the mask\n skinMask = cv2.GaussianBlur(skinMask, (9, 9), 0)\n # only display the masked pixels\n skin = cv2.bitwise_and(frame, frame, mask = skinMask)\n cv2.imshow(\"HSV\", skin)\n # quit or save frame\n #key = cv2.waitKey(1000 / 12) & 0xff\n #if key == ord(\"q\"):\n # break\n #if key == ord(\"p\"):\n # cv2.imwrite(\"skin.jpg\", skin)\n cv2.waitKey(0) \n\n cv2.destroyAllWindows()\n\n###7)\n\"\"\"\nDemo program that displays a webcam using OpenCV\n\"\"\"\ndef Demo_OpenCV_Webcam():\n\n sg.ChangeLookAndFeel('LightGreen')\n\n # define the window layout\n layout = [[sg.Text('OpenCV Demo', size=(40, 1), justification='center', font='Helvetica 20')],\n [sg.Image(filename='', key='image')],\n [sg.Button('Record', size=(10, 1), font='Helvetica 14'),\n sg.Button('Stop', size=(10, 1), font='Any 14'),\n sg.Button('Exit', size=(10, 1), font='Helvetica 14'),\n #sg.Button('About', size=(10,1), font='Any 14')\n ]]\n\n # create the window and show it without the plot\n window = sg.Window('Demo Application - OpenCV Integration',\n location=(800,400))\n window.Layout(layout).Finalize()\n\n # ---===--- Event LOOP Read and display frames, operate the GUI --- #\n cap = cv2.VideoCapture(\"tomcruise.mp4\")\n recording = False\n while True:\n event, values = window.Read(timeout=0, timeout_key='timeout')\n if event == 'Exit' or event is None:\n sys.exit(0)\n elif event == 'Record':\n recording = True\n elif event == 'Stop':\n recording = False\n img = np.full((480, 640),255)\n imgbytes=cv2.imencode('.png', img)[1].tobytes() #this is faster, shorter and needs less includes\n window.FindElement('image').Update(data=imgbytes)\n \"\"\"\n elif event == 'About':\n sg.PopupNoWait('Made with PySimpleGUI',\n 'www.PySimpleGUI.org',\n 'Check out how the video keeps playing behind this window.',\n 'I finally figured out how to display frames from a webcam.',\n 'ENJOY! Go make something really cool with this... please!',\n keep_on_top=True)\n \"\"\"\n if recording:\n ret, frame = cap.read()\n imgbytes=cv2.imencode('.png', frame)[1].tobytes() #ditto\n window.FindElement('image').Update(data=imgbytes)\n\n###8)\ndef Demo_OpenCV_Simple_GUI():\n sg.ChangeLookAndFeel('LightGreen')\n\n # define the window layout\n layout = [[sg.Text('OpenCV Demo', size=(40, 1), justification='center')],\n [sg.Image(filename='', key='image')],\n [sg.Radio('None', 'Radio', True, size=(10, 1))],\n [sg.Radio('threshold', 'Radio', size=(10, 1), key='thresh'),\n sg.Slider((0, 255), 128, 1, orientation='h', size=(40, 15), key='thresh_slider')],\n [sg.Radio('canny', 'Radio', size=(10, 1), key='canny'),\n sg.Slider((0, 255), 128, 1, orientation='h', size=(20, 15), key='canny_slider_a'),\n sg.Slider((0, 255), 128, 1, orientation='h', size=(20, 15), key='canny_slider_b')],\n [sg.Radio('contour', 'Radio', size=(10, 1), key='contour'),\n sg.Slider((0, 255), 128, 1, orientation='h', size=(20, 15), key='contour_slider'),\n sg.Slider((0, 255), 80, 1, orientation='h', size=(20, 15), key='base_slider')],\n [sg.Radio('blur', 'Radio', size=(10, 1), key='blur'),\n sg.Slider((1, 11), 1, 1, orientation='h', size=(40, 15), key='blur_slider')],\n [sg.Radio('hue', 'Radio', size=(10, 1), key='hue'),\n sg.Slider((0, 225), 0, 1, orientation='h', size=(40, 15), key='hue_slider')],\n [sg.Radio('enhance', 'Radio', size=(10, 1), key='enhance'),\n sg.Slider((1, 255), 128, 1, orientation='h', size=(40, 15), key='enhance_slider')],\n [sg.Button('Exit', size=(10, 1))]]\n\n # create the window and show it without the plot\n window = sg.Window('Demo Application - OpenCV Integration',\n location=(800, 400))\n window.Layout(layout).Finalize()\n\n cap = cv2.VideoCapture(\"rtsp://192.168.16.207:8554/h264\")\n while True:\n event, values = window.Read(timeout=0, timeout_key='timeout')\n if event == 'Exit' or event is None:\n sys.exit(0)\n ret, frame = cap.read()\n if values['thresh']:\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2LAB)[:, :, 0]\n _, frame = cv2.threshold(frame, values['thresh_slider'], 255, cv2.THRESH_BINARY)\n if values['canny']:\n frame = cv2.Canny(frame, values['canny_slider_a'], values['canny_slider_b'])\n if values['blur']:\n frame = cv2.GaussianBlur(frame, (21, 21), values['blur_slider'])\n if values['hue']:\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n frame[:, :, 0] += values['hue_slider']\n frame = cv2.cvtColor(frame, cv2.COLOR_HSV2BGR)\n if values['enhance']:\n enh_val = values['enhance_slider'] / 40\n clahe = cv2.createCLAHE(clipLimit=enh_val, tileGridSize=(8, 8))\n lab = cv2.cvtColor(frame, cv2.COLOR_BGR2LAB)\n lab[:, :, 0] = clahe.apply(lab[:, :, 0])\n frame = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)\n if values['contour']:\n hue = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n hue = cv2.GaussianBlur(hue, (21, 21), 1)\n hue = cv2.inRange(hue, np.array([values['contour_slider'], values['base_slider'], 40]),\n np.array([values['contour_slider'] + 30, 255, 220]))\n _, cnts, _ = cv2.findContours(hue, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n cv2.drawContours(frame, cnts, -1, (0, 0, 255), 2)\n imgbytes = cv2.imencode('.png', frame)[1].tobytes() # ditto\n window.FindElement('image').Update(data=imgbytes)\n\nif __name__ == '__main__':\n# main() # 或是任何你想執行的函式\n# test1()\n# test2()\n# cafe_test()\n# Demo_OpenCV_Webcam()\n# Demo_OpenCV_Simple_GUI()\n play_the_video()\n# skin()\n exit()\n","sub_path":"RTSP_make/rtspTest.py","file_name":"rtspTest.py","file_ext":"py","file_size_in_byte":10430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"312008900","text":"import socket\n\ntargetHost = \"www.google.com\"\nport = 80\n\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nclient.connect((targetHost, port))\nclient.send(b\"GET / HTTP/1.1\\r\\nHost: google.com\\r\\n\\r\\n\")\n\nresponse = client.recv(4096)\n\nprint(response.decode())\nclient.close()\n","sub_path":"tcpClient.py","file_name":"tcpClient.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"80446178","text":"print(\"Please enter the date in the format DD/MM/YYYY:\")\ndate = str(input(\">\"))\n\n# Parse the date for the values\ndateParsed = date.split(\"/\")\nday = int(dateParsed[0])\nmonth = int(dateParsed[1])\nyear = int(dateParsed[2])\n\n# Define some arrays to search for the differently lengthed months\nmonths31 = [1,3,5,7,8,10,12]\nmonths30 = [4,6,9,11]\n\n# Set the appropriate day limit based on the month\nif month in months31:\n daysmax = 31\nelif month in months30:\n daysmax = 30\nelif month == 2:\n if (year / 4) % 1 == 0:\n if year % 100 == 0 and year % 400 != 0:\n daysmax = 28\n else:\n daysmax = 29\n else:\n daysmax = 28\n\n# Actually perform all the checks\nif month > 12:\n print(\"Imaginary month, invalid\")\nelif day > daysmax:\n print(\"Too many days in that month, invalid\")\nelse:\n print(\"Valid\")\n","sub_path":"week2/funcVersions/question4pt2.py","file_name":"question4pt2.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"602819658","text":"import pytest\nfrom GoodPair import Solution \n\ndef test_123113():\n s = Solution()\n input = [1,2,3,1,1,3]\n expect = 4\n result = s.numIdenticalPairs(input)\n assert expect == result\n\ndef test_1111():\n s = Solution()\n input = [1,1,1,1]\n expect = 6\n result = s.numIdenticalPairs(input)\n assert expect == result\n\ndef test_123():\n s = Solution()\n input = [1,2,3]\n expect = 0\n result = s.numIdenticalPairs(input)\n assert expect == result\n","sub_path":"1512. Number of Good Pairs/test_Good_Pair.py","file_name":"test_Good_Pair.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"58739565","text":"import json\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.core.exceptions import ValidationError\nfrom django.http import HttpResponse, JsonResponse, QueryDict, HttpResponseRedirect\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom django.views.generic import View\n\nfrom common import parse_request_body\nfrom services.jira_client_service import JiraClientService\nfrom standup.forms.standup_task_form import StandupTaskForm, StandupTaskWorkForm\nfrom services.standup_task_service import StandupTaskService\n\n\nclass StandupTaskView(LoginRequiredMixin, View):\n\n def __init__(self, **kwargs):\n super(StandupTaskView, self).__init__(**kwargs)\n self.standup_task_service = StandupTaskService()\n\n def _get_context(self, standup_task_form, standup_task_work_form, *args, **kwargs):\n jira_service = JiraClientService()\n\n jira_issues = jira_service.get_issues_in_project(\"DER\")\n context = {\n 'standup_task_form': standup_task_form,\n 'standup_task_work_form': standup_task_work_form,\n 'jira_issues': jira_issues\n }\n return context\n\n def get(self, request):\n context = self._get_context(StandupTaskForm(), StandupTaskWorkForm())\n standup_task_service = StandupTaskService()\n\n standup_tasks = standup_task_service.get_standup_tasks_for_user(request.user.id)\n context['standup_tasks'] = standup_tasks\n return render(request, 'standup/index.html', context)\n\n def post(self, request, *args, **kwargs):\n request_body = parse_request_body(request)\n\n standup_task_form = StandupTaskForm(request_body)\n standup_task_work_form = StandupTaskWorkForm(request_body)\n try:\n create_result = self.standup_task_service.create_standup_task_with_work(\n standup_task_form, standup_task_work_form, request.user\n )\n location_uri = request.build_absolute_uri() + str(create_result)\n if request.is_ajax():\n response = HttpResponse(status=201)\n response[\"Location\"] = location_uri\n\n return response\n\n return HttpResponseRedirect('/standup/')\n\n except ValueError as e:\n if request.is_ajax():\n errors_dict = e.args[0]\n return HttpResponse(status=400, content_type=\"application/json\", content=json.dumps(errors_dict))\n\n context = self._get_context(standup_task_form, standup_task_work_form)\n return render(request, 'standup/index.html', context)\n except Exception as e:\n if request.is_ajax():\n return HttpResponse(status=500, content=e.args[0])\n\n context = self._get_context(standup_task_form, standup_task_work_form)\n return render(request, 'standup/index.html', context)\n\n\n","sub_path":"standup/views/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"193330947","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport datetime\nimport logging\nimport os\n\nfrom sqlalchemy.sql import text\n\nimport db\nimport settings\nfrom db.models import SQLAlchemyBase, User, GenereEnum, UserToken, Anunci, AnunciLevelEnum, AnunciTypeEnum\nfrom settings import DEFAULT_LANGUAGE\n\n# LOGGING\nmylogger = logging.getLogger(__name__)\nsettings.configure_logging()\n\n\ndef execute_sql_file(sql_file):\n sql_folder_path = os.path.join(os.path.dirname(__file__), \"sql\")\n sql_file_path = open(os.path.join(sql_folder_path, sql_file), encoding=\"utf-8\")\n sql_command = text(sql_file_path.read())\n db_session.execute(sql_command)\n db_session.commit()\n sql_file_path.close()\n\n\nif __name__ == \"__main__\":\n settings.configure_logging()\n\n db_session = db.create_db_session()\n\n # -------------------- REMOVE AND CREATE TABLES --------------------\n mylogger.info(\"Removing database...\")\n SQLAlchemyBase.metadata.drop_all(db.DB_ENGINE)\n mylogger.info(\"Creating database...\")\n SQLAlchemyBase.metadata.create_all(db.DB_ENGINE)\n\n\n\n # -------------------- CREATE USERS --------------------\n mylogger.info(\"Creating default users...\")\n # noinspection PyArgumentList\n user_admin = User(\n created_at=datetime.datetime(2020, 1, 1, 0, 1, 1),\n username=\"admin\",\n email=\"admin@damcore.com\",\n name=\"Administrator\",\n surname=\"DamCore\",\n genere=GenereEnum.male,\n phone=\"655619850\",\n zone=\"\"\n )\n user_admin.set_password(\"DAMCoure\")\n\n # noinspection PyArgumentList\n user_1= User(\n created_at=datetime.datetime(2020, 1, 1, 0, 1, 1),\n username=\"usuari1\",\n email=\"usuari1@gmail.com\",\n name=\"usuari\",\n surname=\"1\",\n birthdate=datetime.datetime(1989, 1, 1),\n genere=GenereEnum.male,\n phone=\"655619850\",\n zone = \"\"\n )\n user_1.set_password(\"a1s2d3f4\")\n user_1.tokens.append(UserToken(token=\"656e50e154865a5dc469b80437ed2f963b8f58c8857b66c9bf\"))\n\n # noinspection PyArgumentList\n user_2 = User(\n created_at=datetime.datetime(2020, 1, 1, 0, 1, 1),\n username=\"user2\",\n email=\"user2@gmail.com\",\n name=\"user\",\n surname=\"2\",\n birthdate=datetime.datetime(2017, 1, 1),\n genere=GenereEnum.male,\n phone=\"655619850\",\n zone=\"\"\n )\n user_2.set_password(\"r45tgt\")\n user_2.tokens.append(UserToken(token=\"0a821f8ce58965eadc5ef884cf6f7ad99e0e7f58f429f584b2\"))\n\n db_session.add(user_admin)\n db_session.add(user_1)\n db_session.add(user_2)\n db_session.commit()\n\n # -------------------- CREATE ANUNCIS --------------------\n mylogger.info(\"Creating default anuncis...\")\n\n anunci1 = Anunci(\n title=\"Busco profe mates\",\n description=\"Busco profe mates per ...\",\n price=10.0,\n distance_to_serve = 20,\n level = AnunciLevelEnum.eso,\n owner_id = 2,\n type= AnunciTypeEnum.busco\n )\n\n anunci2 = Anunci(\n title=\"Soc profe mates\",\n description=\"Soc profe de mates per ...\",\n price=10.0,\n distance_to_serve=20,\n level=AnunciLevelEnum.eso,\n owner_id=3,\n type=AnunciTypeEnum.doy\n )\n\n db_session.add(anunci1)\n db_session.add(anunci2)\n db_session.commit()\n db_session.close()\n","sub_path":"dev/reset_database.py","file_name":"reset_database.py","file_ext":"py","file_size_in_byte":3309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"632496424","text":"import pickle\r\nimport collections\r\nimport numpy as np\r\n\r\n\r\nchild_name = 'Adam'\r\nquerywords = ['think', 'know', 'want', 'see', 'that', 'what', 'this']\r\n\r\ndef sentence_to_frame(sentence):\r\n\tframeList = []\r\n\tfor i in range(len(sentence)):\r\n\t\tleft = sentence[i - 1] if i > 0 else '#'\r\n\t\tright = sentence[i + 1] if i + 1 < len(sentence) else '#'\r\n\t\tframeList.append(left + '_' + right)\r\n\treturn frameList\r\n\r\n\r\ndef shortlist(list_cnt, freqThreshold=25):\r\n\tfor i in range(len(list_cnt)):\r\n\t\tif list_cnt[i][1] < freqThreshold:\r\n\t\t\tbreak\r\n\treturn list_cnt[:i]\t\t\r\n\r\n\r\n# collect frames\r\ndef collectFrams(database):\r\n\tframe_cnt = collections.Counter()\r\n\tfor the_sentence in database:\r\n\t\tframe_cnt.update(sentence_to_frame(the_sentence))\r\n\r\n\tlist_frame_cnt = list(frame_cnt.items())\r\n\tlist_frame_cnt.sort(key=lambda item:item[1], reverse=True)\r\n\tlist_frame_cnt = shortlist(list_frame_cnt)\r\n\r\n\treturn list_frame_cnt\r\n\r\n\r\n# generate word vectors\r\ndef generateMatrix(database):\r\n\tlist_frame_cnt = collectFrams(database)\r\n\tdim = len(list_frame_cnt)\r\n\tframeset = [pair[0] for pair in list_frame_cnt]\r\n\r\n\tmatrix = collections.defaultdict(list)\r\n\tfor the_sentence in database:\r\n\t\tfor i, word in enumerate(the_sentence):\r\n\t\t\tif word in querywords:\r\n\t\t\t\tleft = the_sentence[i - 1] if i > 0 else '#'\r\n\t\t\t\tright = the_sentence[i + 1] if i + 1 < len(the_sentence) else '#'\r\n\t\t\t\tthis_frame = left + '_' + right\r\n\t\t\t\tif this_frame in frameset:\r\n\t\t\t\t\tframe_id = frameset.index(this_frame)\r\n\t\t\t\t\tif word in matrix:\r\n\t\t\t\t\t\tmatrix[word][frame_id] += 1\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tmatrix[word] = np.zeros(dim)\r\n\t\t\t\t\t\tmatrix[word][frame_id] = 1\r\n\r\n\treturn (frameset, matrix)\r\n\r\nwith open('adamCHIsents.pkl', 'rb') as f1:\r\n\tadamCHISents = pickle.load(f1)\r\n\t(adamCHIFrame, adamCHIMatrix) = generateMatrix(adamCHISents)\r\n\t# with open('adamCHIFrame.txt', 'w') as f1out:\r\n\t# \tf1out.write(str(adamCHIFrame))\r\n\twith open('adamCHIMat.pkl', 'wb') as f1out:\r\n\t\tpickle.dump(adamCHIMatrix, f1out)\r\n\r\nwith open('adamMOTsents.pkl', 'rb') as f2:\r\n\tadamMOTSents = pickle.load(f2)\r\n\t(adamMOTFrame, adamMOTMatrix) = generateMatrix(adamMOTSents)\r\n\t# with open('adamMOTFrame.txt', 'w') as f2out:\r\n\t# \tf2out.write(str(adamMOTFrame))\r\n\twith open('adamMOTMat.pkl', 'wb') as f2out:\r\n\t\tpickle.dump(adamMOTMatrix, f2out)\r\n","sub_path":"childesExp.py","file_name":"childesExp.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"327822661","text":"\n\n##############################################################################\n# Copyright (c) 2015, Network Science and Engineering Group (NetSE group)) at Kansas State University.\n# http://ece.k-state.edu/sunflower_wiki/index.php/Main_Page\n#\n# Written by:\n# Heman Shakeri:heman@ksu.edu\n# All rights reserved.\n#\n# For details, see https://github.com/scalability-llnl/AutomaDeD\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) version 2.1 dated February 1999.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and\n# conditions of the GNU General Public License for more details.\n##############################################################################\nimport numpy as np\nimport networkx as nx\nimport scipy\nimport matplotlib.pyplot as plt\nimport random\nimport numpy.random as rand\n# %matplotlib inline\nfrom scipy.sparse import *\nfrom scipy import *\nfrom scipy.sparse import coo_matrix, bmat\nimport itertools\n\n\n# In[38]:\n\ndef NeighborhoodData ( N , L1 , L2, W):\n \"\"\"\n A DB that gives the adjacent nodes (not necessary neighbors). For directed graphs we need NNeighborhoodData too.\n (Heman)\n \"\"\" \n junk = np.sort ( L1 ) \n index = np.argsort( L1 )\n \n\n NeighVec = L2[index]\n NeighWeight = W[index]\n\n# junk = np.sort ( dummy1 ) \n# index = np.argsort( dummy1 )\n# for i in index:\n# NeighVec.extend([dummy2[i]])\n# NeighWeight.extend([dummy3[i]])\n \n l = len( junk ); d = np.zeros ( N , dtype=int32) \n I1 = np.zeros ( N , dtype=int32) ;\n# I1 = np.zeros ( N ) ; I2 = np.zeros ( N ) \n I1 = -np.ones ( N , dtype=int32) #starts from -1, since the first edge is zero\n i = 0 \n while i+1 < l: #i starts from zero\n node = junk[i]\n I1[node] = i #link number, starts from 0\n while junk[i + 1] == junk[i]:\n d[node] = d[node] + 1 ;\n i += 1\n if i+1 == l:\n break\n i += 1\n if i+1 == l:\n node = junk[i]; I1[node] = i; d[node] = 0 \n I2 = I1 + d \n Temp1 = np.subtract(I2,I1)\n Temp2 = [int(I1[i]!=0) for i in range(len(I1)) ]\n# d = np.sum(Temp1, Temp2 ) \n return NeighVec, I1, I2, d, NeighWeight \n#--------------------------------------------------------\ndef NNeighborhoodData ( N , L1 , L2, W): \n \"\"\"\n A DB that gives the adjacent nodes (not necessary neighbors). Useful only for directed graphs.\n (Heman)\n \"\"\"\n# NNeighVec = []; NI1 = [] ; NI2 = [] ; dummy1 = L1; dummy2 = L2 ; dummy3 = W\n# NNeighWeight = []\n \n# junk = np.sort ( dummy2 ) \n# index = np.argsort( dummy2 )\n# #instead of the following for loop: NNeighVec = dummy1[index]\n# for i in index:\n# NNeighVec.extend([dummy1[i]])\n# NNeighWeight.extend([dummy3[i]])\n \n \n junk = np.sort ( L2 ) \n index = np.argsort( L2 )\n\n NNeighVec = L1[index]\n NNeighWeight = W[index]\n \n l = len( junk ); Nd = np.zeros ( N , dtype=int32) \n# NI1 = np.zeros ( N , dtype=int32)\n NI1 = -np.ones ( N , dtype=int32) \n i = 0 \n I1 = [] ; I2 = [] ;\n while i+1 < l: #i starts from zero\n node = junk[i]\n NI1[node] = i #link number, starts from 0\n while junk[i + 1] == junk[i]:\n Nd[node] = Nd[node] + 1 ;\n i += 1\n if i+1 == l:\n break\n i += 1\n if i+1 == l:\n node = junk[i]; NI1[node] = i; Nd[node] = 0 \n NI2 = NI1 + Nd \n Temp1 = np.subtract(NI2, NI1)\n Temp2 = [int(NI1[i]!=0) for i in range(len(NI1)) ]\n# d = np.sum(Temp1, Temp2 ) \n return NNeighVec, NI1, NI2, Nd, NNeighWeight \n\n\n# In[48]:\n\ndef EIG1(G):\n adj=nx.to_scipy_sparse_matrix(G)\n k=adj.sum(axis=1);\n k=k/float(k.sum())\n err = 1; lambda1 = 0\n while err>1e-3:\n k = adj.dot(k)\n# k = np.dot(adj,k)\n temp = k.sum()\n err = temp - lambda1\n lambda1 = temp\n k = k/lambda1\n v1 = k\n return lambda1, v1\n#----------------------------\ndef Initial_Cond_Gen(N, J, NJ, x0):\n \"\"\"\n J = initial state for NJ number of whole population N\n Example : x0 = np.zeros(N, dtype = int32)\n Initial_Cond_Gen(10, Para[1][0], 2, x0)\n \"\"\"\n if sum(NJ) > N:\n return 'Oops! Initial infection is more than the total population'\n else:\n temp = np.random.permutation(N); nj=temp[0:sum(NJ)]\n for i in range(len(nj)):\n x0[nj[i]] = J\n return x0\n#----------------------------\ndef rnd_draw(p):\n \"\"\"\n To draw a sample using a probability distribution.\n \"\"\"\n a = [0]\n a = np.append(a, np.cumsum(p[0:-1]))/np.sum(p)\n b = cumsum(p)/np.sum(p)\n toss = rand()\n k = np.intersect1d(np.nonzero(a=toss)[0])\n return k\n\n\n# In[49]:\n\ndef MyNet(G, weight=None):\n \n \"\"\"\n MyNet(G, weight='weight')\n \"\"\"\n G_adj = nx.to_scipy_sparse_matrix(G, weight=weight)\n cx = G_adj.tocoo() \n L2 = cx.row\n L1 = cx.col\n W = cx.data\n N = G.number_of_nodes()\n# adj = [L1, L2, W, N]\n NeighVec, I1, I2, d, NeighWeight = NeighborhoodData ( N , L1 , L2, W)\n if nx.is_directed(G):\n# if True:\n NNeighVec, NI1, NI2, Nd, NNeighWeight = NNeighborhoodData ( N , L1 , L2, W) #ver2\n \n# Net = [NeighVec, I1, I2, d, adj, NeighWeight]\n Net = [NeighVec, I1, I2, d, NeighWeight, NNeighVec, NI1, NI2, NNeighWeight]#ver2\n else:\n Net = [NeighVec, I1, I2, d, NeighWeight]#ver2\n return Net\n\n\n# In[50]:\n\ndef NetCmbn(NetSet): \n \"\"\"\n Combine different network layers data. This function is used for directed networks.\n \"\"\"\n \n if len(NetSet[0])>5: #Means it is directed\n Neigh = []; I1 = []; I2 = []; d = []; NeighW = []; NNeigh = []; NI1 = []; NI2 = []; NNeighW = []\n for l in range(len(NetSet)):\n Neigh.append(NetSet[l][0]) #each layer append as a seperate: Neigh = [[Neigh_L1],[Neigh_L2]]\n I1.append(NetSet[l][1]) #I1 and I2 into each row of the new I1 and I2\n I2.append(NetSet[l][2])\n d.append(NetSet[l][3])\n # adj.append(NetSet[l][4])\n NeighW.append(NetSet[l][4])\n NNeigh.append(NetSet[l][5]) #ver2\n NI1.append(NetSet[l][6]) #ver2\n NI2.append(NetSet[l][7])\n NNeighW.append(NetSet[l][8])\n Net = [Neigh,I1,I2,d, NeighW, NNeigh, NI1, NI2, NNeighW]\n else:\n Neigh = []; I1 = []; I2 = []; d = []; adj = []; NeighW = []\n for l in range(len(NetSet)):\n Neigh.append(NetSet[l][0]) #each layer append as a seperate: Neigh = [[Neigh_L1],[Neigh_L2]]\n I1.append(NetSet[l][1]) #I1 and I2 into each row of the new I1 and I2\n I2.append(NetSet[l][2])\n d.append(NetSet[l][3])\n # adj.append(NetSet[l][4])\n NeighW.append(NetSet[l][4]) \n Net = [Neigh,I1,I2,d, NeighW]\n return Net\n\n\n# In[51]:\n\ndef GEMF_SIM(Para, Net, x0, StopCond, N, Directed = False):\n \"\"\"\n An event-driven approach to simulate the stochastic process. \n \n \"\"\"\n M = Para[0]; q = Para[1]; L = Para[2]; A_d = Para[3]; A_b = Para[4]\n Neigh = Net[0]; I1 = Net[1]; I2 = Net[2]; NeighW = Net[4]\n \n n_index = []; j_index = []; i_index = []\n #------------------------------\n bil = np.zeros((M,L))\n for l in range(L):\n bil[:,l] = A_b[l].sum(axis=1) #l'th column is row sum of l'th A_b\n #------------------------------\n bi = np.zeros((M,M,L))\n for i in range(M):\n for l in range(L):\n bi[i, :, l] = A_b[l][i,:]\n #------------------------------\n di = A_d.sum(axis=1) #The rate that we leave compartment i, due to nodal transitions\n #------------------------------\n #X = copy(x0)\n X = x0.astype(int32)#since compartments are just numbers we are using integer types. If \n \n #------------------------------\n Nq = np.zeros((L,N))\n #------------------------------ver 2\n for n in range(N):\n for l in range(L):\n Nln = Neigh[l][I1[l][n]:I2[l][n]+1]\n Nq[l][n] = sum((X[Nln]==q[l])*NeighW[l][I1[l][n]:I2[l][n]+1] ) \n #------------------------------ver2\n Rn = np.zeros(N)\n \n for n in range(N):\n# print 'di[X[n]]: '+str(di[X[n]])\n# print 'Nq[:,n]: '+str(Nq[:,n])\n# print 'bil[X[n],:]: '+str(bil[X[n],:])\n# print 'np.dot(bil[X[n],:],Nq[:,n]): '+str(np.dot(bil[X[n],:],Nq[:,n]))\n Rn[n] = di[X[n]] + np.dot(bil[X[n],:],Nq[:,n])\n R = sum(Rn)\n #------------------------------\n EventNum = StopCond[1]; RunTime= StopCond[1] \n ts = []\n# #------------------------------\n s=-1; Tf=0 \n if len(Net)>5:\n NNeigh = Net[5]; NI1 = Net[6]; NI2 = Net[7]; NNeighW = Net[8] \n while Tf < RunTime:\n s +=1\n ts.append(-log( rand() )/R) \n #------------------------------ver 2\n ns = rnd_draw(Rn)\n iss = X[ns]\n\n js = rnd_draw( np.ravel(A_d[iss,:].T + np.dot(bi[iss],Nq[:,ns]) ))\n n_index.extend(ns)\n j_index.extend(js)\n i_index.extend(iss)\n # -------------------- % Updateing ver2\n X[ns] = js\n R -= Rn[ns]\n Rn[ns] = di[js] + np.dot(bil[js,:] , Nq[:,ns])\n R += Rn[ns] \n\n infl = (q == js).nonzero()[0]#inf is layers with influencer compartment \n for l in infl: \n Nln = NNeigh[l][NI1[l][ns]:NI2[l][ns]+1] #finding nodes that are adjacent to new infected\n IncreasEff = NNeighW[l][NI1[l][ns]:NI2[l][ns]+1]\n Nq[l][Nln] += IncreasEff #add the new infection weight edges\n k = 0\n for n in Nln:\n Rn[n] += bil[X[n],l]*IncreasEff[k]\n R += bil[X[n],l]*IncreasEff[k]\n k +=1 \n\n infl2 = (q == iss).nonzero()[0]#infl2 is layers with influencer compartment \n \n # print 'inf2: '+str(inf2)\n for l in infl2: #finding influencer compartments\n Nln = NNeigh[int(l)][int(NI1[l][ns]):int(NI2[l][ns])+1] #finding nodes that are adjacent to new infected\n reducEff = NNeighW[int(l)][int(NI1[l][ns]):int(NI2[l][ns])+1]\n Nq[l][Nln] -= reducEff #subtract the new infection weight edges\n k = 0\n for n in Nln: \n Rn[n] -= bil[X[n],l]*reducEff[k] \n R -= bil[X[n],l]*reducEff[k]\n k += 1\n if R < 1e-6:\n break\n Tf += ts[s]\n else:\n while Tf < RunTime:\n s +=1\n ts.append(-log( rand() )/R) \n #------------------------------ver 2\n ns = rnd_draw(Rn)\n iss = X[ns]\n\n js = rnd_draw( np.ravel(A_d[iss,:].T + np.dot(bi[iss],Nq[:,ns]) ))\n n_index.extend(ns)\n j_index.extend(js)\n i_index.extend(iss)\n # -------------------- % Updateing ver2\n X[ns] = js\n R -= Rn[ns]\n Rn[ns] = di[js] + np.dot(bil[js,:] , Nq[:,ns])\n R += Rn[ns] \n\n infl = (q == js).nonzero()[0]#inf is layers with influencer compartment \n for l in infl: \n Nln = Neigh[int(l)][int(I1[l][ns]):int(I2[l][ns])+1] #finding nodes that are adjacent to new infected\n IncreasEff = NeighW[int(l)][int(I1[l][ns]):int(I2[l][ns])+1]\n Nq[l][Nln] += IncreasEff #add the new infection weight edges\n k = 0\n for n in Nln:\n Rn[n] += bil[X[n],l]*IncreasEff[k]\n R += bil[X[n],l]*IncreasEff[k]\n k +=1 \n\n infl2 = (q == iss).nonzero()[0]#infl2 is layers with influencer compartment \n # print 'inf2: '+str(inf2)\n for l in infl2: #finding influencer compartments\n Nln = Neigh[int(l)][int(I1[l][ns]):int(I2[l][ns])+1] #finding nodes that are adjacent to new infected\n reducEff = NeighW[int(l)][int(I1[l][ns]):int(I2[l][ns])+1]\n Nq[l][Nln] -= reducEff #subtract the new infection weight edges\n k = 0\n for n in Nln: \n Rn[n] -= bil[X[n],l]*reducEff[k] \n R -= bil[X[n],l]*reducEff[k]\n k += 1\n if R < 1e-6:\n break\n Tf += ts[s] \n \n return ts, n_index, i_index, j_index\n\n\n# In[52]:\n\ndef Post_Population(x0, M, N, ts, i_index, j_index):\n\n X0 = np.zeros((M,N))\n for i in range(N):\n X0[int(x0[i])][i] = 1\n T = [0]\n T.extend(np.cumsum(ts))\n StateCount = np.zeros((M,len(ts)+1))\n StateCount[:,0] = X0.sum(axis=1)\n DX = np.zeros(M); DX[i_index[0]] = -1; DX[j_index[0]] = 1\n StateCount[:,1] = StateCount[:,0]+DX\n for k in range(len(ts)):\n DX = np.zeros(M); DX[i_index[k]] = -1; DX[j_index[k]] = 1\n StateCount[:,k+1] = StateCount[:,k] + DX\n \n return T, StateCount\n\n\n# In[53]:\n\ndef Para_SIS(delta,beta):\n M = 2; q = np.array([1]); L = len(q);\n A_d = np.zeros((M,M)); A_d[1][0] = delta\n A_b = []\n for l in range(L):\n# A_b.append(asmatrix(np.zeros((M,M))))\n A_b.append(np.zeros((M,M)))\n A_b[0][0][1] = beta #[l][M][M]\n Para=[M,q,L,A_d,A_b]\n return Para\n\n\n# In[54]:\n\ndef Para_SIR(delta, beta):\n M = 3; q = np.array([1]); L = len(q);\n A_d = np.zeros((M,M)); A_d[1][2] = delta\n A_b = []\n for l in range(L):\n A_b.append(np.zeros((M,M)))\n A_b[0][0][1] = beta #[l][M][M]\n Para=[M,q,L,A_d,A_b]\n return Para\n\n\n# In[55]:\n\ndef Para_SEIR(delta, beta, Lambda):\n M = 4; q = np.array([2]); L = len(q);\n A_d = np.zeros((M,M)); A_d[1][2] = Lambda; A_d[2][3] = Lambda\n A_b = []\n for l in range(L):\n# A_b.append(asmatrix(np.zeros((M,M))))\n A_b.append(np.zeros((M,M)))\n A_b[0][0][1] = beta #[l][M][M]\n Para=[M,q,L,A_d,A_b]\n return Para\n\n\n# In[56]:\n\ndef Para_SAIS_Single(delta, beta, beta_a, kappa):\n M = 3; q = np.array([1]); L = len(q); \n A_d = np.zeros((M,M)); A_d[1][0] = delta\n A_b = []\n for l in range(L):\n A_b.append(np.zeros((M,M)))\n A_b[0][0][1] = beta #[l][M][M]\n A_b[0][0][2] = kappa \n A_b[0][2][1] = beta_a \n Para = [M, q, L, A_d, A_b]\n return Para\n\n\n# In[57]:\n\ndef Para_SAIS(delta, beta, beta_a, kappa, mu):\n M = 3; q = np.array([1,1]); L = len(q); \n A_d = np.zeros((M,M)); A_d[1][0] = delta\n A_b = []\n for l in range(L):\n A_b.append(np.zeros((M,M)))\n A_b[0][0][1] = beta #[l][M][M]\n A_b[0][0][2] = kappa\n A_b[1][2][1] = beta_a \n A_b[1][0][2] = mu \n Para = [M, q, L, A_d, A_b]\n return Para\n\n\n# In[58]:\n\ndef Para_SI1I2S(delta1, delta2, beta1, beta2):\n M = 3; q = np.array([1,2]); L = len(q); \n A_d = np.zeros((M,M)); A_d[1][0] = delta1; A_d[2][0] = delta2\n A_b = []\n for l in range(L):\n A_b.append(np.zeros((M,M)))\n A_b[0][0][1] = beta1 #[l][M][M]\n A_b[1][0][2] = beta2 #[l][M][M]\n \n Para = [M, q, L, A_d, A_b]\n return Para\n\n\n# In[59]:\n\n\ndef MonteCarlo(Net, Para, StopCond, Init_inf, M, step, nsim, N, x_init = None ):\n# StopCond=['RunTime',500]\n# T_final = 80;\n t_interval = np.arange(0,StopCond[1], step) \n tsize = int(StopCond[1]/float(step))\n t_interval = np.linspace(0, StopCond[1], num=tsize)\n f = np.zeros(( M, tsize ))\n# nsim = 20; \n for n in range(nsim):\n x0 = Initial_Cond_Gen(N, Para[1][0], Init_inf, x0 = np.zeros(N, dtype = int32))\n [ts, n_index, i_index, j_index] = GEMF_SIM(Para, Net, x0, StopCond, N)\n [T, StateCount] = Post_Population(x0, M, N, ts, i_index, j_index)\n k=0\n y=np.zeros((M,tsize))\n NewT = T.extend([1000])\n for t in t_interval:\n ind, tr = np.histogram(t,bins = T)\n index = np.nonzero(ind)[0][0]\n# print index\n y[:,k] = StateCount[:, index]/N\n k+=1\n f += y;\n return t_interval, f/nsim\n\n\n# In[60]:\n\ndef Simulation(G, Para, StopCond, Init_inf, nsim, Monte_Carlo = False, step = .1):\n \"\"\" -> \n >>> StopCond = ['RunTime', 20]\n \"\"\"\n Net = NetCmbn([MyNet(G)])\n N = G.number_of_nodes()\n x0 = np.zeros(N)\n M = Para[0]\n if Monte_Carlo:\n# t_interval, f = MonteCarlo(StopCond, M, T_final, step, nsim, N)\n return MonteCarlo(Net, Para, StopCond, Init_inf, M, step, nsim, N, x_init = x0)\n else:\n x0 = Initial_Cond_Gen(N, Para[1][0], Init_inf, x0)\n ts, n_index, i_index, j_index = GEMF_SIM(Para, Net, x0, StopCond,N) \n# T, StateCount = Post_Population(x0, M, N, ts, i_index, j_index)\n return Post_Population(x0, M, N, ts, i_index, j_index)\n return T, StateCount\n#-------------------------------------------------------------------------\ndef Sim_vacc(G, Para, C, Init_inf = 3, Num_of_Vacc = None, StopCond = None, nsim = None):\n \"\"\"\n >>> t_interval, f_pass, f_rnd, f_outDeg, f_Mod = Sim_vacc(H, Para, Init_inf, C_Geo_d, Num_of_Vacc = 30, StopCond = ['RunTime', 30], nsim = 80)\n \"\"\"\n# StopCond = StopCond\n G_Mod = G_Mod_vaccination(G, C, Num_of_Vacc)\n G_outDeg = G_Out_Deg_vaccination(G, Num_of_Vacc)\n G_rnd = G_rnd_vaccination(G, Num_of_Vacc)\n# G_LEig = G_LeftEig_vaccination(G, Num_of_Vacc)\n t_interval, f_pass = Simulation(G, Para, StopCond, Init_inf, nsim, Monte_Carlo = True )\n t_interval, f_rnd = Simulation(G_rnd, Para, StopCond, Init_inf, nsim, Monte_Carlo = True )\n t_interval, f_outDeg = Simulation(G_outDeg, Para, StopCond, Init_inf, nsim, Monte_Carlo = True )\n t_interval, f_Mod = Simulation(G_Mod, Para, StopCond, Init_inf, nsim, Monte_Carlo = True )\n# t_interval, f_LEig = Simulation(G_LEig, Para, StopCond2, Init_inf = Init_inf, Monte_Carlo = True)\n return t_interval, f_pass, f_rnd, f_outDeg, f_Mod\n\n\n## Animation\n\n# In[61]:\n\nfrom matplotlib import animation\n\ndef animate_discrete_property_over_graph( g, model, steps, fig, n_index,i_index, j_index, comp, property = None,\n color_mapping = None, pos = None, Node_radius = None, **kwords ):\n \"\"\"Draw a graph and animate the progress of a property over it. The\n property values are converted to colours that are then used to colour\n the nodes.\n \"\"\"\n x0 = model[0]; n_index = model[1]; i_index = model[2]; j_index = model[3]\n \n # manipulate the axes, since this isn't a data plot\n ax = fig.gca()\n\n pos\n ax.grid(False) # no grid\n ax.get_xaxis().set_ticks([]) # no ticks on the axes\n ax.get_yaxis().set_ticks([])\n nx.draw_networkx_edges(g, pos)\n\n if Node_radius == None:\n Node_radius = .02\n \n # draw the graph, keeping hold of the node markers\n nodeMarkers = []\n for v in g.nodes(): # nodes_iter()\n# circ = plt.Circle(pos[v], radius = 0.02, zorder = 2) # node markers at top of the z-order\n circ = plt.Circle(pos[v], radius = Node_radius, zorder = 2) # node markers at top of the z-order\n ax.add_patch(circ)\n nodeMarkers.append({ 'node_key': v, 'marker': circ })\n\n # initialisation colours the markers according to the current\n # state of the property being tracked\n def colour_nodes():\n for nm in nodeMarkers:\n v = nm['node_key']\n state = g.node[v][property]\n c = color_mapping[state]\n marker = nm['marker']\n marker.set(color = c)\n\n # initialisation coours the markers according to the current\n # state of the property being tracked\n \n# comp = ['S', 'I' ]\n def init_state():\n \"\"\"Initialise all node in the graph to be susceptible.\"\"\"\n for i in g.node.keys():\n g.node[i]['state'] = comp[int(x0[i])] \n colour_nodes()\n \n # per-frame animation just iterates the model and then colours it\n # to reflect the changed property status of each node\n \n def frame(i):\n changing_node = n_index[i]\n new_comp = j_index[i]\n g.node[changing_node]['state'] = comp[new_comp]\n colour_nodes()\n \n \n \n \n # return the animation with the functions etc set up\n return animation.FuncAnimation(fig, frame, init_func = init_state, frames = steps, **kwords)\n\n\n","sub_path":"GEMFPy.py","file_name":"GEMFPy.py","file_ext":"py","file_size_in_byte":20611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"463070855","text":"import pandas\nimport json\n\nfname = 'nyse_friday_tweet.json'\nf = open(fname, 'r') \n\ndates_nyse = []\n\n# f is the file pointer to the JSON data set\nfor line in f:\n tweet = json.loads(line)\n # let's focus on hashtags only at the moment\n terms_hash = [term for term in preprocess(tweet['text']) if term.startswith('#')]\n # track when the hashtag is mentioned\n if '#nyse' in terms_hash:\n dates_nyse.append(tweet['created_at'])\n \n\n# a list of \"1\" to count the hashtags\nones = [1]*len(dates_nyse)\n# the index of the series\nidx = pandas.DatetimeIndex(dates_nyse)\n# the actual series (at series of 1s for the moment)\nnyse = pandas.Series(ones, index=idx)\n \n# Resampling / bucketing\n#per_minute = nyse.resample('1Min', how='sum').fillna(0)\nper_hour = nyse.resample('H', how='sum').fillna(0) \n\n\ntime_chart = vincent.Line(per_hour)\ntime_chart.axis_titles(x='Time', y='Freq')\ntime_chart.to_json('time_chart.json')\n\n","sub_path":"5_data_visualisation-time-series.py","file_name":"5_data_visualisation-time-series.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"463438430","text":"\"\"\"\nProgrammer: Chris Tralie\nPurpose: To create a collection of functions for making families of curves and applying\nrandom rotations/translations/deformations/reparameterizations to existing curves\nto test out the isometry blind time warping algorithms\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.interpolate as interp\nimport sys\nfrom CSMSSMTools import *\n\n###################################################\n# TOPC Utility Functions #\n###################################################\n\ndef applyRandomRigidTransformation(X, special = False):\n \"\"\"\n Randomly rigidly rotate and translate a time-ordered point cloud\n :param X: Nxd matrix representing a time-ordered point cloud\n :param special: Whether to restrict to the special orthogonal group\n (no flips; determinant 1)\n :return Y: Nxd matrix representing transformed version of X\n \"\"\"\n dim = X.shape[1]\n CM = np.mean(X, 0)\n X = X - CM\n #Make a random rotation matrix\n R = np.random.randn(dim, dim)\n R, S, V = np.linalg.svd(R)\n if special and np.linalg.det(R) < 0:\n idx = np.arange(R.shape[0])\n idx[0] = 1\n idx[1] = 0\n R = R[idx, :]\n T = 5*np.std(X)*np.random.randn(dim)\n return CM[None, :] + np.dot(X, R) + T[None, :]\n\ndef getMeanDistNeighbs(X, Kappa):\n N = X.shape[0]\n K = int(Kappa*N)\n D = getSSM(X)\n Neighbs = np.partition(D, K+1, 1)[:, 0:K+1]\n return np.mean(Neighbs, 1)*float(K+1)/float(K)\n\ndef addGaussianNoise(X, Kappa, NRelMag):\n N = X.shape[0]\n MeanDist = getMeanDistNeighbs(X, Kappa)\n return X + NRelMag*MeanDist[:, None]*np.random.randn(N, X.shape[1])\n\ndef addRandomBumps(X, Kappa, NRelMag, NBumps):\n N = X.shape[0]\n Y = np.array(X)\n MeanDist = getMeanDistNeighbs(X, Kappa)\n Bumps = np.zeros((NBumps, X.shape[1]))\n for i in range(NBumps):\n idx = np.random.randint(N)\n u = np.random.randn(1, X.shape[1])\n u = u/np.sqrt(np.sum(u**2))\n x = Y[idx, :] + MeanDist[idx]*NRelMag*u\n Bumps[i, :] = x\n diff = -Y+x\n distSqr = np.sum(diff**2, 1)\n idx = np.argmin(distSqr)\n t = (idx - np.arange(N))/(N*Kappa)\n sigma = np.sqrt(distSqr[idx])/np.sqrt(-np.log(0.9))\n Y += diff*np.exp(-t**2)[:, None]*np.exp(-distSqr/(sigma**2))[:, None]\n return (Y, Bumps)\n\ndef smoothCurve(X, Fac):\n \"\"\"\n Use splines to smooth the curve\n :param X: Nxd matrix representing a time-ordered point cloud\n :param Fac: Smoothing factor\n :return Y: An (NxFac)xd matrix of a smoothed, upsampled point cloud\n \"\"\"\n NPoints = X.shape[0]\n dim = X.shape[1]\n idx = range(NPoints)\n idxx = np.linspace(0, NPoints, NPoints*Fac)\n Y = np.zeros((NPoints*Fac, dim))\n NPointsOut = 0\n for ii in range(dim):\n Y[:, ii] = interp.spline(idx, X[:, ii], idxx)\n #Smooth with box filter\n y = (0.5/Fac)*np.convolve(Y[:, ii], np.ones(Fac*2), mode='same')\n Y[0:len(y), ii] = y\n NPointsOut = len(y)\n Y = Y[0:NPointsOut-1, :]\n Y = Y[2*Fac:-2*Fac, :]\n return Y\n\ndef makeRandomWalkCurve(res, NPoints, dim):\n \"\"\"\n Make a random walk curve with \"NPoints\" in dimension \"dim\"\n :param res: An integer specifying the resolution of the random walk grid\n :param NPoints: Number of points in the curve\n :param dim: Dimension of the ambient Euclidean space of the curve\n :return X\n \"\"\"\n #Enumerate all neighbors in hypercube via base 3 counting between [-1, 0, 1]\n Neighbs = np.zeros((3**dim, dim))\n Neighbs[0, :] = -np.ones((1, dim))\n idx = 1\n for ii in range(1, 3**dim):\n N = np.copy(Neighbs[idx-1, :])\n N[0] += 1\n for kk in range(dim):\n if N[kk] > 1:\n N[kk] = -1\n N[kk+1] += 1\n Neighbs[idx, :] = N\n idx += 1\n #Exclude the neighbor that's in the same place\n Neighbs = Neighbs[np.sum(np.abs(Neighbs), 1) > 0, :]\n\n #Pick a random starting point\n X = np.zeros((NPoints, dim))\n X[0, :] = np.random.choice(res, dim)\n\n #Trace out a random path\n for ii in range(1, NPoints):\n prev = np.copy(X[ii-1, :])\n N = np.tile(prev, (Neighbs.shape[0], 1)) + Neighbs\n #Pick a random next point that is in bounds\n idx = np.sum(N > 0, 1) + np.sum(N < res, 1)\n N = N[idx == 2*dim, :]\n X[ii, :] = N[np.random.choice(N.shape[0], 1), :]\n return X\n\n###################################################\n# Curve Families #\n###################################################\n\n#Note: All function assume the parameterization is given\n#in the interval [0, 1]\n\n\n#######2D Curves\ndef getLissajousCurve(A, B, a, b, delta, pt):\n \"\"\"\n Return the curve with\n x = Asin(at + delta)\n y = Bsin(bt)\n \"\"\"\n N = len(pt)\n t = 2*np.pi*pt\n X = np.zeros((N, 2))\n X[:, 0] = A*np.sin(a*t + delta)\n X[:, 1] = B*np.sin(b*t)\n return X\n\ndef get2DFigure8(pt):\n \"\"\"Return a figure 8 curve parameterized on [0, 1]\"\"\"\n return getLissajousCurve(1, 1, 1, 2, 0, pt)\n\n\ndef getPinchedCircle(pt):\n \"\"\"Return a pinched circle paramterized on [0, 1]\"\"\"\n N = len(pt)\n t = 2*np.pi*pt\n X = np.zeros((N, 2))\n X[:, 0] = (1.5 + np.cos(2*t))*np.cos(t)\n X[:, 1] = (1.5 + np.cos(2*t))*np.sin(t)\n return X\n\ndef getEpicycloid(R, r, pt):\n N = len(pt)\n t = 2*np.pi*pt\n X = np.zeros((N, 2))\n X[:, 0] = (R+r)*np.cos(t) - r*np.cos(t*(R+r)/r)\n X[:, 1] = (R+r)*np.sin(t) - r*np.sin(t*(R+r)/r)\n return X\n\ndef getTschirnhausenCubic(a, pt):\n \"\"\"\n Return the plane curve defined by the polar equation\n r = asec^3(theta/3)\n \"\"\"\n N = len(pt)\n t = 5*(pt-0.5)\n X = np.zeros((N, 2))\n X[:, 0] = a*(1-3*t**2)\n X[:, 1] = a*t*(3-t**2)\n X = 2*X/np.max(np.abs(X))\n return X\n\n#######3D Curves\ndef getVivianiFigure8(a, pt):\n \"\"\"\n Return the curve that results from the intersection of\n a sphere of radius 2a centered at the origin and a cylinder\n centered at (a, 0, 0) of radius a (the figure 8 I have is\n a 2D projection of this)\n \"\"\"\n N = len(pt)\n t = 4*np.pi*pt - np.pi\n X = np.zeros((N, 3))\n X[:, 0] = a*(1+np.cos(t))\n X[:, 1] = a*np.sin(t)\n X[:, 2] = 2*a*np.sin(t/2)\n return X\n\n\ndef getTorusKnot(p, q, pt):\n \"\"\"Return a p-q torus not parameterized on [0, 1]\"\"\"\n N = len(pt)\n t = 2*np.pi*pt\n X = np.zeros((N, 3))\n r = np.cos(q*t) + 2\n X[:, 0] = r*np.cos(p*t)\n X[:, 1] = r*np.sin(p*t)\n X[:, 2] = -np.sin(q*t)\n return X\n\ndef getConeHelix(c, NPeriods, pt):\n \"\"\"Return a helix wrapped around a double ended cone\"\"\"\n N = len(pt)\n t = NPeriods*2*np.pi*pt\n zt = c*(pt-0.5)\n r = zt\n X = np.zeros((N, 3))\n X[:, 0] = r*np.cos(t)\n X[:, 1] = r*np.sin(t)\n X[:, 2] = zt\n return X\n\n\n","sub_path":"SyntheticCurves.py","file_name":"SyntheticCurves.py","file_ext":"py","file_size_in_byte":6805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"473193787","text":"# Chris DeBoever\n# cdeboeve@ucsd.edu\n\nimport sys, argparse, pdb, glob, os, re, traceback\nimport numpy as np\nfrom bisect import bisect_left \nfrom scipy.stats import binom\n\n### helper functions ###\n\ndef find_lt(a,x):\n \"\"\"\n Find rightmost value less than x in list a\n Input: list a and value x\n Output: rightmost value less than x in a\n \"\"\"\n i = bisect_left(a,x)\n if i:\n return a[i-1]\n raise ValueError\n\ndef find_ge(a,x):\n \"\"\"\n Find leftmost item greater than or equal to x in list a\n Input: list a and value x\n Output: leftmost value less than or equal to x in a\n \"\"\"\n i = bisect_left(a,x)\n if i != len(a):\n return a[i]\n raise ValueError\n\ndef get_altL(fn):\n \"\"\"\n Make a list of alternate allele frequencies and number of reads\n Input: tsv file with reference freq in first column and alterate freq in second column\n Output: a list of tuples with number of reads and alternate allele frequency\n \"\"\"\n f = open(fn,'r')\n linesL = [ x.strip().split('\\t') for x in f.readlines() ]\n f.close()\n if linesL[0][0][0] == '#':\n linesL = linesL[1:]\n for i in range(len(linesL)):\n if linesL[i][4] == '0': # if the number of reads supporting alternate is 0, we'll switch to 1 so avoid numeric issues\n linesL[i][4] = '1'\n return zip([ int(x[4])+int(x[5]) for x in linesL ], [ float(x[5])/(float(x[4])+float(x[5])) for x in linesL ]) # each tuple is [freq,num_reads]\n\n# def generate_cancer_possible_freqL(pL,sL,er): \n# I want to make a function which generates the likely frequencies seen in a cancer sample. This would exclude double-hit mutations (i.e. a single site gains somatic mutations on both chromosomes). This simplifications can only be made in the diploid case, however, because ploidy-variable populations might be weird...\n\ndef generate_possible_freqL(pL,sL,er): \n \"\"\"\n Generate list of possible allele frequencies\n Input: ploidy list, frequency (of each subpopulation) list, and sequencing error rate\n Output: list of possible allele frequences\n \"\"\"\n h = sum(pL) # number of different haplotypes\n L = [ bin(x)[2:] for x in range(1,2**h-1) ] # range from 1 to 2**h-1 because we don't want 0% or 100% allele freq\n M = [ '0'*(len(L[-1])-len(x))+x for x in L ]\n p_freqL = []\n for i in range(len(pL)):\n p_freqL += [sL[i]/pL[i]]*pL[i]\n p_freqA = np.array(p_freqL)\n sA = np.array(sL)\n aL = []\n for g in M:\n aL.append(sum(np.array([ int(x) for x in list(g) ])*p_freqL))\n return sorted(list(set(aL+[er,1-er]))) \n\ndef freq_to_genotype(pL,sL,er): \n \"\"\"\n Creates dict of expected alternate allele frequencies and consistent genotypes\n Input: ploidy list, frequency (of each subpopulation) list, and sequencing error rate\n Output: dict of expected alternate allele frequencies and consistent genotypes. Genotypes represented as binary strings in the order of the ploidy list\n \"\"\"\n h = sum(pL) # number of different haplotypes\n L = [ bin(x)[2:] for x in range(1,2**h-1) ] # range from 1 to 2**h-1 because we don't want 0% or 100% allele freq\n M = [ '0'*(len(L[-1])-len(x))+x for x in L ]\n p_freqL = []\n for i in range(len(pL)):\n try:\n p_freqL += [sL[i]/pL[i]]*pL[i]\n except:\n print >>sys.stderr, 'wacka'\n print >>sys.stderr, sL, pL, i\n sys.stderr.flush()\n 0 / asdf\n p_freqA = np.array(p_freqL)\n sA = np.array(sL)\n aD = {} # dict where each key is an expected alternate allele frequency and each value is a list of genotypes consistent with this alternate allele frequency\n for g in M:\n alt_freq = sum(np.array([ int(x) for x in list(g) ])*p_freqL)\n if aD.has_key(alt_freq):\n aD[alt_freq].append(g)\n else:\n aD[alt_freq] = [g]\n aD[er] = ['0'*(len(L[-1])-1) + bin(0)[2:]] # add genotype for 0% alternate allele freq\n aD[1-er] = [bin(2**h-1)[2:]] # add genotype for 100% alternate allele freq\n return aD\n\ndef collapse_genotypes(pL,gL):\n \"\"\"\n Reduces a list of genotypes to distinct genotypes given ploidy\n Input: ploidy list pL and list of genotypes gL where each genotype is a binary string ordered according to ploidy list\n Output: genotype list with non-redundant genotypes\n \"\"\"\n if len(gL) < 2:\n return gL\n else:\n uniqueL = [] # list of unique genotypes relative to ploidy\n for g in gL:\n s = ''\n for i in xrange(len(pL)):\n s += ''.join(sorted(g[0:pL[i]]))\n g = g[pL[i]:]\n if s not in uniqueL:\n uniqueL.append(s)\n return uniqueL\n \ndef grid_search_parameters(step):\n \"\"\"\n Make a list of parameters to try\n Input: step size\n Output: subpopulation frequencies to try\n \"\"\"\n f1 = list(np.arange(step,1,step))\n f2 = list(np.arange(step,1,step))\n f2.reverse()\n return zip(f1,f2)\n\ndef estimate_genotype(alt_freq,exp_freqL):\n \"\"\"\n Maximum likelihood estimator of alt_freq given possibilities in exp_freqL\n Input: observed alternate frequency and list of expected alternate frequencies\n Output: ML estimator of true alternate allele frequency\n \"\"\"\n try:\n i = find_lt(exp_freqL,alt_freq) # Find rightmost value less than x\n except ValueError:\n i = float(\"-inf\")\n try:\n j = find_ge(exp_freqL,alt_freq) # Find leftmost item greater than or equal to x\n except ValueError:\n j = float(\"inf\")\n if alt_freq-i < j-alt_freq:\n return i\n else:\n return j\n\ndef main():\n ### magic variables ###\n # these variables can be set at the command line as well\n ploidyL = [2,2] # the entries in this list are the expected ploidy of each subpopulation. Default is two diploid subpopulations\n error_rate = 0.001 # sequencing error rate\n cov_cutoff = 4 # coverage cutoff for variant sites\n\n ### gather command line arguments ###\n parser = argparse.ArgumentParser(description='This script determines the relative frequencies of different populations and estimates the genotypes.')\n parser.add_argument('infile', help='Input tsv file. Columns should be: chrom, position, ref base, alt base, number of reads supporting reference, number of reads supporting alternate.')\n parser.add_argument('-o', nargs='?', type=argparse.FileType('w'),default=sys.stdout, help='Output file. Default: standard out')\n parser.add_argument('-pL', default=ploidyL, type=int, nargs='+', help='A list of ploidies. Each entry in the list represents the anticipated ploidy of a subpopulation. For instance, if you expect two diploid subpopulations and one triploid subpopulation, enter 2 2 3. Default: {0}'.format(' '.join([str(x) for x in ploidyL])))\n parser.add_argument('-er', default=error_rate, type=float, help='Sequencing error rate. For instance, 0.01 means that 1/100 base calls will be incorrect. Default: {0}'.format(error_rate))\n parser.add_argument('-cc', default=cov_cutoff, type=int, help='Coverage cutoff. If the coverage of either the alternate or reference allele is less than or equal to this value, the site will not be considered as a variant site. Default: {0}'.format(cov_cutoff))\n parser.add_argument('-d', action='store_true', help='Enable python debugger.')\n \n args = parser.parse_args()\n \n inN = args.infile\n outF = args.o\n ploidyL = args.pL\n error_rate = args.er\n debug = args.d\n cov_cutoff = args.cc\n\n inN = os.path.realpath(inN) # get the input file path\n\n if len(ploidyL) > 2:\n print >>sys.stderr, 'Sorry, only two subpopulations are currently supported.'\n sys.exit(1)\n\n ### find population frequencies ###\n\n parL = grid_search_parameters(0.01) # grid search\n\n germ_mu = 0.001\n soma_mu = 0.00001\n\n at_prob = 1/2. # Marginal probability of normal being AT\n tt_prob = 1/2. # Marginal probability of normal being TT\n\n # List of possible genotype pairs (normal, cancer)\n genotypes = [('AA', 'AA'), ('AA','AT'), ('AT','AT'), ('TT','TT')]\n\n genL = [(0, 0, (1 - germ_mu)*(1 - soma_mu)), # ('AA','AA')\n (0, 0.5, (1 - germ_mu) * soma_mu), # ('AA','AT')\n (0.5, 0.5, germ_mu * at_prob * (1 - soma_mu)) , # ('AT','AT')\n (1, 1, germ_mu * tt_prob * (1 - soma_mu)) , # ('TT','TT')\n ]\n\n np.seterr(divide='ignore') # Disable numpy warning messages for dividing by 0\n\n read_list = [x.split('\\t')[4:6] for x in open(inN).read().split('\\n') if x!='' and x[0]!='#']\n read_list = [(int(x[1]), int(x[0])+int(x[1])) for x in read_list]\n \n # print >>sys.stderr, 'Enumerating log likelihoods'\n \n from numpy import log # Faster function call\n from scipy.stats import binom\n from scipy.stats import poisson\n\n binom_pmf = binom.pmf\n poisson_pmf = poisson.pmf\n\n def compute_likelihood(alt_reads, num_reads, normal_freq, normal_alpha, cancer_freq, cancer_alpha, error_rate):\n alt_freq = round(normal_freq*normal_alpha + cancer_freq*cancer_alpha, 4)\n\n def pmf_mod(x, N, p):\n if x < 0 or x > N:\n return 0\n elif (x==0 and p==0) or (x==N and p==1):\n return 1\n else:\n return binom_pmf(x,N,p)\n\n mu = num_reads * error_rate # Poisson parameter lambda\n\n x = 0\n x += sum([pmf_mod(alt_reads + k, num_reads, alt_freq)*poisson_pmf(k, mu) for k in range(0,min(2, num_reads-alt_reads)+1)])\n x += sum([pmf_mod(alt_reads - k, num_reads, alt_freq)*poisson_pmf(k, mu) for k in range(1,min(2, alt_reads)+1)])\n return x\n\n read_list = [(alt_reads, num_reads) for alt_reads, num_reads in read_list if alt_reads > cov_cutoff and (num_reads - alt_reads) > cov_cutoff and num_reads > cov_cutoff]\n \n f = open(inN.split('.txt')[0]+'.ll', 'w')\n\n ll_list = []\n for normal_alpha, cancer_alpha in parL:\n\n ll = sum([\\\n log(sum([freq_prob*compute_likelihood(alt_reads, num_reads, normal_freq, normal_alpha, cancer_freq, cancer_alpha, error_rate)\\\n for normal_freq, cancer_freq, freq_prob in genL]))\\\n for alt_reads, num_reads in read_list if alt_reads!=0 and alt_reads!=num_reads])\n\n print >>f, str(ll)+'\\t'+str(normal_alpha)+'\\t'+str(cancer_alpha)\n f.flush()\n\n ll_list.append(ll)\n\n f.close()\n\n best_ll, best_par = max(zip(ll_list, parL), key=lambda x: x[0]) \n\n ### Determine genotypes\n print >>outF, '#log-likelihood\\t{0}\\n#population frequencies\\t{1}'.format(best_ll,'\\t'.join([ str(x) for x in best_par ]))\n \n # Re-read the input tsv file (before imposing coverage cutoff)\n site_list = [x.split('\\t') for x in open(inN).read().split('\\n') if x!='' and x[0]!='#']\n\n parser.add_argument('infile', help='Input tsv file. Columns should be: chrom, position, ref base, alt base, number of reads supporting reference, number of reads supporting alternate.')\n \n for chrom, pos, t1, t2, ref_reads, alt_reads in site_list:\n alt_reads = int(alt_reads)\n num_reads = int(ref_reads) + alt_reads\n \n ll_list = [freq_prob*compute_likelihood(alt_reads, num_reads, normal_freq, best_par[0], cancer_freq, best_par[1], error_rate) for normal_freq, cancer_freq, freq_prob in genL]\n gen_idx, ll = max(enumerate(ll_list), key=lambda x:x[1])\n \n normal_gen, cancer_gen = genotypes[gen_idx]\n \n print >>outF, '\\t'.join([chrom,pos,normal_gen,cancer_gen])\n\nif __name__ == '__main__':\n main()\n","sub_path":"mixed_variant_calling_fork_fork.py","file_name":"mixed_variant_calling_fork_fork.py","file_ext":"py","file_size_in_byte":11667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"336087465","text":" #!/usr/bin/env python\nimport os\nimport re\nimport sys\nimport warnings\nimport versioneer\n\nfrom setuptools import setup, find_packages\n\nDISTNAME = 'xmitgcm'\nLICENSE = 'Apache'\nAUTHOR = 'Ryan Abernathey'\nAUTHOR_EMAIL = 'rpa@ldeo.columbia.edu'\nURL = 'https://github.com/MITgcm/xmitgcm'\nCLASSIFIERS = [\n 'Development Status :: 4 - Beta',\n 'License :: OSI Approved :: Apache Software License',\n 'Operating System :: OS Independent',\n 'Intended Audience :: Science/Research',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n 'Topic :: Scientific/Engineering',\n]\n\nINSTALL_REQUIRES = ['xarray >= 0.14.1', 'dask >= 1.0', 'cachetools']\nSETUP_REQUIRES = ['pytest-runner']\nTESTS_REQUIRE = ['pytest >= 4.0', 'coverage']\n\nDESCRIPTION = \"Read MITgcm mds binary files into xarray\"\ndef readme():\n with open('README.rst') as f:\n return f.read()\n\nsetup(name=DISTNAME,\n version=versioneer.get_version(),\n cmdclass=versioneer.get_cmdclass(),\n license=LICENSE,\n author=AUTHOR,\n author_email=AUTHOR_EMAIL,\n classifiers=CLASSIFIERS,\n description=DESCRIPTION,\n long_description=readme(),\n install_requires=INSTALL_REQUIRES,\n setup_requires=SETUP_REQUIRES,\n tests_require=TESTS_REQUIRE,\n url=URL,\n packages=find_packages(),\n python_requires='>=3.7')\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"67003301","text":"\"\"\"\nNose tests for free_times.py\nAuthor: Solomon Zook\n\"\"\"\nfrom free_times import get_free_times # this is what flask_main uses\nimport arrow\nimport time\nimport datetime\n\nd1 = arrow.get(\"2016/11/21\", \"YYYY/MM/DD\")\nd2 = arrow.get(\"2016/11/25\", \"YYYY/MM/DD\")\n\nt1 = arrow.get(\"12:00 AM\", \"h:mm A\")\nt2 = arrow.get(\"2:00 AM\", \"h:mm A\")\nt3 = arrow.get(\"3:00 PM\", \"h:mm A\")\nt4 = arrow.get(\"4:00 PM\", \"h:mm A\")\n\nev1 = [] #events from 12-15 each day\nfor i in range(3):\n ev1.append([d1.replace(days=i, hour=12), d1.replace(days=i, hour=15), \"12-15\"])\n\nev2 = [] #events from 12-13, 13-15, and 13:30-14 each day\nfor i in range(3):\n ev2.append([d1.replace(days=i, hour=12), d1.replace(days=i, hour=13), \"12-13\"])\n ev2.append([d1.replace(days=i, hour=13), d1.replace(days=i,hour=15), \"13-15\"])\n ev2.append([d1.replace(days=i, hour=13, minute=30), d1.replace(days=i, hour=14), \"13:30-14\"])\n \nev3 = [] #events from 12-14 and 13-15 each day\nfor i in range(3):\n ev3.append([d1.replace(days=i, hour=12), d1.replace(days=i,hour=14), \"12-14\"])\n ev3.append([d1.replace(days=i, hour=13), d1.replace(days=i,hour=15), \"13-15\"])\n\nev4 = [] #events from 2-4 and 5-11 each day\nfor i in range(3):\n ev4.append([d1.replace(days=i, hour=2), d1.replace(days=i,hour=4), \"2-4\"])\n ev4.append([d1.replace(days=i, hour=5), d1.replace(days=i,hour=11), \"5-11\"])\n\npiazza_test_cal = [] #test calendar taken from a piazza post\n\n\nd1=d1.isoformat()\nd2=d2.isoformat()\nt1=t1.isoformat()\nt2=t2.isoformat()\nt3=t3.isoformat()\nt4=t4.isoformat()\n\ndef test_invalid():\n \"\"\"\n test for invalid inputs\n \"\"\"\n assert get_free_times(t2, t1, d1, d2, ev1) == []#time range can't go backwards\n assert get_free_times(t1,t1,d1,d2,ev1) == []#no time gap would crash Appt class\n assert get_free_times(t1,t3,d2,d1,ev1) == []#date range can't go backwards\n assert get_free_times(t2,t3,d1,d1,ev1) != []#searching for 1 day is okay\n\ndef test_output():\n \"\"\"\n test that outputs are the expected values for a test list with 2 events each day.\n Also, test that when the date range is one day to itself get_free_times returns an \n enrty for a single day and contains the correct values.\n \"\"\"\n li1 = get_free_times(t1,t3,d1,d2,ev4)\n assert len(li1) == 5\n days = []\n times = [[0,2], [4,5], [11, 15]]\n\n for i in range(3):\n days.append(arrow.get(d1).replace(days=i))\n assert len(li1[i]) == 3\n for j in range(3):\n assert li1[i][j]['begin'] == days[i].replace(hour=times[j][0]).isoformat()\n assert li1[i][j]['end'] == days[i].replace(hour=times[j][1]).isoformat()\n\n li2 = get_free_times(t1,t3,d1,d1,ev4)\n assert len(li2) == 1\n for i in range(3):\n assert li1[0][i]['begin'] == li2[0][i]['begin']\n assert li1[0][i]['end'] == li2[0][i]['end']\n\n\ndef test_touching():\n \"\"\"\n make sure no free times are given between touching appointments\n \"\"\"\n li1 = get_free_times(t1,t4,d1,d2,ev1)\n li2 = get_free_times(t1,t4,d1,d2,ev2)\n assert len(li1) == len(li2)\n for i in range(len(li1)):\n assert len(li1[i]) == len(li2[i])\n for j in range(len(li1[i])):\n assert li1[i][j]['begin'] == li2[i][j]['begin']\n assert li1[i][j]['end'] == li2[i][j]['end']\n\ndef test_overlapping():\n \"\"\"\n make sure no free times are given between overlapping appointments\n \"\"\"\n li1 = get_free_times(t1,t4,d1,d2,ev1)\n li2 = get_free_times(t1,t4,d1,d2,ev3)\n assert len(li1) == len(li2)\n for i in range(len(li1)):\n assert len(li1[i]) == len(li2[i])\n for j in range(len(li1[i])):\n assert li1[i][j]['begin'] == li2[i][j]['begin']\n assert li1[i][j]['end'] == li2[i][j]['end']\n\n","sub_path":"test_free_times.py","file_name":"test_free_times.py","file_ext":"py","file_size_in_byte":3700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"626745587","text":"# Official documentation for the FileBound API can be found at\n# https://yoursite.com/api/documentation\n\n\"\"\" This script contains three functions to login, query, and save content from the FileBound server.\nWhen ran by itself, the script will perform a query on a file with a member ID of\n12965113, a convention start date of 07/16/2018, that is a DELCredForm Doctype. The images within the file\nare saved to a 'afscme_images' folder that is made by the script wherever the script is ran from. \"\"\"\n\nimport requests, os, base64\n\nfbsite = 'https://yoursite.com/'\noutputpath = os.path.dirname(os.path.realpath(__file__)) + '/afscme_images/'\nif not os.path.exists(outputpath):\n os.makedirs(outputpath)\n\ndef login(fbserver):\n \"\"\"Authenticates into the site, returns a GUID if successful\"\"\"\n \n #Take creds from input, or hardcode them here\n #u = input('Username: ')\n #p = input('Password: ')\n data = {\n 'username': 'not-batman',\n 'password': 'your-cool-password'\n }\n \n #format login string, then try to login\n login = '{}api/login'.format(fbserver)\n try:\n r = requests.post(login, data)\n return r.json()\n except error as e:\n print(e)\n\n\ndef query_site(field4, field5, field7):\n \"\"\"Queries the site, if the query finds a file. Returns response data as a JSON values if content is found\"\"\"\n #Format the query URL that will be used to GET content from the site\n url = '{}api/query/projectId_5/F4_{}~,F5From_{}~_F5To_{}~,F7_{}~/divider_/binaryData?guid={}'.format(fbsite, field4, field5, field5, field7, guid)\n\n #Make the request, get a response\n r = requests.get(url)\n \n #If status 404, successfully found no files\n if r.status_code == 404:\n print('File not found')\n \n #If status 200, successfully found file(s)\n elif r.status_code == 200:\n data = r.json()\n \n #Check the response for files, return data if it has contents\n if data[0]['files']['collection']:\n print('File(s) with Member ID {} found on site'.format(field4))\n return(data)\n\n #If the response had no collection, it is because the returned file had no contents\n else:\n print('File with Member ID {} not found on site'.format(field4))\n \n #Unsuccessful query, print the response object's contents and code\n else:\n print(r.text + '\\n' + r.status_code)\n\n\ndef save_images(data):\n \"\"\"Opens JSON object from the query, accesses the content and saves it out to disk\"\"\"\n \n #Iterate through files\n for item in data[0]['files']['collection']:\n \n #Iterate through documents\n for doc in item['documents']['collection']:\n \n #convert image data from base64 to binary\n image = base64.b64decode(doc['binaryData'])\n\n #save off DocID to be used in the saved image filename\n docId = doc['documentId']\n\n #save off extension to be used in the saved image filename\n extension = doc['extension']\n\n #define where images will be written to\n doc_output = outputpath + '{}.{}'.format(docId, extension)\n\n #iterate through images, writing them to disk\n with open(doc_output, 'wb') as f:\n f.write(image)\n print('wrote out DocID{} to {}'.format(docId, doc_output))\n\n \n \n\n#If this script isn't being imported into another script, do the following:\nif __name__ == '__main__':\n print('Running main code')\n guid = login(fbsite)\n query_response = query_site('12965113', '2018-07-16', 'DELCredForm')\n\n print('accessing the content...')\n save_images(query_response)\n","sub_path":"afscme-code-example.py","file_name":"afscme-code-example.py","file_ext":"py","file_size_in_byte":3701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"437064462","text":"# Collatz Conjecture\n# if number is even, divide by 2; if odd, multiply by 3 and add 1\n\ndef start():\n number = int(input(\"Hi, it's Collatz Conjecture algorithm, please insert number bigger than 1: \"))\n count = 0\n while number != 1:\n if number % 2 == 0:\n number /= 2\n count += 1\n elif number % 2 != 0:\n number = (number*3)+1\n count += 1\n return (\"You needed %s operations to reach one\" % count)\n\nprint(start()) \n \ninput()\n","sub_path":"SmallProjects/CollatzConjecture.py","file_name":"CollatzConjecture.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"32410299","text":"def dictionary():\n N=int(input())\n paper=[]\n query_li=[]\n dic={}\n for i in range(0,N):\n paper.append(input().split(\" \"))\n M=int(input())\n for i in range(0,M):\n query_li.append(input())\n for item in paper:\n L=int(item[0])\n for i in range(1,L+1):\n if item[i] not in dic.keys():\n dic[item[i]]=[paper.index(item)+1]\n else:\n dic[item[i]].append(paper.index(item)+1)\n for query in query_li:\n if query not in dic.keys():\n print(\" \")\n else:\n for idx in dic[query]:\n print(idx,end=\" \")\n print()\n\nif __name__=='__main__':\n dictionary()\n","sub_path":"Code/CodeRecords/2446/60617/303164.py","file_name":"303164.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"293898505","text":"# for command and option parsing\nfrom optparse import make_option\nfrom django.core.management.base import BaseCommand, CommandError\n\n# for event retrieval and saving\nfrom cfsite.apps.events.models import Event, Location, Category, MAX_DESCRIPTION_LEN, MAX_NAME_LEN\nfrom cfsite.apps.crawlers.deduplication import SimpleDeduplicator\nfrom cfsite.apps.crawlers.management.commands._import_from_feeds \\\n import get_and_parse_stanford_general, get_and_parse_stanford_sport, get_and_parse_cityofpaloalto, \\\n get_and_parse_paloaltoplayers\nfrom cfsite.apps.crawlers.management.commands._import_from_ebrite import get_and_parse_eventbrite_JSON\nfrom cfsite.apps.crawlers.management.commands._import_from_meetup import get_and_parse_meetup_JSON\nfrom cfsite.apps.crawlers.management.commands._errors import SourceRetrievalError\nfrom django.db.utils import DataError\n\nclass Command(BaseCommand):\n \"\"\"\n Defines the behavior of and options accepted by\n python manage.py import_events.\n\n Since this command could be called from call_command, in\n which case we might want to redirect the output, nothing\n in this class or the helper methods that it calls should\n call print. All output should be directed to self.stdout\n or self.stderr.\n \"\"\"\n help = 'Pulls events from various apis and feeds and adds to database'\n\n SOURCE_TYPES = ['api', 'feed']\n API_SOURCES = ['ebrite','meetup']\n FEED_SOURCES = ['stanford-general', 'stanford-sport', 'cityofpaloalto', 'paloaltoplayers']\n SOURCES = API_SOURCES + FEED_SOURCES\n SOURCE_TO_GEN = dict(zip(SOURCES, [\n get_and_parse_eventbrite_JSON,\n get_and_parse_meetup_JSON,\n get_and_parse_stanford_general,\n get_and_parse_stanford_sport,\n get_and_parse_cityofpaloalto,\n get_and_parse_paloaltoplayers]))\n\n option_list = BaseCommand.option_list + (\n make_option('--source_type',\n action='store',\n type='string',\n help='What type of sources to pull from. '\n 'Either \\'apis\\' or \\'feeds\\''),\n make_option('--sources',\n action='store',\n type='string',\n help='Which sources to pull from. '\n 'Choices are %s' % (' '.join(FEED_SOURCES)),\n )\n )\n\n def handle(self, *args, **options):\n source_list = options.get('sources')\n source_type = options.get('source_type')\n source_generators = self.SOURCES # default to all sources\n if source_list and source_type:\n raise SourceRetrievalError(\"Cannot simultaneously specify both sources and source_type\")\n elif source_list:\n source_list = self._validate_and_parse_into_list(source_list)\n source_generators = source_list\n elif source_type:\n if source_type == \"apis\":\n source_generators = self.API_SOURCES\n elif source_type == \"feeds\":\n source_generators = self.FEED_SOURCES\n else:\n raise SourceRetrievalError(\"Unrecognized source_type: %s\" % source_type)\n\n self._import_events(self._get_sources_generators(source_generators))\n\n def _get_sources_generators(self, sources_str_list):\n \"\"\"\n Takes a list of strings specifying the sources.\n Returns a list of generators that yield data from those sources.\n \"\"\"\n return [self.SOURCE_TO_GEN[source_str]() for source_str in sources_str_list]\n\n def _validate_and_parse_into_list(self,sources_str):\n \"\"\"\n Takes a comma, separated list of sources, checks that each listed\n source is a valid source to pull from, returns list of source\n names that can be passed to _get_sources_generators\n \"\"\"\n sources_list = sources_str.split(\",\")\n for source in sources_list:\n if not source in self.SOURCES:\n raise SourceRetrievalError(\"Unrecognized source: %s\" % source)\n return sources_list \n\n def _save_event_model(self, event_list):\n \"\"\"\n Save each of the events (represented as dicts)\n in event_list.\n \"\"\"\n self.stdout.write('Saving events to database:')\n for event_dict in event_list:\n ev = Event(\n name=event_dict['name'][:MAX_NAME_LEN],\n event_location=Location.objects.get_or_create(\n city='Palo Alto',\n state_province='CA',\n zip_code=94303,\n country='United States',\n timezone='US/Pacific',\n )[0], # discard second element (a bool) of tuple\n event_start_date=event_dict['start_datetime'].date(),\n event_start_time=event_dict['start_datetime'].time(),\n is_valid_event=True)\n\n if 'end_datetime' in event_dict:\n ev.event_end_date = event_dict['end_datetime'].date()\n ev.event_end_time = event_dict['end_datetime'].time()\n if 'price' in event_dict:\n ev.price = event_dict['price']\n if 'url' in event_dict:\n ev.website = event_dict['url']\n if 'description' in event_dict:\n if len(event_dict['description']) > MAX_DESCRIPTION_LEN:\n ev.description = 'Please visit event website for the event description.'\n else:\n ev.description = event_dict['description'][:MAX_DESCRIPTION_LEN]\n self.stdout.write('Description len: %s' % len(ev.description))\n if 'address' in event_dict:\n ev.address = event_dict['address']\n\n if (SimpleDeduplicator.is_duplicate(ev)):\n self.stdout.write('Skipping duplicate...')\n else:\n self.stdout.write(event_dict['name'])\n try: \n ev.save()\n for category in event_dict['categories']:\n cat, unused_is_new_bool = Category.objects.get_or_create(base_name=category)\n ev.category.add(cat)\n except DataError:\n pass # could not save event, probably some field is too long for our db. skip\n\n def _import_events(self, sources_generators):\n for gen in sources_generators:\n try:\n while True:\n self._save_event_model(next(gen))\n except StopIteration:\n self.stdout.write('...Finished pulling from one data source') # TODO (susanctu): in future, maybe we want to print some stats\n\n\n","sub_path":"cfsite/apps/crawlers/management/commands/import_events.py","file_name":"import_events.py","file_ext":"py","file_size_in_byte":6597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"495123276","text":"# _ __ _ ___ _ ___ _ _\n# | |/ /_ _ __ _| |_ ___ __/ __| __ _| |___ _ __ ___| _ \\ |_ _ __ _(_)_ _\n# | ' <| '_/ _` | _/ _ (_-<__ \\/ _` | / _ \\ ' \\/ -_) _/ | || / _` | | ' \\\n# |_|\\_\\_| \\__,_|\\__\\___/__/___/\\__,_|_\\___/_|_|_\\___|_| |_|\\_,_\\__, |_|_||_|\n# |___/\n# License: BSD License ; see LICENSE\n#\n# Main authors: Philipp Bucher (https://github.com/philbucher)\n#\n\n# set up testing environment (before anything else)\nimport initialize_testing_environment\n\n# python imports\nimport unittest\n\n# plugin imports\nimport kratos_salome_plugin.utilities as utils\n\n# tests imports\nimport testing_utilities\n\nif utils.IsExecutedInSalome():\n # imports that have dependenices on salome, hence can only be imported if executed in salome\n import salome\n import GEOM\n import SMESH\n import salome_study\n import kratos_salome_plugin.salome_dependent.salome_utilities as salome_utils\n\n\nclass TestSalomeTestCaseStudyCleaning(testing_utilities.SalomeTestCase):\n # test to make sure that the cleaning of studies between tests works correctly\n\n # the order of execution is not deterministic, hence we need a flag\n already_executed = False\n num_objs_in_study = None\n\n def setUp(self):\n super().setUp()\n\n # create geometry\n O = self.geompy.MakeVertex(0, 0, 0)\n OX = self.geompy.MakeVectorDXDYDZ(1, 0, 0)\n OY = self.geompy.MakeVectorDXDYDZ(0, 1, 0)\n OZ = self.geompy.MakeVectorDXDYDZ(0, 0, 1)\n Box_1 = self.geompy.MakeBoxDXDYDZ(200, 200, 200)\n self.geompy.addToStudy( O, 'O' )\n self.geompy.addToStudy( OX, 'OX' )\n self.geompy.addToStudy( OY, 'OY' )\n self.geompy.addToStudy( OZ, 'OZ' )\n self.geompy.addToStudy( Box_1, 'Box_1' )\n\n # create mesh\n from salome.smesh import smeshBuilder\n Mesh_1 = self.smesh.Mesh(Box_1)\n Regular_1D = Mesh_1.Segment()\n Max_Size_1 = Regular_1D.MaxSize(34.641)\n MEFISTO_2D = Mesh_1.Triangle(algo=smeshBuilder.MEFISTO)\n NETGEN_3D = Mesh_1.Tetrahedron()\n isDone = Mesh_1.Compute()\n\n ## Set names of Mesh objects\n self.smesh.SetName(Regular_1D.GetAlgorithm(), 'Regular_1D')\n self.smesh.SetName(NETGEN_3D.GetAlgorithm(), 'NETGEN 3D')\n self.smesh.SetName(MEFISTO_2D.GetAlgorithm(), 'MEFISTO_2D')\n self.smesh.SetName(Max_Size_1, 'Max Size_1')\n self.smesh.SetName(Mesh_1.GetMesh(), 'Mesh_1')\n\n def test_1(self):\n self.__CheckStudy()\n\n def test_2(self):\n self.__CheckStudy()\n\n def __CheckStudy(self):\n if TestSalomeTestCaseStudyCleaning.already_executed:\n # make sure the number of components is the same!\n current_num_objs_in_study = GetNumberOfObjectsInStudy(self.study)\n # if this check fails it means that the study was not cleaned, leftover objects exist!\n self.assertEqual(current_num_objs_in_study, TestSalomeTestCaseStudyCleaning.num_objs_in_study)\n else:\n TestSalomeTestCaseStudyCleaning.already_executed = True\n # if executed for the first time then count the components\n TestSalomeTestCaseStudyCleaning.num_objs_in_study = GetNumberOfObjectsInStudy(self.study)\n\n\ndef GetNumberOfObjectsInStudy(the_study):\n # adapted from python script \"salome_study\" in KERNEL py-scripts\n def GetNumberOfObjectsInComponent(SO):\n num_objs_in_comp = 0\n it = the_study.NewChildIterator(SO)\n while it.More():\n CSO = it.Value()\n num_objs_in_comp += 1 + GetNumberOfObjectsInComponent(CSO)\n it.Next()\n return num_objs_in_comp\n\n # salome_study.DumpStudy() # for debugging\n\n itcomp = the_study.NewComponentIterator()\n num_objs_in_study = 0\n while itcomp.More(): # loop components (e.g. GEOM, SMESH)\n SC = itcomp.Value()\n num_objs_in_study += 1 + GetNumberOfObjectsInComponent(SC)\n itcomp.Next()\n return num_objs_in_study\n\n\nclass TestSalomeUtilities(testing_utilities.SalomeTestCaseWithBox):\n def test_IsMesh(self):\n meshes = [\n self.mesh_tetra\n ]\n\n not_meshes = [\n self.mesh_tetra.GetMesh(),\n self.sub_mesh_tetra_f_1,\n self.sub_mesh_tetra_g_1,\n self.box,\n self.face_1,\n self.group_faces,\n self.group_tetra_0D_elements,\n self.group_hexa_ball_elements,\n self.group_tetra_f1_nodes,\n self.group_tetra_f1_faces,\n self.group_hexa_edges\n ]\n\n for mesh in meshes:\n self.assertTrue(salome_utils.IsMesh(mesh))\n\n for not_mesh in not_meshes:\n self.assertFalse(salome_utils.IsMesh(not_mesh))\n\n\n def test_IsMeshProxy(self):\n meshes = [\n self.mesh_tetra.GetMesh()\n ]\n\n not_meshes = [\n self.mesh_tetra,\n self.sub_mesh_tetra_f_1,\n self.sub_mesh_tetra_g_1,\n self.box,\n self.face_1,\n self.group_faces,\n self.group_tetra_0D_elements,\n self.group_hexa_ball_elements,\n self.group_tetra_f1_nodes,\n self.group_tetra_f1_faces,\n self.group_hexa_edges\n ]\n\n for mesh in meshes:\n self.assertTrue(salome_utils.IsMeshProxy(mesh))\n\n for not_mesh in not_meshes:\n self.assertFalse(salome_utils.IsMeshProxy(not_mesh))\n\n def test_IsSubMeshProxy(self):\n sub_meshes = [\n self.sub_mesh_tetra_f_1,\n self.sub_mesh_tetra_g_1\n ]\n\n not_sub_meshes = [\n self.mesh_tetra,\n self.mesh_tetra.GetMesh(),\n self.box,\n self.face_1,\n self.group_faces,\n self.group_tetra_0D_elements,\n self.group_hexa_ball_elements,\n self.group_tetra_f1_nodes,\n self.group_tetra_f1_faces,\n self.group_hexa_edges\n ]\n\n for sub_mesh in sub_meshes:\n self.assertTrue(salome_utils.IsSubMeshProxy(sub_mesh))\n\n for not_sub_mesh in not_sub_meshes:\n self.assertFalse(salome_utils.IsSubMeshProxy(not_sub_mesh))\n\n def test_IsMeshGroup(self):\n mesh_groups = [\n self.group_tetra_0D_elements, # type \"SMESH._objref_SMESH_Group\"\n self.group_hexa_ball_elements, # type \"SMESH._objref_SMESH_Group\"\n self.group_tetra_f1_nodes, # type \"SMESH._objref_SMESH_GroupOnGeom\"\n self.group_tetra_f1_faces, # type \"SMESH._objref_SMESH_GroupOnGeom\"\n self.group_hexa_edges # \"SMESH._objref_SMESH_GroupOnFilter\"\n ]\n\n not_mesh_groups = [\n self.sub_mesh_tetra_f_1,\n self.sub_mesh_tetra_g_1,\n self.mesh_tetra,\n self.mesh_tetra.GetMesh(),\n self.box,\n self.face_1,\n self.group_faces\n ]\n\n for mesh_group in mesh_groups:\n self.assertTrue(salome_utils.IsMeshGroup(mesh_group))\n\n for not_mesh_group in not_mesh_groups:\n self.assertFalse(salome_utils.IsMeshGroup(not_mesh_group))\n\n def test_IsAnyMesh(self):\n mesh_groups = [\n self.group_tetra_0D_elements,\n self.group_hexa_ball_elements,\n self.group_tetra_f1_nodes,\n self.group_tetra_f1_faces,\n self.group_hexa_edges,\n self.sub_mesh_tetra_f_1,\n self.sub_mesh_tetra_g_1,\n self.mesh_tetra,\n self.mesh_tetra.GetMesh()\n ]\n\n not_mesh_groups = [\n self.box,\n self.face_1,\n self.group_faces\n ]\n\n for mesh_group in mesh_groups:\n self.assertTrue(salome_utils.IsAnyMesh(mesh_group))\n\n for not_mesh_group in not_mesh_groups:\n self.assertFalse(salome_utils.IsAnyMesh(not_mesh_group))\n\n def test_DoMeshesBelongToSameMainMesh(self):\n self.assertTrue(salome_utils.DoMeshesBelongToSameMainMesh([])) # empty input should return True\n\n meshes_same_main_mesh = [\n self.mesh_tetra.GetMesh(),\n self.sub_mesh_tetra_f_1,\n self.sub_mesh_tetra_g_1,\n self.sub_mesh_tetra_e_2,\n self.group_tetra_f1_faces,\n self.group_tetra_0D_elements\n ]\n\n meshes_not_same_main_mesh = [\n self.mesh_hexa.GetMesh(),\n self.sub_mesh_tetra_f_1,\n self.sub_mesh_tetra_g_1,\n self.sub_mesh_tetra_e_2,\n self.group_tetra_f1_faces,\n self.group_tetra_0D_elements\n ]\n\n meshes_not_meshes = [\n self.mesh_hexa.GetMesh(),\n self.box\n ]\n\n mesh_identifiers_same_main_mesh = [salome_utils.GetSalomeID(mesh) for mesh in meshes_same_main_mesh]\n mesh_identifiers_not_same_main_mesh = [salome_utils.GetSalomeID(mesh) for mesh in meshes_not_same_main_mesh]\n identifiers_not_meshes = [salome_utils.GetSalomeID(mesh) for mesh in meshes_not_meshes]\n\n self.assertTrue(salome_utils.DoMeshesBelongToSameMainMesh(mesh_identifiers_same_main_mesh))\n self.assertFalse(salome_utils.DoMeshesBelongToSameMainMesh(mesh_identifiers_not_same_main_mesh))\n\n with self.assertRaisesRegex(Exception, 'Object with identifier \"0:1:1:1\" is not a mesh! Name: \"main_box\" , Type:'):\n salome_utils.DoMeshesBelongToSameMainMesh(identifiers_not_meshes)\n\n def test_GetSalomeObject(self):\n object_id_list = [\n (salome.smesh.smeshBuilder.meshProxy, \"0:1:2:3\"),\n (salome.smesh.smeshBuilder.submeshProxy, \"0:1:2:3:7:1\"),\n (salome.smesh.smeshBuilder.submeshProxy, \"0:1:2:3:10:1\"),\n (GEOM._objref_GEOM_Object, \"0:1:1:1\"),\n (GEOM._objref_GEOM_Object, \"0:1:1:1:1\"),\n (GEOM._objref_GEOM_Object, \"0:1:1:1:5\")\n ]\n\n for obj_id in object_id_list:\n self.assertTrue(salome_utils.ObjectExists(obj_id[1]))\n self.assertEqual(obj_id[0], type(salome_utils.GetSalomeObject(obj_id[1])))\n\n def test_GetSalomeID(self):\n # this test might fail if salome orders the ids differently in different versions\n # it should not, since the order in which the objects are added is always the same\n object_id_list = [\n (\"0:1:2:3\", self.mesh_tetra.GetMesh()),\n (\"0:1:2:3:7:1\", self.sub_mesh_tetra_f_1),\n (\"0:1:2:3:10:1\", self.sub_mesh_tetra_g_1),\n (\"0:1:1:1\", self.box),\n (\"0:1:1:1:1\", self.face_1),\n (\"0:1:1:1:5\", self.group_faces)\n ]\n\n for obj_id in object_id_list:\n self.assertEqual(obj_id[0], salome_utils.GetSalomeID(obj_id[1]))\n\n def test_GetObjectName(self):\n identifier = salome_utils.GetSalomeID(self.box)\n self.assertEqual(salome_utils.GetObjectName(identifier), self.name_main_box)\n\n identifier = salome_utils.GetSalomeID(self.mesh_tetra.GetMesh())\n self.assertEqual(salome_utils.GetObjectName(identifier), self.name_main_mesh_tetra)\n\n identifier = salome_utils.GetSalomeID(self.sub_mesh_hexa_g_2)\n self.assertEqual(salome_utils.GetObjectName(identifier), self.name_mesh_group)\n\n def test_ObjectExists(self):\n identifier = salome_utils.GetSalomeID(self.box)\n self.assertTrue(salome_utils.ObjectExists(identifier))\n\n identifier = salome_utils.GetSalomeID(self.mesh_tetra.GetMesh())\n self.assertTrue(salome_utils.ObjectExists(identifier))\n\n identifier = salome_utils.GetSalomeID(self.sub_mesh_hexa_g_2)\n self.assertTrue(salome_utils.ObjectExists(identifier))\n\n self.assertFalse(salome_utils.ObjectExists(\"0:1:2:4:10:2:1:1:4:7:8\")) # random identifier, should not exist\n self.assertFalse(salome_utils.ObjectExists(\"0:15555\")) # random identifier, should not exist\n\n def test_EntityTypeToString(self):\n self.assertEqual(\"Tetra\", salome_utils.EntityTypeToString(SMESH.Entity_Tetra))\n self.assertEqual(\"Quadrangle\", salome_utils.EntityTypeToString(SMESH.Entity_Quadrangle))\n\n def test_EntityTypeFromString(self):\n self.assertEqual(SMESH.Entity_Tetra, salome_utils.EntityTypeFromString(\"Tetra\"))\n self.assertEqual(SMESH.Entity_Quadrangle, salome_utils.EntityTypeFromString(\"Quadrangle\"))\n\n with self.assertRaisesRegex(Exception, 'The requested entity type \"WeirdGeometry\" is not available!\\nOnly the following entity types are available:\\n'):\n salome_utils.EntityTypeFromString(\"WeirdGeometry\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_salome_utilities.py","file_name":"test_salome_utilities.py","file_ext":"py","file_size_in_byte":12599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"593544364","text":"import numpy as np\nimport pandas as pd\nimport config\n\ndef convert_to_hdf():\n buys = pd.read_csv('data/buys.dat',\n index_col = False,\n names=['Session_ID','Timestamp','Item_ID','Price','Quantity'],\n parse_dates=['Timestamp'])\n buys.to_hdf('buys.hdf', 'buys')\n buys.loc[np.random.choice(buys.index, config.buys_subsample_size, replace=False)].to_hdf('buys_restricted.hdf', 'buys')\n clicks = pd.read_csv('data/clicks.dat',\n index_col = False,\n names=['Session_ID','Timestamp','Item_ID','Category'],\n parse_dates=['Timestamp'],\n dtype={'Category': 'str'})\n clicks.loc[clicks['Category'] == 'S', 'Category'] = 13\n clicks['Category'] = clicks['Category'].astype(int)\n clicks.to_hdf('clicks.hdf', 'clicks')\n clicks.loc[np.random.choice(clicks.index, config.clicks_subsample_size, replace=False)].to_hdf('clicks_restricted.hdf', 'clicks')\n test = pd.read_csv('data/test.dat',\n index_col = False,\n names=['Session_ID','Timestamp','Item_ID','Category'],\n parse_dates=['Timestamp'],\n dtype={'Category': 'str'})\n test.loc[test['Category'] == 'S', 'Category'] = 13\n test['Category'] = test['Category'].astype(int)\n test.to_hdf('test.hdf', 'test')\n test.loc[np.random.choice(test.index, config.clicks_subsample_size, replace=False)].to_hdf('test_restricted.hdf', 'test')\n\n\nconvert_to_hdf()\n","sub_path":"preproc.py","file_name":"preproc.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"339751208","text":"import requests,pyimgur\n\nclass telegram_bot():\n def __init__(self,chat_id,token):\n self.chat_id = chat_id\n self.token = token\n def send_message(self,mes):\n method = 'sendMessage'\n response = requests.post(\n url='https://api.telegram.org/bot{0}/{1}'.format(self.token, method),\n data={'chat_id': self.chat_id, 'text': mes}\n ).json()\n def send_photo(self,res):\n PATH = f'./pictures/{res}.png'\n files = {'photo':open(PATH,'rb')}\n method = \"sendPhoto\"\n response = requests.post(f'https://api.telegram.org/bot{self.token}/{method}?chat_id={self.chat_id}',files=files)\n\n\n# if __name__ == '__main__':\n # token = 'xxx'\n # chat_id = xxx\n # tb = telegram_bot(chat_id,token)\n # tb.send_photo(5)\n # tb.send_message(5)\n","sub_path":"telegram_bot.py","file_name":"telegram_bot.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"560789248","text":"from django.urls import path, include \nfrom . import views\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('signup/', views.signup, name='signup'),\n path('accounts/', include('django.contrib.auth.urls')),\n # path('secret/', views.secret_page, name='secret'),\n # path('secret2/', views.SecretPage.as_view(), name='secret2'),\n path('login/', views.LoginView.as_view(), name='login'),\n]","sub_path":"django/django_extras/pokemon/register_login_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"502247992","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2019-2020 VMware, Inc. All Rights Reserved.\n# SPDX-License-Identifier: BSD-2-Clause\n\n\"\"\"\nRun analysis on a Dockerfile\n\"\"\"\n\nimport docker\nimport logging\nimport subprocess # nosec\n\nfrom tern.utils import constants\nfrom tern.utils import rootfs\nfrom tern.classes.notice import Notice\nfrom tern.classes.image_layer import ImageLayer\nfrom tern.classes.image import Image\nfrom tern.classes.package import Package\nfrom tern.load import docker_api\nfrom tern import prep\nfrom tern.analyze import common\nfrom tern.analyze.default import filter as fltr\nfrom tern.analyze.default.dockerfile import parse\nfrom tern.analyze.default.dockerfile import lock\nfrom tern.analyze.default.container import run as crun\nfrom tern.analyze.default.container import image as cimage\nfrom tern.report import report\nfrom tern.report import formats\n\n\n# global logger\nlogger = logging.getLogger(constants.logger_name)\n\n\ndef get_dockerfile_packages():\n '''Given a Dockerfile return an approximate image object. This is mosty\n guess work and shouldn't be relied on for accurate information. Add\n Notice messages indicating as such:\n 1. Create an image with a placeholder repotag\n 2. For each RUN command, create a package list\n 3. Create layer objects with incremental integers and add the package\n list to that layer with a Notice about parsing\n 4. Return stub image'''\n stub_image = Image('easteregg:cookie')\n layer_count = 0\n for cmd in lock.docker_commands:\n if cmd['instruction'] == 'RUN':\n layer_count = layer_count + 1\n layer = ImageLayer(layer_count)\n install_commands, msg = fltr.filter_install_commands(cmd['value'])\n if msg:\n layer.origins.add_notice_to_origins(\n cmd['value'], Notice(msg, 'info'))\n pkg_names = []\n for command in install_commands:\n pkg_names.append(fltr.get_installed_package_names(command))\n for pkg_name in pkg_names:\n pkg = Package(pkg_name)\n # shell parser does not parse version pins yet\n # when that is enabled, Notices for no versions need to be\n # added here\n layer.add_package(pkg)\n return stub_image\n\n\ndef analyze_full_image(full_image, redo, driver, extension):\n \"\"\"If we are able to load a full image after a build, we can run an\n analysis on it\"\"\"\n # set up for analysis\n crun.setup(full_image)\n # analyze image\n cimage.analyze(full_image, redo, driver, extension)\n # clean up after analysis\n rootfs.clean_up()\n # we should now be able to set imported layers\n lock.set_imported_layers(full_image)\n # save to the cache\n common.save_to_cache(full_image)\n return [full_image]\n\n\ndef load_base_image():\n '''Create base image from dockerfile instructions and return the image'''\n base_image, dockerfile_lines = lock.get_dockerfile_base()\n # try to get image metadata\n if docker_api.dump_docker_image(base_image.repotag):\n # now see if we can load the image\n try:\n base_image.load_image()\n except (NameError,\n subprocess.CalledProcessError,\n IOError,\n docker.errors.APIError,\n ValueError,\n EOFError) as error:\n logger.warning('Error in loading base image: %s', str(error))\n base_image.origins.add_notice_to_origins(\n dockerfile_lines, Notice(str(error), 'error'))\n return base_image\n return None\n\n\ndef analyze_base_image(base_image, redo, driver, extension):\n \"\"\"If we are unable to load the full image, we will try to analyze\n the base image and try to extrapolate\"\"\"\n # set up for analysis\n crun.setup(base_image)\n # analyze image\n cimage.analyze(base_image, redo, driver, extension)\n # clean up\n rootfs.clean_up()\n # save the base image to cache\n common.save_to_cache(base_image)\n # let's try to figure out what packages were going to be installed in\n # the dockerfile anyway\n stub_image = get_dockerfile_packages()\n return [base_image, stub_image]\n\n\ndef full_image_analysis(dfile, redo, driver, keep, extension):\n \"\"\"This subroutine is executed when a Dockerfile is successfully built\"\"\"\n image_list = []\n # attempt to load the built image metadata\n full_image = cimage.load_full_image(dfile)\n if full_image.origins.is_empty():\n # Add an image origin here\n full_image.origins.add_notice_origin(\n formats.dockerfile_image.format(dockerfile=dfile))\n image_list = analyze_full_image(full_image, redo, driver, extension)\n else:\n # we cannot analyze the full image, but maybe we can\n # analyze the base image\n logger.error('Cannot retrieve full image metadata')\n # cleanup for full images\n if not keep:\n prep.clean_image_tars(full_image)\n return image_list\n\n\ndef base_and_run_analysis(dfile, redo, driver, keep, extension):\n \"\"\"This subroutine is executed when a Dockerfile fails build. It returns\n a base image and any RUN commands in the Dockerfile.\"\"\"\n image_list = []\n # Try to analyze the base image\n logger.debug('Analyzing base image...')\n # this will pull, dump and load the base image\n base_image = load_base_image()\n if base_image:\n if base_image.origins.is_empty():\n # add a notice stating failure to build image\n base_image.origins.add_notice_to_origins(dfile, Notice(\n formats.image_build_failure, 'warning'))\n image_list = analyze_base_image(\n base_image, redo, driver, extension)\n else:\n # we cannot load the base image\n logger.warning('Cannot retrieve base image metadata')\n # cleanup for base images\n if not keep:\n prep.clean_image_tars(base_image)\n else:\n logger.error('Cannot analyze base image')\n return image_list\n\n\ndef execute_dockerfile(args, locking=False):\n \"\"\"Execution path for Dockerfiles\"\"\"\n dfile = ''\n if locking:\n dfile = args.lock\n else:\n dfile = args.dockerfile\n logger.debug(\"Parsing Dockerfile...\")\n dfobj = parse.get_dockerfile_obj(dfile)\n # expand potential ARG values so base image tag is correct\n parse.expand_arg(dfobj)\n parse.expand_vars(dfobj)\n # Store dockerfile path and commands so we can access it during execution\n lock.load_docker_commands(dfobj)\n # attempt to build the image\n logger.debug('Building Docker image...')\n image_info = docker_api.build_and_dump(dfile)\n image_list = []\n if image_info:\n logger.debug('Docker image successfully built. Analyzing...')\n # analyze the full image\n image_list = full_image_analysis(\n dfile, args.redo, args.driver, args.keep_wd, args.extend)\n else:\n # cannot build the image\n logger.warning('Cannot build image')\n # analyze the base image and any RUN lines in the Dockerfile\n image_list = base_and_run_analysis(\n dfile, args.redo, args.driver, args.keep_wd, args.extend)\n # generate report based on what images were created\n if image_list:\n if not locking:\n report.report_out(args, *image_list)\n else:\n logger.debug('Generating locked Dockerfile...')\n # we can only lock based on a fully built image for now\n locked_dfobj = lock.lock_dockerfile(dfobj, image_list[0])\n output = lock.create_locked_dockerfile(locked_dfobj)\n lock.write_locked_dockerfile(output, args.output_file)\n","sub_path":"tern/analyze/default/dockerfile/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":7690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"79883873","text":"from requests import get\nfrom bs4 import BeautifulSoup\nimport random\nimport os\nfrom PIL import Image\nimport requests\nfrom io import BytesIO\n\n\ndef fetch_image(subreddits, sorting, past_images):\n \"\"\"\n This module essentially uses beautiful soup and requests to get the HTML data from reddit and finds the image\n link directly. There is a lot of data management and reconstruction which is most of the work.\n Returns the image url as string literal.\n \"\"\"\n\n # Choosing the subreddit and loading the page\n sub = subreddits[random.randint(0, len(subreddits) - 1)].lower() # randomly selecting a subreddit\n url = 'https://old.reddit.com/r/' + sub + \"/\"\n print(\"Grabbing from\", sub)\n if sorting == \"TOP\":\n url += 'top/?t=all/'\n url += '?limit=100'\n\n response = get(url, headers={'User-agent': 'ImaginaryEscapism'}) # Required to be allowed to get reddit data\n html_soup = BeautifulSoup(response.text, 'lxml')\n\n # Getting all the URLs on the page\n split = str(html_soup).split(',')\n containers = html_soup.find_all('a', class_='thumbnail invisible-when-pinned may-blank outbound')\n urls = []\n\n for k in containers: # Actually getting the url out of the container selected\n k = str(k).split(\" \")\n for a in range(0, len(k), 2):\n a = k[a]\n if 'href' in a:\n # print(a[15:-1])\n urls.append(a[15:-1])\n\n for i in split: # Making sure the selected url is an image\n if '\"content\":\"' in i and 'preview':\n if 'jpg' in i or 'png' in i or 'bmp' in i:\n i = i.split('\"')\n urls.append(i[3])\n\n print(len(urls), \"urls found\")\n trigger_load = True # This variable ensures that we don't load multiple images over each other\n if len(urls) > 5: # If it's less than 5 a loading issue probably occurred so will wait to try again\n while trigger_load is True:\n try:\n ranin = random.randint(0, len(urls)-1)\n # print(ranin)\n image_url = urls[ranin] # Selecting the image\n except ValueError:\n try:\n image_url = urls[0]\n except IndexError:\n image_url = past_images[random.randint(0, len(past_images)-1)]\n if image_url not in past_images: # If we've selected a new image, continue with loading\n trigger_load = False\n print(\"Image not repeated.\")\n else:\n print(\"Image repeated.\")\n print(\"Image url:\", image_url)\n response_img = requests.get(image_url) # Getting image\n try:\n '''\n This code block checks to see if the image is longer width than height as we want desktop landscape\n backgrounds instead of phone vertical ones. This mostly removes the issue with strange aspect ratios\n but I don't mind them personally (and most aren't 16:9 anyway)\n '''\n img = Image.open(BytesIO(response_img.content))\n img.save(os.getcwd() + \"/background.png\")\n width, height = img.size\n # if width != \"1280\" and width != \"1920\" and width != \"2560\" and width != \"3840\":\n # print(\"Image not within aspect ratio of 16:9. Skipping.\")\n if height > width:\n print(\"Aspect ratio wrong way round. Skipping.\")\n fetch_image(subreddits, sorting, past_images) # Trying again\n except OSError:\n print(\"Error in parsing image. Likely image is corrupt. Skipping.\")\n fetch_image(subreddits, sorting, past_images) # Unsure why this occurs, possibly bad url or old image.\n print(\"Saved new image\")\n return image_url\n else:\n return \"\"\n","sub_path":"image_fetcher.py","file_name":"image_fetcher.py","file_ext":"py","file_size_in_byte":3792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"6672164","text":"import pygame\r\n\r\nflag = False \r\npygame.init() \r\nscreen = pygame.display.set_mode((720, 480)) \r\n\r\nback = pygame.Surface((720, 480))\r\nback.fill((162, 250, 248)) \r\nback = back.convert() \r\n\r\npygame.draw.polygon(back, (131, 52, 235), ((180, 300), (280, 60), (380, 300), (155, 150), (405, 150)), 2) # by using polygon\r\n\r\nscreen.blit(back, (0, 0))\r\npygame.display.flip() \r\nwhile not flag: \r\n for event in pygame.event.get(): \r\n if event.type == pygame.QUIT: \r\n flag = True ","sub_path":"lab7/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"236760322","text":"import os\nimport done_domain as done\nimport sqlite3\nfrom datetime import datetime\nfrom typing import List\nfrom contextlib import contextmanager, closing\n\n\nPATH = 'done.db'\n\n\n# https://www.digitalocean.com/community/tutorials/how-to-use-the-sqlite3-module-in-python-3\n# https://docs.python.org/3.6/library/sqlite3.html#sqlite3-controlling-transactions\n# https://stackoverflow.com/questions/1829872/how-to-read-datetime-back-from-sqlite-as-a-datetime-instead-of-string-in-python\n# declare CompletedOn as TIMESTAMP and use detect_types to get back datetime\n@contextmanager\ndef _cursor(db_path: str):\n with closing(sqlite3.connect(db_path, isolation_level=None, detect_types=sqlite3.PARSE_DECLTYPES)) as connection:\n with closing(connection.cursor()) as cursor:\n yield cursor\n\ndef _initialize_db(db_path: str):\n with _cursor(db_path) as cursor:\n cursor.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS CompletedItems (\n Id INTEGER PRIMARY KEY,\n CompletedOn TIMESTAMP,\n Item VARCHAR(255)\n )\"\"\"\n )\n\ndef save(db_path: str, completed_items: List[done.CompletedItem]):\n if not os.path.exists(PATH): _initialize_db(PATH)\n with _cursor(db_path) as cursor:\n for completed_item in completed_items:\n cursor.execute(\n \"INSERT INTO CompletedItems (CompletedOn, Item) VALUES (?, ?)\",\n (completed_item.completed_on, completed_item.item)\n )\n\ndef get(db_path: str, completed_since: datetime) -> List[done.CompletedItem]:\n if not os.path.exists(PATH): _initialize_db(PATH)\n with _cursor(db_path) as cursor:\n rows = cursor.execute(\n \"SELECT Item, CompletedOn from CompletedItems WHERE CompletedOn > ?\",\n (completed_since,)\n )\n return [done.CompletedItem(*row) for row in rows.fetchall()]\n","sub_path":"done_db.py","file_name":"done_db.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"115567110","text":"\r\n\"https://www.practicepython.org/exercise/2015/11/01/25-guessing-game-two.html\"\r\n\r\nfrom random import randint\r\nx= \"\"\r\na=0\r\nb=100\r\nz=1\r\nwhile x != \"correct\":\r\n y=randint(a,b)\r\n print(y)\r\n x = input(\"Answer: \")\r\n if x == \"Too high\":\r\n b = y+1\r\n elif x == \"Too low\":\r\n a = y-1\r\n elif x == \"correct\":\r\n print(\"Number of attempt: \"+ str(z))\r\n elif x == \"close\":\r\n print(\"Number of attempt: \"+ str(z)) \r\n break\r\n else:\r\n print(\"wrong input\")\r\n z=z-1\r\n z=z+1","sub_path":"ex25.py","file_name":"ex25.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"389008202","text":"import os\nfrom flask import Flask\nfrom flask_socketio import SocketIO\n\n\napp = Flask(__name__)\napp.config['FILEDIR'] = 'static/_files/'\napp.config['CHAT_URL'] = os.environ.get('CHAT_URL')\napp.config['POLLS_VOTE_URL'] = os.environ.get('POLLS_VOTE_URL')\napp.config['WHERE_PIN_URL'] = os.environ.get('WHERE_PIN_URL')\napp.config['GOOGLE_MAPS_KEY'] = os.environ.get('GOOGLE_MAPS_KEY')\nsocketio = SocketIO(app)\n","sub_path":"createapp.py","file_name":"createapp.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"485408760","text":"from collections import namedtuple\nimport asyncio\nimport logging\n\n\nclass Connection(namedtuple('Connection', ['from_module', 'from_output',\n 'to_module', 'to_input',\n 'key'])):\n async def establish(self):\n from_node, to_node = self.from_module.node, self.to_module.node\n\n connect = from_node.connect(self.from_module, self.from_output,\n self.to_module, self.to_input)\n set_key_from = from_node.set_key(self.from_module, self.from_output,\n self.key)\n set_key_to = to_node.set_key(self.to_module, self.to_input, self.key)\n\n await asyncio.gather(connect, set_key_from, set_key_to)\n\n logging.info('Connection from %s:%s on %s to %s:%s on %s established',\n self.from_module.name, self.from_output, from_node.name,\n self.to_module.name, self.to_input, to_node.name)\n\n","sub_path":"reactivetools/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"170549759","text":"import sys\r\nwith open(sys.argv[1],\"r\") as f:List=filter(None,f.read().strip().splitlines())\r\nfor num in List:\r\n day,stock=num.split(\";\");stock = [int(i) for i in stock.split(\" \")]\r\n print(max([sum(stock[i:i+int(day)]) for i in range(len(stock)-int(day)+1)]+[0]))\r\n\r\n \r\n \r\n \r\n \r\n\r\n\r\n","sub_path":"Max Range Sum.py","file_name":"Max Range Sum.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"303281778","text":"# -*- encoding: utf-8 -*-\n#\n# Copyright © 2018 Mehdi Abaakouk \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 daiquiri\n\nimport github\n\nimport voluptuous\n\nfrom mergify_engine import actions\nfrom mergify_engine import branch_updater\nfrom mergify_engine import check_api\nfrom mergify_engine import config\nfrom mergify_engine import mergify_pull\nfrom mergify_engine import utils\nfrom mergify_engine.worker import app\n\nLOG = daiquiri.getLogger(__name__)\n\n\ndef merge_report(pull):\n if pull.g_pull.merged:\n if pull.g_pull.merged_by.login == 'mergify[bot]':\n mode = \"automatically\"\n else:\n mode = \"manually\"\n conclusion = \"success\"\n title = \"The pull request has been merged %s\" % mode\n summary = (\"The pull request has been merged %s at *%s*\" %\n (mode, pull.g_pull.merge_commit_sha))\n elif pull.g_pull.state == \"closed\":\n conclusion = \"cancelled\"\n title = \"The pull request has been closed manually\"\n summary = \"\"\n else:\n return\n\n return conclusion, title, summary\n\n\ndef output_for_mergeable_state(pull, strict):\n # NOTE(sileht): Take care of all branch protection state\n if pull.g_pull.mergeable_state == \"dirty\":\n return None, \"Merge conflict needs to be solved\", \"\"\n elif pull.g_pull.mergeable_state == \"unknown\":\n return (\"failure\", \"Pull request state reported as `unknown` by \"\n \"GitHub\", \"\")\n # FIXME(sileht): We disable this check as github wrongly report\n # mergeable_state == blocked sometimes. The workaround is to try to merge\n # it and if that fail we checks for blocking state.\n # elif pull.g_pull.mergeable_state == \"blocked\":\n # return (\"failure\", \"Branch protection settings are blocking \"\n # \"automatic merging\", \"\")\n elif (pull.g_pull.mergeable_state == \"behind\" and not strict):\n # Strict mode has been enabled in branch protection but not in\n # mergify\n return (\"failure\", \"Branch protection setting 'strict' conflicts \"\n \"with Mergify configuration\", \"\")\n # NOTE(sileht): remaining state \"behind, clean, unstable, has_hooks\"\n # are OK for us\n\n\nclass MergeAction(actions.Action):\n only_once = True\n\n validator = {\n voluptuous.Required(\"method\", default=\"merge\"):\n voluptuous.Any(\"rebase\", \"merge\", \"squash\"),\n voluptuous.Required(\"rebase_fallback\", default=\"merge\"):\n voluptuous.Any(\"merge\", \"squash\", None),\n voluptuous.Required(\"strict\", default=False):\n voluptuous.Any(bool, \"smart\"),\n voluptuous.Required(\"strict_method\", default=\"merge\"):\n voluptuous.Any(\"rebase\", \"merge\")\n }\n\n def run(self, installation_id, installation_token,\n event_type, data, pull, missing_conditions):\n LOG.debug(\"process merge\", config=self.config, pull=pull)\n\n output = merge_report(pull)\n if output:\n return output\n\n output = output_for_mergeable_state(pull, self.config[\"strict\"])\n if output:\n return output\n\n if self.config[\"strict\"] and pull.is_behind():\n if not pull.base_is_modifiable():\n return (\"failure\", \"Pull request can't be updated with latest \"\n \"base branch changes, owner doesn't allow \"\n \"modification\", \"\")\n elif self.config[\"strict\"] == \"smart\":\n key = _get_queue_cache_key(pull)\n redis = utils.get_redis_for_cache()\n score = utils.utcnow().timestamp()\n LOG.debug(\"add pull request to merge queue\", pull=pull)\n redis.zadd(key, {pull.g_pull.number: score}, nx=True)\n redis.set(_get_update_method_cache_key(pull),\n self.config[\"strict_method\"])\n return (None, \"Base branch will be updated soon\",\n \"The pull request base branch will \"\n \"be updated soon, and then merged.\")\n else:\n return update_pull_base_branch(\n pull, installation_id, self.config[\"strict_method\"])\n else:\n\n if self.config[\"strict\"] == \"smart\":\n redis = utils.get_redis_for_cache()\n LOG.debug(\"removing pull request from merge queue\", pull=pull)\n redis.zrem(_get_queue_cache_key(pull), pull.g_pull.number)\n redis.delete(_get_update_method_cache_key(pull))\n\n if (self.config[\"method\"] != \"rebase\" or\n pull.g_pull.raw_data['rebaseable']):\n return self._merge(pull, self.config[\"method\"])\n elif self.config[\"rebase_fallback\"]:\n return self._merge(pull, self.config[\"rebase_fallback\"])\n else:\n return (\"action_required\", \"Automatic rebasing is not \"\n \"possible, manual intervention required\", \"\")\n\n def cancel(self, installation_id, installation_token,\n event_type, data, pull, missing_conditions):\n # We just rebase the pull request, don't cancel it yet if CIs are\n # running. The pull request will be merge if all rules match again.\n # if not we will delete it when we received all CIs termination\n if self.config[\"strict\"] and self._required_statuses_in_progress(\n pull, missing_conditions):\n return\n\n if self.config[\"strict\"] == \"smart\":\n redis = utils.get_redis_for_cache()\n redis.zrem(_get_queue_cache_key(pull), pull.g_pull.number)\n redis.delete(_get_update_method_cache_key(pull))\n\n return self.cancelled_check_report\n\n @staticmethod\n def _required_statuses_in_progress(pull, missing_conditions):\n # It's closed, it's not going to change\n if pull.g_pull.state == \"closed\":\n return False\n\n need_look_at_checks = []\n for condition in missing_conditions:\n if condition.attribute_name.startswith(\"status-\"):\n need_look_at_checks.append(condition)\n else:\n # something else does not match anymore\n return False\n\n if need_look_at_checks:\n checks = list(pull._get_checks())\n if not checks:\n # No checks have been send yet\n return True\n\n # Take only checks we care about\n checks = [s for s in checks\n for cond in need_look_at_checks\n if cond(**{cond.attribute_name: s.context})]\n if not checks:\n return True\n\n for s in checks:\n if s.state in (\"pending\", None):\n return True\n\n return False\n\n @staticmethod\n def _merge(pull, method):\n try:\n pull.g_pull.merge(sha=pull.g_pull.head.sha,\n merge_method=method)\n except github.GithubException as e: # pragma: no cover\n if pull.g_pull.is_merged():\n LOG.info(\"merged in the meantime\", pull=pull)\n\n elif e.status == 405:\n LOG.error(\"merge fail\", error=e.data[\"message\"],\n pull=pull)\n if pull.g_pull.mergeable_state == \"blocked\":\n return (\"failure\", \"Branch protection settings are \"\n \"blocking automatic merging\", e.data[\"message\"])\n else:\n return (\"failure\",\n \"Repository settings are blocking automatic \"\n \"merging\", e.data[\"message\"])\n\n elif 400 <= e.status < 500:\n LOG.error(\"merge fail\", error=e.data[\"message\"],\n pull=pull)\n return (\"failure\",\n \"Mergify fails to merge the pull request\",\n e.data[\"message\"])\n else:\n raise\n else:\n LOG.info(\"merged\", pull=pull)\n\n pull.g_pull.update()\n return merge_report(pull)\n\n\ndef _get_queue_cache_key(pull):\n return \"strict-merge-queues~%s~%s~%s~%s\" % (\n pull.installation_id,\n pull.g_pull.base.repo.owner.login.lower(),\n pull.g_pull.base.repo.name.lower(),\n pull.g_pull.base.ref\n )\n\n\ndef _get_update_method_cache_key(pull):\n return \"strict-merge-method~%s~%s~%s~%s\" % (\n pull.installation_id,\n pull.g_pull.base.repo.owner.login.lower(),\n pull.g_pull.base.repo.name.lower(),\n pull.g_pull.number,\n )\n\n\ndef update_pull_base_branch(pull, installation_id, method):\n updated = branch_updater.update(pull, installation_id, method)\n if updated:\n redis = utils.get_redis_for_cache()\n # NOTE(sileht): We store this for dismissal action\n redis.setex(\"branch-update-%s\" % updated, 60 * 60, updated)\n\n # NOTE(sileht): We update g_pull to have the new head.sha,\n # so future created checks will be posted on the new sha.\n # Otherwise the checks will be lost the GitHub UI on the\n # old sha.\n pull.wait_for_sha_change()\n return (None, \"Base branch updates done\",\n \"The pull request has been automatically \"\n \"updated to follow its base branch and will be \"\n \"merged soon\")\n else:\n # NOTE(sileht): Maybe the PR have been rebased and/or merged manually\n # in the meantime. So double check that to not report a wrong status\n pull.g_pull.update()\n output = merge_report(pull)\n if output:\n return output\n else:\n return (\"failure\", \"Base branch update has failed\", \"\")\n\n\ndef handle_first_pull_in_queue(installation_id, owner, reponame, branch,\n pull, queue):\n old_checks = [c for c in check_api.get_checks(pull.g_pull)\n if (c.name.endswith(\" (merge)\") and\n c._rawData['app']['id'] == config.INTEGRATION_ID)]\n\n redis = utils.get_redis_for_cache()\n merge_output = merge_report(pull)\n mergeable_state_output = output_for_mergeable_state(pull, True)\n if merge_output or mergeable_state_output:\n LOG.debug(\"removing pull request from merge queue\", pull=pull)\n redis.zrem(queue, pull.g_pull.number)\n redis.delete(_get_update_method_cache_key(pull))\n conclusion, title, summary = merge_output or mergeable_state_output\n else:\n LOG.debug(\"updating base branch of pull request\", pull=pull)\n method = redis.get(_get_update_method_cache_key(pull)) or \"merge\"\n conclusion, title, summary = update_pull_base_branch(\n pull, installation_id, method)\n\n if pull.g_pull.state == \"closed\":\n LOG.debug(\"removing pull request from merge queue\", pull=pull)\n redis.zrem(queue, pull.g_pull.number)\n redis.delete(_get_update_method_cache_key(pull))\n elif conclusion == \"failure\":\n # NOTE(sileht): If we have a failure, try other PR first, put this\n # one at the end of the queue\n score = utils.utcnow().timestamp()\n redis.zadd(queue, {pull.g_pull.number: score}, xx=True)\n\n status = \"completed\" if conclusion else \"in_progress\"\n for c in old_checks:\n check_api.set_check_run(\n pull.g_pull, c.name, status, conclusion,\n output={\"title\": title, \"summary\": summary})\n\n\n@app.task\ndef handle_merge_queue(queue):\n integration = github.GithubIntegration(config.INTEGRATION_ID,\n config.PRIVATE_KEY)\n _, installation_id, owner, reponame, branch = queue.split(\"~\")\n try:\n installation_token = integration.get_access_token(\n installation_id).token\n except github.UnknownObjectException: # pragma: no cover\n LOG.error(\"token for install %d does not exists anymore (%s/%s)\",\n installation_id, owner, reponame)\n return\n\n redis = utils.get_redis_for_cache()\n pull_number = redis.zrange(queue, 0, 0)\n pull_number = pull_number[0] if pull_number else None\n if pull_number:\n pull = mergify_pull.MergifyPull.from_number(\n installation_id, installation_token,\n owner, reponame, int(pull_number))\n\n if pull.g_pull.state == \"closed\" or pull.is_behind():\n LOG.debug(\"pull request needs to be updated again or \"\n \"has been closed\",\n installation_id=installation_id,\n pull_number=pull_number,\n repo=owner + \"/\" + reponame, branch=branch)\n\n # NOTE(sileht): Pick up this pull request and rebase it again or\n # update its status and remove it from the queue\n handle_first_pull_in_queue(installation_id, owner, reponame,\n branch, pull, queue)\n\n else:\n # NOTE(sileht): Pull request has not been merged or cancelled\n # yet wait next loop\n LOG.debug(\"pull request checks are still in progress\",\n installation_id=installation_id,\n pull_number=pull_number,\n repo=owner + \"/\" + reponame, branch=branch)\n\n\n@app.task\ndef smart_strict_workflow_periodic_task():\n redis = utils.get_redis_for_cache()\n LOG.debug(\"smart strict workflow loop start\")\n for queue in redis.keys(\"strict-merge-queues~*\"):\n try:\n handle_merge_queue(queue)\n except Exception:\n # NOTE(sileht): Don't use the celery retry mechnism here, the\n # periodic tasks already retries. This ensure a repo can't block\n # another one.\n # FIXME(sileht): This is not perfect because is a PR of a repo hit\n # the \"Invalid mergeable_state Github bug\", this will still loop\n # for even for this repo.\n LOG.error(\"Fail to process merge queue: %s\", queue, exc_info=True)\n\n LOG.debug(\"smart strict workflow loop end\")\n","sub_path":"mergify_engine/actions/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":14599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"91695282","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('home', '0028_auto_20150807_1406'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='homepage',\n name='slider2_header1',\n field=models.CharField(default='This displays bible verse', max_length=255, help_text='maximum length of 100 characters'),\n ),\n ]\n","sub_path":"source/home/migrations/0029_auto_20150808_0858.py","file_name":"0029_auto_20150808_0858.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"519484904","text":"# -*- coding: utf-8 -*-\nimport logging\n_logger = logging.getLogger(__name__)\n\nfrom openerp import api, models, fields\nfrom openerp.exceptions import Warning\nfrom datetime import datetime\n\nimport requests, json\n\nclass ResPartnerBank(models.Model):\n _inherit = 'res.partner.bank'\n\n @api.one\n def check_iban_convert(self):\n if self.acc_number!=False:\n if self.acc_type=='bank':\n if self.bank_id.id>0:\n if self.bank_id.code!=False:\n if self.acc_country_id.id>0:\n if self.acc_country_id.code!=False:\n #limpiamos caracteres + reemplazamos espacios\n account_number = str(self.acc_number).strip().replace(' ', '') \n #revisamos longitud de la cuenta bancaria\n if len(account_number)==20:\n account_number = account_number.replace(self.bank_id.code, '')\n #request\n url = 'https://openiban.com/v2/calculate/'+str(self.acc_country_id.code)+'/'+str(self.bank_id.code)+'/'+str(account_number)\n response = requests.get(url)\n if response.status_code==200:\n response_json = json.loads(response.text)\n if 'valid' in response_json:\n if response_json['valid']==True: \n if 'iban' in response_json:\n if response_json['iban']!='':\n #update\n self.acc_number = str(response_json['iban'])\n self.acc_type = 'iban' \n\n @api.model\n def create(self, values):\n return_item = super(ResPartnerBank, self).create(values)\n #check_iban_convert\n return_item.check_iban_convert()\n #return\n return return_item\n \n @api.one\n def write(self, vals): \n return_write = super(ResPartnerBank, self).write(vals)\n #check_iban_convert\n self.check_iban_convert()\n #return \n return return_write","sub_path":"partner_bank_iban_convert/models/res_partner_bank.py","file_name":"res_partner_bank.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"251983042","text":"\"\"\"ProjectsApp URL Configuration\n\nCreated by Harris Christiansen on 10/02/16.\n\"\"\"\nfrom django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^project/all$', views.getProjects, name='Projects'),\n url(r'^project$', views.getProject, name='Project'),\n url(r'^project/form$', views.getProjectForm, name='GetProjectForm'),\n url(r'^project/formsuccess$', views.getProjectFormSuccess, name='GetProjectFormSuccess'),\n url(r'^project/edit$', views.editProject, name='EditProject'),\n url(r'^project/bookmark', views.bookmark, name='Bookmark'),\n url(r'^project/unbookmark$', views.unbookmark, name='Unbookmark'),\n]","sub_path":"ProjectsApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"332748721","text":"import attr\nfrom datetime import datetime\nfrom functools import partial\nfrom tfont.objects.anchor import Anchor\nfrom tfont.objects.component import Component\nfrom tfont.objects.guideline import Guideline\nfrom tfont.objects.misc import Transformation, obj_setattr\nfrom tfont.objects.path import Path\nfrom tfont.util.slice import slicePaths\nfrom tfont.util.tracker import (\n LayerAnchorsDict, LayerComponentsList, LayerGuidelinesList, LayerPathsList)\nfrom time import time\nfrom typing import Any, Dict, List, Optional, Set, Tuple, Union\n\n\ndef squaredDistance(x1, y1, item):\n x2, y2 = item\n dx, dy = x2 - x1, y2 - y1\n return dx*dx + dy*dy\n\n\n@attr.s(cmp=False, repr=False, slots=True)\nclass Layer:\n masterName: str = attr.ib(default=\"\")\n _name: str = attr.ib(default=\"\")\n location: Optional[Dict[str, int]] = attr.ib(default=None)\n\n width: Union[int, float] = attr.ib(default=600)\n # should default to ascender+descender and only be stored if different from\n # that value -- add a None value for it and a property?\n height: Union[int, float] = attr.ib(default=0)\n yOrigin: Optional[Union[int, float]] = attr.ib(default=None)\n\n _anchors: Dict[str, Anchor] = attr.ib(default=attr.Factory(dict))\n _components: List[Component] = attr.ib(default=attr.Factory(list))\n _guidelines: List[Guideline] = attr.ib(default=attr.Factory(list))\n _paths: List[Path] = attr.ib(default=attr.Factory(list))\n\n # Color format: RGBA8888.\n color: Optional[Tuple[int, int, int, int]] = attr.ib(default=None)\n _extraData: Optional[Dict] = attr.ib(default=None)\n\n _bounds: Optional[Tuple] = attr.ib(default=None, init=False)\n _closedGraphicsPath: Optional[Any] = attr.ib(default=None, init=False)\n _openGraphicsPath: Optional[Any] = attr.ib(default=None, init=False)\n _parent: Optional[Any] = attr.ib(default=None, init=False)\n _selectedPaths: Optional[Any] = attr.ib(default=None, init=False)\n _selection: Set = attr.ib(default=attr.Factory(set), init=False)\n _selectionBounds: Optional[Tuple] = attr.ib(default=None, init=False)\n _visible: bool = attr.ib(default=False, init=False)\n\n def __attrs_post_init__(self):\n for anchor in self._anchors.values():\n anchor._parent = self\n for component in self._components:\n component._parent = self\n for guideline in self._guidelines:\n guideline._parent = self\n for path in self._paths:\n path._parent = self\n\n def __bool__(self):\n return bool(self._paths or self._components)\n\n # add __lt__ to display layers ordered\n\n def __repr__(self):\n try:\n more = \", glyph %r%s\" % (\n self._parent.name, \" master\" * self.masterLayer)\n except AttributeError:\n more = \"\"\n return \"%s(%r, %d paths%s)\" % (\n self.__class__.__name__, self.name, len(self._paths), more)\n\n def __setattr__(self, key, value):\n try:\n glyph = self._parent\n except AttributeError:\n pass\n else:\n if glyph is not None and key[0] != \"_\":\n oldValue = getattr(self, key)\n if value != oldValue:\n obj_setattr(self, key, value)\n glyph._lastModified = time()\n return\n obj_setattr(self, key, value)\n\n @property\n def anchors(self):\n return LayerAnchorsDict(self)\n\n @property\n def bottomMargin(self):\n bounds = self.bounds\n if bounds is not None:\n value = bounds[1]\n if self.yOrigin is not None:\n value -= self.yOrigin - self.height\n return value\n return None\n\n @bottomMargin.setter\n def bottomMargin(self, value):\n bounds = self.bounds\n if bounds is None:\n return\n oldValue = bounds[1]\n if self.yOrigin is not None:\n oldValue -= self.yOrigin - self.height\n else:\n self.yOrigin = self.height\n self.height += value - oldValue\n\n @property\n def bounds(self):\n bounds = self._bounds\n left = None\n if bounds is None:\n # TODO: we could have a rect type, in tools\n paths = self._paths\n for path in paths:\n l, b, r, t = path.bounds\n if left is None:\n left, bottom, right, top = l, b, r, t\n else:\n if l < left:\n left = l\n if b < bottom:\n bottom = b\n if r > right:\n right = r\n if t > top:\n top = t\n if left is not None:\n bounds = self._bounds = (left, bottom, right, top)\n # we can't stash component bounds, we aren't notified when it changes\n for component in self._components:\n l, b, r, t = component.bounds\n if left is None:\n if bounds is not None:\n left, bottom, right, top = bounds\n else:\n left, bottom, right, top = l, b, r, t\n continue\n if l < left:\n left = l\n if b < bottom:\n bottom = b\n if r > right:\n right = r\n if t > top:\n top = t\n if left is not None:\n return (left, bottom, right, top)\n return bounds\n\n @property\n def closedComponentsGraphicsPath(self):\n return self.closedComponentsGraphicsPathFactory()\n\n @property\n def closedGraphicsPath(self):\n graphicsPath = self._closedGraphicsPath\n if graphicsPath is None:\n graphicsPath = self._closedGraphicsPath = \\\n self.closedGraphicsPathFactory()\n return graphicsPath\n\n @property\n def components(self):\n return LayerComponentsList(self)\n\n @property\n def extraData(self):\n extraData = self._extraData\n if extraData is None:\n extraData = self._extraData = {}\n return extraData\n\n @property\n def font(self):\n glyph = self._parent\n if glyph is not None:\n return glyph._parent\n return None\n\n @property\n def glyph(self):\n return self._parent\n\n @property\n def guidelines(self):\n return LayerGuidelinesList(self)\n\n @property\n def leftMargin(self):\n bounds = self.bounds\n if bounds is not None:\n return bounds[0]\n return None\n\n @leftMargin.setter\n def leftMargin(self, value):\n bounds = self.bounds\n if bounds is None:\n return\n delta = value - bounds[0]\n self.transform(Transformation(xOffset=delta))\n self.width += delta\n\n @property\n def master(self):\n try:\n return self._parent._parent._masters[self.masterName]\n except (AttributeError, KeyError):\n pass\n return None\n\n @property\n def masterLayer(self):\n return self.masterName and not self._name\n\n @property\n def name(self):\n if self.masterLayer:\n return self.master.name\n return self._name\n\n @name.setter\n def name(self, value):\n self._name = value\n\n @property\n def openComponentsGraphicsPath(self):\n return self.openComponentsGraphicsPathFactory()\n\n @property\n def openGraphicsPath(self):\n graphicsPath = self._openGraphicsPath\n if graphicsPath is None:\n graphicsPath = self._openGraphicsPath = \\\n self.openGraphicsPathFactory()\n return graphicsPath\n\n @property\n def paths(self):\n return LayerPathsList(self)\n\n @property\n def rightMargin(self):\n bounds = self.bounds\n if bounds is not None:\n return self.width - bounds[2]\n return None\n\n @rightMargin.setter\n def rightMargin(self, value):\n bounds = self.bounds\n if bounds is None:\n return\n self.width = bounds[2] + value\n\n @property\n def selectedPaths(self):\n paths = self._selectedPaths\n if paths is None:\n paths = self._selectedPaths = self.selectedPathsFactory()\n return paths\n\n @property\n def selection(self):\n return self._selection\n\n @property\n def selectionBounds(self):\n selectionBounds = self._selectionBounds\n left = None\n if selectionBounds is None:\n for element in self._selection:\n if element.__class__ is Component:\n # we can't stash component bounds, we aren't notified when\n # it changes\n continue\n x, y = element.x, element.y\n if left is None:\n left, bottom, right, top = x, y, x, y\n else:\n if x < left:\n left = x\n elif x > right:\n right = x\n if y < bottom:\n bottom = y\n elif y > top:\n top = y\n if left is not None:\n selectionBounds = self._selectionBounds = (\n left, bottom, right, top)\n for component in self._components:\n if component.selected:\n l, b, r, t = component.bounds\n if left is None:\n if selectionBounds is not None:\n left, bottom, right, top = selectionBounds\n else:\n left, bottom, right, top = l, b, r, t\n continue\n if l < left:\n left = l\n if b < bottom:\n bottom = b\n if r > right:\n right = r\n if t > top:\n top = t\n if left is not None:\n return (left, bottom, right, top)\n return selectionBounds\n\n @property\n def topMargin(self):\n bounds = self.bounds\n if bounds is not None:\n value = -bounds[3]\n if self.yOrigin is not None:\n value += self.yOrigin\n else:\n value += self.height\n return value\n return None\n\n @topMargin.setter\n def topMargin(self, value):\n bounds = self.bounds\n if bounds is None:\n return\n top = bounds[3]\n oldValue = -top\n if self.yOrigin is not None:\n oldValue += self.yOrigin\n else:\n oldValue += self.height\n self.yOrigin = top + value\n self.height += value - oldValue\n\n @property\n def visible(self):\n if self.masterLayer:\n return self.master.visible\n return self._visible\n\n @visible.setter\n def visible(self, value):\n if self.masterLayer:\n self.master.visible = value\n else:\n self._visible = value\n\n def clearSelection(self):\n for element in list(self._selection):\n element.selected = False\n for guideline in self.master.guidelines:\n guideline.selected = False\n\n def copy(self):\n global TFontConverter\n try:\n TFontConverter\n except NameError:\n from tfont.converters.tfontConverter import TFontConverter\n conv = TFontConverter(indent=None)\n l = conv.structure(conv.unstructure(self), self.__class__)\n l._name = datetime.now().strftime(\"%b %d %y {} %H:%M\").format(\"–\")\n l.visible = False\n return l\n\n def decomposeComponents(self):\n for component in self._components:\n component.decompose()\n\n # components=False?\n def intersectLine(self, x1, y1, x2, y2):\n intersections = [(x1, y1), (x2, y2)]\n intersections_append = intersections.append\n for path in self._paths:\n for segment in path.segments:\n for x, y, _ in segment.intersectLine(x1, y1, x2, y2):\n intersections_append((x, y))\n intersections.sort(key=partial(squaredDistance, x1, y1))\n return intersections\n\n def sliceLine(self, x1, y1, x2, y2):\n paths = self._paths\n if not paths:\n return\n newPaths = slicePaths(self, x1, y1, x2, y2)\n if not newPaths:\n return\n self._paths = newPaths\n # notify\n self.paths.applyChange()\n\n def transform(self, transformation, selectionOnly=False) -> bool:\n changed = False\n anchors = self._anchors\n if anchors:\n if transformation.transformSequence(\n anchors, selectionOnly=selectionOnly):\n self.anchors.applyChange()\n changed = True\n for component in self._components:\n doTransform = not selectionOnly or component.selected\n changed |= doTransform\n if doTransform:\n component.transformation.concat(transformation)\n for path in self._paths:\n changed |= path.transform(\n transformation, selectionOnly=selectionOnly)\n return changed\n","sub_path":"src/tfont/objects/layer.py","file_name":"layer.py","file_ext":"py","file_size_in_byte":13230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"96646205","text":"#!/bin/env python3\nimport sys\nimport os\nimport argparse\nimport html\n\nparser = argparse.ArgumentParser(description=\"Parse a logfile and creates a sortable/filterable/searchable HTML table.\")\nparser.add_argument('infile', metavar='', type=str, help=\"file to read, if '-', stdin is used\")\nparser.add_argument('outfile', metavar='', nargs='?', default='-', help=\"file to write, if '-' or no filename is given, stdout is used\")\n#parser.add_argument(\"-V\", \"--verbose\", help=\"Be more verbose\", action=\"store_true\")\n#parser.add_argument(\"-d\", \"--debug\", help=\"debug flag\", action='append', nargs=\"*\")\nparser.add_argument(\"-l\", \"--logtype\", help=\"logfile type\", choices=['spyglass', 'verilator'])\nargs = parser.parse_args()\n \nhtml_h = \"\"\"\n\n\n\n\n\n\n Excel Bootstrap Table Filter\n \n \n \n \n \n \n \n \n\n\n\n
\n\n\n
\n
\n
\n \n \n \n {}\n \n \n \n\"\"\"\nhtml_t = \"\"\"\n \n
\n
\n
\n
\n\n\n\n\n\"\"\"\n\nverilator_header =(\"Type\", \"File\", \"Line\", \"Col\", \"Message\")\ndef convert_verilator_log(flog, fhtml):\n print(html_h.format(\"\".join([\"\"+i+\"\" for i in verilator_header])), file=fhtml)\n for l in flog.readlines():\n if not l.startswith('%'):\n continue\n lw = ''\n for w in l.split(':', 4):\n lw += '{}'.format(html.escape(w))\n print('{}'.format(lw), file=fhtml)\n print(html_t, file=fhtml)\n\n#ID Rule Alias Severity File Line Wt Message\nspyglass_header = ('ID', 'Rule', 'Alias', 'Severity', 'File', 'Line', 'Wt', 'Message')\nspyg_hdr_pos = [0, 9, 29, 49, 61, 202, 211, 217, 0]\ndef convert_spyglass_log(flog, fhtml):\n s = spyg_hdr_pos \n print(html_h.format(\"\".join([\"\"+i+\"\" for i in spyglass_header])), file=fhtml)\n for l in flog.readlines():\n if not l.startswith('['):\n continue\n lw = ''\n s[-1] = len(l)\n for i in range(len(s)-1):\n lw += '{}'.format(html.escape(l[s[i]:s[i+1]].strip()))\n print('{}'.format(lw), file=fhtml)\n print(html_t, file=fhtml)\n\ndef convert_any_log(flog, fhtml):\n if args.logtype == 'verilator':\n convert_verilator_log(flog, fhtml)\n elif args.logtype == 'spyglass':\n convert_spyglass_log(flog, fhtml)\n\ndef convert_log(fhtml):\n if args.infile == \"-\":\n convert_any_log(sys.stdin, fhtml)\n else:\n with open(args.infile, \"r\") as flog:\n convert_any_log(flog, fhtml)\n\nif args.outfile == \"-\":\n convert_log(sys.stdout)\nelse:\n with open(args.outfile, \"w\") as fhtml:\n convert_log(fhtml)\n\n\n\n","sub_path":"verilator2html.py","file_name":"verilator2html.py","file_ext":"py","file_size_in_byte":3950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"122162693","text":"from __future__ import unicode_literals; del unicode_literals\n\ndef _text_gen(minutes=1, seconds=-1, debug=-1):\n from . import _END, _DEBUG, _INTERVAL\n if seconds == -1:\n seconds = _INTERVAL\n if debug == -1:\n debug = _DEBUG\n for min_ in range(minutes, 1, -1):\n for sec in range(debug - seconds, -seconds, -seconds):\n yield r'%d %d' % (min_, sec)\n for sec in range(debug - seconds, 0, -seconds):\n yield r'1 %d' % sec\n yield _END\n","sub_path":"impl/text_gen.py","file_name":"text_gen.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"175595057","text":"# coding=utf-8\nfrom cardlib.Card import Card\nfrom client import GameClient\nfrom poker_rounds.poker_game import PokerGame, PokerPlayer\n\n\nclass PokerSetup(GameClient):\n \"\"\"This class runs once after the player hands have been dealt to initialise\n the poker game state.\"\"\"\n def __init__(self, cli, state=None, max_players=3):\n self.max_players = max_players\n super().__init__(cli, state)\n self.game = None\n\n def init_existing_state(self, state):\n super().init_existing_state(state)\n self.build_player_map(state)\n\n @staticmethod\n def have_built_poker_player_map(state):\n return PokerPlayer.POKER_PLAYER in list(\n state['peer_map'].items())[0][1]\n\n def build_player_map(self, state):\n self.game = PokerGame(self.max_players)\n for card in state['hand']:\n self.game.state_log.append({PokerGame.ACTION: PokerGame.DEALT_CARD,\n PokerGame.DEALT_CARD: str(Card(card))})\n for ident, player in state['peer_map'].items():\n player[PokerPlayer.POKER_PLAYER] = PokerPlayer(ident, self.game)\n self.peer_map = state['peer_map']\n\n def is_round_over(self):\n state = {'peer_map': self.peer_map}\n return self.have_built_poker_player_map(state)\n\n def get_final_state(self):\n state = super().get_final_state()\n state.update({'peer_map': self.peer_map,\n 'game': self.game})\n return state\n","sub_path":"poker_rounds/poker_setup.py","file_name":"poker_setup.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"550532825","text":"\n#from django.contrib.auth.models import User\n#from apps.usuarios.models import *\nfrom apps.evaluacion.models import *\ndef obj_search(sh,ar,areares):\n\tfor rx in range(sh.nrows):\n\t\tarb = sh.cell_value(rowx=rx,colx=1)\n\t\tif rx>0 and arb==ar:\n\t\t\tobj = sh.cell_value(rowx=rx,colx=2)\n\t\t\tprint(Fore.CYAN+obj)\n\t\t\tobjetivo_institusional.objects.create(area=areares,gestion=2018,objetivo=obj)\n\nfrom xlrd import open_workbook\nfrom colorama import init\nfrom colorama import Fore, Back, Style\ninit()\n\nbook = open_workbook(\"areas objetivos.xlsx\")\nsh = book.sheet_by_index(1)\n#print(sh.cell_value(rowx=2,colx=8))\n\n\nareaa=[]\nfor rx in range(sh.nrows):\n\tif rx>0 and sh.cell_value(rowx=rx,colx=1) not in areaa:\n\t\tar = sh.cell_value(rowx=rx,colx=1)\n\t\tareaa.append(ar)\n\t\tareares=area.objects.create(nombre=ar)\n\t\tprint(Fore.GREEN+ar)\n\t\tobj_search(sh,ar,areares)","sub_path":"crareasobj.py","file_name":"crareasobj.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"594178464","text":"### 1302 베스트셀러\n### https://www.acmicpc.net/problem/1302\nimport sys\nN = int(sys.stdin.readline())\nbooksSold = {}\nfor i in range(N):\n bookSold = sys.stdin.readline().strip()\n if (bookSold in booksSold) == True:\n booksSold[bookSold] += 1\n else:\n booksSold[bookSold] = 1\ngaJangManIPalIn = max(list(booksSold.values()))\nsortedBooks = {key:value for key, value in booksSold.items() if value == gaJangManIPalIn}\nsortedBooks = sorted(sortedBooks)\nprint(sortedBooks[0])","sub_path":"Baekjoon/1302.py","file_name":"1302.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"456411371","text":"import glob\nimport imageio\nimport matplotlib.pyplot as plt\nfrom skimage.exposure import rescale_intensity\n\nfrom ..io.io_image import load_image\n\ndef make_gif_from_data(imgs, file_name=None, duration=None, cmap=None, loop=True):\n if cmap is None:\n cmap = plt.cm.viridis\n imgs_color = [cmap(rescale_intensity(img, out_range=(0., 1.))) for img in imgs]\n if file_name == None:\n file_name = 'animated.gif'\n if duration == None:\n duration = 0.5\n kwargs = {'duration': duration, 'loop': loop }\n imageio.mimsave(file_name, imgs_color, **kwargs)\n\n\n\ndef make_gif(file_name, fname=None, duration=1, loop=True):\n\n imgs = []\n for name in glob.glob(file_name):\n img = load_image(name)\n imgs.append(img)\n # duration in seconds\n kwargs = {'duration': duration, 'loop': loop }\n if fname is None:\n fname = 'animated.gif'\n imageio.mimsave(fname, imgs, **kwargs)","sub_path":"utils/images2gif.py","file_name":"images2gif.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"261209185","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\"\"\"\nThis script downloads articles from Ideas y Valores\nand saves them in raw HTML. It also retrieves their metadata\nand saves them in JSON format.\n\nEach article will be saved in the folder data/raw_html/{articleID}/.\n\"\"\"\n\nimport requests # Allows us to make web requests\nfrom bs4 import BeautifulSoup # Parses HTML\nimport os # To save HTML files\nfrom time import sleep # To wait between requests\nimport json # We save metadata in JSON format\nimport re\nimport lxml\n\n# Headers for requests\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0',\n}\n\n# Years to scrape (initially 2009 - 2017)\nyearStart = 2009\nyearEnd = 2017\n\n# We look at the archive and parse it with BeautifulSoup\nurlArchive = 'https://revistas.unal.edu.co/index.php/idval/issue/archive'\nhtmlArchive = requests.get(urlArchive).content\nsoupArchive = BeautifulSoup(htmlArchive, features = 'lxml')\n\n# We make a list to save all issue links\nissueLinks = []\n\n# For each year we save the link each issue's table of contents.\nfor year in range(yearStart, yearEnd + 1):\n # Issue links are in h4 tags\n # We look at each h4 and if it contains the year we are looking for,\n # we save it.\n # We append '/showToc' to the URL.\n issueLinks += [link.a['href']+'/showToc' for link in soupArchive.find_all('h4') if str(year) in link.text]\n\n# We visit each issue and download every article in HTML.\nfor issueURL in issueLinks:\n\n issueHTML = requests.get(issueURL, headers=headers).content\n soup = BeautifulSoup(issueHTML, features = 'lxml')\n articleLinks = [link for link in soup.find_all('a', href=True) if link.text == 'HTML']\n\n # Which issue are we visiting?\n print(soup.title.text)\n\n # We visit each article in each issue.\n for link in articleLinks:\n\n articleHTML = requests.get(link['href']).content\n soup = BeautifulSoup(articleHTML, features = 'lxml')\n\n # Which article are we visiting?\n print(f'\\t{soup.title.text}')\n\n # We extract the metadata and pass it to a dictionary.\n meta = soup.find_all('meta', attrs={'name': True})\n\n metaDict = {}\n for item in meta:\n metaDict[item['name']] = item['content']\n\n # We extract the article ID to use it as a filename later.\n articleID = metaDict['DC.Identifier']\n\n # We visit printer friendly versions which are easier to parse.\n printerURL = re.findall('\\'(.*)\\'', soup.find(text=re.compile('Imprima')).parent['href'])[0]\n\n printerfriendlyHTML = requests.get(printerURL, headers=headers).content\n soup = BeautifulSoup(printerfriendlyHTML, features = 'lxml')\n content = soup.find('div', id = 'content')\n\n # We create a folder for each article.\n folder = f'../data/raw_html/{articleID}/'\n\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n with open(f\"{folder}/{articleID}.html\", 'w') as f:\n f.write(str(content))\n\n with open(f\"{folder}/{articleID}.json\", 'w') as f:\n json.dump(metaDict, f)\n\n # We wait five seconds before our next requests.\n sleep(5)\n","sub_path":"utils/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":3182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"612736278","text":"import json\nfrom haunt import logger as log\n\n_config_file = ''\nsettings = {}\nscenarios = {}\n\n\ndef dump():\n log.i('Dumping Configuration File: ' + _config_file, {'m': 'haunt.config.dump'})\n log.i(settings, {'m': 'haunt.config.dump'})\n\n for scenario in scenarios:\n log.i(scenario, {'m': 'haunt.config.dump'})\n\n return\n\n\ndef load(config_file):\n\n log.i('Loading Configuration File: ' + config_file, {'m': 'haunt.config.load'})\n\n global _config_file\n _config_file = config_file\n\n with open(config_file) as input_file:\n data = json.load(input_file)\n\n global settings\n settings = data['settings']\n\n global scenarios\n scenarios = data['scenarios']\n\n # Initialize the logging\n log.init('haunt', settings['log_level'])\n log.i('Loaded Configuration File: ' + config_file, {'m': 'haunt.config.load'})\n\n return\n","sub_path":"haunt/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"22924557","text":"from tempest import tvaultconf\n\n#Workload commands\nworkload_list = \"workloadmgr workload-list | grep available | wc -l\"\nworkload_create = \"workloadmgr workload-create --workload-type-id \"+tvaultconf.workload_type_id+\\\n \" --display-name \"+tvaultconf.workload_name+\\\n \" --source-platform \"+tvaultconf.source_platform\nworkload_delete = \"workloadmgr workload-delete \"\nworkload_modify = \"workloadmgr workload-modify \"\nworkload_unlock = \"workloadmgr workload-unlock \"\nworkload_type_list = \"workloadmgr workload-type-list | grep '[a-z0-9]-[a-z0-9]' | wc -l\"\nworkload_type_show = \"workloadmgr workload-type-show \" + str(tvaultconf.workload_type_id)\nworkload_show = \"workloadmgr workload-show \"\nworkload_import = \"workloadmgr workload-importworkloads\"\n\nget_storage_usage = \"workloadmgr workload-get-storage-usage\" \nget_import_workloads_list = \"workloadmgr workload-get-importworkloads-list\" \nworkload_disable_global_job_scheduler = \"workloadmgr disable-global-job-scheduler\"\nworkload_enable_global_job_scheduler = \"workloadmgr enable-global-job-scheduler\"\nget_nodes = \"workloadmgr workload-get-nodes\" \nget_auditlog = \"workloadmgr workload-get-auditlog\"\n\n\n#Snapshot commands\nsnapshot_list = \"workloadmgr snapshot-list | grep available | wc -l\"\nsnapshot_create = \"workloadmgr workload-snapshot \" + \" --full --display-name \" +tvaultconf.snapshot_name + \" \"\nsnapshot_delete = \"workloadmgr snapshot-delete \"\nincr_snapshot_create = \"workloadmgr workload-snapshot \" + \" --display-name \" +tvaultconf.snapshot_name + \" \"\nsnapshot_cancel = \"workloadmgr snapshot-cancel \"\n\n#Restore commands\nrestore_list = \"workloadmgr restore-list | grep available | wc -l\"\nrestore_delete = \"workloadmgr restore-delete \"\noneclick_restore = \"workloadmgr snapshot-oneclick-restore --display-name \" +tvaultconf.restore_name\nselective_restore = \"workloadmgr snapshot-selective-restore --display-name \" +tvaultconf.selective_restore_name+ \" --filename \" +tvaultconf.restore_filename\nrestore_show = \"workloadmgr restore-show \"\ninplace_restore = \"workloadmgr snapshot-inplace-restore --display-name test_name_inplace --display-description test_description_inplace --filename \"\nrestore_cancel = \"workloadmgr restore-cancel \"\n\n#Nova commands\ndelete_vm = \"nova delete \"\nlist_vm = \"nova list | awk -F '|' '{print $2}' | grep -v ID\"\n\n#License commands\nlicense_create = \"workloadmgr license-create \"\nlicense_check = \"workloadmgr license-check\"\nlicense_list = \"workloadmgr license-list\"\n\n#Config backup commands\nconfig_workload_configure = \"workloadmgr config-workload-configure\"\nconfig_workload_show = \"workloadmgr config-workload-show\"\nconfig_backup = \"workloadmgr config-backup\"\nconfig_backup_show = \"workloadmgr config-backup-show\"\nconfig_backup_delete = \"workloadmgr config-backup-delete\"\n\n#Workload policy commands\npolicy_create = \"workloadmgr policy-create --policy-fields \"\npolicy_update = \"workloadmgr policy-update --policy-fields \"\npolicy_assign = \"workloadmgr policy-assign --add_project \"\npolicy_delete = \"workloadmgr policy-delete \"\n\n#Quota commands\nquota_type_list_count = \"workloadmgr project-quota-type-list | grep '[a-z0-9]-[a-z0-9]' | wc -l\"\nquota_type_list = \"workloadmgr project-quota-type-list -f json \"\nquota_create = \"workloadmgr project-allowed-quota-create \"\nquota_update = \"workloadmgr project-allowed-quota-update \"\nquota_list = \"workloadmgr project-allowed-quota-list -f json \"\nquota_show = \"workloadmgr project-allowed-quota-show -f value \"\nquota_delete = \"workloadmgr project-allowed-quota-delete \"\n","sub_path":"tempest/command_argument_string.py","file_name":"command_argument_string.py","file_ext":"py","file_size_in_byte":3516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"427128611","text":"# The Computer Language Benchmarks Game\n# http://benchmarksgame.alioth.debian.org/\n#\n# originally by Kevin Carson\n# modified by Tupteq, Fredrik Johansson, and Daniel Nanz\n# modified by Maciej Fijalkowski\n# 2to3\n\nimport argparse\nimport itertools\nimport multiprocessing\nimport time\n\nimport dask\nimport numpy as np\nimport numba\n\n\n@dask.delayed\n@numba.jit(nogil=True)\ndef force(i, positions, velocities, masses, dt):\n for j in range(N):\n\n x1, x2 = positions[i], positions[j]\n v1, v2 = velocities[i], velocities[j]\n m1, m2 = masses[i], masses[j]\n\n dx = x1 - x2\n\n mag = dt * np.linalg.norm(dx)\n F = m2 * mag * dx\n\n if i < j:\n velocities[i] += F\n else:\n velocities[i] -= F\n\ndef step(num_steps, positions, velocities, masses, dt):\n \"\"\"\n Advance the simulation by 'num_steps' time steps.\n \"\"\"\n positions[0, :] = 0\n\n for step in range(num_steps):\n results = []\n for i in range(N):\n results.append(force(i, positions, velocities, masses, dt))\n dask.compute(results)\n positions += dt * velocities\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(description='N-body simulation')\n parser.add_argument('N', default=5, type=int)\n parser.add_argument('nsteps', nargs='?', default=100, type=int)\n parser.add_argument('--animate', action='store_true')\n\n args = parser.parse_args()\n\n # ensure repeatable results\n np.random.seed(0)\n\n # number of time steps per frame\n STEPS_PER_FRAME = 5\n\n N = args.N\n nsteps = args.nsteps\n animate = args.animate\n\n if not animate:\n import matplotlib\n matplotlib.use('Agg')\n\n import matplotlib.animation as animation\n import matplotlib.pyplot as plt\n\n positions = np.random.rand(N, 3) * 80 - 40\n velocities = np.random.rand(N, 3) * 2 - 1\n masses = np.random.rand(N) * 0.05\n\n dt = 0.001\n\n # initial conditions:\n positions[0, :] = 0\n masses[0] = 100\n\n ims = []\n\n fig, ax = plt.subplots()\n sc = ax.scatter([], [])\n\n def init_func():\n ax.set_xlim([-100, 100])\n ax.set_ylim([-100, 100])\n return sc,\n\n def frame(i):\n \"\"\"\n Compute one frame of the animation.\n \"\"\"\n t1 = time.time()\n step(STEPS_PER_FRAME, positions, velocities, masses, dt)\n t2 = time.time()\n\n sc.set_offsets(positions[:, :2])\n\n print(\"Time for frame {}: {}s\".format(i, t2-t1))\n return sc,\n\n if animate:\n im_ani = animation.FuncAnimation(\n fig,\n frame,\n nsteps,\n repeat=False,\n blit=True,\n interval=10,\n init_func=init_func)\n plt.show()\n else:\n for i in range(nsteps):\n frame(i)\n\n print(\"Position of particle 2: {}\".format(positions[2]))\n","sub_path":"solutions/nbody/nbody_SOLUTION_5.py","file_name":"nbody_SOLUTION_5.py","file_ext":"py","file_size_in_byte":2884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"49972449","text":"\nfrom odoo import api, fields, models\n\nclass ProductTmpl(models.Model):\n _inherit = 'product.template'\n\n warehouse_id = fields.Many2one(\n string=\"Default warehouse\",\n comodel_name=\"stock.warehouse\",\n help=\"Will be forced in sale, purchase and manufacture orders.\",\n )\n\n @api.depends('categ_id')\n def _set_wh(self):\n for prod in self:\n product.write({'warehouse_id': categ_id.warehouse_id and categ_id.warehouse_id.id,})\n\nclass ProductCat(models.Model):\n _inherit = 'product.category'\n\n warehouse_id = fields.Many2one(\n string=\"Default warehouse\",\n comodel_name=\"stock.warehouse\",\n help=\"Will be forced in sale, purchase and manufacture orders of products in this category.\",\n )\n\n @api.depends('parent_id')\n def _set_wh(self):\n warehouse_id = parent_id.warehouse_id\n\nclass SaleOrder(models.Model):\n _inherit = 'sale.order'\n\n @api.model\n def _prepare_procurement_group_by_line(self, line):\n vals = super(SaleOrder, self)._prepare_procurement_group_by_line(line)\n wh_id = line.product_id.product_tmpl_id.warehouse_id or \\\n line.product_id.categ_id.warehouse_id\n\n if wh_id:\n vals['name'] += '/' + wh_id.name\n return vals\n\nclass SaleOrderLine(models.Model):\n _inherit = 'sale.order.line'\n\n @api.multi\n def _prepare_order_line_procurement(self, group_id=False):\n values = super(SaleOrderLine, self).\\\n _prepare_order_line_procurement(group_id=group_id)\n wh_id = self.product_id.product_tmpl_id.warehouse_id or \\\n self.product_id.categ_id.warehouse_id\n if wh_id:\n values['warehouse_id'] = wh_id.id\n return values\n\n\nclass PurchaseOrder(models.Model):\n _inherit = 'purchase.order'\n\n @api.multi\n def _create_picking(self):\n StockPicking = self.env['stock.picking']\n for order in self:\n if any([ptype in ['product', 'consu'] for ptype in order.order_line.mapped('product_id.type')]):\n pickings = order.picking_ids.filtered(lambda x: x.state not in ('done','cancel'))\n if not pickings:\n # we need to create a picking per prod.wh or per po wh\n for line in order.order_line:\n # get wh_id of prod or categ_id or PO\n wh_id = line.product_id.product_tmpl_id.warehouse_id or \\\n line.product_id.categ_id.warehouse_id or \\\n order.picking_type_id.warehouse_id\n\n picking = order.picking_ids.filtered(\n lambda p: p.location_dest_id == wh_id.lot_stock_id)\n\n if not picking:\n res = order._prepare_picking()\n res.update({\n 'location_dest_id': wh_id.lot_stock_id.id,\n 'picking_type_id': self.env['stock.picking.type'].search([\n ('code','=',order.picking_type_id.code),\n ('default_location_dest_id','=',wh_id.lot_stock_id.id)\n ])[0].id,\n })\n picking = StockPicking.create(res)\n\n moves = line._create_stock_moves(picking)\n moves = moves.filtered(lambda x: x.state not in ('done', 'cancel')).action_confirm()\n moves.action_assign()\n\n else:\n picking = pickings[0]\n # moves = order.order_line._create_stock_moves(picking)\n # moves = moves.filtered(lambda x: x.state not in ('done', 'cancel')).action_confirm()\n seq = 0\n for move in sorted(moves, key=lambda move: move.date_expected):\n seq += 5\n move.sequence = seq\n moves.force_assign()\n picking.message_post_with_view('mail.message_origin_link',\n values={'self': picking, 'origin': order},\n subtype_id=self.env.ref('mail.mt_note').id)\n return True\n\n\n # @api.multi\n # def button_confirm(self):\n # super(PurchaseOrder, self).button_confirm()\n # stk_pcks = self.env['stock.picking'].search([\n # # ('purchase_id','=',False),\n # # ('sale_id','=',False),\n # ('move_lines','=',False),\n # ('group_id','=',False),\n # ('origin','=',self.name),\n # ])\n #\n # for order in self:\n # for pick in stk_pcks:\n # pick.unlink()\n #\n # return True\n\n\n\n# class PurchaseOrderLine(models.Model):\n# _inherit = 'purchase.order.line'\n#\n# @api.multi\n# def _prepare_stock_moves(self, picking):\n# res = super(PurchaseOrderLine, self)._prepare_stock_moves(picking)\n# wh_id = self.product_id.product_tmpl_id.warehouse_id or \\\n# self.product_id.product_tmpl_id.categ_id.warehouse_id\n# if wh_id and picking.location_dest_id != wh_id.lot_stock_id:\n# pick_id = picking.copy()\n# pick_id.update({\n# 'location_dest_id': wh_id.lot_stock_id.id,\n# 'picking_type_id': self.env['stock.picking.type'].search([\n# ('code','=','incoming'),\n# ('default_location_dest_id','=',wh_id.lot_stock_id.id)\n# ])[0].id,\n# # 'purchase_id': picking.purchase_id.id,\n# })\n# for move in res:\n# move.update({\n# 'picking_id': pick_id.id,\n# 'warehouse_id': wh_id.id,\n# 'location_dest_id': wh_id.lot_stock_id.id,\n# 'name': move.get('name') + '/' + wh_id.name,\n# })\n# return res\n","sub_path":"custom/dvit-odoo-10.0/dvit_product_warehouse/model/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"3378360","text":"#distribution of days\nimport random\nimport tweepy\nimport io\nimport json\nimport subprocess\nfrom tweepy import Stream\nfrom tweepy.streaming import StreamListener\nimport argparse\nimport datetime\nimport json\nimport os\nimport subprocess\nimport sys\nimport time\nimport urllib\nimport pymongo\nfrom tweepy import *\nfrom collections import Counter\nimport operator\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclient = pymongo.MongoClient(host='45.113.235.235', port=30003)\ndb = client.harvesting\ncollection = db.new_filtered\ncursor = collection.find()\n\ncount1 = 0\ncount2 = 0\ncount3 = 0\ncount4 = 0\ncount5 = 0\ncount6 = 0\ncount7 = 0\ncountuser = 0\ncountselfie = 0\nfor line in cursor:\n if line['selfie_tweets']:\n countuser += 1\n for i in line['selfie_tweets']:\n countselfie += 1\n if 'Mon' in i['created_at']:\n count1 += 1\n if 'Tue' in i['created_at']:\n count2 += 1\n if 'Wed' in i['created_at']:\n count3 += 1\n if 'Thu' in i['created_at']:\n count4 += 1\n if 'Fri' in i['created_at']:\n count5 += 1\n if 'Sat' in i['created_at']:\n count6 += 1\n if 'Sun' in i['created_at']:\n count7 += 1\nprint(count1)\nprint(count2)\nprint(count3)\nprint(count4)\nprint(count5)\nprint(count6)\nprint(count7)\nprint(countuser)\nprint(countselfie)\n#draw bar chart with day distribution\nvalues = (count1,count2,count3,count4,count5,count6,count7)\nindex = ('Mon','Tue','Wed','Thu','Fri','Sat','Sun')\nwidth = 1\ncolor = ['silver','tan','darksalmon','purple','blue','c','green','yellow','orange','indianred']\nplt.bar(index, values, width, label=\"selfies in region\",color=color)\nplt.ylabel('Num of selfies')\nplt.xlabel('Day')\nplt.title('Selfie Distribution by Day')\nplt.show()","sub_path":"analytics/scripts/day distribution.py","file_name":"day distribution.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"366994729","text":"#!/usr/bin/python\n\n# tomsom\n# Derived from Sara Edwards' SANS FOR518\n\n# Truffleshuffle is a simple script that parses the Mac OS \n# ChunkStoreDatabase and ChunkStorage to carve versioned files.\n\nimport os\nimport sqlite3\nfrom optparse import OptionParser\n\nparser = OptionParser()\nparser.add_option(\"-c\", dest=\"csfile\", help=\"ChunkStorage file\")\nparser.add_option(\"-d\", dest=\"csdb\", help=\"ChunkStoreDatabase SQLite file\")\nparser.add_option(\"-o\", dest=\"outdir\", help=\"Output folder\", default=\"output\")\n(options, args) = parser.parse_args()\n\ntry:\n if not os.path.exists(options.outdir):\n os.makedirs(options.outdir)\nexcept OSError as err:\n print(\"OS error - %s\" % str(err))\n exit()\n\n# open ChunkStoreDatabase and ChunkStorage file\ndb = sqlite3.connect(str(options.csdb)) \ncs = open(str(options.csfile), 'r')\n\ntry: \n for [clt_rowid, clt_inode] in db.execute('SELECT clt_rowid,clt_inode FROM CSStorageChunkListTable'):\n for [offset, dataLen] in db.execute(\"SELECT offset,dataLen from CSChunkTable where ct_rowid = '%s'\" % clt_rowid):\n\n filenameraw = \"%s/%s-%s-raw\" % (options.outdir, clt_inode, clt_rowid)\n filename = \"%s/%s-%s\" % (options.outdir, clt_inode, clt_rowid)\n\n outputraw = open(filenameraw, 'w') \n output = open(filename, 'w') \n\n cs.seek(offset) \n file = cs.read(dataLen)\n outputraw.write(file)\n outputraw.close()\n\n cs.seek(offset + 25)\n file = cs.read(dataLen - 25)\n output.write(file)\n output.close()\n\nexcept sqlite3.Error as err:\n print(\"SQLite error - %s\" % str(err))\n exit()\n\ndb.close()\n","sub_path":"truffleshuffle.py","file_name":"truffleshuffle.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"504339275","text":"# -*- coding: utf-8 -*-\n# +--------------------------------------------------+\n# + 解方程 Ax = b \n# + Creator: 玉木 先生 \n# + Modified by: 沈 雷 \n# + Time: 2019/04/30 \n# +--------------------------------------------------+\n\n# [名词解释] 学习画像: 可能是根据原向量或者矩阵的值生成的画像\n\n# [1] load modules\n# 加载模块\nimport numpy as np\nimport skimage.data\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import imshow\nplt.gray()\nimport sklearn\nfrom sklearn.datasets import fetch_olivetti_faces\n\n\n# [2] check versions\n# 确认版本信息\nprint(\"sklearn version :\", sklearn.__version__, \" >= 0.18.0\")\nprint(\"skimage version :\", skimage.__version__, \" >= 0.12.0\")\nprint(\"numpy version :\", np.__version__, \" >= 0.12.0\")\nprint(\"matplotlib version:\", matplotlib.__version__, \">= 2.0.0\")\n\n\n\n# ここではsklearnのデータセットとして準備されているOlivetti facesデータセットを用いる. 詳しくはsklearnのマニュアルを参照.\n# このデータセットには400枚の顔画像があり,それぞれが4096次元のベクトルである(64x64画像を表す).\n# -----\n# 这里,作为sklearn的数据集、准备了Olivetti faces数据集。 详细请访问sklearn的手册:\n# 【 sklearn: https://scikit-learn.org/stable/modules/generated/sklearn.datasets.fetch_olivetti_faces.html 】\n# 这个数据集有400枚的人脸画像,各自分别为4096维的向量(以64x64的画像表示)\n\n# [3] load the face dataset\n# 加载人脸数据集\n# [变量定义] - faces: 人脸数据集,这里是一个矩阵\ndataset = fetch_olivetti_faces(shuffle=False)\nfaces = dataset.data\n\n\n# [4] faces has images as its row vectors\n# faces数据集将图像维度作为其行向量的元素\n# [变量定义] - nsample: faces矩阵的行数,表示有多少样本(图像)\n# - dim: faces矩阵的列数,表示样本维度\nnsamples, dim = faces.shape\nprint(\"there are\", nsamples, \"samples of dimension\", dim)\n\n\n# [5] see the inside of faces\n# 让我们康康faces数据集里面的样子\nprint(faces)\n\n\n# # [6] \n# # show 0-th image with colorbar (pixel values range from 0 to 1)\n# # reshape(64,64) converts a vector into a 64x64 image \n# # ---\n# # 用colorbar(色阶条)展示第一张图片(像素值范围为0~1),这里理解为更为直观地展示图像亮度?\n# # reshape(64, 64) 方法实现了将一个向量转换为一个64x64的图片\n# imshow(faces[0].reshape(64,64), vmin=0, vmax=1) # set vmin=0 and vmax=1 to display value 0 to be black, \n# # 将vmin定为0、vmax定为1,这样一来0便展示为纯黑\n# # and 1 white (otherwise min value is black and max value is white)\n# # 以及1是纯白(否则最小值是纯黑、最大值是纯白)\n# plt.colorbar() # show colorbar\n# plt.axis('off') # turn off border ticks\n# plt.title(\"0th image\") # set title\n# plt.show()\n\n\n# # [7]\n# # show all 400 images. takes time, wait for a while....\n# plt.figure(figsize=(20, 20))\n# for i, p in enumerate(faces):\n# plt.subplot(20, 20, i + 1)\n# plt.imshow(faces[i].reshape(64,64), vmin=0, vmax=1)\n# plt.axis('off')\n# plt.show()\n\n\n# ====== 行列 A の定義 ======\n\n\n# [8] データセットの各学習画像をベクトル xi とみなす. 各画像は2次元配列だが,\n# 1次元配列にreshapeする(Olivetti facesデータセットの場合にはすでに各画像が1次元配列になっている). \n# 学習画像として最初の200枚を用いることにする.\n# ---\n# 将数据集的各学习图像分别定义为 xi, 各图像虽然是二维数组,\n# 但这时需要将它们reshape成一维数组(使用Olivetti faces的数据集时,各画像已经是一维数组了)\n# [变量定义] - A: 数据集中前200张图像的集合(N = 200)\nA = faces[:200].transpose()\n\n\n# [9] Aの各列は4096次元のベクトルである\n# A的各列是4096维的列向量\nprint(A.shape)\n\n\n# [10] テスト画像であるベクトル b としては201〜400枚目のどれかを用いる.\n# 将(数据集中)第201~400张画像的某一张作为测试图像的向量b\nb = faces[201] # 例えば201枚目\n\n\n# # [11]\n# imshow(b.reshape(64,64), vmin=0, vmax=1)\n# plt.colorbar()\n# plt.axis('off')\n# plt.title(\"vector b\")\n# plt.show()\n# fig1 = plt.figure('fig1')\n\n\n# ====== 連立方程式を解く ======\n\n\n# [12] A は正方行列ではないため,一般化逆行列を用いてxを求める.\n# x = (A^T A)^{-1} A^T b\n# ---\n# 因为A不是方阵,所以这里要用广义逆矩阵求得x\n# x = (A^T A)^{-1} A^T b\nx_solution = np.linalg.inv(A.transpose().dot(A)).dot(A.transpose().dot(b))\n\n\n# [13] [14]\n# なお,通常の実装上で逆行列を用いてはならない(逆行列が存在しないかもしれないし,存在しても条件数が悪いかもしれない.また逆行列の計算コストが大きい).\n# そのかわりに,ほぼ同じように動作するnp.linalg.lstsqを用いる.\n# ---\n# 并且,由于一般情况下实现代码的时候不会使用到逆矩阵(逆矩阵可能不存在,即使存在也可能存在限制条件,而且计算逆矩阵的计算成本太大)\n# 因此,作为替换、用几乎是同样功能的 np.linalg.lstsq 代替之\nx_solution_np, _, _, _ = np.linalg.lstsq(A, b, rcond=None)\nnp.linalg.norm(x_solution - x_solution_np) # 两种方法之间的差值\n\n\n# [15] [16]\n# 求めた係数ベクトル x を用いて Ax を計算し,画像として表示して,これが b とどれだけ似ているのかを確認する.\n# 将求得的系数向量 x 带入到 Ax 式中计算,将所求结果以图像的形式表示,并将结果与 b 进行对比、研究其与 b 的相似程度\nx = x_solution_np\n\n# imshow((A @ x).reshape(64,64), vmin=0, vmax=1)\n# plt.colorbar()\n# plt.axis('off')\n# plt.title(\"vector Xa\")\n# fig2 = plt.figure('fig2')\n# plt.show()\n\n\n# [17] np.linalg.norm 方法求取二乗平均平方根誤差 RMSE\n# 算出来的系数向量x、乘上数据集A后的结果、与目标图像b的误差\nrmse = np.linalg.norm(A @ x - b) / b.shape[0]\nprint(\"RMSE: \", rmse)\n\n\n# [18] [19]\n# 係数ベクトル x の要素の内,大きい方から10個の要素の値と,それに対応する学習画像を表示する.これらは画像 b を再構成する時に最も寄与が大きい.\n# 系数向量x的元素中,选出最大的十个元素,并表示出与其对应的学习图像。 这些图像在再生成图像b时的贡献最多\nrank = np.argsort(x)[::-1] # sort in decending order\n# plt.figure(figsize=(10, 7))\n\n# for i, top_rank in enumerate(rank[:10]):\n# plt.subplot(3, 4, i + 1)\n \n# plt.imshow(A[:, top_rank].reshape(64,64), vmin=0, vmax=1)\n# plt.title(x[top_rank], fontsize=10)\n# plt.axis('off')\n\n\n\n# ATb はbとAの各列との類似度である.この類似度の大きい方から10個の要素の値と,それに対応する学習画像を表示する.これらは類似度としては大きいが,bを再構成するためには不向きである.\n# 同じ人物の画像と類似度が高い.この理由は,ベクトルのノルムが大きいと類似度も大きくなってしまう,つま���明るい画像はどんな画像とも類似度が大きいためである.\n# ---\n# A_^{T}b 是 b与A的各列的类似度. 将这个类似度最大的十个元素对应的学习画像表示出来. 虽然这些作为类似度来说是很大,但是在再生成b的过程中并没有起到很大作用\n# 同样人物的不同图像之间类似度很高,这是因为向量的范数越大、类似度也越大的原因。 也就是说明亮的图像无论和怎样的图像之间的类似度都很大\n# [20] [21]\nsimilarity = A.transpose() @ b\nsimilarity_rank = np.argsort(similarity)[::-1] # sort in decending order\n\n# plt.figure(figsize=(10, 7))\nfor i, top_rank in enumerate(similarity_rank[:10]):\n plt.subplot(3, 4, i + 1)\n \n plt.imshow(A[:, top_rank].reshape(64,64), vmin=0, vmax=1)\n plt.title(similarity[top_rank], fontsize=10)\n plt.axis('off')\nplt.show() ","sub_path":"190511/project_human_face/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":8415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"120205670","text":"from openpyxl import load_workbook\nimport csv\nworkbook = load_workbook('20min_data.xlsx')\n#booksheet = workbook.active\nsheets = workbook.get_sheet_names()\nbooksheet = workbook.get_sheet_by_name(sheets[0])\n \nrows = booksheet.rows\ncolumns = booksheet.columns\ntemp=[]\nfor row in rows:\n line = [col.value for col in row]\n print (row[0].value)\n v=str(row[0].value).split(':')\n print(str(int(v[0])*60+int(v[1])));\n temp.append([str(int(v[0])*60+int(v[1]))])\n\nwith open(\"time.csv\",\"w\") as csvfile: \n writer = csv.writer(csvfile)\n writer.writerows(temp)\n'''\nwith open(\"mapOfAddress.csv\",\"r\") as csvfile:\n reader = csv.reader(csvfile)\n index=0\n rows=[]\n for line in reader:\n\t#print line\n\tif line[2]=='Match':\n temp=[line[0],line[1],line[2],line[3],line[4],line[8].zfill(2)+line[9].zfill(3)+line[10].zfill(6)+line[11][0]]\n\t print temp\n\telse:\n\t temp=[line[0],line[1],line[2],line[3]]\n\t print temp\n\tindex=index+1\n\trows.append(temp)\n\t#print(temp)\n #print rows\n with open(\"out.csv\",\"w\") as csvfile: \n \twriter = csv.writer(csvfile)\n \twriter.writerows(rows)\nwith open(\"data_simple.csv\",\"r\") as csvfile:\n reader = csv.reader(csvfile)\n index=0\n rows=[]\n for line in reader:\n\t#print line\n\tif line[14]=='Match':\n\t if line[0]=='Active':\n\t\ttemp=['1',line[13],line[5],line[13].zfill(12)]\n\t else:\n\t\ttemp=['0',line[13],line[5],line[13].zfill(12)]\n\t print temp\n\t rows.append(temp)\n\t#print(temp)\n #print rows\n with open(\"label.csv\",\"w\") as csvfile: \n \twriter = csv.writer(csvfile)\n \twriter.writerows(rows)\n'''\n","sub_path":"QuerySimulation-master/data/realData/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"485826465","text":"from rply.token import Token, SourcePosition\n\nclass Lexer(object):\n EOF = chr(0)\n\n def __init__(self, source):\n self.source = source\n self.idx = 0\n self.columno = 0\n self.lineno = 1\n self.current_value = []\n\n def add(self, ch):\n self.current_value.append(ch)\n\n def clear(self):\n del self.current_value[:]\n\n def current_pos(self):\n return SourcePosition(self.idx, self.lineno, self.columno)\n\n def newline(self):\n self.lineno += 1\n self.columno = 1\n\n def emit(self, token):\n value = \"\".join(self.current_value)\n self.clear()\n return Token(token, value, self.current_pos())\n\n def read(self):\n try:\n ch = self.source[self.idx]\n except IndexError:\n ch = self.EOF\n self.idx += 1\n self.columno += 1\n return ch\n\n def unread(self):\n idx = self.idx - 1\n assert idx >= 0\n self.idx = idx\n self.columno -= 1\n\n KEYWORDS = {\n \"+\": \"PLUS\",\n \"-\": \"MINUS\",\n \"*\": \"MULT\",\n \"/\": \"DIV\",\n \"(\": \"LPAREN\",\n \")\": \"RPAREN\",\n \"[\": \"LBRACKET\",\n \"]\": \"RBRACKET\",\n \"{\": \"LBRACE\",\n \"}\": \"RBRACE\",\n \",\": \"COMMA\",\n \".\": \"DOT\",\n \":\": \"COLON\",\n \"=\": \"EQUAL\",\n \"|\": \"PIPE\",\n }\n\n def tokenize(self):\n skip_newline = False\n\n while True:\n ch = self.read()\n\n if ch == self.EOF:\n break\n elif ch.isdigit():\n skip_newline = False\n for token in self.number(ch):\n yield token\n elif ch in \" \\r\":\n pass\n elif ch == \":\":\n self.add(ch)\n skip_newline = False\n more = self.read()\n if more == \"=\":\n self.add(more)\n yield self.emit(\"RECUPDATE\")\n elif more == \"~\":\n self.add(more)\n yield self.emit(\"RECMETHOD\")\n else:\n self.unread()\n yield self.emit(\"COLON\")\n\n elif ch in \"+-*/(),.:=[]|{}\":\n skip_newline = not ch in \")]}\"\n self.add(ch)\n yield self.emit(self.KEYWORDS[ch])\n elif ch in \"\\n\":\n if not skip_newline:\n self.add(ch)\n yield self.emit(\"NEWLINE\")\n self.newline()\n skip_newline = True\n elif ch in \";\":\n skip_newline = True\n self.add(ch)\n yield self.emit(\"SEMICOLON\")\n else:\n for token in self.identifier(ch):\n yield token\n\n yield None\n\n def number(self, ch):\n self.add(ch)\n symbol = \"INTEGER\"\n while True:\n ch = self.read()\n if ch.isdigit():\n self.add(ch)\n else:\n yield self.emit(symbol)\n self.unread()\n break\n\n def identifier(self, ch):\n self.add(ch)\n symbol = \"IDENT\"\n while True:\n ch = self.read()\n if ch == self.EOF:\n yield self.emit(symbol)\n self.unread()\n break\n elif ch.isalnum() or ch == \"_\" or ord(ch) > 127:\n self.add(ch)\n else:\n yield self.emit(symbol)\n self.unread()\n break\n\n","sub_path":"uno/lexer.py","file_name":"lexer.py","file_ext":"py","file_size_in_byte":3557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"644220080","text":"from conclusion.models import ManufacturingTransaction, ManufacturingTransactionLine, Outage, PowerGeneration, \\\n Consumtion\nfrom rest_framework.serializers import ModelSerializer\nfrom mgpAPI.serializers.manufacturing_shifthead_serializers import OutageSerializer\nfrom django.db import transaction\nfrom rest_framework import serializers\n\n\nclass ConsumptionOutageSerializer(ModelSerializer):\n outage_lines = OutageSerializer(many=True)\n\n class Meta:\n model = Consumtion\n fields = '__all__'\n\n @transaction.atomic\n def create(self, validated_data):\n outages_data = validated_data.pop('outage_lines')\n consumption = Consumtion.objects.create(title='mark')\n\n for outage_data in outages_data:\n Outage.objects.create(consumption=consumption,\n created_user=self.context['request'].user,\n last_modified_users=self.context['request'].user,\n **outage_data)\n\n return consumption\n","sub_path":"mgpAPI/serializers/manufacturing_outage_serializers.py","file_name":"manufacturing_outage_serializers.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"322599717","text":"import sys\nimport os\nimport boto3\nsys.path.append(os.path.dirname(os.path.abspath(\"configuration.py\")))\nfrom configuration import Config\n\nif not len(sys.argv) == 3:\n print(\"Usage: createInstance.py \")\n sys.exit()\n\nACCESS_KEY = sys.argv[1]\nSECRET_KEY = sys.argv[2]\n\nclient = boto3.resource(\n 'ec2',\n aws_access_key_id=ACCESS_KEY,\n aws_secret_access_key=SECRET_KEY,\n region_name=Config.ec2_region\n )\nresponse = client.create_instances(ImageId = Config.ec2_amis[0],\n InstanceType = Config.ec2_instancetype, \n KeyName = Config.ec2_keypair,\n MaxCount = 1,\n MinCount = 1,\n SecurityGroups = Config.ec2_secgroups)\n\nprint(\"INSTANCE CREATED\")\nprint(\"INSTANCE ID: \" + response[0].id)","sub_path":"utilityScripts/createInstance.py","file_name":"createInstance.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"281912992","text":"\nimport test_settings\nimport requests\nimport time\nimport getToken\nfrom discoverDevice import discoverDevice\nfrom cleanup import cleanup\nfrom approveDevice import approveDevice\nimport importlib\nfrom bemoss_lib.utils.BEMOSS_ONTOLOGY import BEMOSS_ONTOLOGY\n\nimport logging\nmain_logger = logging.getLogger(\"testlogger\")\n\n\ndef deviceControlTest(token, device_model,agent_id, controlCommandList):\n main_logger.info(\"Starting control test\")\n device_info = test_settings.DEVICE_INFO[device_model]\n device_type = device_info['device_type']\n token_dict = {\"token\": token}\n\n device_api = importlib.import_module(\"DeviceAPI.\" + device_info['api'])\n device_ontology = device_api.API().ontology()\n #check if you can read all the device data from the metadata\n device_list_url = test_settings.URL + \"/api/get_better_list\"\n device_control_url = test_settings.URL +\"/device/api_update_device\"\n query_dict = dict(token_dict)\n query_dict.update({\"agent_id\": agent_id})\n\n for controlCommand in controlCommandList:\n d = {\"agent_id\":agent_id,'user':\"testingScript\"}\n controlCommand.update(d)\n\n main_logger.debug(\"Sending control command:\" + str(controlCommand))\n response = requests.post(device_control_url,params=query_dict,json={'data':controlCommand})\n response.raise_for_status()\n time.sleep(5) #wait for the control command to be processed\n main_logger.info(\"Control command sent successfully\")\n recheck_count = 3\n\n while recheck_count:\n result = requests.get(url=device_list_url, params=token_dict)\n unchanged_vars = []\n try:\n result.raise_for_status()\n except:\n main_logger.error(\"Get better list api call failed. Webserver issue\")\n raise\n\n device_data = result.json()\n main_logger.debug(\"Got device data:\" + str(device_data))\n if not device_data or 'Building1' not in device_data or device_type not in device_data['Building1']['devices'] or \\\n not device_data['Building1']['devices'][device_type]:\n time.sleep(5)\n recheck_count -=1\n else:\n device_data = device_data['Building1']['devices'][device_type][0]\n for val in device_ontology.values():\n if val.NAME not in device_data:\n main_logger.error(\"One of the ontology variable doesn't exist in device data: \"+val.NAME)\n raise Exception(\"One of the ontology variable doesn't exist in device data: \"+val.NAME)\n if val.NAME in controlCommand and device_data[val.NAME] != controlCommand[val.NAME]:\n unchanged_vars.append(val.NAME)\n recheck_count -= 1\n time.sleep(5) #There is a mismatch, lets wait 5 more seconds and see if it will match next time\n main_logger.debug(\"Some variables did not change; waiting 5 sec: \" + str(unchanged_vars))\n break\n else:\n break\n if not recheck_count:\n main_logger.error(\"Device Was approved, but the control was not successfull. The following vars didn't change:\" + str(unchanged_vars))\n raise Exception(\"Device Was approved, but the control was not successfull. The following vars didn't change:\" + str(unchanged_vars))\n\n main_logger.info(\"Control successfully verified in postgresdb.\")\n time.sleep(2)\n #check if you can read the historical data\n device_history_url = test_settings.URL + \"/charts/get_historical_data\"\n recheck_count = 3\n while recheck_count:\n unchanged_vars = list()\n result = requests.get(url=device_history_url, params=query_dict)\n try:\n result.raise_for_status()\n except Exception as exp:\n main_logger.error(\"get_historical_data end point failed. Webserver issue\")\n raise\n\n\n device_data = result.json()\n main_logger.debug(\"Historical data:\"+str(device_data))\n device_ontology = device_api.API().ontology()\n for val in device_ontology.values():\n if val.NAME in controlCommand and device_data[val.NAME][-1][1] != controlCommand[val.NAME]:\n unchanged_vars.append(val.NAME)\n recheck_count -= 1\n time.sleep(5) # There is a mismatch, lets wait 5 more seconds and see if it will match next time\n main_logger.debug(\"Some variables did not change; waiting 5 sec: \" + str(unchanged_vars))\n break\n break\n\n if not recheck_count:\n main_logger.error(\"Device Was approved, but it could not get data from device in cassandra\")\n raise Exception(\"Device Was approved, but it could not get data from device in cassandra\")\n\n main_logger.info(\"Control successfully verified in cassandradb.\")\n\n\nif __name__ == \"__main__\":\n device_model = \"RTH8580WF\"\n # agent_id = \"ICM1_BGQKEKRXBGFV_contract1\"\n agent_id = u'RTH8_3994424_contract1'\n #cleanup()\n token = getToken.login(test_settings.testusername, test_settings.testuserpassword)\n # device_info = test_settings.DEVICE_INFO[device_model]\n # devices = discoverDevice(token, device_info)\n # one_device = devices[0]\n # approveDevice(token, one_device)\n # agent_id = one_device['agent_id']\n controlCommandList = test_settings.test_control_commands['RTH8580WF']\n\n print(deviceControlTest(token, device_model, agent_id, controlCommandList))\n # cleanup()","sub_path":"Web_Server/test/deviceControlTest.py","file_name":"deviceControlTest.py","file_ext":"py","file_size_in_byte":5697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"608438688","text":"from qiskit import QuantumCircuit, QuantumRegister\nimport os\nos.chdir('../../Preprocessing')\nfrom data_preparation import is_stochastic_vector\nos.chdir('../Encoding/Unary-Encoding')\nimport numpy as np\nfrom qiskit.aqua.circuits.gates import mcry\n\n\ndef partial_swap(angle, circuit, target_qubits):\n if len(target_qubits) != 2:\n raise NameError('The target qubits list is not of size 2.')\n else:\n ctrl_qubit = target_qubits[0]\n target_qubit = target_qubits[1]\n circuit.cx(target_qubit, ctrl_qubit)\n circuit.cry(-angle, ctrl_qubit, target_qubit)\n circuit.cx(target_qubit, ctrl_qubit)\n return circuit\n\n\ndef unary_encoding_angles(distribution): #ADD THE POSSIBILITY TO HAVE AN ODD N\n distribution = np.array(distribution)\n n = len(distribution)\n if is_stochastic_vector(distribution) == True and n % 2 == 0: \n angles = [] \n for i in range(n - 1):\n i = i + 1\n if i < n / 2:\n angles.append(2 * np.arctan2(np.sqrt(np.sum(distribution[0:i])), np.sqrt(distribution[i]))) \n elif i == n / 2 :\n inter = int(n / 2)\n angles.append(2 * np.arctan2(np.sqrt(1 - np.sum(distribution[inter:n])), np.sqrt(np.sum(distribution[inter:n]))))\n else : \n angles.append(2 * np.arctan2(np.sqrt(np.sum(distribution[i:n])), np.sqrt(distribution[i - 1])))\n return angles\n else :\n raise NameError(\"The input vector is not a probability distribution or its dimension is not a multiple of 2.\")\n \n\ndef unary_encoding(distribution, circuit = QuantumCircuit(), distribution_qubits = None):\n n_qubits = len(distribution)\n if distribution_qubits == None:\n distribution_qubits = QuantumRegister(n_qubits)\n if circuit == QuantumCircuit(): \n circuit = QuantumCircuit(distribution_qubits)\n else:\n circuit.add_register(distribution_qubits)\n else:\n if len(distribution_qubits) != n_qubits:\n raise NameError('The number of distribution qubits is incompatible with the distribution size.')\n theta = unary_encoding_angles(distribution)\n middle = int(n_qubits / 2)\n circuit.x(distribution_qubits[middle])\n circuit = partial_swap(theta[middle - 1], circuit, [distribution_qubits[middle - 1], distribution_qubits[middle]])\n for step in range(middle - 1):\n step = step + 1\n circuit = partial_swap(theta[middle - 1 - step], circuit, [distribution_qubits[middle - 1 - step], distribution_qubits[middle - step]])\n circuit = partial_swap(-theta[middle - 1 + step], circuit, [distribution_qubits[middle - 1 + step], distribution_qubits[middle + step]])\n return circuit, distribution_qubits\n\n\n### CONTROLLED VERSIONS\n \n\ndef controlled_partial_swap(angle, circuit, ancillae_qubits, control_qubits, target_qubits):\n if len(target_qubits) != 2:\n raise NameError('The target qubits list is not of size 2.')\n else:\n ctrl_qubit = target_qubits[0]\n target_qubit = target_qubits[1]\n circuit.mct(list(control_qubits) + [target_qubit], ctrl_qubit, ancillae_qubits[1:])\n circuit.mcry(angle, list(control_qubits) + [ctrl_qubit], target_qubit, None, 'noancilla')\n circuit.mct(list(control_qubits) + [target_qubit], ctrl_qubit, ancillae_qubits[1:])\n return circuit\n \n \ndef controlled_unary_encoding(distribution, circuit, ancillae_qubits, control_qubits, distribution_qubits = None): #on veut aussi retourner distribution_qubits, modifier ce qui en découle\n theta = unary_encoding_angles(distribution)\n n_qubits = len(distribution)\n if distribution_qubits != None:\n if len(distribution_qubits) != n_qubits:\n raise NameError('The number of the distribution qubits is incompatible with the distribution size.')\n else:\n distribution_qubits = QuantumRegister(n_qubits)\n circuit.add_register(distribution_qubits)\n middle = int(n_qubits / 2)\n circuit.mct(control_qubits, distribution_qubits[middle], ancillae_qubits[1:])\n circuit = controlled_partial_swap(theta[middle - 1], circuit, ancillae_qubits, control_qubits, [distribution_qubits[middle - 1], distribution_qubits[middle]])\n for step in range(middle - 1):\n step = step + 1\n circuit = controlled_partial_swap(theta[middle - 1 - step], circuit, ancillae_qubits, control_qubits, [distribution_qubits[middle - step - 1], distribution_qubits[middle - step]])\n circuit = controlled_partial_swap(-theta[middle - 1 + step], circuit, ancillae_qubits, control_qubits, [distribution_qubits[middle + step - 1], distribution_qubits[middle + step]])\n return circuit, distribution_qubits\n\n\ndef inverse_controlled_unary_encoding(distribution, circuit, ancillae_qubits, control_qubits, distribution_qubits):\n theta = unary_encoding_angles(distribution)\n n_qubits = len(distribution)\n if len(distribution_qubits) != n_qubits:\n raise NameError('The number of threshold qubits is incompatible with the distribution size.')\n else:\n middle = int(n_qubits / 2)\n for step in range(middle - 1):\n circuit = controlled_partial_swap(-theta[step], circuit, ancillae_qubits, control_qubits, [distribution_qubits[step], distribution_qubits[step + 1]])\n circuit = controlled_partial_swap(-theta[n_qubits - step - 2], circuit, ancillae_qubits, control_qubits, [distribution_qubits[n_qubits - step - 2], distribution_qubits[n_qubits - step - 1]])\n circuit = controlled_partial_swap(-theta[inter - 1], circuit, ancillae_qubits, control_qubits, [distribution_qubits[middle - 1], distribution_qubits[middle]])\n circuit.mct(control_qubits, distribution_qubits[middle], ancillae_qubits[1:])\n return circuit\n","sub_path":"Encoding/Unary-Encoding/Unary_encoding.py","file_name":"Unary_encoding.py","file_ext":"py","file_size_in_byte":5795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"446242195","text":"# This is the file used to help create basic nlp responses\n# It uses the cordial algorithm\n\n# Very basic NLP using simple ifs and elses\n\ndef return_quest(text):\n words = text.split(\" \")\n current_index = 0\n past_index = 0\n for i in range(len(words)):\n word = words[i]\n if word.count(\"?\") > 0:\n current_index = i\n for j in range(0, current_index):\n if words[j].count(\".\") > 0:\n past_index = j\n break\n break\n \n quest_sent = words[i:j]\n quest_str = \"\"\n for word in quest_sent:\n quest_str = quest_str + \" \" + word\n return quest_str\n\ndef return_statement(text: str, question: str):\n question.replace('?', '')\n question.lower()\n quest_list = question.split(\" \")\n words = text.split(\" \")\n start_index = 0\n end_index = 0\n for i in range(len(words)):\n word = words[i]\n if word.lower() == \"answer\":\n for j in range(0, i):\n if words[j].count('.') > 0:\n start_index = j\n break\n for j in range (i, len(words)):\n if words[j].count('.') > 0:\n end_index = j\n break\n break\n statement_sentance = words[start_index:end_index]\n statement = \"\"\n for word in statement_sentance:\n statement = statement + \" \" + word\n return statement\n","sub_path":"misc/nlp.py","file_name":"nlp.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"224066687","text":"#!/usr/bin/python3\n\nimport urllib.request\nimport json\nimport pymongo\nimport datetime\nimport csv\nimport subprocess\nfrom urllib.parse import urljoin, quote\nfrom pymongo import MongoClient\n\nextended_print = False\n\ndef query(word, page, per_page=50):\n text = 'vacancies?text={0}&page={1}&per_page={2}'.format(quote(word), page, per_page)\n uri = urljoin('https://api.hh.ru/', text) \n return uri\n\ndef request(url):\n with urllib.request.urlopen(url) as resp:\n respData = resp.read()\n return respData\n\ndef parce_responce(responce):\n encoded = responce.decode('utf-8').encode('cp866','ignore').decode('cp866')\n return json.loads(encoded)\n\ndef append_loaded(vacances_list, object): \n vacances = (Vacance.parce(item) for item in object['items'])\n for i in vacances:\n vacances_list.append(i) \n \ndef load_vacances(word):\n vacances = []\n pager = Pager(word)\n\n while pager.hasNext():\n responce = request(pager.nextUrl())\n result = parce_responce(responce)\n pager.update(result)\n print(pager.pretty())\n append_loaded(vacances, result)\n\n print(\"loaded = \" + str(len(vacances)))\n return vacances\n\nclass Vacance:\n def parce(item):\n id = item['id']\n name = item['name']\n employer = item['employer']['name']\n salary_from = Vacance.get_salary(item,'from')\n salary_to = Vacance.get_salary(item,'to')\n return Vacance(id, name, employer, salary_from, salary_to)\n\n def get_salary(item,key):\n salary = 0\n try:\n salary = int(item['salary'][key])\n except Exception:\n pass\n return salary\n\n def deserialize(item):\n id = item['_id']\n name = item['name']\n employer = item['employer']\n salary_from = item['salary_from']\n salary_to = item['salary_to']\n vacance = Vacance(id, name, employer, salary_from, salary_to)\n vacance.date = item['date']\n vacance.last_date = Vacance.get_last_date(item)\n return vacance\n\n def get_last_date(item):\n last_date = datetime.datetime.utcnow()\n try:\n last_date = int(item['last_date'][key])\n except Exception:\n pass\n return last_date\n\n def __init__(self, id, name, employer, salary_from, salary_to):\n self._id = id\n self.name = name\n self.employer = employer\n self.salary_from = salary_from\n self.salary_to = salary_to\n self.date = datetime.datetime.utcnow()\n self.last_date = datetime.datetime.utcnow()\n\n def pretty(self):\n return \"{0}\\n\\t{1}\\t{2}\\t{3}\\n\\t{4}\".format(self.name, self.salary_from, self.salary_to, self.date, self.employer)\n\nclass Pager:\n def update(self, item):\n self.found = item['found']\n self.page = item['page']\n self.pages = item['pages'] \n\n def __init__(self, word):\n self.word = word\n self.found = 0\n self.page = -1\n self.pages = 1\n\n def hasNext(self):\n return self.page + 1 < self.pages \n\n def nextUrl(self):\n self.page += 1\n return query(self.word, self.page)\n\n def pretty(self):\n return \"Found = {0}, Page = {1} / {2}\".format(self.found, self.page, self.pages)\n \ndef get_db_collection():\n client = MongoClient()\n db = client.hunter\n return db.vacances\n\ndef save_to_db(vacanses):\n collection = get_db_collection() \n for i in vacanses:\n collection.insert(i.__dict__)\n\ndef update_db_items(vacances):\n collection = get_db_collection() \n for i in vacances:\n collection.update_one({'_id': i._id},{'$set':{'last_date': i.last_date}})\n\ndef load_from_db():\n collection = get_db_collection()\n return [Vacance.deserialize(i) for i in collection.find()]\n\ndef sort_vacances(hh_vacances, db_vacances):\n db_dict = {i._id:i for i in db_vacances}\n new_vacances_dict = {}\n old_vacances_dict = {}\n for i in hh_vacances:\n if i._id in db_dict:\n old_vacances_dict[i._id] = db_dict[i._id]\n else:\n new_vacances_dict[i._id] = i\n return (new_vacances_dict.values(), old_vacances_dict.values())\n\ndef print_vacances(vacances):\n if(extended_print):\n for i in new_vacances:\n print(i.pretty())\n print(\"\\n\")\n else:\n print(\"Found {0} vacances\\n\".format(len(vacances)))\n\ndef update_db_for_word(word, black_list):\n print(\"Look for '{0}'\".format(word))\n\n hh_vacances = load_vacances(word)\n db_vacances = load_from_db()\n new_vacances, old_vacances = sort_vacances(hh_vacances, db_vacances)\n\n if(len(old_vacances) > 0):\n update_db_items(old_vacances)\n \n filtered = filter_by_black_list(new_vacances, black_list)\n if(len(filtered) > 0):\n print_vacances(filtered)\n save_to_db(filtered)\n else:\n print(\"New vacances not found\\n\") \n\ndef load_keywords():\n client = MongoClient()\n db = client.hunter\n return [item['word'] for item in db.words.find()]\n\ndef load_black_list():\n client = MongoClient()\n db = client.hunter\n return [item['employer'] for item in db.black.find()]\n\ndef clear_from_black_list(black_list):\n collection = get_db_collection()\n for word in load_black_list():\n collection.remove({'employer':word})\n\ndef filter_by_black_list(vacances, black_list):\n return [i for i in vacances if i.employer not in black_list]\n\ndef dump_to_file():\n d = datetime.date.today()\n file_name = \"Dump_{0}_{1}_{2}.scv\".format(d.year,d.month,d.day)\n subprocess.call('mongoexport --db hunter --collection vacances -o {0} --type=csv -f name,salary_from,salary_to,employer,date'.format(file_name))\n \ndef main():\n black_list = load_black_list()\n clear_from_black_list(black_list)\n for word in load_keywords():\n update_db_for_word(word, black_list)\n #dump_to_file()\n \nmain()\n","sub_path":"Scripts/hunter.py","file_name":"hunter.py","file_ext":"py","file_size_in_byte":5884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"299060079","text":"import logging\nimport operator\nfrom collections import Counter\n\nfrom unipath import Path\n\nfrom image_detection.train_images.classify_image import get_image_classification\n\n\nclass ImageRecognition(object):\n DEFAULT_BEST_SCORE = 0.73\n\n def __init__(self, filename):\n self.filename = filename\n\n def classify_image(self):\n classifications = get_image_classification(self.filename)\n logging.debug(classifications)\n max_key = max(classifications.keys(), key=float)\n keys = {}\n if max_key > self.DEFAULT_BEST_SCORE:\n logging.debug('max_key={}'.format(max_key))\n image_classification = classifications[max_key]['value']\n else:\n keys_values = [sentences['value']\n for key, sentences in classifications.items()]\n logging.debug('keys_values={}'.format(keys_values))\n keys = self.find_keyword(keys_values)\n logging.debug('keys={}'.format(keys))\n max_count_key = max(keys.items(), key=operator.itemgetter(1))\n logging.debug('max_count_key={}'.format(max_count_key[0]))\n image_classification = max_count_key[0]\n\n return {\n 'value': image_classification,\n 'helpers': keys,\n 'accuracy': max_key}\n\n def find_keyword(self, keywords):\n words = []\n for keyword in keywords:\n sentence = str(keyword).split()\n sentence = self.get_common_keys_in_sentence(sentence)\n words += sentence\n return dict(Counter(words))\n\n def get_common_keys_in_sentence(self, sentence):\n new_words = []\n words = sentence\n for word in words:\n for second_word in words:\n if word in second_word:\n if word is second_word:\n pass\n else:\n found_word = second_word.replace(word, '')\n if ',' in found_word:\n found_word = found_word.replace(',', '')\n new_words.append(found_word)\n new_words = [char for char in new_words if char != '']\n words = [old_word.replace(',', ' ') for old_word in words]\n all_words = words + new_words\n return all_words\n\n\nif __name__ == '__main__':\n recognition = ImageRecognition(Path(Path(__file__).parent, 'test_bag.jpg'))\n classification = recognition.classify_image()\n print(classification['value'])\n","sub_path":"image_detection/train_images/ImageContentRecognition.py","file_name":"ImageContentRecognition.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"474296232","text":"#\n# @lc app=leetcode.cn id=338 lang=python3\n#\n# [338] 比特位计数\n#\n\n# @lc code=start\nclass Solution:\n def countBits(self, num: int) -> List[int]:\n res = [0] * (num + 1)\n for i in range(1, num + 1):\n res[i] = res[i & (i - 1)] + 1\n\n return res\n# @lc code=end\n\n","sub_path":"Week08/338.比特位计数.py","file_name":"338.比特位计数.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"572199033","text":"import os\n\n\nCLIENT_SECRET = os.getenv(\"CLIENT_SECRET\") # Our Quickstart uses this placeholder\n# In your production app, we recommend you to use other ways to store your secret,\n# such as KeyVault, or environment variable as described in Flask\"s documentation here\n# https://flask.palletsprojects.com/en/1.1.x/config/#configuring-from-environment-variables\n# CLIENT_SECRET = os.getenv(\"CLIENT_SECRET\")\n# if not CLIENT_SECRET:\n# raise ValueError(\"Need to define CLIENT_SECRET environment variable\")\n\nAUTHORITY = \"https://login.microsoftonline.com/pnnl.gov\"\n# AUTHORITY = \"https://login.microsoftonline.com/common\" # For multi-tenant app\n# AUTHORITY = \"https://login.microsoftonline.com/Enter_the_Tenant_Name_Here\"\n\nCLIENT_ID = os.getenv(\"CLIENT_ID\")\n\n# You can find more Microsoft Graph API endpoints from Graph Explorer\n# https://developer.microsoft.com/en-us/graph/graph-explorer\nENDPOINT = \"https://graph.microsoft.com/v1.0/me/memberOf\" # This resource requires no admin consent\n\n# You can find the proper permission names from this document\n# https://docs.microsoft.com/en-us/graph/permissions-reference\nSCOPE = [\"User.ReadBasic.All\"]\n\nSESSION_TYPE = \"filesystem\" # So token cache will be stored in server-side session\n\n# tags to filter on, add new tags with comma \",\" seperation\nTAGS=[\"stack-finder\"]\n\n# group id or id's that you would like to filter on\n# these can be found at: https://portal.azure.com\nGROUP_ID=[\n \"6244b1cd-56a0-4f32-b192-9f418cf7239f\", # panda-viking group\n \"614be0eb-4e41-4ccf-99b6-a702572671a4\", # ardis aws group\n \"0ba160f8-742c-4ec2-8d5a-60df11b66d95\", # ardis adfs group\n #\"c5b17646-d605-48ef-b405-a66545f5dd7a\" # voltron - testing to make sure i get blocked\n]\n\n# provide users that you would like to add\nGROUP=[\n \"henry.macias@pnnl.gov\",\n \"bryan.gerber@pnnl.gov\",\n \"juan.barajas@pnnl.gov\",\n \"devin.wright@pnnl.gov\"\n]","sub_path":"stack_finder/routes/endpoints/app_config.py","file_name":"app_config.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"106824835","text":"import webapp2\nfrom google.appengine.api import users\nfrom google.appengine.ext import blobstore\nfrom google.appengine.api import images\nfrom google.appengine.ext.webapp import blobstore_handlers\nfrom google.appengine.ext.blobstore import delete, delete_async\nfrom google.appengine.api import channel\nfrom webapp2 import uri_for,redirect\nimport os\nimport urllib\nimport json\nimport cgi\nimport logging\nimport datetime\nimport time\nimport csv\nimport jwt # google wallet token\nimport jinja2\nfrom models import *\nfrom myUtil import *\nfrom secrets import *\n\nJINJA_ENVIRONMENT = jinja2.Environment(\n\tloader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\n\textensions=['jinja2.ext.autoescape'])\n \n \nclass MyBaseHandler(webapp2.RequestHandler):\n\tdef __init__(self, request=None, response=None):\n\t\twebapp2.RequestHandler.__init__(self,request,response) # extend the base class\n\t\tself.template_values={} \n\t\tself.template_values['user']=self.user = users.get_current_user()\n\t\tself.template_values['url_login']=users.create_login_url(self.request.url)\n\t\tself.template_values['url_logout']=users.create_logout_url('/')\n\nclass AdminContactHandler(MyBaseHandler):\n\tdef get(self):\n\t\t# get all contacts\n\t\tself.template_values['contacts']=contacts=Contact.query()\n\t\ttemplate = JINJA_ENVIRONMENT.get_template('/template/AdminContact.html')\n\t\tself.response.write(template.render(self.template_values))\n\t\t\t\t\n\tdef post(self):\n\t\tcontact_id=self.request.get('contact id')\n\t\trole=self.request.get('role')\n\t\tcontact=Contact.get_by_id(contact_id)\n\t\tassert contact\n\t\tcontact.cancel_membership(role)\n\t\t\n\t\tself.response.write('0')\n\nclass AdminContactReputationLinkHandler(MyBaseHandler):\n\tdef post(self):\n\t\tcontact_id=self.request.get('contact id')\n\t\tlink=self.request.get('link')\n\t\tcontact=Contact.get_by_id(contact_id)\n\t\tassert contact\n\t\tcontact.reputation_link=link\n\t\tcontact.put()\n\t\t\n\t\tself.response.write('0')\n\nclass AdminContactReputationScoreHandler(MyBaseHandler):\n\tdef post(self):\n\t\tcontact_id=self.request.get('contact id')\n\t\tscore=self.request.get('score')\n\t\tcontact=Contact.get_by_id(contact_id)\n\t\tassert contact\n\t\tcontact.reputation_score=int(score)\n\t\tcontact.put()\n\t\t\n\t\tself.response.write('0')\n\nclass AdminProductOrderHandler(MyBaseHandler):\n\tdef get(self):\n\t\t# get all carts\n\t\tself.template_values['orders']=orders=MyProductOrder.query()\n\t\t\n\t\ttemplate = JINJA_ENVIRONMENT.get_template('/template/AdminProductOrder.html')\n\t\tself.response.write(template.render(self.template_values))\n\t\t\t\t\n\tdef post(self):\n\t\tpass\n\nclass AdminProductHandler(MyBaseHandler):\n\tdef get(self):\n\t\tself.template_values['products']=products=MyProduct.query()\n\t\t\n\t\ttemplate = JINJA_ENVIRONMENT.get_template('/template/AdminProduct.html')\n\t\tself.response.write(template.render(self.template_values))\n\t\t\t\t\n\tdef post(self):\n\t\tproducts=self.request.get('products').strip().replace('\\r','\\n').replace('\\n',',')\n\t\tproducts=products.split(',')\n\t\tp_list=[(products[i],products[i+1]) for i in xrange(0, len(products),2)]\n\t\t\n\t\tbatch=[]\n\nclass AdminPurgeProductHandler(webapp2.RequestHandler):\n\tdef get(self):\n\t\tproducts=MyProduct.query()\n\t\tndb.delete_multi([p.key for p in products])\n","sub_path":"admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"497099306","text":"from pydoc import doc\nfrom sqlite3.dbapi2 import NotSupportedError\n\nimport pytest\nfrom data_collection import __version__\nfrom data_collection.riksdagens_open_data.rdo_client import RODClient, RODQuery\n\n\ndef test_version():\n assert __version__ == '0.1.0'\n\n\ndef test_rod_client_catalog():\n\n client = RODClient()\n\n response = client.find()\n\n assert response is not None\n assert response.status_code == 200\n\n\ndef test_find_call_with_prot_argument_succeeds():\n\n client = RODClient()\n\n query_result = client.find(doktyp='prot')\n\n assert query_result is not None\n assert len(list(query_result)) > 0\n\n\ndef test_find_documents_with_prot_argument_succeeds():\n\n client = RODClient()\n\n criterias = {'doktyp': 'prot', 'from': '2001-02-01', 'tom': '2001-12-31'}\n\n query_result = client.find(**criterias)\n n_expected_documents = int(query_result['@traffar'])\n\n documents = client.find_documents(**criterias)\n\n n_documents = 0\n with pytest.raises(StopIteration):\n while True:\n _ = next(documents)\n n_documents += 1\n\n assert n_documents == n_expected_documents\n\n\ndef test_store_documents():\n\n client = RODClient()\n\n criterias = {'doktyp': 'prot', 'from': '2001-02-01', 'tom': '2001-12-31'}\n\n documents = [x for x in client.find_documents(**criterias)]\n\n import json\n\n with open('pro.documents.json', 'w') as fp:\n json.dump(documents, fp)\n\n\ndef test_create_query_with_doktype_specified():\n\n q = RODQuery(doktyp='kalle')\n url = q.get_url()\n assert 'doktyp=kalle' in url\n\n\ndef test_create_query_with_empty_doktyp_value_succeeds():\n\n q = RODQuery()\n url = q.get_url()\n assert 'doktyp=&' in url\n\n\ndef test_create_query_with_utformat_is_not_json():\n\n with pytest.raises(NotSupportedError):\n _ = RODQuery(utformat='xml')\n\n\ndef test_create_query_with_no_arguments_should_still_have_all_attributes():\n\n q = RODQuery()\n url = q.get_url()\n\n assert all((k in url for k in q.default_criterias.keys()))\n","sub_path":"tests/test_data_collection.py","file_name":"test_data_collection.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"594790203","text":"from tkinter import *\r\n\r\nroot = Tk()\r\nframe = Frame(root)\r\nframe.pack()\r\n\r\nv1 = StringVar()\r\nv2 = StringVar()\r\nv3 = StringVar()\r\n\r\ndef judge(n): #validatecommand判断条件\r\n if n.isdigit():\r\n return True\r\n else:\r\n return False\r\n\r\ndef calc(): #计算\r\n if v1.get() and v2.get():#输入为空时不可计算\r\n v3.set(int(v1.get())+int(v2.get()))\r\n\r\ndef clear():#清空输入栏\r\n v1.set('')\r\n v2.set('')\r\n v3.set('')\r\n\r\ntest = root.register(judge)\r\nEntry(frame, textvariable=v1, width=10, validate='key',\r\n validatecommand=(test,'%P')).grid(row=0, column=0)\r\nLabel(frame, text='+').grid(row=0, column=1)\r\nEntry(frame, textvariable=v2, width=10, validate='key',\r\n validatecommand=(test,'%P')).grid(row=0, column=2)\r\nLabel(frame, text='=').grid(row=0, column=3)\r\nEntry(frame, textvariable=v3,state='readonly', width=10).grid(row=0, column=4)\r\n\r\nButton(frame, text=' calculate ', command=calc).grid(row=1,column=2,sticky=W)\r\nButton(frame, text=' clear ', command=clear).grid(row=1,column=4,sticky=W)\r\n\r\nmainloop()\r\n","sub_path":"数据结构与算法/第三次/calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"649633210","text":"# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.3.3\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# +\nfrom gssutils import *\n\nscraper = Scraper(\"https://www.gov.uk/government/collections/uk-regional-trade-in-goods-statistics-disaggregated-by-smaller-geographical-areas\")\nscraper\n# -\n\nscraper.select_dataset(latest=True)\nscraper\n\ntabs = {tab.name: tab for tab in scraper.distribution(title=lambda t: 'Data Tables' in t).as_databaker()}\n\n# Get the relevant year\nyear_cell = tabs['Title'].filter('Detailed Data Tables').shift(UP)\nyear_cell.assert_one()\ndataset_year = int(year_cell.value)\n\ntab = tabs['T2 NUTS2']\n\n# +\n#savepreviewhtml(tab)\n#tabs\n# -\n\ntidy = pd.DataFrame()\n\nflow = tab.filter('Flow').fill(DOWN).is_not_blank().is_not_whitespace()\nEuNonEu = tab.filter('EU / Non-EU').fill(DOWN).is_not_blank().is_not_whitespace()\ngeography = tab.filter('EU / Non-EU').fill(DOWN).is_not_blank().is_not_whitespace() \nnut = tab.filter('NUTS2').fill(DOWN).is_not_blank().is_not_whitespace() \nobservations = tab.filter('Statistical Value (£ million)').fill(DOWN).is_not_blank().is_not_whitespace()\nobservations = observations.filter(lambda x: type(x.value) != str or 'HMRC' not in x.value)\nDimensions = [\n HDim(flow,'Flow',DIRECTLY,LEFT),\n HDim(EuNonEu,'EU / Non EU',DIRECTLY,LEFT),\n HDim(geography,'HMRC Partner Geography',DIRECTLY,LEFT),\n HDim(nut,'NUTS Geography',DIRECTLY,LEFT),\n HDimConst('SITC 4', 'all'),\n HDimConst('Measure Type', 'Statistical Value'),\n HDimConst('Unit', 'statistical-value'),\n HDimConst('Year', dataset_year)\n ]\nc1 = ConversionSegment(observations, Dimensions, processTIMEUNIT=True)\ntable1 = c1.topandas()\ntidy = pd.concat([tidy, table1])\n\nsavepreviewhtml(c1)\n\nobservations1 = tab.filter('Business Count').fill(DOWN).is_not_blank().is_not_whitespace()\nobservations1 = observations1.filter(lambda x: type(x.value) != str or 'HMRC' not in x.value)\nDimensions = [\n HDim(flow,'Flow',DIRECTLY,LEFT),\n HDim(EuNonEu,'EU / Non EU',DIRECTLY,LEFT),\n HDim(geography,'HMRC Partner Geography',DIRECTLY,LEFT),\n HDim(nut,'NUTS Geography',DIRECTLY,LEFT),\n HDimConst('SITC 4', 'all'),\n HDimConst('Measure Type', 'Businesses'),\n HDimConst('Unit', 'businesses'),\n HDimConst('Year', dataset_year)\n ]\nc2 = ConversionSegment(observations1, Dimensions, processTIMEUNIT=True)\ntable2 = c2.topandas()\ntidy = pd.concat([tidy, table2], sort=True)\n\n# +\n#tidy\n#savepreviewhtml(c2)\n# -\n\ntidy['Marker'] = tidy['DATAMARKER'].map(lambda x:'not-applicable'\n if (x == 'N/A')\n else (x))\n\nimport numpy as np\ntidy['OBS'].replace('', np.nan, inplace=True)\n# tidy.dropna(subset=['OBS'], inplace=True)\n# tidy.drop(columns=['Marker'], inplace=True)\ntidy.rename(columns={'OBS': 'Value', 'FLOW' :'Flow'}, inplace=True)\n# tidy['Value'] = tidy['Value'].astype(int)\ntidy['Value'] = tidy['Value'].map(lambda x:''\n if (x == ':') | (x == 'xx') | (x == '..') | (x == 'N/A')\n else (x))\n\n# +\n# tidy['NUTS Geography'] = tidy['NUTS Geography'].map(\n# lambda x: {\n# 'East':'East of England', \n# 'Exp' : 'nuts1/all',\n# 'Imp': 'nuts1/all'}.get(x, x))\n\n# tidy['HMRC Partner Geography'] = tidy['HMRC Partner Geography'].map(\n# lambda x: {\n# 'Exp' : 'europe',\n# 'Imp': 'europe'}.get(x, x))\n# -\n\nfor col in tidy.columns:\n if col not in ['Value', 'Year']:\n tidy[col] = tidy[col].astype('category')\n display(col)\n display(tidy[col].cat.categories)\n\n# +\ntidy['NUTS Geography'] = tidy['NUTS Geography'].cat.rename_categories({\n 'All NUTS2 areas': 'nuts2/all',\n 'Bedfordshire and Hertfordshire': 'nuts2/UKH2',\n 'Berkshire, Buckinghamshire and Oxfordshire': 'nuts2/UKJ1',\n 'Cheshire':'nuts2/UKD6',\n 'Cornwall and Isles of Scilly':'nuts2/UKK3',\n 'Cumbria':'nuts2/UKD1',\n 'Derbyshire and Nottinghamshire':'nuts2/UKF1',\n 'Devon':'nuts2/UKK4',\n 'Dorset and Somerset':'nuts2/UKK2',\n 'East Anglia':'nuts2/UKH1',\n 'EA BTTA': 'nuts2/ea-btta',\n 'EA Energy':'nuts2/ea-energy',\n 'EA Other':'nuts2/ea-other',\n 'East Wales':'nuts2/UKL2',\n 'East Yorkshire and Northern Lincolnshire':'nuts2/UKE1',\n 'Eastern Scotland':'nuts2/UKM7',\n 'EM BTTA':'nuts2/em-btta',\n 'EM Energy':'nuts2/em-energy',\n 'EM Other':'nuts2/em-other',\n 'Essex':'nuts2/UKH3',\n 'Gloucestershire, Wiltshire and Bath/Bristol area':'nuts2/UKK1',\n 'Greater Manchester':'nuts2/UKD3',\n 'Hampshire and Isle of Wight':'nuts2/UKJ3',\n 'Herefordshire, Worcestershire and Warwickshire':'nuts2/UKG1',\n 'Highlands and Islands':'nuts2/UKM6',\n 'Inner London - East':'nuts2/UKI4',\n 'Inner London - West':'nuts2/UKI3',\n 'Kent':'nuts2/UKJ4',\n 'Lancashire':'nuts2/UKD4',\n 'Leicestershire, Rutland and Northamptonshire':\t'nuts2/UKF2',\n 'Lincolnshire':'nuts2/UKF3',\n 'LO BTTA':'nuts2/lo-btta',\n 'LO Other':'nuts2/lo-other',\n 'Merseyside':'nuts2/UKD7',\n 'NE BTTA':'nuts2/ne-btta',\n 'NE Energy':'nuts2/ne-energy',\n 'NE Other':'nuts2/ne-other',\n 'North Eastern Scotland':'nuts2/UKM5',\n 'North Yorkshire':'nuts2/UKE2',\n 'Northern Ireland':'nuts2/UKN0',\n 'Northumberland and Tyne and Wear':\t'nuts2/UKC2',\n 'NW BTTA':'nuts2/nw-btta',\n 'NW Energy':'nuts2/nw-energy',\n 'NW Other':'nuts2/nw-other',\n 'Outer London - East and North East':'nuts2/UKI5',\n 'Outer London - South':'nuts2/UKI6',\n 'Outer London - West and North West':'nuts2/UKI7',\n 'SC BTTA':'nuts2/sc-btta',\n 'SC Energy':'nuts2/sc-energy',\n 'SC Other':'nuts2/sc-other',\n 'SE BTTA':'nuts2/se-btta',\n 'SE Energy':'nuts2/se-energy',\n 'SE Other':'nuts2/se-other',\n 'Shropshire and Staffordshire':\t'nuts2/UKG2',\n 'South Western Scotland':'nuts2/swsc',\n 'SW BTTA':'nuts2/sw-btta',\n 'SW Other':'nuts2/sw-other',\n 'South Yorkshire':'nuts2/UKE3',\n 'Southern Scotland':'nuts2/UKM9',\n 'Surrey, East and West Sussex':'nuts2/UKJ2',\n 'Tees Valley and Durham':'nuts2/UKC1',\n 'West Central Scotland':'nuts2/UKM8',\n 'West Midlands':'nuts2/UKG3',\n 'West Wales':'nuts2/UKL1',\n 'West Wales and The Valleys' : 'nuts2/UKL1',\n 'West Yorkshire':'nuts2/UKE4',\n 'WA BTTA':'nuts2/wa-btta',\n 'WA Energy':'nuts2/wa-energy',\n 'WA Other':'nuts2/wa-other',\n 'WM BTTA':'nuts2/wm-btta',\n 'WM Other':'nuts2/wm-other',\n 'YH BTTA':'nuts2/yh-btta',\n 'YH Energy':'nuts2/yh-energy',\n 'YH Other':'nuts2/yh-other'\n\n})\ntidy['HMRC Partner Geography'] = tidy['HMRC Partner Geography'].cat.rename_categories({\n 'EU' : 'C',\n 'Non-EU' : 'non-eu'})\ntidy['Flow'] = tidy['Flow'].cat.rename_categories({\n 'Exp' : 'exports',\n 'Imp' : 'imports'})\n\n# +\n#tidy = tidy.rename(columns={'EU / Non EU' : 'EU - Non-EU'})\n# -\n\ntidy =tidy[['Year', 'NUTS Geography','HMRC Partner Geography','Flow','SITC 4','Measure Type', 'Value', 'Unit','Marker']]\n\ntidy\n\n\n","sub_path":"datasets/HMRC-RTS-Small-area/T2.py","file_name":"T2.py","file_ext":"py","file_size_in_byte":7271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"240922916","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[5]:\n\n\nimport pickle\nimport pandas as pd\nimport os\nimport numpy as np\nimport eli5\nfrom eli5.sklearn import PermutationImportance\nfrom IPython.display import display\n\n\n# In[2]:\n\n\nfeature_df = pd.read_csv('P:\\\\My Documents\\\\Thesis\\\\Feature Engineering result new dataset(vector operators)\\\\New feature dataset based on acceleration whole data\\\\new_feature_dataset_whole_original.csv')\nIMU_class = pd.read_csv('P:\\\\My Documents\\\\Thesis\\\\Feature Engineering result new dataset(vector operators)\\\\Class_dataset_whole.csv')\n\nfeature_df = feature_df.drop(\"Unnamed: 0\", axis=1)\nIMU_class = IMU_class.drop(\"Unnamed: 0\", axis=1)\n\n\n# In[3]:\n\n\nx_train = feature_df.iloc[0:600349 , :]\nx_test = feature_df.iloc[600349: , :]\n\ny_train = IMU_class.iloc[0:600349 , :]\ny_test = IMU_class.iloc[600349: , :]\n\n\n# In[6]:\n\n\ny_train = np.ravel(y_train)\ny_test = np.ravel(y_test)\n\n\n# In[7]:\n\n\n#start = time.time()\n#perm_rf = PermutationImportance(rf_model).fit(x_test, y_test)\n#end = time.time()\n#print(end - start)\n\nwith open('P:\\\\My Documents\\\\Thesis\\\\NEW Dataset classifications via cluster\\\\Feature Engineered\\\\Permutation\\\\RF_perm.pkl', 'rb') as f:\n perm_rf = pickle.load(f)\n\n\n# In[10]:\n\n\neli5_perm_rf = eli5.show_weights(perm_rf, feature_names = x_test.columns.tolist())\n\n\n# In[11]:\n\n\neli5.show_weights(perm_rf, feature_names = x_test.columns.tolist(), top = None )\n\n\n# In[12]:\n\n\nimport eli5\nfrom eli5.sklearn import PermutationImportance\n\n\n# In[13]:\n\n\nwith open('P:\\\\My Documents\\\\Thesis\\\\NEW Dataset classifications via cluster\\\\Feature Engineered\\\\Permutation\\\\XGB_perm.pkl', 'rb') as f:\n perm_xgb = pickle.load(f)\n\n\n# In[14]:\n\n\neli5.show_weights(perm_xgb, feature_names = x_test.columns.tolist(), top = None)\n\n\n# In[15]:\n\n\nwith open('P:\\\\My Documents\\\\Thesis\\\\NEW Dataset classifications via cluster\\\\Feature Engineered\\\\Permutation\\\\log_perm.pkl', 'rb') as f:\n perm_log = pickle.load(f)\n\n\n# In[16]:\n\n\neli5.show_weights(perm_log, feature_names = x_test.columns.tolist(), top= None)\n\n\n# In[55]:\n\n\n# knearest neighbour\nfrom sklearn.neighbors import KNeighborsClassifier\nk_model = KNeighborsClassifier(n_neighbors = 5, metric = \"euclidean\")\n\n\n# In[56]:\n\n\nstart = time.time()\nk_model.fit(x_train, y_train)\n\nend = time.time()\nprint(end - start)\n\n\n# In[57]:\n\n\nstart = time.time()\nperm_k = PermutationImportance(k_model).fit(x_test, y_test)\n\nend = time.time()\nprint(end - start)\n\n\n# In[58]:\n\n\neli5.show_weights(perm_k, feature_names = x_test.columns.tolist(), top = None)\n\n\n# In[17]:\n\n\nwith open('P:\\\\My Documents\\\\Thesis\\\\NEW Dataset classifications via cluster\\\\Feature Engineered\\\\Permutation\\\\LDA_perm.pkl', 'rb') as f:\n perm_lda = pickle.load(f)\n\n\n# In[18]:\n\n\neli5.show_weights(perm_lda, feature_names = x_test.columns.tolist(), top = None)\n\n\n# In[19]:\n\n\nwith open('P:\\\\My Documents\\\\Thesis\\\\NEW Dataset classifications via cluster\\\\Feature Engineered\\\\Permutation\\\\extra_perm.pkl', 'rb') as f:\n perm_extra = pickle.load(f)\n\n\n# In[20]:\n\n\neli5.show_weights(perm_extra, feature_names = x_test.columns.tolist(), top = None)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"PermutationImportance_features.py","file_name":"PermutationImportance_features.py","file_ext":"py","file_size_in_byte":3076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"47980447","text":"import gzip\nimport json\nimport re\n\ndef extractBritish():\n with gzip.open('jawiki-country.json.gz','rt') as json_file:\n for line in json_file:\n json_data = json.loads(line)\n if json_data['title'] == 'イギリス':\n return json_data['text']\n\npattern = re.compile(r\".*Category*.\")\nremove_pattern = re.compile(r\".*\\|.*\")\nBritish_data = extractBritish()\nfor line in British_data.split(\"\\n\"):\n if pattern.match(line):\n if remove_pattern.match(line):\n print(line.split(\"|\")[0][11:])\n else:\n print(line[11:len(line)-2])","sub_path":"chap3/22.py","file_name":"22.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"625201115","text":"#!/usr/bin/python3\r\n\r\n# this needs plot testing\r\n\r\nimport json\r\nimport os\r\nimport os.path as op\r\n\r\nfrom itertools import product\r\n\r\nimport matplotlib\r\nmatplotlib.use('Agg')\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nfrom tqdm import tqdm\r\n\r\n\r\ndef parse_timestamp(path):\r\n ts = np.sort([int(t) for t in json.load(open(path)).values()])\r\n return (np.max(ts) - np.min(ts)) / 1000000000\r\n\r\n_RAPL_WRAPAROUND = 16384\r\n\r\n\r\ndef rapl_wrap_around(reading):\r\n if reading >= 0:\r\n return reading\r\n else:\r\n return max(reading + _RAPL_WRAPAROUND, 0)\r\n\r\n\r\ndef parse_energy(path, i):\r\n energy = pd.read_csv(path, delimiter = ';')\r\n\r\n energy.package = energy.groupby('socket').package.diff()\r\n energy.dram = energy.groupby('socket').dram.diff()\r\n\r\n energy.package = energy.package.map(rapl_wrap_around)\r\n energy.dram = energy.dram.map(rapl_wrap_around)\r\n energy = energy.fillna(0)\r\n\r\n energy = energy.groupby('epoch')[['package', 'dram']].sum().sum(axis = 1).reset_index()\r\n energy['timestamp'] = energy.epoch.map(i).fillna(0).astype(int) // 1000000\r\n energy.set_index('timestamp')[0]\r\n energy.name = 'energy'\r\n\r\n return energy\r\n\r\n\r\ndef filter_to_application_(trace):\r\n try:\r\n while len(trace) > 0:\r\n record = trace[0]\r\n exclude = False\r\n exclude = any((\r\n (r'.' not in record),\r\n (r'java.' in record and '.java\\.' not in record),\r\n (r'javax.' in record and '.javax\\.' not in record),\r\n (r'jdk.' in record and '.jdk\\.' not in record),\r\n (r'sun.' in record and '.sun\\.' not in record),\r\n (r'org.apache.commons.' in record and '.org.apache.commons\\.' not in record),\r\n (r'' in record),\r\n (r'.so' in record),\r\n (r'::' in record),\r\n (r'[' in record),\r\n (r']' in record)\r\n ))\r\n if not exclude:\r\n return trace\r\n else:\r\n trace.pop(0)\r\n except:\r\n pass\r\n\r\n return 'end'\r\n\r\n\r\ndef filter_to_application(df):\r\n mask = (df.trace == 'end') | df.trace.str.contains('chappie') | df.trace.str.contains('jlibc') | df.trace.str.contains('jrapl')\r\n df = df[~mask]\r\n df.trace = df.trace.str.split('@').map(filter_to_application_)\r\n method = df.trace.str[0]\r\n df = df[(df.trace != 'end') & (method != 'e') & ~(method.str.contains('org.dacapo.harness'))]\r\n\r\n return df\r\n\r\n\r\ndef ranking_plot(df):\r\n ax = df.plot.bar(\r\n legend = False,\r\n color = u'#2ca02c',\r\n edgecolor = 'black',\r\n figsize = (16, 9)\r\n )\r\n\r\n ax.spines['right'].set_visible(False)\r\n ax.spines['top'].set_visible(False)\r\n\r\n plt.ylim(0, ((5 * df.max().max()).astype(int) + 1) / 5)\r\n\r\n plt.xlabel('Method', fontsize = 24)\r\n plt.ylabel('Aware vs Oblivious Attributed Energy Ratio', fontsize = 24)\r\n\r\n plt.xticks(fontsize = 20, rotation = 45)\r\n plt.yticks(fontsize = 28)\r\n\r\n return ax.get_figure()\r\n\r\n\r\ndef main():\r\n if not op.exists('plots'):\r\n os.mkdir('plots')\r\n root = op.join('..', 'chappie-data', 'fse2020')\r\n\r\n ref_dir = op.join(root, 'freq')\r\n data_dir = op.join(root, 'profile')\r\n file_from = lambda k: op.join('raw', str(k))\r\n\r\n benchs = np.sort(os.listdir(ref_dir))\r\n benchs_ = tqdm(benchs)\r\n\r\n summary = []\r\n for bench in benchs_:\r\n benchs_.set_description(bench)\r\n\r\n if not op.exists('plots/{}'.format(bench)):\r\n os.mkdir('plots/{}'.format(bench))\r\n\r\n a = 2; b = 10\r\n\r\n df = pd.concat([pd.read_csv(\r\n op.join(data_dir, bench, str(n), file_from(k), 'method.csv'),\r\n delimiter = ';'\r\n ).assign(iter = k) for n, k in product(os.listdir(op.join(data_dir, bench)), range(a, b))])\r\n df.timestamp //= 1000000\r\n\r\n id = [{int(k): int(v) for k, v in json.load(open(\r\n op.join(data_dir, bench, str(n), file_from(k), 'time.json'))\r\n ).items()} for n, k in product(os.listdir(op.join(data_dir, bench)), range(a, b))]\r\n\r\n energy = pd.concat([parse_energy(\r\n op.join(data_dir, bench, str(n), file_from(k), 'energy.csv'),\r\n i\r\n ) for (n, k), i in zip(product(os.listdir(op.join(data_dir, bench)), range(a, b)), id)])\r\n\r\n df = pd.merge(df, energy, on = 'timestamp', how = 'left').dropna(subset = [0])\r\n df = filter_to_application(df)\r\n df['method'] = df.trace.str[0]\r\n obliv = df.groupby('method')[0].sum()\r\n obliv.name = 'energy'\r\n\r\n df = pd.concat([pd.read_csv(\r\n op.join(data_dir, bench, str(n), 'summary', 'method.csv')\r\n ) for n in os.listdir(op.join(data_dir, bench))])\r\n df['method'] = df.trace.str.split(';').str[0]\r\n df = df.groupby('method').energy.sum() * 8\r\n\r\n df = pd.concat([df, obliv], axis = 1).dropna()\r\n df.columns = ['Aware', 'Oblivious']\r\n df = df.sort_values(by = ['Aware'], ascending = False)\r\n df.index = df.index.str.split('.').str[-2:].str.join('.')\r\n\r\n summary.append(df.corr().iloc[0, 1])\r\n\r\n df = df.Oblivious / df.Aware\r\n\r\n ranking_plot(df.head(5))\r\n plt.savefig(op.join('plots', bench, 'concurrency-awareness.pdf'.format(bench)), bbox_inches = 'tight')\r\n plt.title(bench, fontsize = 32)\r\n plt.close()\r\n s = pd.Series(data = summary, index = benchs)\r\n s.name = 'correlation'\r\n s.index.name = 'bench'\r\n print(s)\r\n s.to_csv(op.join('plots', 'awareness-correlation.csv'), header = True)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"fse2020/analysis/concurrency-plot.py","file_name":"concurrency-plot.py","file_ext":"py","file_size_in_byte":5660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"82049647","text":"from __future__ import annotations\n\nimport lib.entity.inventory\nfrom typing import Optional, Callable\n\n\nclass Item:\n def __init__(self, inventory: lib.entity.inventory.Inventory=None, equipment=None, name: str=\"unnamed item\",\n desc: str=\"\", usable: bool=False, on_use: Optional[Callable]=None, equippable: bool=False,\n on_equip: Optional[Callable]=None, on_unequip: Optional[Callable]=None,\n on_battle: Optional[Callable]=None,\n use_help: str=\"\", sg: Optional[str]=None, pl: Optional[str]=None,\n equip_slot: Optional[str]=None, count: int=1, stack_size: int=1,\n *args, **kwargs):\n \"\"\"\n An Item that can be held, equipped or used by Entities. Able to be transferred and should always be unique,\n even if all attributes are identical with another Item, so be careful not to duplicate Items anywhere.\n\n :param inventory: The master Inventory the Item belongs to.\n :param equipment: If equipped, the Equipment it is in. None otherwise\n :param name: Name of the item.\n :param desc: Description of the item. Rather a physical description than a description of its effects. See\n use_help parameter below.\n :param usable: Whether or not the Item can be used by an Entity.\n :param on_use: A callable called when the Item is used. The arguments given to the callable are, in order:\n playing using the item, itself\n :param equippable: Whether or not the Item can be equipped by an Entity.\n :param on_equip: A callable called when the Item is equipped. The arguments given to the callable are, in order:\n playing equipping the item, itself\n :param use_help: Similar to the description, an info displayed on what happens when the item is used. Despite\n the name, can also be used to describe what happens when the Item is equipped.\n :param sg: Singular name of the Item. Defaults to \"a \" + item_name. Use when the singular needs the article \"an\"\n or \"the\" or anything else.\n :param pl: Plural form of the Item. Defaults to item_name + \"s\". Use when the plural form is irregular.\n :param equip_slot: If the item can be equipped, what slot it is equipped in.\n :param args:\n :param kwargs:\n \"\"\"\n self.inventory = inventory\n self.name = name\n self.desc = desc\n self.use_help = use_help\n self.usable = usable\n self.on_use = on_use if on_use is not None else (lambda _, __: None)\n self.equippable = equippable\n self.on_equip = on_equip if on_equip is not None else (lambda _, __: None)\n self.on_unequip = on_unequip if on_unequip is not None else (lambda _, __: None)\n\n self.on_battle = on_battle\n self.actions = {\n \"on_battle\": self.battle_action\n }\n\n self.equip_slot = equip_slot\n self.equipment = None\n\n self.count = count\n self.stack_size = stack_size\n\n self.sg = sg if sg is not None else \"a \" + self.name\n self.pl = pl if pl is not None else self.name + \"s\"\n\n self.args = args\n self.kwargs = kwargs\n\n def use(self, user: lib.entity.Entity) -> Optional[str]:\n \"\"\"\n Use the item.\n\n :param user: The player using the Item.\n :return: String description of what just happened for the player.\n \"\"\"\n return self.on_use(user, self)\n\n def equip(self, wearer: lib.entity.Entity) -> Optional[str]:\n \"\"\"\n Equip the item in the appropriate equipment slot, replacing anything that was already there\n\n :param wearer: The player equipping the Item\n :return: String description of what just happened for the player.\n \"\"\"\n equip_message = f\"Equipped $WVX{self.name}$E$ in $YVX{self.equip_slot}$E$ slot.\"\n extra_text = self.on_equip(wearer, self)\n if extra_text is not None:\n equip_message += \" \" + extra_text\n substitute_outcome = wearer.equipment.substitute(self.equip_slot, self)\n if substitute_outcome is not None:\n equip_message += \"{}\\n\".format(substitute_outcome[1])\n substitute_outcome[0].on_unequip(wearer, substitute_outcome[0])\n return equip_message\n\n def delete(self, count=1):\n \"\"\"\n Remove a some amount of an item of the item stack from the master Inventory.\n Use when an item has a limited amount of uses and is completely \"used up\" or otherwise destroyed.\n \"\"\"\n if self.inventory:\n self.inventory.remove(self, count)\n\n def annihilate(self):\n \"\"\"\n Remove the entire stack of the item\n \"\"\"\n if self.inventory:\n self.inventory.annihilate(self)\n\n def identical_with(self, other: Item) -> bool:\n \"\"\"\n Check if two items are identical in every way. The inventory the item belongs to and the item count are ignored.\n\n :param other: The other item to compare with self\n :return: true if identical\n \"\"\"\n # this is ugly\n if other is None:\n return False\n\n self_vars = dict(vars(self))\n other_vars = dict(vars(other))\n\n code_check = [\"on_use\", \"on_equip\", \"on_unequip\"]\n ignore = [\"inventory\", \"count\"]\n ignore += code_check\n\n for i in code_check:\n self_code_check = self_vars[i].__code__.co_code\n other_code_check = self_vars[i].__code__.co_code\n if self_code_check != other_code_check:\n return False\n\n for i in ignore:\n del self_vars[i]\n del other_vars[i]\n\n return self_vars == other_vars\n\n def inspect(self) -> str:\n \"\"\"\n Give info about the item to the player.\n\n :return: message\n \"\"\"\n filled = self.count == self.stack_size\n inspect_string = \"\"\n inspect_string += (f\"\\n$YVX{self.name.capitalize()}$E$ \" +\n (f\"{'$RTX' if filled else '$GTX'}x{self.count}$E$ / $CTXx{self.stack_size}$E$\"\n if self.count > 1 else \"\"))\n inspect_string += (\"\\n * Description: \" + self.desc)\n inspect_string += (\"\\n$GVX * Usable$E$\" if self.usable else\n \"\\n$GVX * Equippable$E$\" if self.equippable else\n \"\\n$RTX * Can't be used$E$\")\n inspect_string += f\"\\n{self.use_help}\"\n\n return inspect_string\n\n def battle_action(self, battle):\n if self.on_battle is not None:\n return self.on_battle(battle, self.equipment.entity)\n\n # def serialize(self):\n # return lib.util.serialize(vars(self))\n\n def __str__(self) -> str:\n \"\"\"String representation of the Item. Just its name and count.\"\"\"\n return self.name + \" $GTXx\" + str(self.count) + \"$E$\"\n","sub_path":"lib/item/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":6922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"225643760","text":"from conans import ConanFile, tools, CMake\nimport platform, os, sys\nimport multiprocessing\n\n\nframework = \"KConfig\"\nversion = \"5.29.0\"\nshortversion = \"5.29\"\n\nclassName = framework + \"Conan\"\n\nclass className(ConanFile):\n name = framework\n version = version\n requires = \"QtBase/5.7.1@russelltg/stable\", \"extra-cmake-modules/5.29.0@russelltg/stable\"\n description = \"KDE Config framework\"\n settings = \"os\", \"arch\", \"compiler\", \"build_type\"\n \n options = {}\n default_options = {}\n \n url = \"https://github.com/kde-frameworks-conan/%s\" % name\n license = \"LGPLv2\"\n \n folder_name = \"%s-%s\" % (name.lower(), version)\n \n def config_options(self):\n pass\n \n def configure(self):\n pass\n \n def source(self):\n zip_name = \"%s.zip\" % self.folder_name \n url = \"http://download.kde.org/stable/frameworks/%s/%s\" % (shortversion, zip_name)\n self.output.info(\"Downloading %s...\" % url)\n tools.download(url, zip_name)\n tools.unzip(zip_name)\n os.unlink(zip_name)\n \n def build(self):\n cm = CMake(self.settings)\n \n print(self.folder_name)\n self.run('cmake -DCMAKE_INSTALL_PREFIX=\"%s\" %s %s' % \n (os.path.join(self.conanfile_directory, \"install\"), \n self.conanfile_directory + \"/\" + self.folder_name, \n cm.command_line))\n if platform.os == \"Windows\":\n self.run(\"cmake --build . %s\" % cm.build_config)\n else:\n self.run(\"make -j %d\" % multiprocessing.cpu_count())\n \n self.run(\"cmake --build . %s --target install\" % cm.build_config)\n \n def package(self):\n print(\"packaging!\")\n self.copy(\"*\", dst=\"include\", src=\"install/include\")\n \n self.copy(\"*\", dst=\"lib\", src=\"install/lib\")\n self.copy(\"*\", dst=\"lib\", src=\"install/lib64\")\n \n self.copy(\"*\", dst=\"bin\", src=\"install/bin\")\n \n self.copy(\"*\", dst=\"mkspecs\", src=\"install/mkspecs\")\n \n self.copy(\"*\", dst=\"share\", src=\"install/share\")\n \n","sub_path":"conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"502543272","text":"from redbot.core import commands\nfrom .config import db\n\n\n@commands.check\nasync def leveler_enabled(ctx: commands.Context):\n guild = ctx.message.guild\n if guild is None:\n return True\n if await db.guild(guild).disabled():\n await ctx.send(\"**Leveler commands for this guild are disabled!**\")\n return False\n return True\n","sub_path":"leveler/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"331306547","text":"# coding:iso-8859-9 Türkçe\r\n\r\nfrom random import *\r\nfrom math import *\r\n\r\nprint (\"[1->9] arası küsuratlı 50 tesadüfi sayı: [\", end=\"\")\r\nfor i in range (50):\r\n sayı1 = randint (1, 9)\r\n sayı2 = random()\r\n print (round ((sayı1 + sayı2), 2), end=\" \")\r\nprint (\"]\")\r\nprint (\"\\n[1->51] arası küsuratlı 50 tesadüfi sayı: [\", end=\"\")\r\nfor i in range (50):\r\n sayı1 = randint (1, i+2)\r\n sayı2 = random()\r\n print (round (sayı1 + sayı2, 5), end=\" \")\r\nprint (\"]\")\r\n\r\naçı = eval (input (\"\\n[-180-->180] arası bir açı girin: \"))\r\nif açı >= 0:\r\n if açı <= 180: print (\"Açınız:\", açı, \"derecedir.\")\r\n else: print (\"Açınız: 180 derecedir.\")\r\nelse:\r\n if açı >= -180: print (\"Açınız:\", 360 + açı, \"derecedir.\")\r\n else: print (\"Açınız: 180 derecedir.\")\r\n\r\nsaniye = eval (input (\"\\n[0-->3599] arası bir saniye girin: \"))\r\nif saniye < 0: saniye = 0\r\nif saniye > 3599: saniye = 3599\r\ndakika = saniye // 60\r\nsaniye = saniye % 60\r\nprint (\"Girdiğiniz zaman:\", dakika, \"dakika ve\", saniye, \"saniye'dir.\")\r\n\r\nzaman1 = eval (input (\"\\n[0-->24] arası bir saat girin: \"))\r\nif zaman1 < 0: zaman1 = 0\r\nif zaman1 > 24: zaman1 = 24\r\nzaman2 = eval (input (\"\\nKaç saat daha burada kalacaksın?: \"))\r\nif zaman2 < 0: zaman2 = -zaman2\r\nprint (\"Buradan saat tam \", (zaman1 + zaman2 % 24) % 24, \".00'de ayrılmalısınız!\", sep=\"\")\r\n\r\ndeğer = input (\"\\nHerhangibir (-/+) tamsayı girin: \")\r\nsayı = trunc (eval (değer))\r\nuzunluk = len (değer)\r\nif sayı < 0:\r\n uzunluk = uzunluk - 1\r\n sayı = -sayı\r\n for i in range (uzunluk):\r\n taban = sayı % (10**(i+1))\r\n print (\"2^\", -taban, \" = \", 2**(-taban), sep=\"\")\r\n print()\r\nelse:\r\n for i in range (uzunluk):\r\n taban = sayı % (10**(i+1))\r\n print (\"2^\", taban, \" = \", 2**(taban), sep=\"\")\r\n print()\r\n","sub_path":"Brian Heinold (243) ile Python/p10308a_sınav.py","file_name":"p10308a_sınav.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"450478064","text":"\"\"\"\n\ninstance method : 해당 객체 안에서 호출(self.메서드명)\n해당 메서드를 호출한 객체에만 영향을 미침\n객체 속성에 접근 가능\n\nstatic method : 객체와 독립적인지만,로직상 클래스내에 포함되는 메서드\n\nself 파라미터를 가지고 있지 않음\n객체 속성에 접근 불가\n정적 메서드는 메서드 앞에 @staticmethod라는 Decorator를 넣음\n클래스명.정적메서드명 또는 객체명.정적메서드명 둘 다 호출 가능\n\n\"\"\"\n\nclass Figure:\n def __init__(self,width,height):\n self.width = width\n self.height = height\n def clac_area(self):\n return self.width*self.height\n\n @staticmethod\n def is_square(rect_width,rect_height):\n if rect_width == rect_height:\n print(\"정사각형이 될 수 있는 너비/높이임\")\n else:\n print(\"정사각형이 될 수 없는 너비/높이임\")\n\nfigure1 = Figure(2,3)\n\n# Instance Method\nfigure1.is_square(5,5) # 객체명.정적메서드명으로 호출 가능\n\n# static Method\nFigure.is_square(4,5) # 클래스명.정적메서드명으로 호출 가능\n\nprint(\"==============================\")\n\n# Class Method 클래스 메서드\n# 해당 클래스로 만들어진 객체에서 호출되지 않고 직접 클래스 자체에서 호출\n\"\"\"\n self 파라미터 대신 ,cls 파라미터를 가짐\n 클래스 변수 접근 가능하며 cls.클래스 변수명으로 액세스 가능 단, 객체 속성/메서드는 접근 불가\n @classmethod 라는 Decorator를 넣음\n 클래스명.클래스메서드명 또는 객체명,.클래스메서드명 둘 다 호출 가능\n\n\"\"\"\nclass Figure1:\n count = 0\n def __init__(self,width,height):\n self.width = width\n self.height = height\n Figure1.count +=1\n\n def clac_area(self):\n return self.width*self.height\n\n @classmethod\n def print_count(cls):\n return cls.count\n\nfigure1 = Figure1(2,3)\nfigure2 = Figure1(4,5)\nprint(Figure1.count) # 클래스 변수 호출\nprint(Figure1.print_count()) # 클래스 메서드 호출\nprint(figure1.print_count()) # 인스턴스 변수 호출\n\nprint(\"=\"*40)\n\nclass A(object):\n count = 0 # static member ( class variable)\n def __init__(self,cnt):\n A.count +=1\n self.cnt = cnt # member variable , attribute\n\n def print_cnt(self): # member funtion, method\n print(self.cnt)\n\n @classmethod # class method , static function\n def print_count(cls):\n print(cls.count)\n\na1 = A(1)\na2 = A(2)\na3 = A(44)\n\na1.print_cnt()\na2.print_cnt()\na3.print_cnt()\n\nA.print_count()","sub_path":"Grammer/OOPython/Method_instance_static_class.py","file_name":"Method_instance_static_class.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"20452100","text":"# コンビニでの買い物\n\n# 値段\nbeer_v = 200\notumami_v = 100\nyakitori_v = 100\n\n# 個数\nbeer_c = 2\notumami_c = 1\nyakitori_c = 2\n\n# 割引いた結果の率\nyakitori_w = 0.2\n\n# 値引きするポイント\npoint_card = 150\n\n# 計算\nsum_v = ((beer_v * beer_c) + (otumami_v * otumami_c) + (yakitori_v * yakitori_c))\npayment = (((beer_v * beer_c) + (otumami_v * otumami_c) + ((yakitori_v * (1 - yakitori_w))) * (yakitori_c)) - point_card)\n\n# 結果を表示\nprint('買い物の合計は' , int(sum_v) , \"円\")\nprint('割引して貰うと' , int(payment) , \"円\")\n","sub_path":"src/basic-c2/task20180705.py","file_name":"task20180705.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"285191118","text":"# Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.\n\n# Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure.\n\n# The encoded string should be as compact as possible.\n\n# Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.\n# 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 Codec:\n \n def serialize(self, root):\n \"\"\"Encodes a tree to a single string.\n \n :type root: TreeNode\n :rtype: str\n \"\"\"\n if root is None:\n return ''\n stack = []\n stack.append(root)\n s = ''\n while len(stack) > 0:\n node = stack.pop()\n s += str(node.val) +' '\n if node.right:\n stack.append(node.right)\n if node.left:\n stack.append(node.left)\n return s[:len(s)-1]\n \n \n\n def deserialize(self, data):\n \"\"\"Decodes your encoded data to tree.\n \n :type data: str\n :rtype: TreeNode\n \"\"\"\n pre = [int(i) for i in data.split()]\n inorder = sorted(pre)\n return self.makeTree(pre, inorder)\n def makeTree(self, pre, inorder):\n if inorder:\n root = TreeNode(pre.pop(0))\n k = inorder.index(root.val)\n root.left = self.makeTree(pre, inorder[0:k])\n root.right = self.makeTree(pre, inorder[k+1:])\n return root \n \n \n\n# Your Codec object will be instantiated and called as such:\n# codec = Codec()\n# codec.deserialize(codec.serialize(root))","sub_path":"Design/Serialize_deserializeBST.py","file_name":"Serialize_deserializeBST.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"208364504","text":"import config\nimport crosscutting as cc\nfrom sentiment_amazon import amazon_filename\nfrom sentiment_azure import azure_filename\nfrom sentiment_google import google_filename\n\nFILE_PATHS = [\n cc.pathjoin(config.results_path, azure_filename),\n cc.pathjoin(config.results_path, google_filename),\n cc.pathjoin(config.results_path, amazon_filename),\n cc.pathjoin(config.data_path, config.input_filename),\n]\n\n\ndef merge():\n sentiment_df = load_data()\n round_float_cols(sentiment_df)\n return sentiment_df\n\n\ndef load_data():\n sentiment_df = None\n for file_path in FILE_PATHS:\n sentiment_df = read_and_merge_data(file_path, sentiment_df)\n\n return sentiment_df\n\n\ndef read_and_merge_data(file_path, df = None):\n data_df = cc.pandas_read_csv(file_path)\n if df is None:\n return data_df\n\n return df.merge(data_df, on='id', how='left')\n\n\ndef round_float_cols(df):\n float_cols = df.select_dtypes(include='float64').columns.tolist()\n df[float_cols] = df[float_cols].apply(lambda x: round(x, 2))\n\n\nif __name__ == '__main__':\n data = merge()\n print(data)\n","sub_path":"sentiment_merge.py","file_name":"sentiment_merge.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"212362470","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2017 Novo Nordisk Foundation Center for Biosustainability,\n# Technical University of Denmark.\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\"\"\"Provide commands for generating report files.\"\"\"\n\nfrom __future__ import absolute_import\n\nimport logging\nimport sys\n\nimport click\nimport git\n\nimport memote.suite.api as api\nfrom memote.suite.cli import CONTEXT_SETTINGS\nimport memote.suite.cli.callbacks as callbacks\n\nLOGGER = logging.getLogger(__name__)\n\n\n@click.group()\n@click.help_option(\"--help\", \"-h\")\ndef report():\n \"\"\"Generate one of three different types of reports.\"\"\"\n pass\n\n\n@report.command(context_settings=CONTEXT_SETTINGS)\n@click.help_option(\"--help\", \"-h\")\n@click.argument(\"model\", type=click.Path(exists=True, dir_okay=False),\n envvar=\"MEMOTE_MODEL\",\n callback=callbacks.validate_model)\n@click.option(\"--filename\", type=click.Path(exists=False, writable=True),\n default=\"index.html\", show_default=True,\n help=\"Path for the HTML report output.\")\n@click.option(\"--pytest-args\", \"-a\", callback=callbacks.validate_pytest_args,\n help=\"Any additional arguments you want to pass to pytest. \"\n \"Should be given as one continuous string.\")\n@click.option(\"--solver\", type=click.Choice([\"cplex\", \"glpk\", \"gurobi\"]),\n default=\"glpk\", show_default=True,\n help=\"Set the solver to be used.\")\n@click.option(\"--custom\", type=(click.Path(exists=True, file_okay=False),\n click.Path(exists=True, dir_okay=False)),\n default=(None, None), show_default=True,\n help=\"The absolute path to a directory containing custom test \"\n \"modules followed by the absolute path to a config file \"\n \"corresponding to the custom test modules. Please refer to \"\n \"the documentation for more information on the required \"\n \"file formats.\")\ndef snapshot(model, filename, pytest_args, solver, custom):\n \"\"\"\n Take a snapshot of a model's state and generate a report.\n\n MODEL: Path to model file. Can also be supplied via the environment variable\n MEMOTE_MODEL or configured in 'setup.cfg' or 'memote.ini'.\n \"\"\"\n if not any(a.startswith(\"--tb\") for a in pytest_args):\n pytest_args = [\"--tb\", \"short\"] + pytest_args\n if not any(a.startswith(\"-v\") for a in pytest_args):\n pytest_args.append(\"-vv\")\n model.solver = solver\n _, results = api.test_model(model, results=True, pytest_args=pytest_args,\n custom=custom)\n api.snapshot_report(results, filename)\n\n\n@report.command(context_settings=CONTEXT_SETTINGS)\n@click.help_option(\"--help\", \"-h\")\n@click.argument(\"directory\", type=click.Path(exists=True, file_okay=False),\n envvar=\"MEMOTE_DIRECTORY\")\n@click.option(\"--filename\", type=click.Path(exists=False, writable=True),\n default=\"index.html\", show_default=True,\n help=\"Path for the HTML report output.\")\n@click.option(\"--index\", type=click.Choice([\"hash\", \"time\"]), default=\"hash\",\n show_default=True,\n help=\"Use either commit hashes or time as the independent \"\n \"variable for plots.\")\ndef history(directory, filename, index):\n \"\"\"\n Generate a report over a model's git commit history.\n\n DIRECTORY: Expect JSON files corresponding to the branch's commit history\n to be found here. Can also be supplied via the environment variable\n MEMOTE_DIRECTORY or configured in 'setup.cfg' or 'memote.ini'.\n \"\"\"\n try:\n repo = git.Repo()\n except git.InvalidGitRepositoryError:\n LOGGER.critical(\n \"The history report requires a git repository in order to check \"\n \"the current branch's commit history.\")\n sys.exit(1)\n api.history_report(repo, directory, filename, index)\n\n\n@report.command(context_settings=CONTEXT_SETTINGS)\n@click.help_option(\"--help\", \"-h\")\n@click.argument(\"model1\", type=click.Path(exists=True, dir_okay=False))\n@click.argument(\"model2\", type=click.Path(exists=True, dir_okay=False))\n@click.option(\"--filename\", type=click.Path(exists=False, writable=True),\n default=\"index.html\", show_default=True,\n help=\"Path for the HTML report output.\")\ndef diff(model1, model2, filename):\n \"\"\"Compare two metabolic models against each other.\"\"\"\n raise NotImplementedError(u\"Coming soon™.\")\n","sub_path":"memote/suite/cli/reports.py","file_name":"reports.py","file_ext":"py","file_size_in_byte":4994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"166532720","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 26 21:54:30 2020\n\n@author: andrew\n\"\"\"\nfrom scipy.special import erf as ERF\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef transform_sequence(n, lb=0, ub=185, scale=0.01, lw=0.25, uw=0.75):\n np = (n/ub * (ub -lb)) - ((ub -lb)/2)\n nub = (ub -lb)/2\n nlb = -(ub-lb)/2\n w = (ERF(scale*np) - ERF(scale*nlb))/(ERF(scale*nub) - ERF(scale*nlb))\n w = (w * (uw - lw)) + lw\n return w\n\n\nweight=np.zeros([2000])\nn=np.zeros([2000])\n\n\nfor i in range(2000):\n weight[i]=transform_sequence(i)\n n[i] = i\n \nplt.figure(1)\nplt.cla()\nplt.scatter(n, weight, marker=\"x\", color=\"blue\", alpha=0.35)\n'''\ncircle = plt.Circle((0,0), 1, color=\"blue\", alpha=0.25)\nax = plt.axes()\nax.add_artist(circle)\nplt.axvline(x=0, color=\"black\", alpha=0.15)\nplt.axhline(y=0, color=\"black\", alpha=0.15) \n'''\nplt.draw()\nplt.pause(0.005) ","sub_path":"transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"262211809","text":"# 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\nclass Solution:\n def __init__(self):\n self.map = collections.defaultdict(list)\n \n def verticalTraversal(self, root: 'TreeNode') -> 'List[List[int]]':\n # edge cases\n sol = []\n if not root:\n return sol\n \n # BFS\n queue = [(root, 0)]\n while queue:\n newqueue = []\n for node, pos in queue:\n self.map[pos].append(node.val)\n if node.left:\n newqueue.append((node.left, pos-1))\n if node.right:\n newqueue.append((node.right, pos+1))\n \n newqueue.sort(key=lambda x: x[0].val)\n queue = newqueue\n \n # collect solution\n keys = sorted(self.map.keys())\n for k in keys:\n sol.append(self.map[k])\n \n return sol\n \n","sub_path":"987. Vertical Order Traversal of a Binary Tree/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"401410332","text":"from django.conf.urls import url, include\nfrom app01 import views\n\nurlpatterns = [\n\n url(r'^index/$', views.index, name='index'),\n url(r'^detail/$', views.detail, name='detail'),\n url(r'^pic/(.*)', views.pic, name='pic'),\n\n]","sub_path":"使用crawl-spider爬取货车之家/car/app01/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"119513150","text":"from django.contrib import admin\nfrom django.contrib.auth.admin import UserAdmin\nfrom django.contrib.auth.models import User\nfrom .models import *\n\n\nclass ProfileInline(admin.StackedInline):\n model = UserProfile\n fk_name = 'user'\n max_num = 1\n\n\nclass CustomUserAdmin(UserAdmin):\n inlines = [ProfileInline,]\n\nclass TypeAdmin(admin.ModelAdmin):\n list_display = ['name']\n list_filter = ['name']\n admin.ModelAdmin.actions_on_top = True\n admin.ModelAdmin.actions_on_bottom = True\n search_fields = ['name']\n\n\nclass GroupAdmin(admin.ModelAdmin):\n list_display = ('owner', 'name', 'description', 'type')\n list_filter = ('owner', 'name', 'description', 'type')\n admin.ModelAdmin.actions_on_top = True\n admin.ModelAdmin.actions_on_bottom = True\n search_fields = ('owner', 'name', 'description', 'type')\n\n\nclass SubGroupAdmin(admin.ModelAdmin):\n list_display = ('name', 'group')\n list_filter = ('name', 'group')\n admin.ModelAdmin.actions_on_top = True\n admin.ModelAdmin.actions_on_bottom = True\n search_fields = ('name', 'group')\n\n\n# Register your models here.\nadmin.site.unregister(User)\nadmin.site.register(User, CustomUserAdmin)\nadmin.site.register(Type, TypeAdmin)\nadmin.site.register(Group, GroupAdmin)\nadmin.site.register(SubGroup, SubGroupAdmin)\nadmin.site.register(Scode)\nadmin.site.register(Notiication)\nadmin.site.register(Subscriber)\n","sub_path":"app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"47099134","text":"\n\nfrom xai.brain.wordbase.nouns._pigmy import _PIGMY\n\n#calss header\nclass _PIGMIES(_PIGMY, ):\n\tdef __init__(self,): \n\t\t_PIGMY.__init__(self)\n\t\tself.name = \"PIGMIES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"pigmy\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_pigmies.py","file_name":"_pigmies.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"100111286","text":"def parse_path(path):\n \"\"\"\n Parse a full path dir into a list\n Input:\n path: /home/MyFolder\n Output:\n ['home', 'MyFolder']\n Input:\n path: %2Fhome%2FMy%20Folder%2FFile%29Dojo%28%2Etxt\n Output:\n ['home', 'My Folder', 'File(Dojo).txt']\n \"\"\"\n\n result = []\n split_path = path.split('/')\n for element in split_path:\n if element != '':\n result.append(element)\n return result\n\ndef create_structure(ptr,folder,option):\n \"\"\"\n It creates the structure for the next level \n and change the pointer to new level\n \"\"\"\n if option == 'dic':\n ptr[folder] = {}\n if option == 'lis':\n ptr[folder] = []\n ptr = ptr[folder]\n return ptr\n\n\ndef get_next_structure(ptr,folder,option):\n \"\"\"\n It gets the next existing level when no new structure is needed.\n \"\"\"\n if folder in ptr:\n # point to next existing struct\n ptr = ptr[folder]\n else:\n ptr = create_structure(ptr,folder,option)\n return ptr\n\n\ndef create_folders(ptr,paths,option):\n \"\"\"\n It creates a folder in the next level for all except the last second element\n \"\"\"\n folders = paths[:-2] # all except the last second element\n for folder in folders:\n ptr = get_next_structure(ptr,folder,option)\n return ptr\n\n\ndef create_list(ptr,paths,option):\n \"\"\"\n It creates a list in the last second element\n \"\"\"\n folder = paths[-2] # for last second element\n ptr = get_next_structure(ptr,folder,option)\n return ptr\n\ndef generate_structure(initial_structure, paths):\n \"\"\"\n Generate/Update a structure based on paths list\n Rules:\n The last element must be inside of a list\n except when the paths length is 1.\n If the length is 1 the return\n is gonna be:\n One Level: {'home': []}\n Two levels: {'home': ['xpto']}\n Three levels: {'home': {'xpto': ['last one']}}\n More Examples:\n\n Input:\n initial_structure: {}\n paths: ['home', 'My Folder', 'File(Dojo).txt']\n Output:\n {'home': {'My Folder': ['File(Dojo).txt']]}}\n\n Input:\n initial_structure: {'home': {'My Folder': ['File(Dojo).txt']]}}\n paths: ['home', 'My Folder', 'File2(Dojo).txt']\n Output:\n {'home': {'My Folder': ['File(Dojo).txt', 'File2(Dojo).txt']]]}}\n\n Input:\n initial_structure: {'home': {'My Folder': ['File(Dojo).txt', 'File2(Dojo).txt']}}\n paths: ['home', 'Second Folder', 'foo-bar']\n Output:\n {'home': {\n 'My Folder': ['File(Dojo).txt', 'File2(Dojo).txt'],\n 'Second Folder': ['foo-bar']\n }\n }\n Input:\n initial_structure: {'home': {'My Folder': ['File(Dojo).txt', 'File2(Dojo).txt'],'Second Folder':[]}}\n paths: ['home', 'Third Folder', 'another', 'another']\n Output:\n {'home': {\n 'My Folder': ['File(Dojo).txt', 'File2(Dojo).txt'],\n 'Second Folder': [],\n 'Third Folder': {'another': ['another']}\n }\n }\n \"\"\"\n # all you need is one pointer to allocate new nested structure\n ptr = initial_structure\n \n # 1. Create folders if needed\n ptr = create_folders(ptr,paths,'dic')\n\n # 2. In last folder create list if needed\n ptr = create_list(ptr,paths,'lis')\n \n # 3. Append the file to the list if any\n ptr.append(paths[-1])\n \n # 4. return final structure\n return initial_structure\n\n\ndef get_structure(dir_list):\n \"\"\"\n\n :param dir_list: ['/home/foo-bar/file1.txt', '/home/bar/file1.txt', ...]\n :return: {\n 'home': {\n 'foo-bar': ['file1.txt'],\n 'bar': ['file1.txt'],\n .\n .\n .\n },\n .\n .\n .\n }\n \"\"\"\n initial_structure = {}\n for dir in dir_list:\n full_path = parse_path(dir)\n initial_structure = generate_structure(initial_structure, full_path)\n return initial_structure\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":4064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"59945285","text":"import datetime\nfrom typing import List\n\nfrom guet.config.committer import Committer\nfrom guet.config.get_committers import get_committers\nfrom guet.config.set_committers import set_committers\nfrom guet.config.set_author import set_committer_as_author\nfrom guet.gateways.gateway import PairSetGateway\nfrom guet.git.set_author import configure_git_author\n\n\nclass PostCommitManager:\n\n def manage(self):\n committers = self._rotate_fist_commiter_to_last_committer(get_committers())\n set_committer_as_author(committers[0])\n set_committers(committers)\n configure_git_author(committers[0].name, committers[0].email)\n\n def _rotate_fist_commiter_to_last_committer(self, committers: List[Committer]):\n new_last_committer = committers.pop(0)\n committers.append(new_last_committer)\n return committers\n\n\nclass PreCommitManager:\n\n def __init__(self,\n pair_set_gateway: PairSetGateway = PairSetGateway()):\n self._pair_set_gateway = pair_set_gateway\n\n def manage(self):\n now = round(datetime.datetime.utcnow().timestamp() * 1000)\n twenty_four_hours = 86400000\n twenty_four_hours_ago = now - twenty_four_hours\n most_recent_pair_set_time = self._pair_set_gateway.get_most_recent_pair_set().set_time\n if most_recent_pair_set_time < twenty_four_hours_ago:\n print(\"\\nYou have not reset pairs in over twenty four hours!\\nPlease reset your pairs by using guet set and including your pairs' initials\\n\")\n exit(1)\n else:\n exit(0)\n","sub_path":"guet/commit.py","file_name":"commit.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"154519267","text":"from tkinter import *\nfrom tkinter import messagebox\nfrom tkinter import simpledialog\nfrom functions import center_window\n\n\ndef show_delete_box(prev_class):\n global window\n try:\n if window.root.state() == \"normal\": window.root.focus()\n except:\n prev_class.terminal_data.insert(END, f\"{prev_class.name.upper()} ~ Opening Deleting Product Box\")\n if prev_class.list_items.size() > 0:\n if not prev_class.job == \"admin\":\n response = simpledialog.askstring(\"ADMIN Permission\",\n \"Por favor introduzca una clave ADMIN para continuar.\",\n show=\"*\")\n if response is not None:\n is_admin = False\n with open(\"./records/accounts.txt\") as file:\n for account in file:\n data_list = account.split(\"||\")\n username = data_list[0].strip()\n password = data_list[1].strip()\n job = data_list[2].strip()\n if response == password:\n is_admin = True\n break\n if is_admin:\n window = DeleteBox(prev_class)\n prev_class.terminal_data.insert(END, f\"[{username.upper()} Permission Granted]\")\n prev_class.terminal_data.see(END)\n center_window(window.root, 300, 500)\n else:\n messagebox.showerror(\"Error no access\", \"Lo siento pero la clave no coincide con la de un ADMIN\")\n prev_class.terminal_data.insert(END, \"[Access Denied]: Password is not from ADMIN\")\n prev_class.terminal_data.see(END)\n\n else:\n prev_class.terminal_data.insert(END, \"[Access Denied]: No password received\")\n prev_class.terminal_data.see(END)\n else:\n window = DeleteBox(prev_class)\n prev_class.terminal_data.insert(END, f\"[{prev_class.name.upper()} Permission Granted]\")\n prev_class.terminal_data.see(END)\n center_window(window.root, 300, 500)\n else:\n prev_class.terminal_data.insert(END, \"[Access Denied]: No product selected\")\n prev_class.terminal_data.see(END)\n\n\nclass DeleteBox:\n def __init__(self, previous_class):\n self.root = Toplevel(bg=\"white\")\n self.root.title(\"Delete Product\")\n self.root.iconbitmap(\"./images/favicon.ico\")\n self.root.resizable(False, False)\n self.root.focus()\n\n # Main Window Class\n self.main_class = previous_class\n\n # Title\n self.title = Label(self.root, text=f\"Borrar Producto\", font=(\"Sans-serif\", 18), bg=\"white\")\n self.title.place(x=65, y=15)\n\n self.list_purchase = self.main_class.list_items.get(0, END)\n self.list_purchase_names = self.list_purchase[::4]\n self.data_frame = Frame(self.root, bg=\"white\", relief=RIDGE, bd=3)\n self.data_frame.place(x=15, y=50)\n\n # Scrollbar\n scrollbar_products = Scrollbar(self.data_frame)\n scrollbar_products.pack(side=RIGHT, fill=Y)\n\n # List Products Selected\n self.listbox_products = Listbox(self.data_frame, yscrollcommand=scrollbar_products.set, width=27, height=18,\n cursor=\"hand2\", selectbackground=\"#ccc\", selectforeground=\"black\",\n font=(\"Sans-serif\", 12))\n for index in range(len(self.list_purchase_names)):\n self.listbox_products.insert(END, f\"{index + 1}. {self.list_purchase_names[index]}\")\n self.listbox_products.pack(side=LEFT, fill=BOTH)\n self.listbox_products.bind(\"\", self.deleting_product_on_list)\n\n # Inserting Scrollbar with Listbox\n scrollbar_products.config(command=self.listbox_products.yview)\n\n # Instructions\n Label(self.root, text=\"Instrucciones:\", font=(\"Sans-serif\", 12), bg=\"white\") \\\n .place(x=15, y=410)\n Label(self.root, text=\"1. Hacer doble click sobre el nombre.\",\n font=(\"Sans-serif\", 10), bg=\"white\", wraplength=250) \\\n .place(x=15, y=435)\n Label(self.root, text=\"2. Cerrar esta ventana al finalizar.\", font=(\"Sans-serif\", 10), bg=\"white\") \\\n .place(x=15, y=455)\n\n # Validate the Entry is INT\n def validate_int(self, P):\n if str.isdigit(P) or P == \"\":\n return True\n else:\n return False\n\n def close(self):\n self.main_class.terminal_data.insert(END, f\"{self.main_class.name.upper()} ~ Closing Deleting Product Box\")\n self.main_class.terminal_data.see(END)\n self.root.destroy()\n\n def deleting_product_on_list(self, event):\n selected_product_index = self.listbox_products.curselection()[0]\n item_line_on_bill = (selected_product_index * 4) + 1\n response = messagebox.askyesno(\"Confirm Action\", f\"Desea eleminar \"\n f\"{self.list_purchase_names[selected_product_index]}?\")\n if response:\n item_subtotal = float(self.main_class.list_items.get((item_line_on_bill - 1) + 2).replace(\" $\", \"\"))\n self.main_class.set_subtotal(item_subtotal, \"subtract\")\n\n self.main_class.set_total(self.main_class.subtotal_value, 12)\n self.main_class.list_items.delete(item_line_on_bill - 1, (item_line_on_bill - 1) + 3)\n self.close()\n\n self.main_class.terminal_data.insert(END, f\"{self.main_class.name.upper()} ~ Deleted \"\n f\"{self.list_purchase_names[selected_product_index]} => \"\n f\"- {item_subtotal}$, \"\n f\"on line {item_line_on_bill}\")\n self.main_class.terminal_data.see(END)\n","sub_path":"delete_box.py","file_name":"delete_box.py","file_ext":"py","file_size_in_byte":6108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"399306991","text":"# Copyright @ 2021 Thought Machine Group Limited. All rights reserved.\n# standard libs\nimport os\nimport logging\nimport time\nfrom datetime import datetime, timezone\nfrom typing import List, Optional\n\n# third party\nfrom dateutil.relativedelta import relativedelta\nfrom dateutil import parser\n\n# common\nimport common.test_utils.endtoend as endtoend\nfrom common.test_utils.common.date_helper import extract_date\nfrom common.test_utils.endtoend.kafka_helper import wait_for_messages\n\nlog = logging.getLogger(__name__)\nlogging.basicConfig(\n level=os.environ.get(\"LOGLEVEL\", \"INFO\"),\n format=\"%(asctime)s.%(msecs)03d - %(levelname)s: %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n)\n\n\nSCHEDULER_OPERATION_EVENTS_TOPIC = \"vault.core_api.v1.scheduler.operation.events\"\n\n\ndef wait_for_schedule_operation_events(\n tag_names: List[str],\n use_e2e_mapping: bool = True,\n wait_for_timestamp: datetime = None,\n inter_message_timeout: int = 30,\n matched_message_timeout: int = 30,\n):\n \"\"\"\n List to the vault.core_api.v1.scheduler.operation.events Kafka topic for updates to schedule\n execution. A response from this topic indicates that all schedules associated with an account\n schedule tag have finished being processed by the scheduler.\n :param tag_names: Account schedule tag names to listen for a completion event\n :param use_e2e_mapping: Flag to determine whether or not to look up the mapped e2e tag names\n :param wait_for_timestamp: Set a minimum completion timestamp for the completion event. E.g.\n if you are skipping multiple months worth of schedules and only want a response after a specific\n date.\n \"\"\"\n consumer = endtoend.testhandle.kafka_consumers[SCHEDULER_OPERATION_EVENTS_TOPIC]\n\n if use_e2e_mapping:\n mapped_tags = {\n endtoend.testhandle.schedule_tag_ids_to_e2e_ids[tag]: None\n for tag in tag_names\n }\n else:\n mapped_tags = {tag: None for tag in set(tag_names)}\n\n def matcher(event_msg, unique_message_ids):\n # we also get account_update_created events on this topic\n tag_name = event_msg[\"operation_created\"][\"operation\"][\"tag_name\"]\n event_request_id = event_msg[\"event_id\"]\n if tag_name in unique_message_ids:\n if wait_for_timestamp:\n completed_run_timestamp = extract_date(\n event_msg[\"operation_created\"][\"operation\"][\n \"completed_run_timestamp\"\n ]\n )\n if (\n completed_run_timestamp\n and completed_run_timestamp >= wait_for_timestamp\n ):\n return tag_name, event_request_id, True\n else:\n return tag_name, event_request_id, True\n return \"\", event_request_id, False\n\n log.info(f\"Waiting for {len(mapped_tags)} operation events: {mapped_tags}\")\n\n wait_for_messages(\n consumer,\n matcher=matcher,\n callback=None,\n unique_message_ids=mapped_tags,\n inter_message_timeout=inter_message_timeout,\n matched_message_timeout=matched_message_timeout,\n )\n\n log.info(\"Got all operation events\")\n\n\ndef trigger_next_schedule_execution(\n paused_tag_id: str,\n schedule_frequency: str,\n) -> None:\n \"\"\"\n Triggers the next schedule execution by updating a paused tag. The frequency is used to\n determine how much the test_pause_at_timestamp should be incremented by to guarantee a\n desired number of executions\n :param paused_tag_id: unmapped id of the paused tag that controls the schedule. The\n corresponding mapped tag must have a 'test_pause_at_timestamp' value that is preventing the\n execution of a schedule.\n :param schedule_frequency: frequency of the schedule. Supported values are 'DAILY', 'WEEKLY'\n 'MONTHLY' and 'YEARLY'\n \"\"\"\n mapped_tag_id = endtoend.testhandle.schedule_tag_ids_to_e2e_ids[paused_tag_id]\n\n current_tag = endtoend.core_api_helper.batch_get_account_schedule_tags(\n account_schedule_tag_ids=[mapped_tag_id]\n )[mapped_tag_id]\n\n test_pause_at_timestamp = current_tag[\"test_pause_at_timestamp\"]\n\n if schedule_frequency == \"DAILY\":\n delta = relativedelta(days=1)\n elif schedule_frequency == \"WEEKLY\":\n delta = relativedelta(weeks=1)\n elif schedule_frequency == \"MONTHLY\":\n delta = relativedelta(months=1)\n elif schedule_frequency == \"YEARLY\":\n delta = relativedelta(years=1)\n else:\n raise ValueError(f\"Unexpected frequency {schedule_frequency}\")\n\n # Setting test_pause_at_timestamp in the future currently fast-forwards, so we make sure it\n # is at most now()\n new_test_pause_at_timestamp = min(\n delta + parser.parse(test_pause_at_timestamp), datetime.now(tz=timezone.utc)\n )\n\n log.info(\n f\"Updating test_pause_at_timestamp from {test_pause_at_timestamp}\"\n f\" to {new_test_pause_at_timestamp} for {mapped_tag_id}\"\n )\n\n endtoend.core_api_helper.update_account_schedule_tag(\n account_schedule_tag_id=mapped_tag_id,\n test_pause_at_timestamp=new_test_pause_at_timestamp.isoformat(),\n )\n\n\ndef _check_jobs_status(\n schedule_id: str,\n effective_date: Optional[datetime] = None,\n expected_status: Optional[List[str]] = None,\n) -> bool:\n \"\"\"\n Checks status of all jobs in a schedule.\n :param schedule_id: The ID of the Schedule.\n :param expected_status: All jobs must be of this status.\n :param effective_date: An optional job effective date, helps filter further in case multiple.\n jobs are triggered in the test. if left blank it will check all the dates.\n :return: True if jobs with schedule_timestamp == effective date status is present in\n expected_status else return False, in case no valid jobs were found will also return false.\n \"\"\"\n\n expected_status = expected_status or [\"JOB_STATUS_SUCCEEDED\", \"JOB_STATUS_FAILED\"]\n result = endtoend.core_api_helper.get_jobs(schedule_id)\n flag_no_jobs = True\n\n for job in result:\n job_time_stamp = job[\"schedule_timestamp\"]\n job_time_stamp = parser.parse(job_time_stamp)\n if effective_date is None or effective_date == job_time_stamp:\n flag_no_jobs = False\n if job[\"status\"].upper() not in expected_status:\n return False\n if flag_no_jobs:\n return False\n return True\n\n\ndef wait_for_scheduled_jobs_to_finish(\n schedule_display_name: str,\n account_id: str,\n effective_date: Optional[datetime] = None,\n max_retries: int = 7,\n initial_wait: int = 0,\n job_statuses: List[str] = None,\n):\n \"\"\"\n Polls when all the jobs with same effective date in the schedule are finished.\n It will retry this for 5 times by default, each retry will multiply the current sleep\n by the current sleep so for this case the total time for the polling is = 2^7 total\n seconds which is 128 (or just over 2 mins)\n :param schedule_name: The Display Name of the Schedule, as per the contract event type. The\n 'for account...' suffix is automatically removed if present\n :param account_id: The account ID of the schedule.\n :param effective_date: An optional parameter, helps filter further in case multiple\n jobs are triggered in the test. if left blank it will check all the dates.\n :param max_retries: The number of times to poll before abandoning\n :param initial_wait: an initial number of seconds to wait for before starting to poll. This is\n useful if we know there is a long delay before the results will ever be met. For example, if\n waiting for 30 jobs to skip, we know there is a 30*20 wait just for those jobs to be published\n :param job_statuses: optional list of job statuses to consider. This can be useful if we want\n to check a job was skipped, but it will default to JOB_STATUS_SUCCEEDED and JOB_STATUS_FAILED\n :return: if jobs are finished [JOB_STATUS_SUCCEEDED', 'JOB_STATUS_FAILED']\n do nothing else after multiple attemps raise an assertion\n \"\"\"\n\n job_statuses = job_statuses or [\"JOB_STATUS_SUCCEEDED\", \"JOB_STATUS_FAILED\"]\n schedule_name = schedule_display_name.replace(f\" for {account_id}\", \"\")\n log.info(\n f\"Waiting for {schedule_name} on account {account_id} to reach statuses {job_statuses}\"\n f\"Optional effective_date: {effective_date}\"\n )\n\n if initial_wait > 0:\n time.sleep(initial_wait)\n\n schedules = endtoend.core_api_helper.get_account_schedules(account_id, [])\n schedule_id = schedules[schedule_name][\"id\"]\n\n error_message = f\"Schedule=[{schedule_display_name}] with ID=[{schedule_id}] \"\n error_message += f\"still has pending jobs for Account ID=[{account_id}]\"\n error_message += f' on effective date = {effective_date or \"ALL\"}'\n\n if schedule_id is not None:\n endtoend.helper.retry_call(\n func=_check_jobs_status,\n f_args=[schedule_id, effective_date, job_statuses],\n expected_result=True,\n back_off=2,\n max_retries=max_retries,\n failure_message=error_message,\n )\n\n\ndef set_test_pause_at_timestamp_for_tag(\n schedule_tag_id: str, test_pause_at_timestamp=datetime\n):\n \"\"\"\n Updates the test_pause_at_timestamp for a given schedule tag ID as defined in the Smart\n Contract. Maps the provided schedule tag to the actual E2E schedule tag used in the test\n before sending the request.\n :param schedule_tag_id: The schedule tag ID as defined in the Smart Contract.\n :param test_pause_at_timestamp: The timestamp to which normal execution should run\n before pausing.\n \"\"\"\n\n mapped_tag_id = endtoend.testhandle.schedule_tag_ids_to_e2e_ids[schedule_tag_id]\n\n endtoend.core_api_helper.update_account_schedule_tag(\n account_schedule_tag_id=mapped_tag_id,\n test_pause_at_timestamp=test_pause_at_timestamp.isoformat(),\n )\n\n\ndef skip_scheduled_jobs_between_dates(\n schedule_tag_id: str,\n skip_start_date: datetime,\n skip_end_date: datetime,\n):\n \"\"\"\n Skips all schedule executions for given schedule tag between the provided dates. Execution will\n continue as normal after skipped dates up until the provided test_pause_at_timestamp.\n :param schedule_tag_id: The schedule tag ID as defined in the Smart Contract.\n :param skip_start_date: The timestamp from which to begin skipping execution.\n :param skip_end_date: The timestamp at which to stop skipping execution.\n :param test_pause_at_timestamp: The timestamp until which normal execution should\n continue after all schedules in the defined period have been skipped.\n \"\"\"\n\n mapped_tag_id = endtoend.testhandle.schedule_tag_ids_to_e2e_ids[schedule_tag_id]\n\n endtoend.core_api_helper.update_account_schedule_tag(\n account_schedule_tag_id=mapped_tag_id,\n schedule_status_override_start_timestamp=skip_start_date.isoformat(),\n schedule_status_override_end_timestamp=skip_end_date.isoformat(),\n schedule_status_override=\"ACCOUNT_SCHEDULE_TAG_SCHEDULE_STATUS_OVERRIDE_TO_SKIPPED\",\n )\n","sub_path":"common/test_utils/endtoend/schedule_helper.py","file_name":"schedule_helper.py","file_ext":"py","file_size_in_byte":11086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"222948894","text":"import os\n# class documentation\nwiki_idx = ''\nwiki_doc = \"!!! IBM project link\\n\"\nwiki_doc += \"* [[https://www.ibm.com/developerworks/community/wikis/home?lang=en#!/wiki/IBM%20i%20Technology%20Updates/page/Python]]\\n\"\nwiki_doc += \"\\n!!! Overview\\n\"\nwiki_table = ''\nwiki_table += \"(:table border=1 width=100%:)\\n\"\nwiki_table += \"(:cellnr colspan=2 align=center style='background-color: #CCCCCC;':)[++Index++]\\n\"\nwiki_table += \"(:cellnr:)[++Classes++]\\n\"\nwiki_table += \"(:cell:)[++Sample++]\\n\"\n\nman_doc = ''\nfirst = True\nintro = True\nfor root, dirs, files in os.walk(\"itoolkit/\"):\n # not included in documentation\n if \"/test\" in root:\n continue \n if \"/sample\" in root:\n continue \n if \"/doc\" in root:\n continue \n # look for .py files\n files.sort()\n for file in files:\n if \"__init__\" in file:\n continue\n if file.endswith(\".py\"):\n if \"itoolkit\" in file:\n klass = True\n else:\n klass = False\n fn = os.path.join(root, file)\n f = open(fn,\"r\")\n go = False\n body = ''\n man_doc += \"\\n\\n\"\n for line in f:\n # start/end body text\n if '\"\"\"' in line:\n if go:\n # output body\n if klass:\n man_doc += body\n if intro:\n wiki_doc += \"\\n[@\\n\"\n wiki_doc += body\n if intro:\n wiki_doc += \"\\n@]\\n\"\n intro = False\n body = ''\n go = False\n klass = False\n else:\n go = True\n p = line.split('\"\"\"')\n body = p[0] + p[1]\n continue\n # collect body text\n if go:\n body += line\n else:\n # output class\n if \"class\" in line and \":\" in line:\n man_doc += \"\\n\\n\" + line\n klass = True\n # [[#iBase|iBase]]\n p1 = line.split()\n p2 = p1[1].split('(')\n p3 = p2[0].split(':')\n wiki_idx += \"[[#\"+p3[0]+\"|\"+p3[0]+\"]]\\n\"\n if not first:\n wiki_doc += \"\\n@]\\n\"\n first = False\n p1 = line.split(':')\n wiki_doc += \"\\n[[#\"+p3[0]+\"]]\\n!!! \" + p1[0]\n wiki_doc += \"\\n[@\\n\"\n # output def\n if \"def\" in line and \":\" in line:\n man_doc += \"\\n\\n\" + line\n wiki_doc += \"\\n\\n\" + line\n klass = True\nwiki_doc += \"\\n@]\"\n# sample documentation\nwiki_sample_idx = ''\nwiki_sample_doc = ''\nman_sample = \"\\n\\n\"\nman_sample += \"****************************\\n\"\nman_sample += \"****************************\\n\"\nman_sample += \"****************************\\n\"\nman_sample += \"Samples\\n\"\nman_sample += \"****************************\\n\"\nman_sample += \"****************************\\n\"\nman_sample += \"****************************\\n\"\nman_sample += \"\\n\\n\"\nfor root, dirs, files in os.walk(\"itoolkit/\"):\n # not included in documentation\n if not \"/sample\" in root:\n continue \n # look for .py files \n files.sort()\n for file in files:\n if file.endswith(\".py\"):\n fn = os.path.join(root, file)\n f = open(fn,\"r\")\n p = fn.split('/')\n wiki_sample_idx += \"[[#\"+p[2]+\"|\"+p[2]+\"]]\\n\"\n man_sample += \"\\n\\n\"\n man_sample += \"---------------------------------\\n\"\n man_sample += fn+\"\\n\"\n man_sample += \"---------------------------------\\n\"\n wiki_sample_doc += \"\\n[[#\"+p[2]+\"]]\\n!!! \" + fn + \"\\n\"\n wiki_sample_doc += \"[@\\n\"\n for line in f:\n man_sample += line\n wiki_sample_doc += line\n wiki_sample_doc += \"\\n@]\\n\"\n\n# output\nwith open(\"itoolkit/doc/README\", \"w\") as text_file:\n text_file.write(man_doc)\n\nwiki_table += \"\\n(:cellnr:)\\n\" + wiki_idx\nwiki_table += \"(:cell:)\\n\" + wiki_sample_idx\nwiki_table += \"\\n(:tableend:)\\n\"\n\nprint(wiki_table)\nprint(wiki_doc)\nprint(wiki_sample_doc)\n\n\n","sub_path":"make_doc.py","file_name":"make_doc.py","file_ext":"py","file_size_in_byte":3808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"469571952","text":"# Copyright (C) 2017 Google Inc.\n# Licensed under http://www.apache.org/licenses/LICENSE-2.0 \n\nfrom ggrc import db\nfrom ggrc.access_control.roleable import Roleable\nfrom ggrc.fulltext.mixin import Indexed\nfrom ggrc.models.comment import Commentable\nfrom ggrc.models.directive import Directive\nfrom ggrc.models.mixins import CustomAttributable, TestPlanned\nfrom ggrc.models.mixins import Hierarchical\nfrom ggrc.models.mixins import BusinessObject\nfrom ggrc.models.deferred import deferred\nfrom ggrc.models.object_document import PublicDocumentable\nfrom ggrc.models.object_person import Personable\nfrom ggrc.models import reflection\nfrom ggrc.models.relationship import Relatable\nfrom ggrc.models.relationship import Relationship\nfrom ggrc.models.track_object_state import HasObjectState\n\n\nclass Section(Roleable, HasObjectState, Hierarchical, db.Model,\n CustomAttributable, Personable, Relatable, Indexed,\n Commentable, TestPlanned, PublicDocumentable, BusinessObject):\n\n __tablename__ = 'sections'\n _table_plural = 'sections'\n _aliases = {\n \"document_url\": None,\n \"document_evidence\": None,\n \"description\": \"Text of Section\",\n \"directive\": {\n \"display_name\": \"Policy / Regulation / Standard / Contract\",\n \"type\": reflection.AttributeInfo.Type.MAPPING,\n \"filter_by\": \"_filter_by_directive\",\n }\n }\n\n na = deferred(db.Column(db.Boolean, default=False, nullable=False),\n 'Section')\n notes = deferred(db.Column(db.Text), 'Section')\n\n _api_attrs = reflection.ApiAttributes('na', 'notes')\n _sanitize_html = ['notes']\n _include_links = []\n\n @classmethod\n def _filter_by_directive(cls, predicate):\n types = [\"Policy\", \"Regulation\", \"Standard\", \"Contract\"]\n dst = Relationship.query \\\n .filter(\n (Relationship.source_id == cls.id) &\n (Relationship.source_type == cls.__name__) &\n (Relationship.destination_type.in_(types))) \\\n .join(Directive, Directive.id == Relationship.destination_id) \\\n .filter(predicate(Directive.slug) | predicate(Directive.title)) \\\n .exists()\n src = Relationship.query \\\n .filter(\n (Relationship.destination_id == cls.id) &\n (Relationship.destination_type == cls.__name__) &\n (Relationship.source_type.in_(types))) \\\n .join(Directive, Directive.id == Relationship.source_id) \\\n .filter(predicate(Directive.slug) | predicate(Directive.title)) \\\n .exists()\n return dst | src\n","sub_path":"src/ggrc/models/section.py","file_name":"section.py","file_ext":"py","file_size_in_byte":2545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"33515324","text":"from django.utils.translation import ugettext_lazy as _\nimport os.path\n\nSITE_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))\n\nSTATIC_ROOT = os.path.abspath(os.path.join(SITE_ROOT, '../static'))\nSTATIC_URL = '/static/'\n\nMEDIA_ROOT = os.path.abspath(os.path.join(SITE_ROOT, '../media'))\nMEDIA_URL = '/media/'\n\nLOCALE_PATHS = (\n os.path.abspath(os.path.join(SITE_ROOT, 'locale')),\n os.path.abspath(os.path.join(SITE_ROOT, 'locale-ext')),\n)\n\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\nADMINS = (\n ('ekip', 'ekip@teknolab.org'),\n)\n\nMANAGERS = ADMINS\n\nTIME_ZONE = 'Europe/Istanbul'\n\nLANGUAGE_CODE = 'en'\n\nSITE_ID = 1\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = 'z7xc&y*3--xh-85w&y7)7)ay_6DEwe34Fr#$7+y#3ibosnvpxgmd'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n# 'django.template.loaders.eggs.Loader',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.transaction.TransactionMiddleware',\n 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',\n 'debug_toolbar.middleware.DebugToolbarMiddleware',\n)\n\nLOGIN_URL = '/accounts/login/'\nLOGIN_REDIRECT_URL = '/'\n\nROOT_URLCONF = 'devspaces.urls'\n\nTEMPLATE_DIRS = (\n os.path.join(SITE_ROOT, 'templates'),\n)\n\nFIXTURE_DIRS = (\n os.path.join(SITE_ROOT, 'fixtures'),\n)\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.admin',\n 'django.contrib.gis',\n 'django.contrib.markup',\n 'django.contrib.flatpages',\n\n 'south',\n 'olwidget',\n 'sorl.thumbnail',\n 'debug_toolbar',\n \n 'devspaces.places',\n 'cities',\n)\n\nAUTHENTICATION_BACKENDS = (\n 'allauth.account.auth_backends.AuthenticationBackend',\n 'django.contrib.auth.backends.ModelBackend',\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n \"django.contrib.auth.context_processors.auth\",\n \"django.core.context_processors.debug\",\n \"django.core.context_processors.i18n\",\n \"django.core.context_processors.media\",\n \"django.core.context_processors.static\",\n \"django.core.context_processors.request\",\n \"django.contrib.messages.context_processors.messages\",\n)\n\nAUTH_PROFILE_MODULE = 'profiles.Profile'\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n\nSOUTH_TESTS_MIGRATE = False\n\nCITIES_PLUGINS = []\n","sub_path":"devspaces/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"120381157","text":"from pickle import load\nimport numpy as np\nimport pandas as pd\nimport warnings\nimport xgboost\nimport pkg_resources\nwarnings.filterwarnings(\"ignore\")\n\ndef model_predict(X):\n \n cat_encoder = load(open(pkg_resources.resource_filename(__name__,'model/cat_encoder.pkl'),'rb'))\n model = load(open(pkg_resources.resource_filename(__name__,'model/model.pkl'),'rb'))\n scaler = load(open(pkg_resources.resource_filename(__name__,'model/scaler.pkl'),'rb'))\n X = np.asarray(X)\n one_hot_encode = cat_encoder.transform(X[0:5].reshape(1,-1))\n df_one_hot = pd.DataFrame(one_hot_encode.toarray())\n to_scale = scaler.transform(X[5:10].reshape(1,-1))\n df_scale = pd.DataFrame(to_scale)\n df_scale.rename(columns={0: 'Thickness', 1: 'Width',2: 'length',3: 'Bottom',4:'Quantity' },inplace=True)\n\n \n return model.predict(df_one_hot.join(df_scale))[0]\n\n \n\ndef unit_price_with_tax(X):\n \"\"\" Calculates unit price including tax. The default tax rate is 29%.\"\"\" \n\n input_file = pd.read_csv(pkg_resources.resource_filename(__name__,'model/input_file.csv'))\n tax_rate = input_file.iloc[0,0]\n unit_price = model_predict(X)\n return unit_price + tax_rate/100*unit_price\n\n\ndef total_unit_price_with_freight(X):\n \"\"\" Takes the dimension of size of plastic bag and quantity to estimate the total volume cbm and freight price.\n The default values are:\n zone1 = 10 \n cbm1 (<4cbm) = 217\n cbm2 (4cbm-6cbm) = 187\n cbm3 (6cbm-10cbm) = 172\n cbm4 (10cbm-15cbm) = 157\n cbm5 (15cbm-20cbm) = 142\n returns total unit price including tax and freight \"\"\"\n \n length = X[7]/1000\n width = X[6]/1000\n thickness = 2*X[5]/1000000\n quantity = X[9]\n total_cbm = length*width*thickness*quantity\n\n if total_cbm < 1:\n total_cbm = 1\n\n input_file = pd.read_csv(pkg_resources.resource_filename(__name__,'model/input_file.csv'))\n\n if total_cbm <= 4:\n cbm = input_file.iloc[0,2]\n elif total_cbm > 4 and total_cbm <= 6:\n cbm = input_file.iloc[0,3]\n elif total_cbm > 6 and total_cbm <= 6:\n cbm = input_file.iloc[0,4]\n elif total_cbm > 10 and total_cbm <= 15:\n cbm = input_file.iloc[0,5]\n else:\n cbm = input_file.iloc[0,6]\n\n zone1 = input_file.iloc[0,1] \n\n freight = (cbm + zone1)*total_cbm\n unit_freight = freight/quantity\n\n return unit_price_with_tax(X)+unit_freight\n\ndef total_weight(X):\n \"\"\" Takes the dimension of size of plastic bag and quantity to estimate the total weight.\n returns total weight\"\"\"\n \n length = X[7]/1000\n width = X[6]/1000\n thickness = 0.04/100\n quantity = X[9]\n\n total_cbm = length*width*thickness*quantity\n\n if X[1] == 'PET/AL/PE' or X[1] == 'PET/AL/NY/PE' or X[1] == 'MOPP/AL/PE':\n density = 4800\n else:\n density = 2800\n\n total_kg = length*width*thickness*density*quantity\n\n return total_kg\n\n \n","sub_path":"CalculatorService/Python/price_prediction_v3/prediction/prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"221794691","text":"from kafka import KafkaProducer\nimport json\ndef send_kafka_message(c, topicName):\n servers=[\"localhost:9092\"]\n topicName=\"topik11\"\n producer=KafkaProducer(bootstrap_servers=servers)\n # d={\n # \"name\":\"Natalie\",\n # \"message\":\"Hello! My name is Natalie!\"\n # }\n c={\n \"first_name\":\"Natalie\",\n \"last_name\":\"Hwang\",\n \"email\":\"khvannatalie@gmail.com\"\n }\n # arrJson=json.dumps(d)\n # arrBytes=bytearray(arrJson, 'utf-8')\n # producer.send(topicName, arrBytes)\n # producer.flush()\n lines=json.dumps(c)\n Bytes=bytearray(lines, 'utf-8')\n producer.send(topicName, Bytes)\n producer.flush()\n return \"OK\"","sub_path":"library3/prod.py","file_name":"prod.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"572142137","text":"from tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets('MNIST_data', one_hot = True)\n\nimport tensorflow as tf\nimport pgm_to_tf\n\n#sess = tf.InteractiveSession() #slower than using tf.session\nsess = tf.Session()\n\nx = tf.placeholder(tf.float32, shape=[None, 784])\ny_ = tf.placeholder(tf.float32, shape=[None, 10])\n\ndef weight_variable(shape):\n initial = tf.truncated_normal(shape, stddev = 0.1)\n return tf.Variable(initial)\n\ndef bias_variable(shape):\n initial = tf.constant(0.1, shape = shape)\n return tf.Variable(initial)\n\ndef conv2d(x, W):\n return tf.nn.conv2d(x, W, strides = [1, 1, 1, 1], padding = 'SAME')\n\ndef max_pool_2x2(x):\n return tf.nn.max_pool(x, ksize = [1, 2, 2, 1], strides = [1, 2, 2, 1], padding = 'SAME')\n\nW_conv1 = weight_variable([5, 5, 1, 32])\nb_conv1 = bias_variable([32])\n\nx_image = tf.reshape(x, [-1, 28, 28, 1])\n\nh_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)\nh_pool1 = max_pool_2x2(h_conv1)\n\nW_conv2 = weight_variable([5, 5, 32, 64])\nb_conv2 = bias_variable([64])\n\nh_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\nh_pool2 = max_pool_2x2(h_conv2)\n\nW_fc1 = weight_variable([7 * 7 * 64, 1024])\nb_fc1 = bias_variable([1024])\n\nh_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])\nh_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n\nkeep_prob = tf.placeholder(tf.float32)\nh_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n\nW_fc2 = weight_variable([1024, 10])\nb_fc2 = bias_variable([10])\n\ny_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2\n\nsaver = tf.train.Saver()\n\ncorrect_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\nsess.run(tf.global_variables_initializer())\nsaver.restore(sess, \"./models/mnist.ckpt\")\nfeed_dict = pgm_to_tf.fill_feed_dict(\"8.pgm\", x, y_)\nfeed_dict[keep_prob] = 1.0\n\n#print(\"test accuracy %g\" %accuracy.eval(feed_dict = {x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))\nprint(\"test accuracy %g\" %accuracy.eval(feed_dict = feed_dict, session = sess))\nsess.close()\n","sub_path":"mnist_tester.py","file_name":"mnist_tester.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"47375584","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport shlex\n\n\ndef main():\n text = \"This text says to source quotes.txt before continuing.\"\n print(\"ORIGINAL:\", repr(text))\n print()\n\n print(\"TOKENS:\")\n\n lexer = shlex.shlex(text)\n lexer.wordchars += '.'\n lexer.source = \"source\"\n\n print(\"TOKENS:\")\n for token in lexer:\n print(repr(token))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"standard/077.shlex/shlex_source.py","file_name":"shlex_source.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"389829897","text":"# flake8: noqa\nfrom torch import nn\nfrom torch.nn import functional as F\n\n\nclass SimpleNet(nn.Module):\n \"\"\"Docs? Contribution is welcome\"\"\"\n\n def __init__(\n self,\n num_filters1: int = 6,\n num_filters2: int = 16,\n num_hiddens1: int = 120,\n num_hiddens2: int = 84,\n ):\n \"\"\"Docs? Contribution is welcome\"\"\"\n super().__init__()\n self.conv1 = nn.Conv2d(3, num_filters1, 5)\n self.conv2 = nn.Conv2d(num_filters1, num_filters2, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.num_hiddens0 = num_filters2 * 5 * 5\n self.fc1 = nn.Linear(self.num_hiddens0, num_hiddens1)\n self.fc2 = nn.Linear(num_hiddens1, num_hiddens2)\n self.fc3 = nn.Linear(num_hiddens2, 10)\n\n def forward(self, x):\n \"\"\"Docs? Contribution is welcome\"\"\"\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, self.num_hiddens0)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n","sub_path":"examples/cifar_stages_optuna/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"170598637","text":"#!/usr/bin/env python3\n# coding: utf-8\n\n# Time complexity: O()\n# Space complexity: O()\n\n# https://leetcode.com/problems/alien-dictionary/\n# 首先构建图\n# 打印拓扑结构\n\nclass Solution:\n def alienOrder(self, words: List[str]) -> str:\n graph = {}\n in_degree = {}\n self.build_graph(graph, in_degree, words)\n res = self.dfs(graph, in_degree)\n return res\n\n def build_graph(self, graph, in_degree, words):\n for w in words: # 这里很重要,否则例子['z', 'z']会报错 # 或者使用一个长度26的list保存\n for c in w:\n graph[c] = set()\n in_degree[c] = 0\n\n for i in range(1, len(words)):\n a = words[i - 1]\n b = words[i]\n idx = 0\n while idx < len(a) and idx < len(b):\n if a[idx] != b[idx]:\n if b[idx] not in graph[a[idx]]: # 防止同样组合多次出现\n graph[a[idx]].add(b[idx])\n in_degree[b[idx]] += 1\n break\n idx += 1\n\n def dfs(self, graph, in_degree):\n res = ''\n queue = [i for i in graph if in_degree[i] == 0]\n for q in queue:\n res += q\n for char in graph[q]:\n in_degree[char] -= 1\n if in_degree[char] == 0:\n queue.append(char)\n\n if len(res) == len(graph):\n return res\n else:\n return \"\"\n\n","sub_path":"leetcode_python/269.Alien_Dictionary.py","file_name":"269.Alien_Dictionary.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"83155873","text":"import fresh_tomatoes\nimport media\n\n# This program shows my favorite movies on a web page. When the movie is\n# selected it plays the trailer. This program uses a Python module\n# fresh_tomatoes that when given a movie list launches a web page that displays\n# the poster images of each movie and responds to user clicks on an image by\n# playing the trailer for the movie. A separate module media implements a class\n# that stores the relevant instance variables needed by fresh_tomatoes.\n\njoe_vs_volcano = media.Movie(\"Joe Versus the Volcano\",\n \"An existential adventure\",\n \"https://images-na.ssl-images-amazon.com/\"\n \"images/I/41zfspgSM7L._SY300_.jpg\",\n \"https://www.youtube.com/watch?v=cmQDIne3CLo\")\nblade_runner = media.Movie(\"Blade Runner\",\n \"To be a replicant or not a replicant\",\n \"https://i.pinimg.com/originals/12/3b/85/\"\n \"123b8504866c67df71539f1e0d38c5a8.jpg\",\n \"https://www.youtube.com/watch?v=iYhJ7Mf2Oxs\")\nwizards = media.Movie(\"Wizards\",\n \"Everlasting struggle for world supremacy fought between\"\n \" the powers of tchnology and magic\",\n \"https://images-na.ssl-images-amazon.com/images/\"\n \"M/MV5BOGVmZDIwZjItNTY4Mi00NDE2LTg3NTYtMTNjNThlOThiMWFl\"\n \"L2ltYWdlXkEyXkFqcGdeQXVyNTAyODkwOQ@@._V1_UX182_CR0\"\n \",0,182,268_AL_.jpg\",\n \"https://www.youtube.com/watch?v=eMSOouOkCic\")\nlittle_big_man = media.Movie(\"Little Big Man\",\n \"Western odyssey\",\n \"https://images-na.ssl-images-amazon.com/images/\"\n \"I/91opQoCA8mL._SL1500_.jpg\",\n \"https://www.youtube.com/watch?v=lnRaU39mI5E\")\nthe_revenant = media.Movie(\"The Revenant\",\n \"Another western odyssey\",\n \"https://images-na.ssl-images-amazon.com/images/I/\"\n \"51isa53LFIL._SL500_AC_SS350_.jpg\",\n \"https://www.youtube.com/watch?v=QRfj1VCg16Y\")\n\nprint(media.Movie.__doc__)\nmovies = [joe_vs_volcano, blade_runner, wizards, little_big_man, the_revenant]\nfresh_tomatoes.open_movies_page(movies)\n","sub_path":"my_entertainment_center.py","file_name":"my_entertainment_center.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"197270393","text":"import Races.Race as r\nimport Stats as s\nimport Equipment.Weapon as Weapon\n\nclass Dragonborn(r.Race):\n def __init__(self, age: int=15, alignment: str=\"lawful good\",\n height: int=72, stats: s.Stats=s.Stats(),\n subrace: str=\"black\", weight: int=250,\n gender: str=\"male\", firstName: str=\"arjhan\",\n lastName: str=\"clethtinthiallor\"):\n subrace = subrace.lower()\n if(subrace == \"black\" or subrace == \"copper\"):\n self.breathWeapon = Weapon.Weapon(\"breath weapon\", \"race\", 0, \"gp\", \"2d6\", \"acid\", \"0 lb\", \" You can use your action to exhale destructive energy. Your draconic ancestry determines the size, shape, and damage type of the exhalation. When you use your breath weapon, each creature in the area of the exhalation must make a saving throw, the type of which is determined by your draconic ancestry. The DC for this saving throw equals 8 + your Constitution modifier + your proficiency bonus. A creature takes 2d6 damage on a failed save, and half as much damage on a successful one. The damage increases to 3d6 at 6th level, 4d6 at 11th level, and 5d6 at 16th level\")\n self.resistance = \"acid\"\n elif(subrace == \"blue\" or subrace == \"bronze\"):\n self.breathWeapon = Weapon.Weapon(\"breath weapon\", \"race\", 0, \"gp\", \"2d6\", \"lightning\", \"0 lb\", \" You can use your action to exhale destructive energy. Your draconic ancestry determines the size, shape, and damage type of the exhalation. When you use your breath weapon, each creature in the area of the exhalation must make a saving throw, the type of which is determined by your draconic ancestry. The DC for this saving throw equals 8 + your Constitution modifier + your proficiency bonus. A creature takes 2d6 damage on a failed save, and half as much damage on a successful one. The damage increases to 3d6 at 6th level, 4d6 at 11th level, and 5d6 at 16th level\")\n self.resistance = \"lightning\"\n elif(subrace == \"brass\" or subrace == \"gold\" or subrace == \"red\"):\n self.breathWeapon = Weapon.Weapon(\"breath weapon\", \"race\", 0, \"gp\", \"2d6\", \"fire\", \"0 lb\", \" You can use your action to exhale destructive energy. Your draconic ancestry determines the size, shape, and damage type of the exhalation. When you use your breath weapon, each creature in the area of the exhalation must make a saving throw, the type of which is determined by your draconic ancestry. The DC for this saving throw equals 8 + your Constitution modifier + your proficiency bonus. A creature takes 2d6 damage on a failed save, and half as much damage on a successful one. The damage increases to 3d6 at 6th level, 4d6 at 11th level, and 5d6 at 16th level\")\n self.resistance = \"fire\"\n elif(subrace == \"green\"):\n self.breathWeapon = Weapon.Weapon(\"breath weapon\", \"race\", 0, \"gp\", \"2d6\", \"poison\", \"0 lb\", \" You can use your action to exhale destructive energy. Your draconic ancestry determines the size, shape, and damage type of the exhalation. When you use your breath weapon, each creature in the area of the exhalation must make a saving throw, the type of which is determined by your draconic ancestry. The DC for this saving throw equals 8 + your Constitution modifier + your proficiency bonus. A creature takes 2d6 damage on a failed save, and half as much damage on a successful one. The damage increases to 3d6 at 6th level, 4d6 at 11th level, and 5d6 at 16th level\")\n self.resistance = \"poison\"\n elif(subrace == \"silver\" or subrace == \"white\"):\n self.breathWeapon = Weapon.Weapon(\"breath weapon\", \"race\", 0, \"gp\", \"2d6\", \"cold\", \"0 lb\", \" You can use your action to exhale destructive energy. Your draconic ancestry determines the size, shape, and damage type of the exhalation. When you use your breath weapon, each creature in the area of the exhalation must make a saving throw, the type of which is determined by your draconic ancestry. The DC for this saving throw equals 8 + your Constitution modifier + your proficiency bonus. A creature takes 2d6 damage on a failed save, and half as much damage on a successful one. The damage increases to 3d6 at 6th level, 4d6 at 11th level, and 5d6 at 16th level\")\n self.resistance = \"cold\"\n else:\n self.breathWeapon = Weapon.Weapon(\"breath weapon\", \"race\", 0, \"gp\", \"2d6\", \"acid\", \"0 lb\", \" You can use your action to exhale destructive energy. Your draconic ancestry determines the size, shape, and damage type of the exhalation. When you use your breath weapon, each creature in the area of the exhalation must make a saving throw, the type of which is determined by your draconic ancestry. The DC for this saving throw equals 8 + your Constitution modifier + your proficiency bonus. A creature takes 2d6 damage on a failed save, and half as much damage on a successful one. The damage increases to 3d6 at 6th level, 4d6 at 11th level, and 5d6 at 16th level\")\n subrace = \"black\"\n print(\"That is not a subrace of Dragonborn\")\n self.resistance = \"acid\"\n super().__init__(\"dragonborn\", age, alignment, height,\n \"common draconic\", \"medium\", stats, 30,\n subrace, weight, gender, firstName,\n lastName)\n\n#//----------// //----------// //----------//\n# Other methods associatied with the Human race\n#//----------// //----------// //----------//\n def abilityScoreIncrease(self):\n stats = self.getStats()\n \n print(\"Your Charisma score increases by 1\")\n cha = stats.getStat(\"charisma\")\n cha.setScore(cha.getScore() + 1)\n stats.setStat(cha)\n\n print(\"Your Strength score increases by 2\")\n strength = stats.getStat(\"strength\")\n strength.setScore(strength.getScore() + 2)\n stats.setStat(strength)\n\n super().setStats(stats)\n\n#//----------// //----------// //----------//\n# Print methods:\n# These methods will print out all of the\n# variables.\n#//----------// //----------// //----------//\n def printRace(self, showStats: bool):\n super().printRace(showStats)\n print(\"Resistance:\", self.getResistance())\n self.getBreathWeapon().printWeapon()\n \n\n#//----------// //----------// //----------//\n# Check methods:\n# These methods will give a boolean value.\n#//----------// //----------// //----------//\n def checkAge(self, age: int) -> int:\n if(age < 0):\n print(\"You are too young. Setting age to 16.\")\n return 15\n elif(age > 80):\n print(\"You are too old. Setting age to 80.\")\n return 80\n else:\n return age\n\n # checks that the human is at least medium hight\n # which is 48 in to 96 ft\n def checkHeight(self, height: int) -> bool:\n if(height >= 48 and height <= 96):\n return True\n else:\n return False\n\n def checkSubrace(self, subrace: str) -> bool:\n subrace = subrace.lower()\n if(subrace == \"black\" or subrace == \"blue\" or\n subrace == \"brass\" or subrace == \"branze\" or\n subrace == \"copper\" or subrace == \"gold\" or\n subrace == \"green\" or subrace == \"red\" or\n subrace == \"silver\" or subrace == \"white\"):\n return True\n else:\n return False\n\n\n#//----------// //----------// //----------//\n# Get and Set methods\n#//----------// //----------// //----------//\n def getAge(self) -> int:\n age = self.checkAge(self.age)\n if(age == self.age):\n return age\n else:\n self.setAge(age)\n return age\n\n def setAge(self, age: int):\n age = self.checkAge(age)\n self.age = age\n\n def getBreathWeapon(self) -> Weapon.Weapon:\n return self.breathWeapon\n\n def setBreathWeapon(self, breathWeapon: Weapon.Weapon):\n self.breathWeapon = breathWeapon\n\n def getHeight(self) -> int:\n if(not self.checkHeight(self.height)):\n self.setHeight(60)\n return self.height\n\n def setHeight(self, height: int):\n if(self.checkHeight(height)):\n super().setHeight(height)\n else:\n print(\"Height not a medium creature. A Dragonborn is a medium creature between 5 ft and 6 ft, but medium creatures are between 4 ft and 8 ft\")\n super().setHeight(60)\n\n def getResistance(self) -> str:\n return self.resistance\n\n def setResistance(self, resistance: str):\n self.resistance = resistance\n\n def getSubrace(self) -> str:\n if(self.checkSubrace(self.subrace)):\n return self.subrace\n else:\n self.setSubrace(\"black\")\n return self.subrace\n\n def setSubrace(self, subrace: str):\n if(not self.checkSubrace(subrace)):\n subrace = \"black\"\n self.subrace = subrace\n\n#//----------// //----------// //----------//\n# Main Class\n#//----------// //----------// //----------//\n\n\n\n\n\n","sub_path":"Server/Races/Dragonborn.py","file_name":"Dragonborn.py","file_ext":"py","file_size_in_byte":8989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"14463024","text":"'''\nStudent Name: Eden\nID: 201810701580060\nClass: Network 182\n'''\nnumber=int(input('Enter a number: '))\na=[]\nask=input('Do you want to enter another number?(y or n):')\nb=1\na.append(number)\nwhile ask!='n':\n number = int(input('Enter a number: '))\n a.append(number)\n b+=1\n ask=input('Do you want to enter another number?(y or n):')\n\nelse:\n print('Sum = '+str(sum(a)))\n print('Average = '+str(sum(a)/b))","sub_path":"Python_OOP/Exercise/Exercise 04/201810701580060 - Eden/04-13.py","file_name":"04-13.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"110644656","text":"# -*- coding: utf-8 -*-\n\n#!/usr/bin/env python\n# @Time : 17-12-24 下午4:39\n# @Author : wang shen\n# @web : \n# @File : train.py\n\nimport torch\nimport numpy as np\nfrom torch.autograd import Variable\nfrom sklearn.metrics import accuracy_score\n\n\ndef save_model(model, epoch, loss, acc, dir):\n model_path = dir + '/' + 'loss' + str(round(loss, 4)) + '_acc' + str(round(acc, 4)) + '_' + str(epoch)\n with open(model_path, 'wb') as f:\n torch.save(model, f)\n\n\ndef train(model, train_loader, config):\n print('Train model')\n para = filter(lambda p: p.requires_grad, model.parameters())\n opt = torch.optim.Adam(para, lr=config.learning_rate)\n\n acc = 0.75\n for e in range(config.num_epochs):\n l, a = train_epoch(model, e, config.r, train_loader, opt)\n\n if a >= acc:\n acc = a\n save_model(model, e, l, a, config.model_dir)\n\n print('End model')\n\n\ndef train_epoch(model, epoch, r, loader, opt):\n print('Train epoch :', epoch)\n model.train()\n\n e_loss = 0.0\n n_b = 0\n l_l = []\n p_l = []\n for batch_id, (q, q_id, q_mask, q_o, q_o_id, q_o_mask, c, c_mask, label) in enumerate(loader):\n n_b += 1\n q = Variable(q.long())\n q_id = Variable(q_id.long())\n q_mask = Variable(q_mask.byte())\n q_o = Variable(q_o.long())\n q_o_id = Variable(q_o_id.long())\n q_o_mask = Variable(q_o_mask.byte())\n c = Variable(c.long())\n c_mask = Variable(c_mask.byte())\n label = Variable(label.long(), requires_grad=False)\n\n b = len(q)\n e = torch.eye(r)\n e = Variable(e.expand(b, *e.size()), requires_grad=False)\n\n b_l = model.get_loss(q, q_id, q_mask, q_o, q_o_id, q_o_mask, c, c_mask, label)\n c_l = model.get_loss_c(q, q_id, q_mask, q_o, q_o_id, q_o_mask, c, c_mask, label)\n pred = model.get_tag(q, q_id, q_mask, q_o, q_o_id, q_o_mask, c, c_mask, label)\n a_l = model.att_loss(e)\n\n opt.zero_grad()\n b_l.backward()\n c_l.backward()\n a_l.backward()\n opt.step()\n\n e_loss += sum(b_l.data.cpu().numpy())\n print('-------epoch: ', epoch, ' batch: ', batch_id, '*******train_loss: ', b_l.data[0], '*****context_loss: ', c_l.data[0], '*****attention_loss: ', a_l.data[0])\n print('label: ', label.data.cpu().tolist())\n print('pred : ', pred)\n print('\\n')\n l_l.extend(label.data.cpu().tolist())\n p_l.extend(pred)\n\n e_loss = e_loss / n_b\n\n acc = accuracy_score(np.asarray(l_l), np.asarray(p_l))\n\n print('-----Epoch: ', epoch, ' Train loss: ', e_loss, ' Accuracy: ', acc)\n\n return e_loss, acc\n\n\ndef test(model, loader, id2ids, config):\n print('Test')\n f = open(config.target_file, 'wb')\n print(config.target_file)\n\n n_b = 0\n e_loss = 0\n l_l = []\n p_l = []\n for batch_id, (q, q_id, q_mask, q_o, q_o_id, q_o_mask, c, c_mask, label) in enumerate(loader):\n n_b += 1\n q = Variable(q.long())\n q_id = Variable(q_id.long())\n q_mask = Variable(q_mask.byte())\n q_o = Variable(q_o.long())\n q_o_id = Variable(q_o_id.long())\n q_o_mask = Variable(q_o_mask.byte())\n c = Variable(c.long())\n c_mask = Variable(c_mask.byte())\n label = Variable(label.long(), requires_grad=False)\n\n b_l = model.get_loss(q, q_id, q_mask, q_o, q_o_id, q_o_mask, c, c_mask, label)\n pred = model.get_tag(q, q_id, q_mask, q_o, q_o_id, q_o_mask, c, c_mask, label)\n\n e_loss += sum(b_l.data.cpu().numpy())\n print('------- batch: ', batch_id, ' test_loss: ', b_l.data[0])\n\n for q_i, q_o_i, t in zip(q_id, q_o_id, pred):\n d_1 = id2ids[q_i.data[0]]\n d_2 = id2ids[q_o_i.data[0]]\n d_3 = d_2.split('R')[1]\n d_4 = b_l.data[0]\n d_5 = 'true' if t[0] == 1 else 'false'\n s = d_1 + '\t' + d_2 + '\t' + d_3 + '\t' + str(d_4) + '\t' + str(d_5) + '\\n'\n f.write(s.encode('utf8'))\n\n l_l.extend(label.data.cpu().tolist())\n p_l.extend(pred)\n\n e_loss = e_loss / n_b\n\n acc = accuracy_score(np.asarray(l_l), np.asarray(p_l))\n\n f.close()\n print('----- Train loss: ', e_loss, ' Accuracy: ', acc)\n","sub_path":"Task3/torch_file/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"135490210","text":"\"\"\"\nCreated on Mon Jun 28 08:14:00 2021\n\n@author: Øyvind Taraldsen\n\n\"\"\"\n\n\nimport pygame\nimport logpy as pumpy\nfrom datetime import datetime\nimport pygame_textinput\nimport pygame.freetype\nimport threading\nimport time\n\n### sets communication ports for usb-serial, these must be set manually at the moment\ncom1 = \"COM6\"\ncom2 = \"COM7\"\nchain1 = pumpy.Chain(com1)\nchain2 = pumpy.Chain(com2)\nrun = True\n\n## writes data to a logfile with the current time and date\ndef write_log(logname ,string):\n now = datetime.now()\n dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n with open (logname, \"a\") as file:\n file.write(dt_string + \" \"+ string+ \"\\n\")\n\n## creates logfile\ndef create_log():\n now = datetime.now()\n dt_string = now.strftime(\"%Y-%m-%d-%H-%M-%S\")\n logname =\"Syringe_pump_log\"+ dt_string+\".txt\"\n with open (logname, \"w\") as file:\n file.write(\"\")\n return logname\n\np11 = pumpy.Pump(chain1,address=0) \np12 = pumpy.Pump(chain2, address=0)\nlogfile = create_log()\ncurrent_flowrate1 = \"\"\ncurrent_flowrate2 = \"\"\nsem = threading.Semaphore()\n\n### Gets the flowrate from a pump\ndef get_flowrate1():\n global run\n while True:\n global current_flowrate1\n sem.acquire()\n new_rate1 = p11.logflowrate()\n sem.release()\n print(new_rate1)\n if new_rate1 != current_flowrate1:\n current_flowrate1 = new_rate1\n flow =current_flowrate1[3:]\n pump = current_flowrate1[0:2]\n write_log(logfile, \"Flowrate of pump: 1\"+ \" is set to: \"+flow.rjust(12))\n current_flowrate1= new_rate1\n if run != True:\n write_log(logfile, \"Flowrate of pump: 1\"+ \" is set to: \"+flow.rjust(12))\n break\n\ndef get_flowrate2():\n global run\n while True:\n global current_flowrate2\n sem.acquire()\n new_rate2 = p12.logflowrate()\n sem.release()\n print(new_rate2)\n if new_rate2 != current_flowrate2:\n current_flowrate2 = new_rate2\n flow =current_flowrate2[3:]\n pump = current_flowrate2[0:2]\n write_log(logfile, \"Flowrate of pump: 2\" +\" is set to: \"+flow.rjust(12))\n current_flowrate2= new_rate2\n if run != True:\n write_log(logfile, \"Flowrate of pump: 2\" +\" is set to: \"+flow.rjust(12))\n break\n\n### main loop, draws to the screen and takes user input\ndef gameloop():\n pygame.init()\n unit_pump_1 = \"\"\n unit_pump_2 = \"\"\n\n screen = pygame.display.set_mode((600, 200))\n clock = pygame.time.Clock()\n font = pygame.font.SysFont(\"Arial\", 24)\n textinput = pygame_textinput.TextInput(font_family=\"Arial\", font_size = 24)\n while True:\n screen.fill((225, 225, 225))\n\n events = pygame.event.get() \n for event in events:\n if event.type == pygame.QUIT:\n global run\n run = False\n exit() \n \n loginfo1 = font.render('Current flowrate pump 1: '+current_flowrate1[3:], True, (0, 0, 0))\n loginfo2 = font.render('Current flowrate pump 2: '+current_flowrate2[3:], True, (0, 0, 0))\n if unit_pump_1 == \"\":\n inputinfo = font.render('Please set correct unit for pump 1 (u/h, u/m, u/s): ', True, (0, 0, 0))\n inputinfo2 = font.render('', True, (0, 0, 0))\n if textinput.update(events): \n unit_pump_1 = textinput.get_text()\n textinput = pygame_textinput.TextInput(font_family=\"Arial\", font_size = 24)\n elif unit_pump_2 ==\"\":\n inputinfo = font.render('Please set correct unit for pump 2 (u/h, u/m, u/s): ', True, (0, 0, 0))\n inputinfo2 = font.render('', True, (0, 0, 0))\n if textinput.update(events): \n unit_pump_2 =textinput.get_text()\n textinput = pygame_textinput.TextInput(font_family=\"Arial\", font_size = 24)\n else:\n inputinfo = font.render('To change flowrate, input pump number ', True, (0, 0, 0))\n inputinfo2 = font.render(\"followed by a space and the new flowrate:\", True, (0, 0, 0))\n # Feed it with events every frame\n if textinput.update(events): \n new_flowrate = textinput.get_text()\n\n sem.acquire()\n if new_flowrate[0] == \"1\":\n p11.setiflowrate(textinput.get_text()[1:],unit_pump_1)\n elif new_flowrate[0] ==\"2\":\n p12.setiflowrate(textinput.get_text()[1:],unit_pump_2)\n textinput = pygame_textinput.TextInput(font_family=\"Arial\", font_size = 24)\n sem.release()\n screen.blit(inputinfo,(0,80))\n screen.blit(inputinfo2,(0,100))\n # Blit its surface onto the screen\n screen.blit(loginfo1,(0,0))\n screen.blit(loginfo2, (0,40))\n screen.blit(textinput.get_surface(), (400, 100))\n \n pygame.display.update()\n clock.tick(30)\n \n chain.close()\n\nflowrate_thread1 = threading.Thread(target=get_flowrate1)\nflowrate_thread1.start()\nflowrate_thread2 = threading.Thread(target=get_flowrate2)\nflowrate_thread2.start()\npygame_thread = threading.Thread(target =gameloop)\npygame_thread.start()","sub_path":"several_pumps.py","file_name":"several_pumps.py","file_ext":"py","file_size_in_byte":5218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"178934271","text":"from django.conf.urls.defaults import patterns, url\n\nurlpatterns = patterns('seahub.notifications.views',\n# url(r'^$', 'notification_list', name='notification_list'),\n url(r'^add/$', 'notification_add', name='notification_add'),\n url(r'^delete/(?P[\\d]+)/$', 'notification_delete', name='notification_delete'),\n url(r'^set-primary/(?P[\\d]+)/$', 'set_primary', name='set_primary'),\n\n########## user notifications\n url(r'^list/$', 'user_notification_list', name='user_notification_list'),\n url(r'^more/$', 'user_notification_more', name='user_notification_more'),\n url(r'^remove/$', 'user_notification_remove', name='user_notification_remove'),\n)\n\n\n","sub_path":"seahub/notifications/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"493386279","text":"# -*- coding: utf-8 -*-\n\n# 15-112 Term Project Secondary File\n# Atulya Ravishankar, aravisha, Section H\n# CA Mentor: Lukas Peraza\n# Instructor: David Kosbie\n# Term/Semester: Fall 2014\n\n###############################################################################\n##### This file contains the OCR feature ######################################\n###############################################################################\n\nimport numpy as np\nimport cv2\nimport goslate\nimport os\nimport unicodedata\nimport string\n\n###############################################################################\n##### Uses the webcam to get an image of the characters #######################\n###############################################################################\n\nclass VideoCapture(object):\n \n def __init__(self, language):\n # Initializes the variables for this instance\n self.language = language\n # First get display size\n rows = 720\n cols = 1280\n # Resize the window to make it easier to see\n self.newRows = 600\n ratio = float(self.newRows)/rows\n self.newCols = int(ratio*cols)\n self.length = 700\n self.height = 450\n self.font = cv2.FONT_HERSHEY_SIMPLEX\n \n def drawRectangle(self, frame):\n # Calculate reference rectangle coordinates\n cx = self.newCols/2\n cy = self.newRows/2\n x0 = int(cx-0.5*self.length)\n y0 = int(cy-0.5*self.height)\n x1 = x0+self.length\n y1 = y0+self.height\n cv2.rectangle(frame, (x0, y0), (x1, y1), (0, 255, 0), 3)#green rectangle\n \n def drawText(self, frame):\n # Draws the text instruction on the screen\n cx = self.newCols/2\n x0 = int(cx-0.5*self.length)\n margin = 30\n message1 = \"Position the text inside the green rectangle\"\n message2 = \"Press 'Enter' when you are ready\"\n cyan = (255, 255, 0)\n purple = (255, 0, 255)\n cv2.putText(frame, message1, (x0,int(1.5*margin)), self.font,1, cyan,2)\n cv2.putText(frame, message2, (x0,self.newRows - margin), self.font, 1,\\\n purple, 2)\n \n def getImage(self):\n # Uses the webcam to show the user what the computer is seeing\n # Finishes by getting the image that the user wants to translate\n cap = cv2.VideoCapture(0)\n escaped = False # Variable that allows the user to escape\n while cap.isOpened():\n ret, frame = cap.read()\n finalFrame = frame # Keeps track of the last frame recorded\n # Resizes the video feed to make it easier to see the instructions\n frame = cv2.resize(frame, (self.newCols, self.newRows))\n # Draws the reference rectangle and instructions\n self.drawRectangle(frame)\n self.drawText(frame)\n # Shows the user the live feed at all times\n cv2.imshow(\"live feed\", frame)\n key = cv2.waitKey(1)\n # Stop the video when you press Enter\n if key == 13: \n break\n # Escape from the video feed when you press Escape\n elif key == 27: \n escaped = True\n break\n cap.release() # Releases the video frame\n cv2.destroyAllWindows() # Closes the video feed window\n if not escaped: \n img = finalFrame # define the last frame as the new image\n self.showImage(img) # Shows the user the image they selected \n \n def showImage(self, img):\n # Shows the user the image they selected and asks them to verify\n # that that's the image they want to use\n margin = 30\n message = \"Proceed? Press 'Enter' to continue or 'Escape' to try again\"\n img = cv2.resize(img, (self.newCols, self.newRows))\n red = (0, 0, 255)\n self.drawRectangle(img)\n cv2.putText(img, message, (margin, margin), self.font, 1, red, 2)\n # Shows the user the image that the OCR is going to process\n cv2.imshow(\"newFrame\", img)\n key = cv2.waitKey()\n if key == 13: # If they press Enter, start processing\n cv2.destroyAllWindows() # Closes the window first\n # Passes the image to the processing class\n ImageProcessing(self.language).crop(img) \n elif key == 27: # If they press Escape, go back to a new live feed\n cv2.destroyAllWindows() # Closes the window first\n self.getImage() # New live feed\n\n###############################################################################\n##### Processes the image that the webcam got #################################\n###############################################################################\n\nclass ImageProcessing(object):\n \n def __init__(self, language):\n # Initializes the variables in the Image Processing instance\n self.language = language\n rows = 720\n cols = 1280\n self.newRows = 600\n ratio = float(self.newRows)/rows\n self.newCols = int(ratio*cols)\n self.length = 700\n self.height = 450\n \n def crop(self, img):\n # Crops the image from the last frame recorded to only be what\n # was positioned inside the reference rectangle\n cx = self.newCols/2\n cy = self.newRows/2\n x0 = int(cx-0.5*self.length)\n y0 = int(cy-0.5*self.height)\n x1 = x0+self.length\n y1 = y0+self.height\n img = img[y0:y1, x0:x1]\n # Make the image black-and-white (threshold)\n self.threshold(img)\n \n def makeBW(self, img):\n # Converts the image to black-and-white only\n # Converts the image to grayscale first\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # convert to gray\n (cols, rows) = img.shape\n keyVal = 80 # threshold value\n for row in xrange(rows):\n for col in xrange(cols):\n if img.item(col, row) <= keyVal: # If the pixel is 'dark'\n img.itemset((col, row), 0) # set it to black\n else: # If the pixel is 'light'\n img.itemset((col, row), 255) # set it to white\n return img\n \n def threshold(self, img):\n # Convert it into a black-and-white image, \n # just like it will be in the database\n img = self.makeBW(img)\n img = self.focus(img) # further cropping\n # Send it to the image comparer\n ImageComparison(img, self.language)\n \n def leftMost(self, img, cols, rows):\n # return the first column that has a black pixel\n for col in xrange(cols):\n for row in xrange(rows):\n if img.item(col, row) == 0:\n return col\n \n def rightMost(self, img, cols, rows):\n # return the first column from the right that has a black pixel\n for col in xrange(cols-1, -1, -1):\n for row in xrange(rows):\n if img.item(col, row) == 0:\n return col\n \n def topMost(self, img, cols, rows):\n # return the first row that has a black pixel\n for row in xrange(rows):\n for col in xrange(cols):\n if img.item(col, row) == 0:\n return row\n \n def bottomMost(self, img, cols, rows):\n # return the first row from the bottom that has a black pixel\n for row in xrange(rows-1, -1, -1):\n for col in xrange(cols):\n if img.item(col, row) == 0:\n return row\n \n def focus(self, img):\n # go through all the pixels, find the top left and bottom right pixels.\n # crop the image so that all that remains are the pixels between the \n # top left and bottom right pixels\n (cols, rows) = img.shape\n x0 = self.leftMost(img, cols, rows)\n x1 = self.rightMost(img, cols, rows)\n y0 = self.topMost(img, cols, rows)\n y1 = self.bottomMost(img, cols, rows)\n img = img[x0:x1, y0:y1]\n # Now the image doesn't have large white spaces around it and is\n # as compact as possible\n return img\n \n###############################################################################\n##### Compares the processed image with images in the database ################\n###############################################################################\n\nclass ImageComparison(object):\n \n def __init__(self, img, language):\n # Initializes the variables for each instance\n self.language = language\n self.database = self.getDatabase()\n (self.cols, self.rows) = img.shape\n self.message = \"\"\n self.split(img) # Only ever calls on this once\n \n ####################### Taken from course notes ###########################\n \n def listFiles(self, path):\n # Creates a list of all the files in the path stated\n # In this case, it creates a list of all the files in my database\n if (os.path.isdir(path) == False): # If it is a file/not a directory\n return [path]\n else:\n files = [ ]\n # recusrively go through the sub-directories\n for filename in os.listdir(path): \n files += self.listFiles(path + os.sep + filename)\n return files\n \n ###########################################################################\n \n def getDatabase(self):\n # Gets a list of all the files in my database\n # The file path is an absolute file path\n path1 = \"/Users/atulyaravishankar/Google Drive/Fall 2014/\"\n path2 = \"15-112 Programming/Term Project/Database\"\n path = path1+path2\n return self.listFiles(path)\n \n def splitCols(self, img):\n # splits each row into different columns, one for each character\n (rows, cols) = img.shape\n # Create a list of all the columns that have characters in them\n columns = [] \n for col in xrange(cols):\n for row in xrange(rows):\n if img.item(row, col) == 0: # if the pixel is black\n columns.append(col)\n break\n # Create a list of all the columns that are the start of each character\n keyColumns = [0]\n for index in xrange(1,len(columns)):\n # If there is a gap of 3 columns, it is a gap between characters\n if columns[index] - columns[index-1] > 3:\n keyColumns.append(columns[index])\n keyColumns.append(cols-1)\n return keyColumns\n \n def splitRows(self, img):\n # Splits the image into rows of characters\n (rows, cols) = img.shape\n # Ceates a list of all the rows that have characters in them\n rowsList = []\n for row in xrange(rows):\n for col in xrange(cols):\n if img.item(row, col) == 0: # if the pixel is black\n rowsList.append(row)\n break\n # Creates a list of all the rows that are the start of each character\n keyRows = [0]\n for index in xrange(1, len(rowsList)):\n # If there is a gap of even 1 row, it is a gap between characters\n if rowsList[index] - rowsList[index-1] > 1:\n keyRows.append(rowsList[index])\n keyRows.append(rows-1)\n return keyRows\n \n def getRatio(self, img):\n # Returns the ration of black:total colums in an image\n (rows, cols) = img.shape\n black = 0\n for col in xrange(cols):\n for row in xrange(rows):\n if img.item(row, col) == 0: # if the column has a black pixel\n black += 1\n break\n return float(black)/(cols)\n \n def split(self, img):\n # Splits the larger image into smaller images, each for one character\n (rows, cols) = img.shape\n # First split it up into rows\n keyRows = self.splitRows(img)\n for indexRow in xrange(1, len(keyRows)):\n self.message += \" \" # Add a space at the start of each new row\n startRow = keyRows[indexRow-1]\n endRow = keyRows[indexRow]\n image = img[startRow:endRow, 0:cols]\n image = ImageProcessing(self.language).focus(image)\n # Split each row up into columns, one for each character\n keyColumns = self.splitCols(image)\n for indexCol in xrange(1, len(keyColumns)):\n (newRows, newCols) = image.shape\n startCol = keyColumns[indexCol-1]\n endCol = keyColumns[indexCol]\n # Ignore very small images that are probably errors\n if (newRows <= 3) or endCol - startCol <= 3:\n continue \n imageToCompare = image[0:newRows, startCol:endCol]\n ratio = self.getRatio(imageToCompare)\n keyRatio = 0.6\n shape = imageToCompare.shape[1]\n keyShape = 25\n imageToCompare = \\\n ImageProcessing(self.language).focus(imageToCompare)\n try:\n self.compare(imageToCompare)\n # Check if there should be a space after the character\n if ratio < keyRatio and shape >= keyShape:\n self.message += \" \"\n # For \"I\" and \"1\", a space is incorrectly placed, so undo it\n if self.message[-2] == \"1\" and self.message[-1] == \" \":\n self.message = self.message[:-1] #remove the extra space\n except:\n pass\n # After all the characters have been compared, translate the message\n self.translate(self.message, img)\n \n def compare(self, img):\n # Compares each character to the ones in the database\n possibleMatch = dict()\n # start iterating from index 1 because index 0 isn't a file\n # Loops through all the images in the database\n for template in self.database[1:]: \n comp = cv2.imread(template,0) # reads the template data\n comp = ImageProcessing(self.language).focus(comp)#crops the template\n rows, cols = comp.shape[::-1]\n # Resize the images so that they are the same size\n img = cv2.resize(img, (rows, cols), interpolation=cv2.INTER_AREA)\n comp = cv2.resize(comp, (rows, cols), interpolation=cv2.INTER_AREA)\n if self.findAverage(img, comp, cols, rows) <= 30: # very close match\n return self.name(template, img) # stop and return\n else:\n possibleMatch[self.findAverage(img, comp, cols, rows)]=template\n minKey = 256\n for key in possibleMatch:\n if key < minKey: # find the lowest comparison value\n minKey = key\n # probably an error because the closest match is still quite high\n if minKey >= 100: \n return # don't return anything\n self.name(possibleMatch[minKey], img) # Add the character to the message\n \n def name(self, filename, img):\n # Adds the character to the name\n # Find the index right before the character\n start = filename.find(\"Database/\")\n # Add the length of \"Database/\" to get the actual index\n shift = len(\"Database/\")\n # Find the index right after the character\n end = filename.find(\"template.jpg\")\n # Slice the file name to only get the character\n name = filename[start+shift:end-1]\n # Add the character to the message\n self.message += name\n \n def displayTranslation(self, translation, img):\n # Displays the translation in a new window\n cols, rows = img.shape\n margin = 10\n height = 800\n width = 600\n if len(translation) >= 30:\n # Make the font size smaller to fit on the screen\n size = 0.75\n else:\n size = 1.0\n # Creates new image window\n background = np.zeros((width,height,3), np.uint8)\n font = cv2.FONT_HERSHEY_SIMPLEX\n self.drawTranslation(cols, rows, margin, height, width, translation, \\\n size, background, font)\n \n def drawTranslation(self, cols, rows, margin, height, width, translation, \\\n size, background, font):\n # Draws the translation on the new window\n try:\n cv2.putText(background, \"%s\" %translation,(0, width/2),font,size, \\\n (0, 255, 255), 2)\n except:\n # Normalize the encoding if special characters are involved\n translation = \\\n unicodedata.normalize('NFKD', translation).encode('ascii','ignore')\n cv2.putText(background, \"%s\" %translation, (0, width/2),font,size,\\\n (0, 255, 255), 2)\n instruction = \"Press any key to exit\"\n cv2.putText(background, instruction, (height-18*margin, width-margin),\\\n font, size/2, (255, 255, 255), 1)\n # Shows the user the translation\n cv2.imshow(\"translation\", background)\n cv2.moveWindow(\"translation\", 0, 0)\n cv2.waitKey(0)\n cv2.destroyAllWindows() # Closes the window when done\n \n def translateChinese(self, message):\n # Translates the message into Chinese\n # Returns the pinyin (phonetic)\n gs_roman = goslate.Goslate(goslate.WRITING_ROMAN)\n translation = gs_roman.translate(message, \"zh\")\n return translation\n\n def removeSpaces(self, message):\n # Removes spaces in a Chinese translation \n # (to prevent it messing up the translation)\n newMessage = message.replace(\" \", \"\")\n return newMessage\n \n def translate(self, message, img):\n # Translates the message\n # First get rid of unnecessary white spaces\n message = string.strip(message)\n # Google translate works better with lowercase\n message = string.lower(message)\n gs = goslate.Goslate()\n try:\n language = gs.detect(message) # Detects the input language\n except:\n language = \"en\"\n translation = \"Cannot translate the text.\"\n self.displayTranslation(translation, img)\n return\n if language in [\"zh-CN\", \"zh\"]:\n message = self.removeSpaces(message)\n try:\n if self.language == \"zh\":\n translation = self.translateChinese(message)\n else:\n translation = gs.translate(message, self.language)\n except:\n # In case something goes wrong\n translation = \"Cannot translate the text.\"\n # Display the translation\n self.displayTranslation(translation, img)\n \n def findAverage(self, img, template, cols, rows):\n # Returns the average values of the array after pixel subtraction\n # Takes two images of the same size, subtracts the pixel value of one \n # image from the pixel value of the other image at the same position\n # and adds that value to the list\n subtractedList = []\n for col in xrange(cols):\n for row in xrange(rows):\n imgVal = img.item(col, row)\n templateVal = template.item(col, row)\n subtractedList.append(abs(imgVal-templateVal))\n average = float(sum(subtractedList)) / len(subtractedList)\n return average\n","sub_path":"videoProcessing.py","file_name":"videoProcessing.py","file_ext":"py","file_size_in_byte":19383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"168473172","text":"# The Water Meter Device module\n\n# License\n# This file is part of the Smart-Home-Project distribution\n# (https://github.com/harshitandro/Smart-Home-Project).\n#\n# Copyright (c) 2017 Harshit Singh Lodha .\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, version 3.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\nfrom machine import Pin\nfrom machine import PWM\nfrom machine import Timer\nfrom socket import *\nimport network\nimport time\nimport micropython\nimport machine\nimport btree\nimport os\n\nmicropython.alloc_emergency_exception_buf(100)\n\nif \"conf.txt\" in os.listdir():\n import setup\n\n setup.run()\n setup.close()\n\nimport remote_sender\n\ntry:\n f = open(\"conf\", \"r+b\")\nexcept OSError:\n f = open(\"conf\", \"w+b\")\ndb = btree.open(f)\nirq_state = machine.disable_irq()\nglobal listen_port\nlisten_port = int(str(db[b\"listen_port\"], \"utf-8\"))\nglobal calib\ncalib = float(str(db[b\"calib\"], \"utf-8\"))\n\ndb.close()\nf.close()\nmachine.enable_irq(irq_state)\n\n\nclass WaterMeter:\n def __init__(self):\n # machine.freq(160000000)\n try:\n self.f = open(\"conf\", \"r+b\")\n except OSError:\n self.f = open(\"conf\", \"w+b\")\n self.db = btree.open(self.f)\n self.COUNTER = 0\n self.INSTANT_FLOW = 0.0\n self.LED_PIN_NUMBER = 4 # D2\t\t# indicator LED Connection\n self.SENSOR_PIN_NUMBER = 5 # D1\t\t# data connection to sensor\n self.GLOBAL_COUNTER = 0.0\n try:\n self.GLOBAL_COUNTER = float(str(self.db[b\"GLOBAL_COUNTER\"], \"utf-8\"))\n except KeyError:\n self.GLOBAL_COUNTER = 0.0\n self.led = Pin(self.LED_PIN_NUMBER)\n self.led = PWM(self.led)\n self.sensor = Pin(self.SENSOR_PIN_NUMBER, Pin.IN, Pin.PULL_UP)\n self.timer = Timer(-1)\n self.led.duty(512)\n self.led.freq(1)\n self.sensor.irq(trigger=Pin.IRQ_RISING, handler=self.counter)\n self.timer.init(period=1000, mode=Timer.PERIODIC, callback=self.update_global)\n\n def led_control(self, count):\n if count == 0:\n self.led.duty(0)\n else:\n self.led.duty(512)\n self.led.freq(int(count * 20))\n\n def counter(self, pin):\n self.COUNTER += 1\n\n def update_global(self, loc):\n self.INSTANT_FLOW = (self.COUNTER * calib)\n self.GLOBAL_COUNTER = self.GLOBAL_COUNTER + self.INSTANT_FLOW\n self.COUNTER = 0\n self.led_control(self.INSTANT_FLOW)\n irq_state = machine.disable_irq()\n self.db[b\"GLOBAL_COUNTER\"] = bytes(str(self.GLOBAL_COUNTER), \"utf-8\")\n self.db.flush()\n self.f.flush()\n machine.enable_irq(irq_state)\n\n def getVal(self):\n return str(self.GLOBAL_COUNTER)\n\n\nif __name__ == \"__main__\":\n meter = WaterMeter()\n t1 = Timer(-1)\n t1.init(period=10000, mode=Timer.PERIODIC, callback=lambda t: remote_sender.send_data(meter.getVal()))\n listen_soc = socket(AF_INET, SOCK_DGRAM)\n local_send_soc = socket(AF_INET, SOCK_STREAM)\n listen_soc.bind((\"0.0.0.0\", listen_port))\n while True:\n local_send_soc = socket(AF_INET, SOCK_STREAM)\n listen_soc.settimeout(0.5)\n clientFlag = False\n client_address = []\n while not clientFlag:\n try:\n data, client_addr = listen_soc.recvfrom(4096)\n if (str(data, \"utf-8\").split(\":\"))[0] == \"{}_SERVER_BCAST\".format(dev_type):\n client_address = (client_addr[0], int((str(data, \"utf-8\").split(\":\"))[1]))\n print(client_address[0], client_address[1])\n local_send_soc.connect(client_address)\n print(\"socket connected\")\n clientFlag = True\n except OSError:\n print(\"Socket Timeout\")\n for i in range(5000):\n try:\n local_send_soc.sendall(str.encode(meter.getVal(), encoding='utf-8'))\n except OSError:\n print(\"Client Disconnected\")\n local_send_soc.close()\n clientFlag = False\n break\n","sub_path":"DEVICE_TREE/src/WaterMeter/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"51105575","text":"# -*- coding: utf-8 -*-\n\n#%% IMPORTS\nimport numpy as np\nimport time\nfrom PIL import Image\nimport cv2\nimport os\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms as Transforms\nimport random\nfrom tqdm import tqdm \nfrom copy import deepcopy\nimport sys\nimport math\nimport pandas as pd\nimport cv2\n\nfrom libraries.utils import Paths, ensure_folder\n\npaths = Paths()\n\nNORMAL_PATH = paths.normal_patches_path\nANOM_PATH = paths.anom_patches_path\n\nNORMAL_LABEL = np.float64(0)\nANOMALY_LABEL = np.float64(1)\n#%%\ndef getImages(start, end):\n train = pd.read_csv(paths.csv_directory + 'train_unique.csv')\n \n images = []\n masks = []\n \n count = start\n \n for row in train.index[start : end]:\n print('Image n. {}'.format(count))\n filename = train.iloc[row].Image_Id\n enc_pixels = train.iloc[row].Encoded_Pixels\n \n img = cv2.imread(paths.images_path + filename)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n mask = computeMask(enc_pixels, img) \n \n images.append(img)\n masks.append(mask)\n \n count += 1\n \n return images, masks\n\ndef getPatchesFromImages(start, end, shape):\n train = pd.read_csv(paths.csv_directory + 'train_unique.csv')\n \n patches_list = []\n patch_masks_list = []\n \n count = start\n# print(len(train.index[start : end]))\n for row in train.index[start : end]:\n print('Image n. {}'.format(count))\n filename = train.iloc[row].Image_Id\n enc_pixels = train.iloc[row].Encoded_Pixels\n \n img = cv2.imread(paths.images_path + filename)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n mask = computeMask(enc_pixels, img) \n \n patches, patch_masks = _splitPatches(img, mask, shape)\n \n patches_list.extend(patches)\n patch_masks_list.extend(patch_masks)\n \n count += 1\n \n return patches_list, patch_masks_list\n \ndef _splitPatches(image, mask, shape):\n \n x = image.shape[1]\n y = image.shape[0]\n \n patches = []\n patch_masks = []\n \n # 400 patches per image\n for j in range(0, y, shape):\n for i in range(0, x, shape):\n if(j+shape < y and i+shape < x):\n patch = image[j:j+shape, i:i+shape]\n # print('{}x{}'.format(j,i))\n patches.append(patch)\n \n patch_mask = mask[j:j+shape, i:i+shape]\n patch_masks.append(patch_mask)\n \n return patches, patch_masks\n \n \ndef computeMask(enc_pixel, img):\n width = img.shape[0]\n height= img.shape[1]\n \n mask= np.zeros( width*height ).astype(np.float64)\n if(enc_pixel == 0):\n return np.zeros((width, height))\n \n array = np.asarray([int(x) for x in enc_pixel.split()])\n starts = array[0::2]\n lengths = array[1::2]\n \n current_position = 0\n for index, start in enumerate(starts):\n mask[int(start):int(start+lengths[index])] = 1\n current_position += lengths[index]\n \n mask = np.flipud(np.rot90(mask.reshape(height,width), k=1))\n mask = mask.astype(np.float64)\n \n return mask\n\ndef _setupDataset(opt, train='normal', valid='normal', test='mixed'):\n '''\n train: 'normal' / 'mixed'\n validation: 'normal' / 'mixed'\n test: 'normal' / 'mixed'\n \n '''\n patch_x_img = opt.patch_per_im\n n_images = opt.nFolders\n n_patches = n_images * patch_x_img\n \n n_training_imgs = math.ceil(n_patches * opt.split)\n n_validation_imgs = math.ceil(n_patches * (1-opt.split))\n n_test_imgs = math.ceil(n_patches * (1-opt.split))\n \n# print(n_training_imgs)\n# print(n_validation_imgs)\n# print(n_test_imgs)\n \n training_set = {'DATA':[], 'LABELS':[]}\n validation_set = {'DATA':[], 'LABELS':[]}\n test_set = {'DATA':[], 'LABELS':[]}\n \n start = time.time()\n \n n_anom_patches = int((n_training_imgs + n_validation_imgs + n_test_imgs)/2)\n anom_patches = createAnomalousPatches(n_anom_patches)\n \n n_norm_patches = int(n_training_imgs + n_validation_imgs + n_test_imgs)\n norm_patches = createNormalPatches(n_norm_patches)\n \n # TRAINING SET\n training_set = fillSet(train, norm_patches, anom_patches, int(n_training_imgs))\n \n # VALIDATION\n validation_set = fillSet(train, norm_patches[int(n_training_imgs):],\n anom_patches[int(n_training_imgs//2) : ],\n \n int(n_validation_imgs))\n \n # TEST\n test_set = fillSet(train, norm_patches[int(n_training_imgs + n_validation_imgs):],\n anom_patches[int(n_training_imgs//2) + int(n_validation_imgs//2): ],\n \n int(n_validation_imgs))\n \n\n print('\\n')\n print('Training set: {} images'.format(len(training_set['DATA'])))\n print('Validation set: {} images'.format(len(validation_set['DATA'])))\n print('Test set: {} images'.format(len(test_set['DATA'])))\n \n end = time.time()\n print('Spent time : {:.2f} sec'.format(end - start))\n \n return training_set, validation_set, test_set\n\n \ndef fillSet(set_type, norm_patches, anom_patches, n_images):\n '''\n DESCRIPTION:\n Automatic dataset filling for training, validation and testing sets\n \n PARAMS:\n set_type : 'normal' / 'mixed'\n \n '''\n dataset = {'DATA':[], 'LABELS':[]}\n# anoms = 0\n \n if(set_type == 'normal'):\n # NORMALS\n dataset['DATA'] = norm_patches[0:n_images]\n dataset['LABELS'] = np.zeros([n_images]).fill(NORMAL_LABEL)\n \n elif(set_type == 'mixed'):\n # NORMALS\n dataset['DATA'] = norm_patches[0:int(n_images//2)]\n dataset['LABELS'] = np.zeros([n_images//2])\n dataset['LABELS'].fill(NORMAL_LABEL)\n \n # ANOMALOUS\n dataset['DATA'] = np.concatenate((dataset['DATA'], anom_patches[0:int(n_images//2)]))\n temp = np.zeros([n_images//2])\n temp.fill(ANOMALY_LABEL)\n dataset['LABELS'] = np.concatenate((dataset['LABELS'], temp))\n \n return dataset\n\ndef createAnomalousPatches(N):\n \n anom_patches = []\n i=0\n for index in os.listdir(ANOM_PATH):\n if(len(anom_patches) >= N):\n break\n \n path_anom = ANOM_PATH + str(index) + '/'\n anom_filename = os.listdir(path_anom)\n \n for filename in anom_filename:\n if(len(anom_patches) < N):\n image = cv2.imread(path_anom + filename) \n anom_patches.append(image)\n i += 1\n# print(i)\n else:\n break\n \n random.shuffle(anom_patches)\n return anom_patches\n\ndef createNormalPatches(N):\n \n norm_patches = []\n i=0\n for index in os.listdir(NORMAL_PATH):\n if(len(norm_patches) >= N):\n break\n \n path_norm = NORMAL_PATH + str(index) + '/'\n norm_filename = os.listdir(path_norm)\n \n for filename in norm_filename:\n if(len(norm_patches) < N):\n image = cv2.imread(path_norm + filename) \n norm_patches.append(image)\n i += 1\n# print(i)\n else:\n break\n \n random.shuffle(norm_patches)\n return norm_patches\n \n\ndef loadDataset(opt, test='mixed'):\n '''\n DESCRIPTION:\n Load data in train, validation and test set, in the following way\n \n - Training set: 70 % NORMAL SAMPLES\n - Validation set: 15 % NORMAL SAMPLES\n - Test set: 15 % NORMAL SAMPLES(test='normal') / NORMAL-ANOM(test='mixed')\n \n '''\n training_set = {'DATA':[], 'LABELS':[]}\n validation_set = {'DATA':[], 'LABELS':[]}\n test_set = {'DATA':[], 'LABELS':[]}\n \n patches_per_image = opt.patch_per_im\n \n NORMAL_LABEL = np.float64(0)\n ANOMALY_LABEL = np.float64(1)\n \n training_index = int(patches_per_image * opt.split)\n validation_index = training_index + int(patches_per_image*(1-opt.split))\n n_test_samples = int(training_index * (1-opt.split))\n# print(training_index)\n# print(validation_index)\n# print(n_test_samples)\n \n counter = 0\n start = time.time()\n \n folders = os.listdir(NORMAL_PATH)\n random_folders = random.sample(folders, opt.nFolders)\n \n print('\\nPatches per image: ', patches_per_image)\n for index in random_folders:\n counter += 1\n print('\\n')\n print('Image n.', counter)\n \n path_normal = NORMAL_PATH + str(index) + '/'\n path_anom = ANOM_PATH + str(index) + '/'\n \n norm_filename = os.listdir(path_normal)\n random.shuffle(norm_filename)\n \n anom_filename = os.listdir(path_anom)\n random.shuffle(anom_filename)\n \n # TRAINING SET\n for filename in tqdm(norm_filename[0 : training_index], leave=True, desc='Training-set\\t', file=sys.stdout):\n\n image = cv2.imread(path_normal + filename)\n \n# if(channels == 1):\n# image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n \n\n# train_data.append(image)\n# train_label.append(NORMAL_LABEL)\n training_set['DATA'].append(image)\n training_set['LABELS'].append(NORMAL_LABEL)\n \n # VALIDATION\n for filename in tqdm(norm_filename[training_index : validation_index], leave=True, desc='Validation-set\\t',\n file=sys.stdout):\n \n image = cv2.imread(path_normal + filename)\n \n# if(channels == 1):\n# image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n \n# validation_data.append(image)\n# validation_label.append(NORMAL_LABEL)\n validation_set['DATA'].append(image)\n validation_set['LABELS'].append(NORMAL_LABEL)\n \n if(test=='mixed'):\n test_set['DATA'].append(image)\n test_set['LABELS'].append(NORMAL_LABEL)\n\n # TEST\n if(test=='mixed'):\n test_filename = anom_filename[0:len(validation_set['DATA'])]\n LABEL = ANOMALY_LABEL\n# test_set = deepcopy(validation_set)\n path_images = path_anom\n \n elif(test=='normal'):\n test_filename = norm_filename[validation_index : validation_index+n_test_samples]\n LABEL = NORMAL_LABEL\n path_images = path_normal\n \n else:\n raise Exception('>>> ERROR Load Dataset: wrong test_type <<<')\n \n for filename in tqdm(test_filename, leave=True, desc='Test-set\\t', file=sys.stdout):\n# print(path_anom + filename)\n image = cv2.imread(path_images + filename)\n \n# if(channels == 1):\n# image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n \n# print(image)\n# test_data.append(image)\n# test_label.append(ANOM_PATH)\n test_set['DATA'].append(image)\n test_set['LABELS'].append(LABEL)\n\n print('\\n')\n print('Training set: {} images'.format(len(training_set['DATA'])))\n print('Validation set: {} images'.format(len(validation_set['DATA'])))\n print('Test set: {} images'.format(len(test_set['DATA'])))\n \n end = time.time()\n print('Spent time : {:.2f} sec'.format(end - start))\n \n return training_set, validation_set, test_set\n\n#%%\n \ndef generateDataloader(opt):\n print('\\n>Loading Steel Dataset')\n \n if(opt.loadedData == False):\n opt.loadDatasets()\n \n dataset = {}\n dataset['train'] = SteelDataset(opt, train=True)\n dataset['validation'] = SteelDataset(opt, valid=True)\n dataset['test'] = SteelDataset(opt, test=True)\n \n shuffle = {'train':True, 'validation':True, 'test':True}\n \n dataloader = {x: DataLoader(dataset = dataset[x],\n batch_size = opt.batch_size,\n drop_last = True,\n shuffle = shuffle[x],\n num_workers= opt.n_workers\n )\n \n for x in ['train', 'validation', 'test']}\n \n return dataloader\n\ndef generateDataloaderFromDatasets(opt, training_set, validation_set, test_set):\n print('\\n>Loading Steel Dataset')\n \n dataset = {}\n dataset['train'] = SteelDataset(opt, training_set, train=True)\n dataset['validation'] = SteelDataset(opt, validation_set, valid=True)\n dataset['test'] = SteelDataset(opt, test_set, test=True)\n \n shuffle = {'train':True, 'validation':True, 'test':True}\n \n dataloader = {x: DataLoader(dataset = dataset[x],\n batch_size = opt.batch_size,\n drop_last = True,\n shuffle = shuffle[x],\n num_workers= opt.n_workers\n )\n \n for x in ['train', 'validation', 'test']}\n \n return dataloader\n\ndef generateDataloaderTest(patches, opt):\n \n data = []\n targets = []\n \n \n for patch in patches:\n data.append(patch)\n targets.append(np.float64(patch.anomaly))\n \n dataset = TestDataset(data, targets, opt)\n \n dataloader = DataLoader(dataset,\n batch_size = opt.batch_size,\n# shuffle=True,\n drop_last = True,\n num_workers = 8)\n \n return dataloader\n\ndef dataloaderPatchMasks(opt):\n \n dataset = {}\n dataset['DATA'], dataset['LABELS'] = getPatchesFromImages(opt.start, opt.end, opt.shape)\n \n training_set = {}\n validation_set = {}\n test_set = {}\n \n train_index = int(len(dataset['DATA']) * opt.split)\n valid_index = int(len(dataset['DATA']) * (0.9-opt.split))\n test_index = int(len(dataset['DATA']) * 0.1)\n \n# print(train_index)\n# print(valid_index)\n# print(test_index)\n \n start = 0\n end = train_index\n training_set['DATA'] = dataset['DATA'][start:end]\n training_set['LABELS'] = dataset['LABELS'][start:end]\n \n start = train_index\n end = train_index + valid_index\n validation_set['DATA'] = dataset['DATA'][start:end]\n validation_set['LABELS'] = dataset['LABELS'][start:end]\n \n start = train_index + valid_index \n end = train_index + valid_index + test_index\n test_set['DATA'] = dataset['DATA'][start : end]\n test_set['LABELS'] = dataset['LABELS'][start : end]\n \n dataset = {}\n dataset['train'] = SteelDataset(opt, training_set, train=True)\n dataset['validation'] = SteelDataset(opt, validation_set, valid=True)\n dataset['test'] = SteelDataset(opt, test_set, test=True)\n \n shuffle = {'train':True, 'validation':True, 'test':True}\n \n dataloader = {x: DataLoader(dataset = dataset[x],\n batch_size = opt.batch_size,\n drop_last = True,\n shuffle = shuffle[x],\n num_workers= opt.n_workers\n )\n \n for x in ['train', 'validation', 'test']}\n \n return dataloader\n\n\ndef dataloaderFullImages(opt):\n \n dataset = {}\n dataset['DATA'], dataset['LABELS'] = getImages(opt.start, opt.end)\n \n training_set = {}\n validation_set = {}\n test_set = {}\n \n train_index = int(len(dataset['DATA']) * opt.split)\n valid_index = int(len(dataset['DATA']) * (0.9-opt.split))\n test_index = int(len(dataset['DATA']) * 0.1)\n \n start = 0\n end = train_index\n training_set['DATA'] = dataset['DATA'][start:end]\n training_set['LABELS'] = dataset['LABELS'][start:end]\n \n start = train_index\n end = train_index + valid_index\n validation_set['DATA'] = dataset['DATA'][start:end]\n validation_set['LABELS'] = dataset['LABELS'][start:end]\n \n start = train_index + valid_index \n end = train_index + valid_index + test_index\n test_set['DATA'] = dataset['DATA'][start : end]\n test_set['LABELS'] = dataset['LABELS'][start : end]\n \n dataset = {}\n dataset['train'] = FullSteelDataset(opt, training_set, train=True)\n dataset['validation'] = FullSteelDataset(opt, validation_set, valid=True)\n dataset['test'] = FullSteelDataset(opt, test_set, test=True)\n \n shuffle = {'train':True, 'validation':True, 'test':True}\n \n dataloader = {x: DataLoader(dataset = dataset[x],\n batch_size = opt.batch_size,\n drop_last = True,\n shuffle = shuffle[x],\n num_workers= opt.n_workers\n )\n \n for x in ['train', 'validation', 'test']}\n \n return dataloader\n\ndef saveDataloader(dataloader):\n \n # CHECK EXISTENCY FOLDERS\n \n # TRAINING SET\n ensure_folder(paths.training_set_path)\n # VALIDATION SET\n ensure_folder(paths.validation_set_path)\n # TEST SET\n ensure_folder(paths.test_set_path)\n \n folders = {'train':paths.training_set_path,\n 'validation':paths.validation_set_path,\n 'test':paths.test_set_path}\n \n sets = ['train', 'validation', 'test']\n \n for i in range(len(dataloader['train'].dataset.data)):\n \n for set_type in sets:\n images = dataloader[set_type].dataset.data\n targets= dataloader[set_type].dataset.targets\n \n if(i < len(images)):\n images[i]\n \n \ndef collectNormalSamples(nImages, normal_per_img=None):\n n_normal = 0\n counterImage = 0\n limit = 0\n\n normalTest = []\n \n folders = os.listdir(NORMAL_PATH)\n random_folders = random.sample(folders, nImages)\n \n for index in random_folders:\n counterImage += 1\n path_anom = NORMAL_PATH + str(index) + '/'\n normImages = os.listdir(path_anom)\n \n print('\\nImage n.', counterImage)\n \n if(normal_per_img is None):\n normal_per_img = len(normImages)\n \n limit = 0\n# print(len(normImages))\n for filename in tqdm(normImages, leave=True, desc='Anom. Images:\\t', \n total=normal_per_img, file=sys.stdout):\n \n cond1 = normal_per_img is not None and limit < normal_per_img\n cond2 = normal_per_img is None\n \n if(cond1 or cond2):\n n_normal += 1\n limit += 1\n image = cv2.imread(path_anom + filename)\n normalTest.append(image)\n \n \n \n \n print('> {} anomalous images loaded'.format(n_normal))\n \n return normalTest\n \n \ndef collectAnomalySamples(nImages, anom_per_img=None):\n n_anomaly = 0\n counterImage = 0\n limit = 0\n\n anomalyTest = []\n \n folders = os.listdir(ANOM_PATH)\n random_folders = random.sample(folders, nImages)\n \n for index in random_folders:\n counterImage += 1\n path_anom = ANOM_PATH + str(index) + '/'\n anomImages = os.listdir(path_anom)\n \n print('\\nImage n.', counterImage)\n \n if(anom_per_img is None):\n anom_per_img = len(anomImages)\n \n limit = 0\n \n for filename in tqdm(anomImages, leave=True, desc='Anom. Images:\\t', \n total=anom_per_img, file=sys.stdout):\n \n cond1 = anom_per_img is not None and limit < anom_per_img\n cond2 = anom_per_img is None\n \n if(cond1 or cond2):\n n_anomaly += 1\n limit += 1\n image = cv2.imread(path_anom + filename)\n anomalyTest.append(image)\n else:\n pass\n \n print('> {} anomalous images loaded'.format(n_anomaly))\n \n return anomalyTest\n\nclass TestDataset(Dataset):\n \n def __init__(self, data, targets, opt):\n self.data = data\n self.targets = targets\n self._initTransforms(opt)\n \n def _initTransforms(self, opt):\n self.transforms = Transforms.Compose(\n [\n# transforms.Resize(32, interpolation=Image.BILINEAR),\n Transforms.Grayscale(num_output_channels = opt.in_channels),\n Transforms.ToTensor(),\n Transforms.Normalize((0.5, 0.5, 0.5),\n (0.5, 0.5, 0.5)),\n# Transforms.Grayscale(num_output_channels = opt.in_channels)\n# transforms.ToPILImage()\n ]\n )\n \n def __getitem__(self, index):\n \n if torch.is_tensor(index):\n index = index.tolist()\n \n image, target = self.data[index].patch_image, self.targets[index]\n image = Image.fromarray(image)\n \n # GRAYSCALE\n# image = image.convert('LA')\n \n image = self.transforms(image)\n# print(image.shape)\n return image, target\n \n def __len__(self):\n return len(self.data)\n \n \n\nclass SteelDataset(Dataset):\n \n def __init__(self, opt, dataset=None, train=False, valid=False, test=False):\n \n self.train = train\n self.valid = valid\n self.test = test\n \n if(dataset is None):\n if(train and not valid and not test):\n self.data = opt.training_set['DATA']\n self.targets = opt.training_set['LABELS']\n \n elif(valid and not train and not test):\n self.data = opt.validation_set['DATA']\n self.targets = opt.validation_set['LABELS']\n \n elif(test and not train and not valid):\n self.data = opt.test_set['DATA']\n self.targets = opt.test_set['LABELS']\n \n else:\n if(train and not valid and not test):\n self.data = dataset['DATA']\n self.targets = dataset['LABELS']\n \n elif(valid and not train and not test):\n self.data = dataset['DATA']\n self.targets = dataset['LABELS']\n \n elif(test and not train and not valid):\n self.data = dataset['DATA']\n self.targets = dataset['LABELS']\n \n self.data = np.vstack(self.data).reshape(-1, opt.shape, opt.shape, 3)\n\n print(self.data.shape)\n\n self.transforms = self._initTransforms(opt)\n\n def _initTransforms(self, opt):\n if(self.train):\n if(opt.augmentation==False):\n \n transforms = Transforms.Compose(\n [\n # transforms.Resize(32, interpolation=Image.BILINEAR),\n Transforms.Grayscale(num_output_channels = opt.in_channels),\n Transforms.ToTensor(),\n Transforms.Normalize((0.5,),\n (0.5,)),\n # Transforms.Grayscale(num_output_channels = opt.in_channels)\n # transforms.ToPILImage()\n ]\n )\n \n else:\n transforms = Transforms.Compose(\n [\n # AUGMENTATION\n Transforms.ColorJitter(brightness=0.2,\n contrast=0.2, \n saturation=0.3, \n hue=0.2),\n \n # Transforms.RandomRotation(10),\n Transforms.RandomAffine(degrees=10,\n scale=(0.5,2),\n shear=0.2),\n \n Transforms.Grayscale(num_output_channels = opt.in_channels),\n Transforms.ToTensor(),\n Transforms.Normalize((0.5,),\n (0.5,)) \n \n ]\n ) \n \n elif(self.valid or self.test):\n transforms = Transforms.Compose(\n [\n Transforms.Grayscale(num_output_channels = opt.in_channels),\n Transforms.ToTensor(),\n Transforms.Normalize((0.5,),\n (0.5,)) \n ]\n )\n \n return transforms\n \n def __getitem__(self, index):\n \n if torch.is_tensor(index):\n index = index.tolist()\n \n image, target = self.data[index], self.targets[index]\n\n# image = Image.convert('RGB')\n image = Image.fromarray(image)\n \n # GRAYSCALE\n# image = image.convert('LA')\n \n image = self.transforms(image)\n \n return image, target\n \n def __len__(self):\n return len(self.data)\n\nclass FullSteelDataset(Dataset):\n \n def __init__(self, opt, dataset, train=False, valid=False, test=False):\n \n self.train = train\n self.valid = valid\n self.test = test\n\n if(train and not valid and not test):\n self.data = dataset['DATA']\n self.targets = dataset['LABELS']\n \n elif(valid and not train and not test):\n self.data = dataset['DATA']\n self.targets = dataset['LABELS']\n \n elif(test and not train and not valid):\n self.data = dataset['DATA']\n self.targets = dataset['LABELS']\n \n self.data = np.vstack(self.data).reshape(-1, 256, 1600, 3)\n print(self.data.shape)\n\n self.transforms = self._initTransforms(opt)\n\n def _initTransforms(self, opt):\n if(self.train):\n if(opt.augmentation==False):\n \n transforms = Transforms.Compose(\n [\n # transforms.Resize(32, interpolation=Image.BILINEAR),\n Transforms.Grayscale(num_output_channels = opt.in_channels),\n Transforms.ToTensor(),\n Transforms.Normalize((0.5,),\n (0.5,)),\n # Transforms.Grayscale(num_output_channels = opt.in_channels)\n # transforms.ToPILImage()\n ]\n )\n \n else:\n transforms = Transforms.Compose(\n [\n # AUGMENTATION\n Transforms.ColorJitter(brightness=0.2,\n contrast=0.2, \n saturation=0.3, \n hue=0.2),\n \n # Transforms.RandomRotation(10),\n Transforms.RandomAffine(degrees=10,\n scale=(0.5,2),\n shear=0.2),\n \n Transforms.Grayscale(num_output_channels = opt.in_channels),\n Transforms.ToTensor(),\n Transforms.Normalize((0.5,),\n (0.5,)) \n \n ]\n ) \n \n elif(self.valid or self.test):\n transforms = Transforms.Compose(\n [\n Transforms.Grayscale(num_output_channels = opt.in_channels),\n Transforms.ToTensor(),\n Transforms.Normalize((0.5,),\n (0.5,)) \n ]\n )\n \n return transforms\n \n def __getitem__(self, index):\n \n if torch.is_tensor(index):\n index = index.tolist()\n \n image, target = self.data[index], self.targets[index]\n\n image = Image.fromarray(image)\n \n image = self.transforms(image)\n \n# print(type(target[0][0]))\n \n return image, target\n \n def __len__(self):\n return len(self.data)\n\n\n#%%\nfrom torchvision.datasets import CIFAR10\nimport torchvision.transforms as transforms\n\ndef getCifar10(opt):\n \n print('>Loading Cifar Dataset')\n \n splits = ['train', 'test']\n shuffle = {'train': True, 'test': False}\n drop_last = {'train': True, 'test': True}\n transform = transforms.Compose(\n [\n # transforms.Resize(opt.isize),\n transforms.Resize(opt.img_size),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ]\n )\n \n classes = {\n 'plane': 0, 'car': 1, 'bird': 2, 'cat': 3, 'deer': 4,\n 'dog': 5, 'frog': 6, 'horse': 7, 'ship': 8, 'truck': 9\n }\n \n dataset = {}\n dataset['train'] = CIFAR10(root='./data', train=True, download=True, transform=transform)\n dataset['test'] = CIFAR10(root='./data', train=False, download=True, transform=transform)\n \n #a = CIFAR10(root='./data', train=True, download=True, transform=transform)\n \n dataset['train'].data, dataset['train'].targets, \\\n dataset['test'].data, dataset['test'].targets = get_cifar_anomaly_dataset(\n trn_img=dataset['train'].data,\n trn_lbl=dataset['train'].targets,\n tst_img=dataset['test'].data,\n tst_lbl=dataset['test'].targets,\n # abn_cls_idx=classes[opt.abnormal_class],\n abn_cls_idx=classes['car'],\n # manualseed=opt.manualseed\n )\n \n dataset['train'].targets = dataset['train'].targets.astype('float64')\n dataset['test'].targets = dataset['test'].targets.astype('float64')\n \n dataloader = {x: torch.utils.data.DataLoader(dataset=dataset[x],\n batch_size=opt.batch_size,\n shuffle=shuffle[x],\n # num_workers=int(opt.workers), \n drop_last=drop_last[x],\n # worker_init_fn=(None if opt.manualseed == -1\n # else lambda x: np.random.seed(opt.manualseed))\n )\n for x in splits}\n \n return dataloader\n\n\ndef get_cifar_anomaly_dataset(trn_img, trn_lbl, tst_img, tst_lbl, abn_cls_idx=0, manualseed=-1):\n \"\"\"[summary]\n\n Arguments:\n trn_img {np.array} -- Training images\n trn_lbl {np.array} -- Training labels\n tst_img {np.array} -- Test images\n tst_lbl {np.array} -- Test labels\n\n Keyword Arguments:\n abn_cls_idx {int} -- Anomalous class index (default: {0})\n\n Returns:\n [np.array] -- New training-test images and labels.\n \"\"\"\n # Convert train-test labels into numpy array.\n trn_lbl = np.array(trn_lbl)\n tst_lbl = np.array(tst_lbl)\n\n # --\n # Find idx, img, lbl for abnormal and normal on org dataset.\n nrm_trn_idx = np.where(trn_lbl != abn_cls_idx)[0]\n abn_trn_idx = np.where(trn_lbl == abn_cls_idx)[0]\n nrm_trn_img = trn_img[nrm_trn_idx] # Normal training images\n abn_trn_img = trn_img[abn_trn_idx] # Abnormal training images\n nrm_trn_lbl = trn_lbl[nrm_trn_idx] # Normal training labels\n abn_trn_lbl = trn_lbl[abn_trn_idx] # Abnormal training labels.\n\n nrm_tst_idx = np.where(tst_lbl != abn_cls_idx)[0]\n abn_tst_idx = np.where(tst_lbl == abn_cls_idx)[0]\n nrm_tst_img = tst_img[nrm_tst_idx] # Normal training images\n abn_tst_img = tst_img[abn_tst_idx] # Abnormal training images.\n nrm_tst_lbl = tst_lbl[nrm_tst_idx] # Normal training labels\n abn_tst_lbl = tst_lbl[abn_tst_idx] # Abnormal training labels.\n\n # --\n # Assign labels to normal (0) and abnormals (1)\n nrm_trn_lbl[:] = 0\n nrm_tst_lbl[:] = 0\n abn_trn_lbl[:] = 1\n abn_tst_lbl[:] = 1\n\n # --\n if manualseed != -1:\n # Random seed.\n # Concatenate the original train and test sets.\n nrm_img = np.concatenate((nrm_trn_img, nrm_tst_img), axis=0)\n nrm_lbl = np.concatenate((nrm_trn_lbl, nrm_tst_lbl), axis=0)\n abn_img = np.concatenate((abn_trn_img, abn_tst_img), axis=0)\n abn_lbl = np.concatenate((abn_trn_lbl, abn_tst_lbl), axis=0)\n\n # Split the normal data into the new train and tests.\n idx = np.arange(len(nrm_lbl))\n np.random.seed(manualseed)\n np.random.shuffle(idx)\n\n nrm_trn_len = int(len(idx) * 0.80)\n nrm_trn_idx = idx[:nrm_trn_len]\n nrm_tst_idx = idx[nrm_trn_len:]\n\n nrm_trn_img = nrm_img[nrm_trn_idx]\n nrm_trn_lbl = nrm_lbl[nrm_trn_idx]\n nrm_tst_img = nrm_img[nrm_tst_idx]\n nrm_tst_lbl = nrm_lbl[nrm_tst_idx]\n\n # Create new anomaly dataset based on the following data structure:\n # - anomaly dataset\n # . -> train\n # . -> normal\n # . -> test\n # . -> normal\n # . -> abnormal\n new_trn_img = np.copy(nrm_trn_img)\n new_trn_lbl = np.copy(nrm_trn_lbl)\n new_tst_img = np.concatenate((nrm_tst_img, abn_trn_img, abn_tst_img), axis=0)\n new_tst_lbl = np.concatenate((nrm_tst_lbl, abn_trn_lbl, abn_tst_lbl), axis=0)\n\n return new_trn_img, new_trn_lbl, new_tst_img, new_tst_lbl\n\n","sub_path":"v1/libraries/model/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":35632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"30842999","text":"import os\nimport os.path\nimport ConfigParser\n\nRCNAME = os.path.expanduser('~/.vimpdbrc')\n\nDEFAULT_SCRIPT = os.environ.get(\"VIMPDB_VIMSCRIPT\", \"vim\")\nDEFAULT_SERVERNAME = os.environ.get(\"VIMPDB_SERVERNAME\", \"VIMPDB\")\nDEFAULT_PORT = 6666\n\n\nclass BadConfiguration(Exception):\n pass\n\n\nclass Config(object):\n\n def __init__(self, filename):\n self.filename = filename\n self.read_from_file()\n\n def read_from_file(self):\n if not os.path.exists(self.filename):\n self.write_to_file()\n parser = ConfigParser.RawConfigParser()\n parser.read(self.filename)\n if not parser.has_section('vimpdb'):\n raise BadConfiguration('[vimpdb] section is missing in \"%s\"' %\n self.filename)\n error_msg = (\"'%s' option is missing from section [vimpdb] in \"\n + \"'\" + self.filename + \"'.\")\n if parser.has_option('vimpdb', 'script'):\n self.script = parser.get('vimpdb', 'script')\n else:\n raise BadConfiguration(error_msg % 'script')\n if parser.has_option('vimpdb', 'server_name'):\n self.server_name = parser.get('vimpdb', 'server_name')\n else:\n raise BadConfiguration(error_msg % 'server_name')\n if parser.has_option('vimpdb', 'port'):\n self.port = parser.getint('vimpdb', 'port')\n else:\n raise BadConfiguration(error_msg % 'port')\n\n def write_to_file(self):\n parser = ConfigParser.RawConfigParser()\n parser.add_section('vimpdb')\n parser.set('vimpdb', 'script', DEFAULT_SCRIPT)\n parser.set('vimpdb', 'server_name', DEFAULT_SERVERNAME)\n parser.set('vimpdb', 'port', DEFAULT_PORT)\n rcfile = open(self.filename, 'w')\n parser.write(rcfile)\n rcfile.close()\n\n\ndef getConfiguration():\n return Config(RCNAME)\n","sub_path":"src/vimpdb/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"61209756","text":"# Simple car sim.\n\nimport pygame, sys\nimport numpy as np\nfrom pygame.locals import *\n\nFPS = 60\nfpsClock = pygame.time.Clock()\n\n# Setting up \"viewing window\"\nwinWidth = 400*4\nwinHeight = 300*4\nDISPLAYSURF = pygame.display.set_mode((winWidth,winHeight), 0, 32)\npygame.display.set_caption('Basic Animation')\nbackGndColor = (255,0,255)\n\n\n\n\n\nclass playerSprite:\n\n def __init__(self, imgWidth, imgHeight, spriteFolder):\n\n self.width = imgWidth\n self.height = imgHeight\n self.spriteFolder = spriteFolder\n\n # loading sprite images...\n\n # Thruster flame: #\n self.flameStep_1 = pygame.image.load(self.spriteFolder + 'thrusterFlame_01.png')\n self.flameStep_2 = pygame.image.load(self.spriteFolder + 'thrusterFlame_02.png')\n self.flameStep_3 = pygame.image.load(self.spriteFolder + 'thrusterFlame_03.png')\n self.flameStep_4 = pygame.image.load(self.spriteFolder + 'thrusterFlame_04.png')\n self.flameStep_5 = pygame.image.load(self.spriteFolder + 'thrusterFlame_05.png')\n self.flameStep_6 = pygame.image.load(self.spriteFolder + 'thrusterFlame_06.png')\n\n # Car body: #\n self.carBody = pygame.image.load(self.spriteFolder + 'car_body.png')\n\n\n # placing sprite in center of screen...\n\n self.xCoord = winWidth/2 - self.width/2\n self.yCoord = winHeight/2 - self.height/2\n\n self.theta = 0\n\n\n # variable for storing flame animation FSM state-value.\n\n self.flameState = 0\n\n # Variable for setting-up \"DriveCar\" method.\n\n self.fwd = 0\n\n\n #########################################\n # Method for transforming sprite assets #\n #########################################\n\n def TransformAsset(self, thatWhichMoves):\n spinner = pygame.transform.rotate(thatWhichMoves, self.theta)\n\n rotatedRect1 = spinner.get_rect()\n rotatedRect1.center = (self.xCoord + self.width/2, self.yCoord + self.height/2) # want to rotate about center of sprite (which just happens to be in the middle of the screen!)\n DISPLAYSURF.blit(spinner, rotatedRect1)\n\n\n #############################################\n # Methods for producing outputs for FSM ... #\n #############################################\n\n # functions for generating Sequential flame animation.\n # fs(n+1) : fs(n) & fs(n-1) & ... & fs(2) & fs(1)\n\n def fs1(self):\n self.TransformAsset(self.flameStep_1)\n def fs2(self):\n self.fs1()\n self.TransformAsset(self.flameStep_2)\n def fs3(self):\n self.fs2()\n self.TransformAsset(self.flameStep_3)\n def fs4(self):\n self.fs3()\n self.TransformAsset(self.flameStep_4)\n def fs5(self):\n self.fs4()\n self.TransformAsset(self.flameStep_5)\n def fs6(self):\n self.fs5()\n self.TransformAsset(self.flameStep_6)\n\n\n ########################################\n # FSM for animating the thruster flame #\n ########################################\n\n def animateflame(self):\n\n # Flame-animation FSM ... #\n\n if self.flameState == 0:\n #Do nothing\n self.flameState+=1\n\n elif self.flameState == 1:\n # Flame-layer 1\n self.flameState += 1\n self.fs1()\n\n elif self.flameState == 2:\n # Flame-layer 2\n self.flameState += 1\n self.fs2()\n\n elif self.flameState == 3:\n # Flame-layer 3\n self.flameState += 1\n self.fs3()\n\n elif self.flameState == 4:\n # Flame-layer 4\n self.flameState += 1\n self.fs4()\n\n elif self.flameState == 5:\n # Flame-layer 5\n self.flameState += 1\n self.fs5()\n\n elif self.flameState == 6:\n # Flame-layer 6; recycle to initial state when done.\n self.flameState = 0\n self.fs6()\n\n\n\n ###############################\n # Methods for controlling car #\n ###############################\n\n\n def terminal_vel(self, fwdStep):\n return fwdStep*5\n\n # positive factor = acceleratoin, negative factor = deceleration.\n def accelerate(self, factor=4.0):\n self.fwd += self.fwd*(factor/100)\n\n # Returns true if too fast!\n def tooFast(self, fwdStep):\n return self.fwd > self.terminal_vel(fwdStep)\n\n # Returns true if too slow!\n def tooSlow(self, fwdStep):\n return self.fwd < fwdStep\n\n\n ###############################\n # Main control method for car #\n ###############################\n\n def DriveCar(self, angleStep, fwdStep):\n\n # Check for key-presses.\n pressed = pygame.key.get_pressed()\n\n\n if pressed[K_LEFT]:\n self.theta += angleStep\n if pressed[K_RIGHT]:\n self.theta -= angleStep\n\n # Conditions for going forward: Up-arrow pressed, or speed is above increment value.\n if pressed[K_UP] or self.fwd > fwdStep:\n\n # Sanity check: has makes \"self.fwd\" equal fwdStep when it hasn't been assigned yet (check __init__).\n self.fwd = fwdStep if (self.fwd == 0) else self.fwd\n\n\n # If thruster is ON!\n if pressed[K_LSHIFT]:\n\n # Turn on thruster!\n self.animateflame()\n\n # Car can only accelerate up-to terminal_vel.\n if self.tooFast(fwdStep):\n\n self.fwd = self.terminal_vel(fwdStep)\n else:\n self.accelerate()\n\n # If thruster is Off, decelerate if too fast.\n else:\n\n if self.tooSlow(fwdStep):\n self.fwd = fwdStep\n else:\n self.accelerate(factor=-2.0)\n\n\n # Transforming the car's (x,y) coordinates depending on user-input.\n self.xCoord -= self.fwd*np.sin(self.theta*np.pi/180)\n self.yCoord -= self.fwd*np.cos(self.theta*np.pi/180)\n\n # Debugger.\n print(self.fwd)\n\n # if pressed[K_DOWN]:\n # self.xCoord += self.fwd*np.sin(self.theta*np.pi/180)\n # self.yCoord += self.fwd*np.cos(self.theta*np.pi/180)\n\n # Can Press ESC to quit game.\n if pressed[K_ESCAPE]:\n pygame.quit()\n sys.exit()\n\n\n\n#####################\n# INITIALIZE ASSETS #\n#####################\n\nmyCar = playerSprite(100,100,'./Sprites/')\n\n\n\n\n#############\n# GAME LOOP #\n#############\n\nwhile True:\n\n # Fill game window background with color!\n DISPLAYSURF.fill(backGndColor)\n\n # Call method for controlling car (rotation in steps of 5 deg, linear movement in steps of 5 pixels).\n myCar.DriveCar(5,5)\n\n # Apply coordinate-transformations to car and display it.\n myCar.TransformAsset(myCar.carBody)\n\n # CONDITIONS FOR EXITING GAME LOOP.\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n\n # UPDATE GRAPHICS AND INDUCE FPS DELAY.\n pygame.display.update()\n fpsClock.tick(FPS)\n","sub_path":"EngageThrusters/sourceCode_01.py","file_name":"sourceCode_01.py","file_ext":"py","file_size_in_byte":7029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"597536027","text":"from TwitterSearch import *\ndado = input('Qual dado você quer buscar? ')\nusuario = ''\nuser_list = ''\n\nkeys_file = open(\"keys\", 'r').readlines()\nkeys_file = [x.replace('\\n', '') for x in keys_file]\n\ntry:\n ts = TwitterSearch(\n consumer_key = keys_file[0],#Primeira linha do arquivo keys\n consumer_secret = keys_file[1],#Segunda linha do arquivo keys\n access_token = keys_file[2],#Terceira linha do arquivo keys\n access_token_secret = keys_file[3]#Quarta linha do arquivo keys\n )\n\n tso = TwitterSearchOrder ()\n tso.set_keywords([dado])\n tso.set_language('pt')\n\n for tweet in ts.search_tweets_iterable(tso):\n usuario = tweet['user']\n user_list += str(usuario)+'\\n'+'\\n'\n\n print('@%s tweeted: %s' % (tweet['user']['screen_name'], tweet['text']))\n\nexcept TwitterSearchException as e:\n print(e)\n\n#Conhecendo os id's mostrados.\nprint(len(user_list))\nprint(user_list)\n","sub_path":"Coletor/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"191121844","text":"from nltk.translate import AlignedSent, Alignment\nfrom nltk.translate.ibm1 import IBMModel1\nfrom nltk.translate.ibm2 import IBMModel2\nfrom nltk import word_tokenize\nfrom parse_data import *\nimport datetime\n\n\ndef IBM(target_listOflists_words, source_listOflists_words, flag):\n\t'''\n\tThis function takes parallel corpus as input and flag variable (1 for IBM Model 1 & 2 for IBM Model 2) and outputs \n\tthe alignments\n\t'''\n\n\tmodel1_output_list = []\n\n\tfor target_words,source_words in zip(target_listOflists_words, source_listOflists_words):\n\t\tmodel1_output_list.append(AlignedSent(target_words.split(),source_words.split()))\n\n\tif(flag==1):\n\t\tibm1 = IBMModel1(model1_output_list, 50)\n\telif(flag==2):\n\t\tibm2 = IBMModel2(model1_output_list, 50)\n\n\t#print(model1_output_list)\n\n\treturn model1_output_list\n\ndef tokenize(target_corpus, source_corpus):\n\t'''\n\tThis helper function tokenizes the sentences into words to be used as input for NLTK implementations\n\t'''\n\ttarget_listOflists_words = []\n\tsource_listOflists_words = []\n\tfor target_sent, source_sent in zip(target_corpus,source_corpus):\n\t\ttoken1 = word_tokenize(target_sent)\n\t\ttoken2 = word_tokenize(source_sent)\n\t\ttarget_listOflists_words.append(token1)\n\t\tsource_listOflists_words.append(token2)\n\n\t#print(target_listOflists_words)\n\t#print(\" \")\n\t#print(source_listOflists_words)\n\n\treturn target_listOflists_words,source_listOflists_words\n\nif __name__=='__main__':\n\tfilename='corpus/data1.json'\n\tparallel_corpus=load_data_from_json(filename)\n\t#Creating target and source corpus\n\ttarget_corpus=[]\n\tsource_corpus=[]\n\tfor sent_pair in parallel_corpus:\n\t\teng_sent=str(sent_pair['en'])\n\t\tfor_sent=str(sent_pair['fr'])\n\n\t\ttarget_corpus.append(for_sent)\n\t\tsource_corpus.append(eng_sent)\n\n\t#model1_raw_output = IBM([['klein', 'ist', 'das', 'haus'],['das', 'haus', 'ist', 'ja', 'gro'],['das', 'buch', 'ist', 'ja', 'klein'],['das', 'haus'],['das', 'buch'],['ein', 'buch']], [['the', 'house', 'is', 'small'], ['the', 'house', 'is', 'big'], ['the', 'book', 'is', 'small'], ['the', 'house'], ['the', 'book'], ['a', 'book']],1)\n\n\t#target_listOflists_words,source_listOflists_words = [\"la maison\",\"la fleur\",\"la maison bleu\",\"la fleur bleu\",\"pomme bleu\"],[\"the house\",\"the flower\",\"the blue house\",\"the blue flower\",\"blue apple\"]\n\t\n\t#target_listOflists_words,source_listOflists_words = tokenize(target_corpus,source_corpus)\n\n\ttarget_listOflists_words,source_listOflists_words = target_corpus,source_corpus\n\tt0 = datetime.datetime.now()\n\tmodel1_raw_output = IBM(target_listOflists_words, source_listOflists_words, 1)\n\tt1 = datetime.datetime.now()\n\tmodel2_raw_output = IBM(target_listOflists_words, source_listOflists_words, 2)\n\tt2 = datetime.datetime.now()\n\n\t#print(t1-t0)\n\t#print(t2-t1)\n\tif(filename=='corpus/data2.json'):\n\t\tprint(model2_raw_output)\n\telse:\n\n\t\tprint(\"##### MODEL 1 #####\")\n\t\tfor list in model1_raw_output:\n\t\t\tprint(list.words)\n\t\t\tprint(list.mots)\n\t\t\tprint(list.alignment)\n\t\t\tprint(\" \")\n\n\t\tprint(\" \")\n\t\tprint(\"##### MODEL 2 #####\")\t\n\n\n\t\tfor list in model2_raw_output:\n\t\t\t#print(list)\n\t\t\t\n\t\t\tprint(list.words)\n\t\t\tprint(list.mots)\n\t\t\tprint(list.alignment)\n\t\t\tprint(\" \")\n\t","sub_path":"comparison_nltk.py","file_name":"comparison_nltk.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"110205568","text":"import re\nfrom datetime import datetime\nimport time\nimport logging\nimport logging.handlers\n\nlogger = logging.getLogger(\"GROUPINGTAIL\")\n\nNUM32 = 2 ** 32\n\n\n# Parser parent class\nclass Instrument(object):\n def __init__(self, regex, maxgroups=64, value_cast=float, groupname=None):\n # Compiled regex\n self.test = re.compile(regex)\n # Maxim number of groups\n self.maxgroups = maxgroups\n # Cast function\n self.value_cast = value_cast\n # Regex groupname\n self.regex_group = groupname\n\n # Data collected and processed\n self.data = None\n # Groups timestamps\n self.groups = None\n\n # Reset data and groups structures\n self.reset()\n\n # Empty bucket and start again\n def reset(self):\n self.data = {}\n self.groups = {}\n\n # Mark groups tstamp\n def touch_group(self, groupname):\n self.groups[groupname] = datetime.now()\n\n # Trim groups which haven't been touched\n def trim_groups(self):\n items = self.groups.items()\n items.sort()\n self.groups = dict(items[:self.maxgroups])\n\n # Create newdata with only the members of self.groups and wrap around large integers\n def normalise(self):\n newdata = {}\n for groupname in self.groups.keys():\n newdata[groupname] = self.value_cast(self.data[groupname])\n self.data = newdata\n\n # Return the current results of the bucket\n def read(self):\n self.trim_groups()\n self.normalise()\n return self.data.items()\n\n # Do actual data analysis from line\n def append_data(self, groupname, line, mo):\n raise NotImplementedError()\n\n # Performs matching over line line and do proper analysis\n def write(self, groupname, line):\n # analise log line\n mo = self.test.match(line)\n # If matching\n if mo is not None:\n try:\n # Perform analysis\n self.append_data(groupname, line, mo)\n except ValueError:\n # Contemplated error\n pass\n except Exception as e:\n # The instrument has failed.\n self.reset()\n else:\n # Mark updated group\n self.touch_group(groupname)\n\n\n# Incremental Instrument from 0 with value of line matching\nclass GaugeInt(Instrument):\n def __init__(self, *args, **kwargs):\n # Lambda function to cast into a int\n kwargs[\"value_cast\"] = (lambda x: int(x) % NUM32)\n super(GaugeInt, self).__init__(*args, **kwargs)\n\n def read(self):\n # Return the current results of the bucket\n data_list = super(GaugeInt, self).read()\n\n # Empty bucket and start again\n self.reset()\n return data_list\n\n def append_data(self, groupname, line, mo):\n # Do actual data analysis from line\n if self.regex_group:\n # With groupname\n value = self.value_cast(mo.groupdict().get(self.regex_group))\n else:\n # First group\n value = self.value_cast(mo.groups()[0])\n\n # Update stored data\n self.data[groupname] = self.data.get(groupname, 0) + value\n\n\n# Throughput Instrument for one measurement\nclass GaugeThroughput(Instrument):\n def __init__(self, *args, **kwargs):\n self.grouptime = kwargs[\"grouptime\"]\n del kwargs[\"grouptime\"]\n # List indexs\n self.value_index = 0\n self.elapsed_index = 1\n super(GaugeThroughput, self).__init__(*args, **kwargs)\n\n def read(self):\n # Return the current results of the bucket\n data = super(GaugeThroughput, self).read()\n\n # Empty bucket and start again\n self.reset()\n return data\n\n def append_data(self, groupname, line, mo):\n # Do actual data analysis from line\n if self.regex_group is not None and self.grouptime is not None:\n # Extract value from line\n value = self.value_cast(mo.groupdict().get(self.regex_group))\n # Extract value from line\n elapsed = self.value_cast(mo.groupdict().get(self.grouptime))\n\n # Get current throughput info list\n current = self.data.get(groupname, [0, 0])\n # Increment bytes transferred\n current[self.value_index] += value\n # Increment time elapsed\n current[self.elapsed_index] += elapsed\n\n # Update stored data\n self.data[groupname] = current\n\n def normalise(self):\n # Create newdata with only the members of self.groups and wrap around large integers\n newdata = {}\n # For all groupingnames\n for groupname in self.groups.keys():\n # Get throughput info list\n sample_list = self.data[groupname]\n # Get total bytes transferred\n value = sample_list[self.value_index]\n # Get total time elapsed\n elapsed = sample_list[self.elapsed_index]\n # If elapsed is valid\n if elapsed > 0.0:\n # Perfom bandwidth calculation\n bw = value/elapsed\n else:\n # In case of invalid time set transferred bytes\n bw = value\n newdata[groupname] = bw\n\n # Update stored data\n self.data = newdata\n\n\n# Throughput Instrument for combination of measurements from two different positions\nclass GaugeTotalThroughput(GaugeThroughput):\n def __init__(self, *args, **kwargs):\n self.groupone = kwargs[\"groupone\"]\n self.groupother = kwargs[\"groupother\"]\n del kwargs[\"groupone\"]\n del kwargs[\"groupother\"]\n super(GaugeTotalThroughput, self).__init__(*args, **kwargs)\n\n def append_data(self, groupname, line, mo):\n # Do actual data analysis from line\n value = None\n if self.grouptime is not None:\n # Extract value from line\n elapsed = self.value_cast(mo.groupdict().get(self.grouptime))\n try:\n # Try to extract value one from line\n value = self.value_cast(mo.groupdict().get(self.groupone))\n except:\n try:\n # Try to extract value other from line\n value = self.value_cast(mo.groupdict().get(self.groupother))\n except:\n pass\n\n if value is not None:\n # Get current throughput info list\n current = self.data.get(groupname, [0, 0])\n # Increment bytes transferred\n current[self.value_index] += value\n # Increment time elapsed\n current[self.elapsed_index] += elapsed\n\n # Update stored data\n self.data[groupname] = current\n\n\n# AutoIncremental Instrument from 0 one by one\nclass CounterInc(Instrument):\n def __init__(self, *args, **kwargs):\n kwargs[\"value_cast\"] = (lambda x: int(x) % NUM32)\n super(CounterInc, self).__init__(*args, **kwargs)\n\n def append_data(self, groupname, line, mo):\n # Update stored data\n self.data[groupname] = self.data.get(groupname, 0) + 1\n\n def read(self):\n # Return the current results of the bucket\n data_list = super(CounterInc, self).read()\n\n # Empty bucket and start again\n self.reset()\n return data_list\n\n\n# Not tested\nclass CounterSum(Instrument):\n def append_data(self, groupname, line, mo):\n # Do actual data analysis from line\n minimum = self.value_cast(0)\n if self.regex_group:\n groups = mo.groupdict()\n value = self.value_cast(groups.get(self.regex_group))\n else:\n value = self.value_cast(mo.groups()[0])\n\n # Update stored data\n self.data[groupname] = self.data.get(groupname, minimum) + value\n\n\n# Not tested\nclass Max(GaugeInt):\n def append_data(self, groupname, line, mo):\n # Do actual data analysis from line\n if self.regex_group:\n value = self.value_cast(mo.groupdict().get(self.regex_group))\n else:\n value = self.value_cast(mo.groups()[0])\n current = self.data.get(groupname, None)\n if value > current or current is None:\n # Update stored data\n self.data[groupname] = value\n\n\n# Not tested\nclass DeriveCounter(CounterSum):\n def __init__(self, *args, **kwargs):\n kwargs[\"value_cast\"] = (lambda x: int(x) % NUM32)\n super(DeriveCounter, self).__init__(*args, **kwargs)\n self.last_read = None\n\n def reset(self):\n # Empty bucket and start again\n super(DeriveCounter, self).reset()\n self.last_read = None\n\n def read(self):\n # Return the current results of the bucket\n elapsed = 0\n now = time.time()\n if self.last_read is not None:\n elapsed = now - self.last_read\n self.last_read = now\n if elapsed <= 0:\n elapsed = 1.0\n data_list = super(DeriveCounter, self).read()\n\n samples = []\n for groupname, value in data_list:\n samples.append((groupname, value/elapsed))\n\n return samples\n","sub_path":"src/pretaweb/collectd/groupingtail/instruments.py","file_name":"instruments.py","file_ext":"py","file_size_in_byte":9131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"520804085","text":"from pyjarowinkler import distance\nimport stringdist\n\nblends = open(\"blends.txt\", \"r\")\nblends = blends.readlines()\n\nf2cand = open(\"fil_candidates.txt\", \"r\")\n\ndict = open(\"dict.txt\", \"r\")\ndict = dict.readlines()\n\nf2cand = f2cand.readlines()\nprint(len(f2cand))\n\n\ni = 0\ntarget = []\ns1 = []\ns2 = []\nfor i in range(len(blends)):\n h = blends[i].split()[0]\n target.append(h)\n\nprint(target)\n\ns = \"\\n\"\ndict = [x.rstrip(\"\\n\") for x in dict]\nprint(len(dict))\n\n\nimport random\n\n#train_set = random.sample(target, 20)\n# fixing the train set obtained randomly from the command above\ntrain_set = [\"gravator\", \"metroplex\", \"homeboy\", \"cheeseburger\", \"smush\", \"tweeple\", \"governator\", \"snazzy\", \"muppet\", \"payola\",\n \"sexpert\", \"telethon\", \"fantabulous\", \"flunk\", \"shim\", \"twitterati\", \"webisode\", \"frappuccino\", \"infomercial\", \"newbiew\"]\nprint(len(train_set))\n\ntrain_set = sorted(train_set)\nprint(train_set)\npre = []\nfor i in train_set:\n i = i[:3]\n pre.append(i)\nprint(pre)\nsuf = []\nfor i in train_set:\n i = i[-(len(i)-3):]\n suf.append(i)\nprint(suf)\n\n#cheeseburger\nl1 = [x for x in dict if x.startswith(pre[0]) or x.endswith(suf[0])]\nprint(len(l1))\nprint(l1)\n\nl1_rev = []\nfor i in range(len(l1)):\n if (round(distance.get_jaro_distance(train_set[0], l1[i]), 1)) >= 0.6 and stringdist.levenshtein(train_set[0], l1[i]) <= 5:\n l1_rev.append(l1[i])\nprint(len(l1_rev))\nprint(l1_rev)\n\n\n\n#fantabulous\nl2 = [x for x in dict if x.startswith(pre[1]) or x.endswith(suf[1])]\nprint(len(l2))\nprint(l2)\n\nl2_rev = []\nfor i in range(len(l2)):\n if (round(distance.get_jaro_distance(train_set[1], l2[i]), 1)) >= 0.6 and stringdist.levenshtein(train_set[1], l2[i]) >= 5:\n l2_rev.append(l2[i])\nprint(len(l2_rev))\nprint(l2_rev)\n\n#flunk\n\nl3 = [x for x in dict if x.startswith(pre[2]) or x.endswith(suf[2])]\nprint(len(l3))\nprint(l3)\n\nl3_rev = []\nfor i in range(len(l3)):\n if (round(distance.get_jaro_distance(train_set[2], l3[i]), 1)) >= 0.6 and stringdist.levenshtein(train_set[2], l3[i]) <= 5:\n l3_rev.append(l3[i])\nprint(len(l3_rev))\nprint(l3_rev)\n\n\n#frappuccino\nl4 = [x for x in dict if x.startswith(pre[3]) or x.endswith(suf[3])]\nprint(len(l4))\nprint(l4)\n\nl4_rev = []\nfor i in range(len(l4)):\n if (round(distance.get_jaro_distance(train_set[3], l4[i]), 1)) >= 0.6 and stringdist.levenshtein(train_set[3], l4[i]) <= 5:\n l4_rev.append(l4[i])\nprint(len(l4_rev))\nprint(l4_rev)\n\n#governator\n\nl5 = [x for x in dict if x.startswith(pre[4]) or x.endswith(suf[4])]\nprint(len(l5))\nprint(l5)\n\nl5_rev = []\nfor i in range(len(l5)):\n if (round(distance.get_jaro_distance(train_set[4], l5[i]), 1)) >= 0.6 and stringdist.levenshtein(train_set[4], l5[i]) <= 5:\n l5_rev.append(l5[i])\nprint(len(l5_rev))\nprint(l5_rev)\n\n#gravator\n\nl6 = [x for x in dict if x.startswith(pre[5]) or x.endswith(suf[5])]\nprint(len(l6))\nprint(l6)\n\nl6_rev = []\nfor i in range(len(l6)):\n if (round(distance.get_jaro_distance(train_set[5], l6[i]), 1)) >= 0.6 and stringdist.levenshtein(train_set[5], l6[i]) <= 5:\n l6_rev.append(l6[i])\nprint(len(l6_rev))\nprint(l6_rev)\n\n#homeboy\n\nl7 = [x for x in dict if x.startswith(pre[6]) or x.endswith(suf[6])]\nprint(len(l7))\nprint(l7)\n\nl7_rev = []\nfor i in range(len(l7)):\n if (round(distance.get_jaro_distance(train_set[6], l7[i]), 1)) >= 0.6 and stringdist.levenshtein(train_set[6], l7[i]) <= 5:\n l7_rev.append(l7[i])\nprint(len(l7_rev))\nprint(l7_rev)\n\n#infomercial\n\nl8 = [x for x in dict if x.startswith(pre[7]) or x.endswith(suf[7])]\nprint(len(l8))\nprint(l8)\n\nl8_rev = []\nfor i in range(len(l8)):\n if (round(distance.get_jaro_distance(train_set[7], l8[i]), 1)) >= 0.6 and stringdist.levenshtein(train_set[7], l8[i]) <= 5:\n l8_rev.append(l8[i])\nprint(len(l8_rev))\nprint(l8_rev)\n\n#metroplex\nl9 = [x for x in dict if x.startswith(pre[8]) or x.endswith(suf[8])]\nprint(len(l9))\nprint(l9)\n\nl9_rev = []\nfor i in range(len(l9)):\n if (round(distance.get_jaro_distance(train_set[8], l9[i]), 1)) >= 0.6 and stringdist.levenshtein(train_set[8], l9[i]) <= 5:\n l9_rev.append(l9[i])\nprint(len(l9_rev))\nprint(l9_rev)\n\n#muppet\n\nl10 = [x for x in dict if x.startswith(pre[9]) or x.endswith(suf[9])]\nprint(len(l10))\nprint(l10)\n\nl10_rev = []\nfor i in range(len(l10)):\n if (round(distance.get_jaro_distance(train_set[9], l10[i]), 1)) >= 0.6 and stringdist.levenshtein(train_set[9], l10[i]) <= 5:\n l10_rev.append(l10[i])\nprint(len(l10_rev))\nprint(l10_rev)\n\n#newbie\n\nl11 = [x for x in dict if x.startswith(pre[10]) or x.endswith(suf[10])]\nprint(len(l11))\nprint(l11)\n\nl11_rev = []\nfor i in range(len(l11)):\n if (round(distance.get_jaro_distance(train_set[10], l11[i]), 1)) >= 0.6 and stringdist.levenshtein(train_set[10], l11[i]) <= 5:\n l11_rev.append(l11[i])\nprint(len(l11_rev))\nprint(l11_rev)\n\n#payola\n\nl12 = [x for x in dict if x.startswith(pre[11]) or x.endswith(suf[11])]\nprint(len(l12))\nprint(l12)\n\nl12_rev = []\nfor i in range(len(l12)):\n if (round(distance.get_jaro_distance(train_set[11], l12[i]), 1)) >= 0.6 and stringdist.levenshtein(train_set[11], l12[i]) <= 5:\n l12_rev.append(l12[i])\nprint(len(l12_rev))\nprint(l12_rev)\n\n\n#sexpert\n\nl13 = [x for x in dict if x.startswith(pre[12]) or x.endswith(suf[12])]\nprint(len(l13))\nprint(l13)\n\nl13_rev = []\nfor i in range(len(l13)):\n if (round(distance.get_jaro_distance(train_set[12], l13[i]), 1)) >= 0.6 and stringdist.levenshtein(train_set[12], l13[i]) <= 5:\n l13_rev.append(l13[i])\nprint(len(l13_rev))\nprint(l13_rev)\n\n#shim\n\nl14 = [x for x in dict if x.startswith(pre[13]) or x.endswith(suf[13])]\nprint(len(l14))\nprint(l14)\n\nl14_rev = []\nfor i in range(len(l14)):\n if (round(distance.get_jaro_distance(train_set[13], l14[i]), 1)) >= 0.6 and stringdist.levenshtein(train_set[13], l14[i]) <= 5:\n l14_rev.append(l14[i])\nprint(len(l14_rev))\nprint(l14_rev)\n\n#smush\n\nl15 = [x for x in dict if x.startswith(pre[14]) or x.endswith(suf[14])]\nprint(len(l15))\nprint(l15)\n\nl15_rev = []\nfor i in range(len(l15)):\n if (round(distance.get_jaro_distance(train_set[14], l15[i]), 1)) >= 0.6 and stringdist.levenshtein(train_set[14], l15[i]) <= 5:\n l15_rev.append(l15[i])\nprint(len(l15_rev))\nprint(l15_rev)\n\n#snazzy\n\nl16 = [x for x in dict if x.startswith(pre[15]) or x.endswith(suf[15])]\nprint(len(l16))\nprint(l16)\n\nl16_rev = []\nfor i in range(len(l16)):\n if (round(distance.get_jaro_distance(train_set[15], l16[i]), 1)) >= 0.6 and stringdist.levenshtein(train_set[15], l16[i]) <= 5:\n l16_rev.append(l16[i])\nprint(len(l16_rev))\nprint(l16_rev)\n\n#telethon\n\nl17 = [x for x in dict if x.startswith(pre[16]) or x.endswith(suf[16])]\nprint(len(l17))\nprint(l17)\n\nl17_rev = []\nfor i in range(len(l17)):\n if (round(distance.get_jaro_distance(train_set[16], l17[i]), 1)) >= 0.6 and stringdist.levenshtein(train_set[16], l17[i]) <= 5:\n l17_rev.append(l17[i])\nprint(len(l17_rev))\nprint(l17_rev)\n\n#tweeple\n\nl18 = [x for x in dict if x.startswith(pre[17]) or x.endswith(suf[17])]\nprint(len(l18))\nprint(l18)\n\nl18_rev = []\nfor i in range(len(l18)):\n if (round(distance.get_jaro_distance(train_set[17], l18[i]), 1)) >= 0.6 and stringdist.levenshtein(train_set[17], l18[i]) <= 5:\n l18_rev.append(l18[i])\nprint(len(l18_rev))\nprint(l18_rev)\n\n#twitterati\n\nl19 = [x for x in dict if x.startswith(pre[18]) or x.endswith(suf[18])]\nprint(len(l19))\nprint(l19)\n\nl19_rev = []\nfor i in range(len(l19)):\n if (round(distance.get_jaro_distance(train_set[18], l19[i]), 1)) >= 0.6 and stringdist.levenshtein(train_set[18], l19[i]) <= 5:\n l19_rev.append(l19[i])\nprint(len(l19_rev))\nprint(l19_rev)\n\n#webisode\n\nl20 = [x for x in dict if x.startswith(pre[19]) or x.endswith(suf[19])]\nprint(len(l20))\nprint(l20)\n\nl20_rev = []\nfor i in range(len(l20)):\n if (round(distance.get_jaro_distance(train_set[19], l20[i]), 1)) >= 0.6 and stringdist.levenshtein(train_set[19], l20[i]) <= 5:\n l20_rev.append(l20[i])\nprint(len(l20_rev))\nprint(l20_rev)\n\n\npred = 5\ntrue = 20\n\naccuracy = 5*100/20\n\nprint(\"The accuracy is = \" + str(accuracy) + \"%\")","sub_path":"kt2.py","file_name":"kt2.py","file_ext":"py","file_size_in_byte":7992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"456473060","text":"import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\ndef applySettings(title):\n plt.xlabel('Cores')\n plt.ylabel('Execution Time (sec)')\n plt.title(title)\n plt.legend(loc=0)\n#8 processors per node, 7ppn, 1 comm\n\nf = open('scalabilitynums2.txt', 'r')\ntotlines = f.readline().split('\\r')\nfor run in range(1):\n plt.figure()\n line = totlines.pop(0).strip().split(',')\n size_labels = line[:2]\n line = totlines.pop(0).strip().split(',')\n sizes = line[:2]\n labels = totlines.pop(0).strip().split(',')\n data = []\n for i in range(4):\n data.append(map(float,totlines.pop(0).strip().split(',')))\n data = np.array(data)\n title = 'Strong Scaling with Multiple Images (' + sizes[1][:2] + ')\\n'\n title += size_labels[0] + ' = ' + sizes[0] + ', ' + size_labels[1] + ' = ' + sizes[1]\n plt.loglog(data[:,0], data[:,1], 'o-', label=labels[1], lw=3, basex=2, basey=2)\n plt.loglog(data[:,0], data[:,2], 'o-', label=labels[2], lw=3, basex=2, basey=2)\n plt.loglog(data[:,0], data[:,3], 'o-', label=labels[3], lw=3, basex=2, basey=2)\n slope1x = data[:,0]\n slope1y = data[:,0][::-1]\n maxbase = np.log2(data[0,2])\n xbase = np.log2(data[-1,0])\n plt.loglog(slope1x, slope1y*2**(maxbase-xbase-1), label='Linear Slope', lw=2, basex=2, basey=2)\n applySettings(title)\n fname = str(sizes[0]) + '_' + str(sizes[1]) + '.pdf'\n plt.savefig(fname)\n \n \n","sub_path":"results/multiple_images/plotgen.py","file_name":"plotgen.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"124632123","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 26 16:19:20 2020\n\n@author: Hawk Shaw\n\"\"\"\n\n\nimport sys\nimport socket\n\n\nclass PyClient():\n\n def __init__(self, host:str, port:int):\n self._host = host\n self._port = port\n self._client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self._connect()\n \n def _connect(self):\n try:\n self._client.connect((self._host, self._port))\n print(\"Socket connected, listening on %s:%d...\\n\" % (self._host, self._port))\n except:\n print(\"ERROR: No socket connection!\")\n\n def send(self, data:str, encoding:str=\"utf-8\"):\n try:\n self._client.send(data.encode(encoding))\n except:\n print(\"ERROR: Failed to send data to server!\")\n","sub_path":"PythonScript/pyclient.py","file_name":"pyclient.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"554757584","text":"# 导入模块\nfrom docx import Document\nimport re\nfrom docx.oxml.ns import qn\nfrom docx.shared import Pt\n\n# 加载原文档\ndocument = Document(\"../source_material/04/01一键拆分word文档/李白古诗大全.docx\")\n\n# 读取段落信息\nparagraph_list = []\nfor paragraph in document.paragraphs:\n if len(paragraph.text) != 0:\n paragraph_list.append(paragraph.text.strip())\n\n# 将下标放进去\nindex_value_list = []\nfor paragraph_value in paragraph_list:\n if paragraph_value[0].isdigit():\n index_value_list.append(paragraph_list.index(paragraph_value))\n\nfor index_num in index_value_list:\n if index_value_list.index(index_num)+1 < len(index_value_list):\n list_index = index_value_list[index_value_list.index(index_num)+1]\n\n # 创建word文档\n document = Document()\n\n # 设置全局字体\n document.styles['Normal'].font.name = \"宋体\"\n document.styles['Normal'].font.size = Pt(20)\n document.styles['Normal'].font._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')\n\n file_names = \"\"\n\n for i in range(index_num, list_index):\n # 判断每一段第一个字符是否为数字\n if paragraph_list[i][0].isdigit():\n file_names = re.sub(r\"[0-9]{1,2}|、\", \"\", paragraph_list[i])\n document.add_heading(file_names, 0)\n else:\n paragraph = document.add_paragraph(paragraph_list[i])\n\n document.save(\"../source_material/04/01一键拆分word文档/李白古诗/\" + file_names + \".docx\")\n print(file_names + \"正在保存中...\")\n","sub_path":"Python_Office_Automation/06-word自动化/04-一键搞定word文档/02-获取数字开头的下标.py","file_name":"02-获取数字开头的下标.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"257019966","text":"from PyQt5 import QtWidgets\r\nimport sys\r\n\r\nclass Window(QtWidgets.QMainWindow):\r\n\r\n def __init__(self):\r\n super(Window, self).__init__()\r\n\r\n self.setGeometry(50, 50, 500, 500)\r\n self.setWindowTitle(\"Menu Bars\")\r\n\r\n menu_item_1 = QtWidgets.QAction(\"Open\", self)\r\n menu_item_1.setShortcut(\"Ctrl+o\")\r\n menu_item_2 = QtWidgets.QAction(\"Exit\", self)\r\n menu_item_2.setShortcut(\"Ctrl+q\")\r\n menu_item_2.triggered.connect(self.close_app)\r\n\r\n menu_item_3 = QtWidgets.QAction(\"Cut\", self)\r\n menu_item_3.setShortcut(\"Ctrl+x\")\r\n\r\n menu_item_4 = QtWidgets.QAction(\"Copy\", self)\r\n menu_item_4.setShortcut(\"Ctrl+c\")\r\n\r\n menu_item_5 = QtWidgets.QAction(\"Paste\", self)\r\n menu_item_5.setShortcut(\"Ctrl+v\")\r\n\r\n self.statusBar()\r\n\r\n fileMenu = self.menuBar()\r\n mainMenu_1 = fileMenu.addMenu('File')\r\n mainMenu_1.addAction(menu_item_1)\r\n mainMenu_1.addAction(menu_item_2)\r\n\r\n mainMenu_2 = fileMenu.addMenu('Edit')\r\n mainMenu_2.addAction(menu_item_3)\r\n mainMenu_2.addAction(menu_item_4)\r\n mainMenu_2.addAction(menu_item_5)\r\n\r\n\r\n self.show()\r\n\r\n def close_app(self):\r\n choice = QtWidgets.QMessageBox.question(self, \"Quit\", \"Do you wanna quit ?\",\r\n QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)\r\n\r\n if choice == QtWidgets.QMessageBox.Yes:\r\n sys.exit()\r\n else:\r\n pass\r\n\r\n # sys.exit()\r\n\r\n\r\napp = QtWidgets.QApplication(sys.argv)\r\nGUI = Window()\r\nsys.exit(app.exec_())","sub_path":"Advance_Python/11-GUI/04-MenuBars.py","file_name":"04-MenuBars.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"612273809","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 20 15:52:06 2017\n\n@author: Diabetes.co.uk\n\"\"\"\n\n#this module need to be used at the start, it will automatically extract all of the\n#entities and nouns of the questions and answer, from the question and answers with class file,\n#and append them to create the sampledatabsecsv file\n#\n#parsing the first sentence of the answer and store it as a dataframe\n#this step can be omitted once we have a database that is annotated, and their features extracted.\n#then it can be a sql query instead of a python query\n#but this can be done using python, as the module can initiate by loading the database as a dataframe locally.\n#the pograms below will be focusing on extracting the adjectives and nouns and entities, and use those as search and match.\nimport pandas as pd\nimport nltk\nimport os\nimport sys\nos.chdir(os.path.dirname(sys.argv[0]))\nimport functions_for_extracting_pronouns_and_entities_using_api as extract\n\n\n################################################################\n##Parsing the 1st sentence of the answer and extracting the adjectives and nouns\n################################################################\n\nQuestions = pd.read_csv('CSVfiles\\\\QuestionsWithAnswersAndClassCSV.csv', index_col = 'ID', encoding = 'utf-8')\n\nAnswers = Questions['ANSWER']\nQuestionsonly = Questions['QUESTION']\n\nfirstsent = []\n\nfor row in Answers:\n results = nltk.sent_tokenize(row)\n firstsent.append(results[0].lower())\n \nQuestions['Answerfirstsent'] = firstsent\n\n#Extracting the adjectives, nouns, named entities of the sentences and storing it in new columns:\n \nAnswerAdjectives = []\nAnswerNouns = []\nAnswerEntities = []\n\nfor rows in firstsent:\n tokens1 = extract.get_tokens(rows)\n aNOUN = extract.Nounswords(tokens1)\n AnswerNouns.append(aNOUN)\n #Adjectives\n aADJECTIVE = extract.Adjectivewords(tokens1)\n AnswerAdjectives.append(aADJECTIVE) \n #Named entities\n named_entities1 = extract.entities_name1(rows)\n AnswerEntities.append(named_entities1)\n\nQuestionsAdjectives = []\nQuestionsNouns = []\nQuestionsEntities = []\n\nfor rows in Questionsonly:\n tokens1 = extract.get_tokens(rows)\n aNOUN = extract.Nounswords(tokens1)\n QuestionsNouns.append(aNOUN)\n #Adjectives\n aADJECTIVE = extract.Adjectivewords(tokens1)\n QuestionsAdjectives.append(aADJECTIVE) \n #Named entities\n named_entities1 = extract.entities_name1(rows)\n QuestionsEntities.append(named_entities1)\n\nQuestions['QuestionsAdjectives'] = QuestionsAdjectives\nQuestions['QuestionsNouns'] = QuestionsNouns\nQuestions['QuestionsEntities'] = QuestionsEntities\nQuestions['AnswerAdjectives'] = AnswerAdjectives\nQuestions['AnswerNouns'] = AnswerNouns\nQuestions['AnswerEntities'] = AnswerEntities\nQuestions.to_csv('CSVfiles\\\\sampledatabase.csv', encoding = 'utf-8')\n#this part will take a while, so ill omit those part of the code, and store and load the result as another csv file\n#can be implemented to parse a new annotated dataset\n\n","sub_path":"creating_initial_sampledatabase.py","file_name":"creating_initial_sampledatabase.py","file_ext":"py","file_size_in_byte":2985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"516037787","text":"\n# coding: utf-8\n\n# # Scraping Twitter Data\n# \n# This code comes from Shadab Hussain (https://github.com/shadab-entrepreneur). \n\n# In[9]:\n\n# Importing libraries\nimport json\nimport tweepy\nimport pandas as pd\nfrom datetime import date\nfrom tweepy import OAuthHandler\nfrom tweepy import Stream\nfrom tweepy.streaming import StreamListener\nimport re \nfrom textblob import TextBlob \n\n\n# # Twitter Text Sentiment Analysis: Correlation of neighborhoods in london vs sentiment\n# \n# Adapted from : https://www.geeksforgeeks.org/twitter-sentiment-analysis-using-python/\n# \n\n# In[10]:\n\nclass TwitterClient(object): \n ''' \n Generic Twitter Class for sentiment analysis. \n '''\n def __init__(self): \n ''' \n Class constructor or initialization method. \n '''\n # keys and tokens from the Twitter Dev Console \n consumer_key = 'Ue6lPHym1DacsbQtFPaFdjUgz'\n consumer_secret = 'yO096IxLzAxkEy2sSpZAJZU1F1hV1MP3lo4xeUfrc8ex71MjK5'\n access_token = '1042063897073733632-E9YhTYt11vut5OWUXUPUGujiAZbAcG'\n access_token_secret = 'R3ResgToyI5JV8KViGBXGqzgUappMDlcSFc1uEdwnXqIc'\n \n # attempt authentication \n try: \n # create OAuthHandler object \n self.auth = OAuthHandler(consumer_key, consumer_secret) \n # set access token and secret \n self.auth.set_access_token(access_token, access_token_secret) \n # create tweepy API object to fetch tweets \n self.api = tweepy.API(self.auth) \n except: \n print(\"Error: Authentication Failed\") \n \n def clean_tweet(self, tweet): \n ''' \n Utility function to clean tweet text by removing links, special characters \n using simple regex statements. \n '''\n return ' '.join(re.sub(\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t]) |(\\w+:\\/\\/\\S+)\", \" \", tweet).split()) \n \n def get_tweet_sentiment(self, tweet): \n ''' \n Utility function to classify sentiment of passed tweet \n using textblob's sentiment method - built on top of NLTK\n '''\n # create TextBlob object of passed tweet text \n analysis = TextBlob(self.clean_tweet(tweet)) \n # set sentiment \n if analysis.sentiment.polarity > 0: \n return 'positive'\n elif analysis.sentiment.polarity == 0: \n return 'neutral'\n else: \n return 'negative'\n \n def get_tweets(self, query, max_count = 200): \n ''' \n Main function to fetch tweets and parse them. \n '''\n # empty list to store parsed tweets \n tweets = [] \n \n try: \n # call twitter api to fetch tweets \n fetched_tweets = self.api.search(q = query, count = max_count) \n \n # parsing tweets one by one \n for tweet in fetched_tweets: \n # empty dictionary to store required params of a tweet \n parsed_tweet = {} \n \n # saving text of tweet \n parsed_tweet['text'] = tweet.text \n # saving sentiment of tweet \n parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text) \n \n # appending parsed tweet to tweets list \n if tweet.retweet_count > 0: \n # if tweet has retweets, ensure that it is appended only once \n if parsed_tweet not in tweets: \n tweets.append(parsed_tweet) \n else: \n tweets.append(parsed_tweet) \n \n # return parsed tweets \n return tweets \n \n except tweepy.TweepError as e: \n # print error (if any) \n print(\"Error : \" + str(e)) \n \n\n\n# In[11]:\n\n# I saved a list of london neighborhoods here\nwith open('London_Neighborhoods.txt') as inputfile: # try open('...', 'rb') as well\n london_neighborhoods = [line.strip() for line in inputfile]\nlondon_neighborhoods\n\n\n# In[14]:\n\nfrom datetime import date\ndf_total = pd.DataFrame(columns=['sentiment', 'text', 'query'])\n\ndef tweets_analysis_per_hashtag(my_query = 'bike', lower_bound = 50, upper_bound = 1000):\n global df_total\n # creating object of TwitterClient Class \n api = TwitterClient() \n # calling function to get tweets \n tweets = api.get_tweets(query = my_query) \n print(\"Found {} tweets with query: {}\".format(len(tweets), my_query))\n if len(tweets) < lower_bound:\n error_message = \"Query {} had only {} tweets, we want at least {}\".format(my_query, len(tweets), lower_bound)\n print(error_message)\n\n # Save as DF\n this_df = pd.DataFrame(tweets)\n this_df['query'] = my_query\n df_total = df_total.append(this_df)\n return df_total\n\n# example\n# df_total = tweets_analysis_per_hashtag(my_query = 'shoreditch', lower_bound = 40, upper_bound = 200)\n\n\n# In[15]:\n\nareas = ['shoreditch','dalston','brixton','peckham','camden','chelsea','clerkenwell','liverpool','Bethnal Green','Clapham','Kensington','City of London','soho']\nlondon_neighborhoods \nfor area in areas:\n df_total = tweets_analysis_per_hashtag(my_query = area, lower_bound = 40, upper_bound = 200)\n\n# save to CSV\ndf_total.to_csv('tweets_{}.csv'.format(str(date.today())))\nprint(\"done\")\n\n\n# In[16]:\n\ndf_total.groupby(['query','sentiment']).count()\n\n\n# In[17]:\n\nround(df_total.groupby(['query','sentiment']).count()/df_total[['query','text']].groupby(['query']).count(),2)\n\n\n# In[19]:\n\n# creating object of TwitterClient Class \n# Example of one neighborhood\napi = TwitterClient() \n# calling function to get tweets \ntweets = api.get_tweets(query = 'shoreditch') \n\n# picking positive tweets from tweets \nptweets = [tweet for tweet in tweets if tweet['sentiment'] == 'positive'] \n# percentage of positive tweets \nprint(\"Positive tweets percentage: {} %\".format(100*len(ptweets)/len(tweets))) \n# picking negative tweets from tweets \nntweets = [tweet for tweet in tweets if tweet['sentiment'] == 'negative'] \n# percentage of negative tweets \nprint(\"Negative tweets percentage: {}%\".format(100*len(ntweets)/len(tweets))) \n# percentage of neutral tweets \nprint(\"Neutral tweets percentage: {}%\".format(100*(len(tweets) - len(ntweets) - len(ptweets))/len(tweets))) \n\n# printing first 5 positive tweets \nprint(\"\\n\\n*Positive tweets*:\\n\") \nfor tweet in ptweets[:10]: \n print(tweet['text']) \n\n# printing first 5 negative tweets \nprint(\"\\n\\n*Negative tweets*:\\n\") \nfor tweet in ntweets[:10]: \n print(tweet['text']) \n\n\n# In[ ]:\n\n\n\n","sub_path":"scraping-twitter.py","file_name":"scraping-twitter.py","file_ext":"py","file_size_in_byte":6451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"118779105","text":"import maya.cmds as cmds\nimport maya.OpenMaya as om\nfrom functools import partial\nimport os, json, utility\n\nreload(utility)\n\nMAIN_PATH = os.path.dirname(__file__)+'/'\nCURVE_PATH = MAIN_PATH + 'curves/'\n\ndef replaceCurves(originCurve, targetCurve):\n snapPivot(originCurve, targetCurve)\n\n targetShape = utility.getShapes(targetCurve)\n if targetShape:\n cmds.delete(targetShape)\n\n curveShapes = utility.getShapes(originCurve)\n for curveShape in curveShapes:\n cmds.parent(curveShape, targetCurve, r=1, s=1)\n\n originCurve = utility.unParentToWorld([originCurve])\n # delect\n cmds.delete(originCurve)\n\n cmds.select(targetCurve)\n\n\ndef mergeCurves(curves):\n curves = utility.unParentToWorld(curves)\n\n for curve in curves:\n cmds.makeIdentity(curve, a=1)\n cmds.bakePartialHistory(curve, pc=1)\n\n # set newTransform as first in selection\n groupTransform = curves[0]\n\n # get groupTransform\n grp = cmds.group(em=1)\n #cmds.matchTransform(grp, groupTransform)\n groupTransform = grp\n\n for curve in curves:\n # make sure curveShapes don't move\n cmds.makeIdentity(curve, a=1)\n\n # merge to groupTransform\n curveShapes = utility.getShapes(curve)\n for curveShape in curveShapes:\n cmds.parent(curveShape, groupTransform, r=1, s=1)\n\n # delect rest\n cmds.delete(curve)\n\n # center pivot and clear history\n cmds.xform(groupTransform, cp=1)\n cmds.bakePartialHistory(groupTransform, pc=1)\n cmds.select(groupTransform)\n\ndef groupIt(ctls, mode=0,*arg):\n \n if mode:\n ctls, SAVE_LIST = utility.unParentToWorld(ctls, parentChild=0, save=1, disconnect=1)\n else:\n ctls, SAVE_LIST = utility.unParentToWorld(ctls, parentChild=0, save=1, disconnect=0)\n print(SAVE_LIST)\n for inx, ctl in enumerate(ctls):\n # identity scale\n cmds.makeIdentity(ctl, a=1, s=1)\n # create group\n grp = cmds.group(em=1)\n\n # parent ctl to grp\n cmds.matchTransform(grp, ctl)\n ctls[inx] = cmds.parent(ctl, grp)[0]\n\n # reparent the grp\n ctls = utility.reparentToOrigin(SAVE_LIST, relatedObjs = ctls)\n\n group_list=[]\n # rename all\n uCtls = cmds.ls(ctls, uid=1)\n for uCtl in uCtls:\n ctl = cmds.ls(uCtl, l=1)[0]\n grp = utility.getPrt(ctl)\n\n ctl_name = ctl.split(\"|\")[-1]\n grp = cmds.rename(grp, ctl_name+\"_grp\")\n group_list.append(grp)\n ctls = cmds.ls(uCtls, l=1)\n\n cmds.select(ctls)\n\n return group_list\n \n\ndef spaceSwitchSetup(targets, contained):\n contained_grp = utility.getPrt(contained)\n if not contained_grp or utility.getShapes(contained_grp):\n contained_grp = groupIt([contained])[0]\n\n select_list = []\n\n # check if it already parentconstrainted\n constraint = cmds.listConnections(\n \"%s.translateX\" % contained_grp, d=0, s=1)\n oldLoc = ''\n loc_name = contained.split(\"|\")[-1].split(\":\")[-1] + '_loc'\n if constraint:\n constraint = constraint[0]\n\n loc_weight_name = cmds.listAttr(constraint, st=loc_name+\"*\", ud=1)\n print(loc_name)\n print(loc_weight_name)\n if loc_weight_name:\n target_name = cmds.listConnections(\n constraint+'.'+loc_weight_name[0], d=1, s=0, p=1)[0]\n target_name = target_name.replace(\n 'targetWeight', 'targetTranslate')\n oldLoc = cmds.listConnections(target_name, d=0, s=1)[0]\n\n if not oldLoc:\n loc = cmds.spaceLocator(name=loc_name)[0]\n cmds.matchTransform(loc, contained_grp)\n contained_grp_prt = utility.getPrt(contained_grp)\n if contained_grp_prt:\n loc = cmds.parent(loc, contained_grp_prt)[0]\n\n cmds.setAttr(\"%s.v\"%loc, 0)\n utility.fixedObj([loc])\n\n oldLoc = loc\n\n print(oldLoc)\n select_list.append(oldLoc)\n loc_name = oldLoc.split(\"|\")[-1].split(\":\")[-1]\n print(loc_name)\n\n for target in targets:\n select_list.append(target)\n\n select_list.append(contained_grp)\n\n cmds.select(cl=1)\n for obj in select_list:\n cmds.select(obj, add=1)\n\n constraint = cmds.parentConstraint(mo=1)[0]\n\n target_list = cmds.listAttr(constraint, st=\"*W*\", ud=1)\n print(target_list)\n\n # edit enum\n enumName = ''\n parentInx = 0\n for inx, target in enumerate(target_list):\n if loc_name == target[0:-2]:\n parentInx = inx\n enumName = enumName + \":origin\"\n else:\n enumName = enumName + \":\" + target[0:-2]\n\n enumName = enumName[1:]\n\n if cmds.attributeQuery('follow', node=contained, ex=1):\n # edit\n cmds.addAttr(\"%s.follow\" % contained, k=1, e=1,\n ln=\"follow\", at=\"enum\", en=enumName)\n else:\n # create\n cmds.addAttr(contained, k=1, ln=\"follow\", at=\"enum\", en=enumName)\n\n # set to parent as defualt\n cmds.setAttr(\"%s.follow\" % contained, parentInx)\n\n condition_nodes = cmds.listConnections(\"%s.follow\" % contained, d=1, s=0)\n # print(condition_nodes)\n if condition_nodes:\n for nodes in condition_nodes:\n cmds.delete(nodes)\n # connect node\n for inx, target in enumerate(target_list):\n condition_node = cmds.shadingNode(\"condition\", au=1)\n\n cmds.connectAttr(\"%s.follow\" % contained,\n \"%s.firstTerm\" % condition_node, f=1)\n\n weight_name = constraint+\".\"+target\n\n cmds.connectAttr(\"%s.outColorR\" % condition_node, weight_name, f=1)\n cmds.setAttr(\"%s.secondTerm\" % condition_node, inx)\n cmds.setAttr(\"%s.operation\" % condition_node, 1)\n \n cmds.select(contained)\n\n\ndef changeSpace(obj, inx, *arg):\n loc = cmds.spaceLocator()\n cmds.matchTransform(loc, obj)\n\n cmds.setAttr(\"%s.follow\" % obj, inx)\n\n cmds.matchTransform(obj, loc)\n cmds.delete(loc)\n cmds.select(obj)\n\n\ndef saveTransform(obj):\n loc = cmds.ls(\"xLEAVEMEALONE\")\n if loc:\n cmds.iconTextButton(\n 'btnSaveLoadTransform',\n e=1,\n image='save_transform.png'\n )\n loc = cmds.ls(\"xLEAVEMEALONE\")\n cmds.matchTransform(obj, loc)\n cmds.delete(loc)\n cmds.select(obj)\n else:\n cmds.iconTextButton(\n 'btnSaveLoadTransform',\n e=1,\n image='load_transform.png'\n )\n loc = cmds.spaceLocator(name=\"xLEAVEMEALONE\")[0]\n cmds.matchTransform(loc, obj)\n cmds.setAttr(\"%s.v\"%loc, 0)\n utility.fixedObj([loc])\n cmds.select(obj)\n\ndef snapTransform(obj, tar):\n if '.vtx[' in tar:\n cmds.select(cl=1)\n cmds.select(tar)\n cmds.select(obj, add=1)\n constraint = cmds.pointOnPolyConstraint(mo=0)\n cmds.delete(constraint)\n else:\n cmds.matchTransform(obj, tar)\n \n cmds.select(obj)\n\n\ndef snapPivot(obj, tar):\n isVertex = False\n if '.vtx[' in tar:\n isVertex = True\n loc = cmds.spaceLocator()\n cmds.select(cl=1)\n cmds.select(tar)\n cmds.select(loc, add=1)\n constraint = cmds.pointOnPolyConstraint(mo=0)\n cmds.delete(constraint)\n tar = loc[0]\n\n objs, SAVE_LIST = utility.unParentToWorld([obj], parentChild=0, save=1, relatedObjs=[obj, tar])\n obj = objs[0]\n tar = objs[1]\n\n pivotT = cmds.xform(tar, q=1, ws=1, rp=1)\n\n obj = cmds.parent(obj, tar)\n\n cmds.makeIdentity(obj, a=1, t=1, r=1, s=1)\n cmds.xform(obj, ws=1, piv=pivotT)\n \n obj = cmds.parent(obj, w=1)\n\n # reparent\n utility.reparentToOrigin(SAVE_LIST)\n\n if isVertex:\n cmds.delete(tar)\n \n cmds.select(obj)\n\n\ndef polyToCurve(*args):\n cmds.polyToCurve(form=2, degree=1, conformToSmoothMeshPreview=1)\n cmds.bakePartialHistory(pc=1)\n\n\ndef polyToCurveS(*args):\n cmds.polyToCurve(form=2, degree=3, conformToSmoothMeshPreview=1)\n cmds.bakePartialHistory(pc=1)\n\n\ndef displayAll(*args):\n panel = cmds.getPanel(wf=1)\n print(panel)\n cmds.modelEditor(panel, e=1, alo=1)\n\n\ndef displayMeshCurve(*args):\n panel = cmds.getPanel(wf=1)\n print(panel)\n cmds.modelEditor(panel, e=1, alo=0)\n cmds.modelEditor(panel, e=1, pm=1, nc=1)\n\n\ndef displayMesh(*args):\n panel = cmds.getPanel(wf=1)\n print(panel)\n cmds.modelEditor(panel, e=1, alo=0)\n cmds.modelEditor(panel, e=1, pm=1)\n\n\ndef doToggleLocalAxis(objs, showOrHide):\n operateOn = cmds.checkBox(\"chbAllOrSelected\", q=True, v=True)\n if operateOn == 1:\n # Hierarchy\n cmds.select(hi=True)\n objs = cmds.ls(sl=1)\n else:\n # Selected\n objs = cmds.ls(sl=1)\n\n for obj in objs:\n cmds.toggle(obj, localAxis=True, state=showOrHide)\n \n cmds.select(objs)\n\n\ndef zeroAll(objs):\n cmds.xform(objs, t=(0, 0, 0), ro=(0, 0, 0), s=(1, 1, 1))\n\n\n\ndef createCurves(shapes, color, name=\"\"):\n list = []\n for shape in shapes:\n if name:\n crv = cmds.curve(\n n=name,\n p=shape['points'],\n d=shape['degree'],\n k=shape['knot']\n )\n else:\n crv = cmds.curve(\n p=shape['points'],\n d=shape['degree'],\n k=shape['knot']\n )\n list.append(crv)\n\n for x in range(len(list)-1):\n cmds.makeIdentity(list[x+1], apply=True, t=1, r=1, s=1, n=0)\n shapes = utility.getShapes(list[x+1])\n cmds.parent(shapes, list[0], add=1, s=1)\n cmds.delete(list[x+1])\n\n utility.applyColor(list[0], color)\n cmds.select(list[0])\n return list[0]\n\n\ndef applyCurvesColor(color, *args):\n sl = cmds.ls(sl=1)\n\n if len(sl) < 1:\n return False\n\n for curve in sl:\n shapes = utility.getShapes(curve)\n for shape in shapes:\n if cmds.objectType(shape, i='nurbsCurve'):\n utility.applyColor(curve, color)\n\n\ndef saveCurve(curve):\n shapes = utility.getShapes(curve)\n name = curve.split(\"|\")[-1]\n info = {}\n info['name'] = name\n info['icon'] = name+'.png'\n info['shape'] = []\n for shape in shapes:\n curveInfo = cmds.shadingNode(\"curveInfo\", au=1)\n cmds.connectAttr(shape+'.worldSpace[0]', curveInfo+'.inputCurve', f=1)\n shapeinfo = {\n 'points': cmds.getAttr(curveInfo+'.cp[:]'),\n 'degree': cmds.getAttr(shape+'.degree'),\n 'knot': cmds.getAttr(curveInfo+'.knots[:]')\n }\n # print(cmds.getAttr(curveInfo+'.cp[:]'))\n # print(cmds.getAttr(shape+'.degree'))\n # print(cmds.getAttr(curveInfo+'.knots[:]'))\n cmds.delete(curveInfo)\n info['shape'].append(shapeinfo)\n cmds.select(curve)\n json_path = CURVE_PATH + '%s.json' % name\n img_path = CURVE_PATH + '%s.png' % name\n\n with open(json_path, 'w') as f:\n json.dump(info, f)\n\n window = cmds.window(w=120, h=131)\n cmds.paneLayout()\n panel = cmds.modelPanel()\n editor = cmds.modelPanel(panel, me=1, q=1)\n cmds.modelEditor(editor, e=1)\n cmds.modelEditor(editor, e=1, grid=0, hud=0,\n manipulators=0, selectionHiliteDisplay=1)\n cmds.isolateSelect(panel, state=1)\n cmds.isolateSelect(panel, loadSelected=True)\n\n cmds.showWindow(window)\n cmds.setFocus(panel)\n cmds.viewFit(curve)\n cmds.refresh(cv=True, fe=\"png\", fn=img_path)\n cmds.isolateSelect(panel, state=0)\n cmds.deleteUI(window)\n\n return info\n\n\ndef orientJoint(jointsToOrient, aimAxis, upAxis, worldUp, guessUp):\n firstPass = 0\n prevUpVector = [0, 0, 0]\n for eachJoint in jointsToOrient:\n childJoints = utility.getChl(eachJoint,type=\"joint\")\n if childJoints:\n \n # Store the name in case when unparented it changes it's name.\n childJoints = cmds.parent(childJoints, w=1)\n print(childJoints)\n\n upDirRecalculated = [0,0,0]\n\n if guessUp == 0:\n # Not guess Up direction\n\n cmds.delete(cmds.aimConstraint(childJoints[0], eachJoint, w=1, o=(0, 0, 0), aim=aimAxis, upVector=upAxis, worldUpVector=worldUp, worldUpType=\"vector\"))\n _freezeJointOrientation(eachJoint)\n childJoints = cmds.parent(childJoints, eachJoint)\n else:\n # Guess Up direction\n parentJoint = utility.getPrt(eachJoint,type=\"joint\")\n if parentJoint:\n posCurrentJoint = cmds.xform(eachJoint, q=True, ws=True, rp=True)\n posParentJoint = cmds.xform(parentJoint, q=True, ws=True, rp=True)\n tolerance = 0.0001\n\n if (abs(posCurrentJoint[0] - posParentJoint[0]) <= tolerance and abs(posCurrentJoint[1] - posParentJoint[1]) <= tolerance and abs(posCurrentJoint[2] - posParentJoint[2]) <= tolerance):\n aimChild = utility.getChl(childJoints[0],type=\"joint\")\n upDirRecalculated = _crossProduct(eachJoint, childJoints[0], aimChild[0])\n cmds.delete(cmds.aimConstraint(childJoints[0], eachJoint, w=1, o=(0, 0, 0), aim=aimAxis, upVector=upAxis, worldUpVector=upDirRecalculated, worldUpType=\"vector\"))\n else:\n upDirRecalculated = _crossProduct(parentJoint, eachJoint, childJoints[0])\n cmds.delete(cmds.aimConstraint(childJoints[0], eachJoint, w=1, o=(0, 0, 0), aim=aimAxis, upVector=upAxis, worldUpVector=upDirRecalculated, worldUpType=\"vector\"))\n else:\n aimChild = utility.getChl(childJoints[0],type=\"joint\")\n upDirRecalculated = _crossProduct(eachJoint, childJoints[0], aimChild[0])\n cmds.delete(cmds.aimConstraint(childJoints[0], eachJoint, w=1, o=(0, 0, 0), aim=aimAxis, upVector=upAxis, worldUpVector=upDirRecalculated, worldUpType=\"vector\"))\n\n dotProduct = utility.vectorDot(upDirRecalculated, prevUpVector)\n\n # For the next iteration\n prevUpVector = upDirRecalculated\n\n if firstPass > 0 and dotProduct <= 0.0:\n # dotProduct\n cmds.xform(eachJoint, r=1, os=1, ra=(\n aimAxis[0] * 180.0, aimAxis[1] * 180.0, aimAxis[2] * 180.0))\n prevUpVector[0] *= -1\n prevUpVector[1] *= -1\n prevUpVector[2] *= -1\n\n _freezeJointOrientation(eachJoint)\n childJoints = cmds.parent(childJoints, eachJoint)\n else:\n # Child joint. Use the same rotation as the parent.\n parentJoint = utility.getPrt(eachJoint,type=\"joint\")\n if parentJoint != None:\n if len(parentJoint) > 0:\n cmds.delete(cmds.orientConstraint(parentJoint, eachJoint, w=1, o=(0, 0, 0)))\n _freezeJointOrientation(eachJoint)\n\n firstPass += 1\n \n cmds.select(jointsToOrient)\n\n\ndef _crossProduct(firstObj, secondObj, thirdObj):\n # We have 3 points in space so we have to calculate the vectors from\n # the secondObject (generally the middle joint and the one to orient)\n # to the firstObject and from the secondObject to the thirdObject.\n xformFirstObj = cmds.xform(firstObj, q=True, ws=True, rp=True)\n xformSecondObj = cmds.xform(secondObj, q=True, ws=True, rp=True)\n xformThirdObj = cmds.xform(thirdObj, q=True, ws=True, rp=True)\n\n vectorA = utility.vectorAdd(xformFirstObj, xformSecondObj, False)\n vectorB = utility.vectorAdd(xformThirdObj, xformSecondObj, False)\n return utility.vectorCross(vectorA, vectorB)\n\n\ndef _freezeJointOrientation(jointToOrient):\n cmds.joint(jointToOrient, e=True, zeroScaleOrient=True)\n cmds.makeIdentity(jointToOrient, apply=True, t=0, r=1, s=0, n=0)\n\n\ndef rotateOrder(jointsToOrient, aimAxis, upAxis):\n rotate_order = ''\n if upAxis == [1, 0, 0]:\n if aimAxis == [0, 1, 0]:\n rotate_order = 'yzx'\n else:\n rotate_order = 'zyx'\n\n elif upAxis == [0, 1, 0]:\n if aimAxis == [1, 0, 0]:\n rotate_order = 'xzy'\n else:\n rotate_order = 'zxy'\n\n else:\n if aimAxis == [1, 0, 0]:\n rotate_order = 'xyz'\n else:\n rotate_order = 'yxz'\n\n cmds.xform(jointsToOrient, p=1, rotateOrder=rotate_order)\n\ndef mirrorJoint(mirrorMode, mirrorPlane, aimAxis, upAxis, replace):\n if mirrorMode == 1:\n cmds.select(hi=True)\n uOrigin = cmds.ls(sl=1, uid=1)\n # print(uOrigin)\n origin = cmds.ls(uOrigin[0], l=1)[0]\n cmds.select(origin)\n mirrored = _mirrorJoint(mirrorPlane, True, replace)\n # print(mirrored)\n\n for inx, jnt in enumerate(mirrored):\n origin = cmds.ls(uOrigin[inx], l=1)[0]\n # print(origin)\n objUp = utility.getVector(origin, upAxis)\n if mirrorPlane == 1:\n objUp[0] = -objUp[0]\n objUp[1] = -objUp[1]\n elif mirrorPlane == 2:\n objUp[1] = -objUp[1]\n objUp[2] = -objUp[2]\n elif mirrorPlane == 3:\n objUp[0] = -objUp[0]\n objUp[2] = -objUp[2]\n\n print(objUp)\n orientJoint([jnt], aimAxis, upAxis, objUp, False)\n\n elif mirrorMode == 2:\n _mirrorJoint(mirrorPlane, True, replace)\n elif mirrorMode == 3:\n _mirrorJoint(mirrorPlane, False, replace)\n\ndef _mirrorJoint(mirrorPlane, behavior, replace):\n if mirrorPlane == 1:\n return cmds.mirrorJoint(mirrorXY=1, mirrorBehavior=behavior, searchReplace=replace)\n elif mirrorPlane == 2:\n return cmds.mirrorJoint(mirrorYZ=1, mirrorBehavior=behavior, searchReplace=replace)\n elif mirrorPlane == 3:\n return cmds.mirrorJoint(mirrorXZ=1, mirrorBehavior=behavior, searchReplace=replace)\n","sub_path":"scripts/icrdrTools/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":17744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"47336826","text":"# A Peterson Graph Problem\n# https://www.geeksforgeeks.org/peterson-graph/\n\n# Python3 program to find the\n# path in Peterson graph\n# path to be checked\n\n# adjacency matrix.\nadj = [[False for i in range(10)] for j in range(10)]\n\n# resulted path - way\nresult = [0]\n\n\n# we are applying breadth first search\n# here\ndef findthepath(S, v):\n result[0] = v\n for i in range(1, len(S)):\n\n # first traverse the outer graph\n if adj[v][ord(S[i]) - ord(\"A\")] or adj[ord(S[i]) - ord(\"A\")][v]:\n v = ord(S[i]) - ord(\"A\")\n\n # then traverse the inner graph\n elif adj[v][ord(S[i]) - ord(\"A\") + 5] or adj[ord(S[i]) - ord(\"A\") + 5][v]:\n v = ord(S[i]) - ord(\"A\") + 5\n\n # if the condition failed to satisfy\n # return false\n else:\n return False\n\n result.append(v)\n\n return True\n\n\n# driver code\n# here we have used adjacency matrix to make\n# connections between the connected nodes\nif __name__ == \"__main__\":\n adj[0][1] = adj[1][2] = adj[2][3] = adj[3][4] = adj[4][0] = adj[0][5] = adj[1][\n 6\n ] = adj[2][7] = adj[3][8] = adj[4][9] = adj[5][7] = adj[7][9] = adj[9][6] = adj[6][\n 8\n ] = adj[\n 8\n ][\n 5\n ] = True\n\n # path to be checked\n S = \"ABB\"\n S = list(S)\n if findthepath(S, ord(S[0]) - ord(\"A\")) or findthepath(S, ord(S[0]) - ord(\"A\") + 5):\n print(*result, sep=\"\")\n else:\n print(\"-1\")\n","sub_path":"09.Graphs/23_peterson_problem.py","file_name":"23_peterson_problem.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"238397833","text":"'''\nName: plot_lead_average.py\nContact(s): Mallory Row\nAbstract: Reads average and CI files from plot_time_series.py to make dieoff plots\nHistory Log: Third version\nUsage: Called by make_plots_wrapper.py \nParameters: None\nInput Files: Text files\nOutput Files: .png images\nCondition codes: 0 for success, 1 for failure\n'''\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport itertools\nimport warnings\nimport logging\nimport datetime\nimport re\nimport sys\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as md\n\nimport plot_util as plot_util\nfrom plot_util import get_ci_file, get_lead_avg_file\n\n# add metplus directory to path so the wrappers and utilities can be found\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__),\n '..',\n '..')))\nfrom metplus.util import do_string_sub\n\n# Read environment variables set in make_plots_wrapper.py\nverif_case = os.environ['VERIF_CASE']\nverif_type = os.environ['VERIF_TYPE']\ndate_type = os.environ['DATE_TYPE']\nvalid_beg = os.environ['VALID_BEG']\nvalid_end = os.environ['VALID_END']\ninit_beg = os.environ['INIT_BEG']\ninit_end = os.environ['INIT_END']\nfcst_valid_hour_list = os.environ['FCST_VALID_HOUR'].split(', ')\nfcst_valid_hour = os.environ['FCST_VALID_HOUR']\nfcst_init_hour_list = os.environ['FCST_INIT_HOUR'].split(', ')\nfcst_init_hour = os.environ['FCST_INIT_HOUR']\nobs_valid_hour_list = os.environ['OBS_VALID_HOUR'].split(', ')\nobs_valid_hour = os.environ['OBS_VALID_HOUR']\nobs_init_hour_list = os.environ['OBS_INIT_HOUR'].split(', ')\nobs_init_hour = os.environ['OBS_INIT_HOUR']\nfcst_lead_list = [os.environ['FCST_LEAD'].split(', ')]\nfcst_var_name = os.environ['FCST_VAR']\nfcst_var_units = os.environ['FCST_UNITS']\nfcst_var_level_list = os.environ['FCST_LEVEL'].split(', ')\nfcst_var_thresh_list = os.environ['FCST_THRESH'].split(', ')\nobs_var_name = os.environ['OBS_VAR']\nobs_var_units = os.environ['OBS_UNITS']\nobs_var_level_list = os.environ['OBS_LEVEL'].split(', ')\nobs_var_thresh_list = os.environ['OBS_THRESH'].split(', ')\ninterp_mthd = os.environ['INTERP_MTHD']\ninterp_pnts = os.environ['INTERP_PNTS']\nvx_mask = os.environ['VX_MASK']\nalpha = os.environ['ALPHA']\ndesc = os.environ['DESC']\nobs_lead = os.environ['OBS_LEAD']\ncov_thresh = os.environ['COV_THRESH']\nstats_list = os.environ['STATS'].split(', ')\nmodel_list = os.environ['MODEL'].split(', ')\nmodel_obtype_list = os.environ['MODEL_OBTYPE'].split(', ')\nmodel_reference_name_list = os.environ['MODEL_REFERENCE_NAME'].split(', ')\ndump_row_filename_template = os.environ['DUMP_ROW_FILENAME']\naverage_method = os.environ['AVERAGE_METHOD']\nci_method = os.environ['CI_METHOD']\nverif_grid = os.environ['VERIF_GRID']\nevent_equalization = os.environ['EVENT_EQUALIZATION']\nmet_version = os.environ['MET_VERSION']\ninput_base_dir = os.environ['INPUT_BASE_DIR']\noutput_base_dir = os.environ['OUTPUT_BASE_DIR']\nlog_metplus = os.environ['LOG_METPLUS']\nlog_level = os.environ['LOG_LEVEL']\n\n# General set up and settings\n# Plots\nwarnings.filterwarnings('ignore')\nplt.rcParams['font.weight'] = 'bold'\nplt.rcParams['axes.labelsize'] = 15\nplt.rcParams['axes.labelweight'] = 'bold'\nplt.rcParams['xtick.labelsize'] = 15\nplt.rcParams['ytick.labelsize'] = 15\nplt.rcParams['axes.titlesize'] = 15\nplt.rcParams['axes.titleweight'] = 'bold'\nplt.rcParams['axes.formatter.useoffset'] = False\ncolors = [\n '#000000', '#2F1E80', '#D55E00', '#882255', \n '#018C66', '#D6B616', '#036398', '#CC79A7'\n]\n# Logging\nlogger = logging.getLogger(log_metplus)\nlogger.setLevel(log_level)\nformatter = logging.Formatter(\n '%(asctime)s.%(msecs)03d (%(filename)s:%(lineno)d) %(levelname)s: '\n +'%(message)s',\n '%m/%d %H:%M:%S'\n )\nfile_handler = logging.FileHandler(log_metplus, mode='a')\nfile_handler.setFormatter(formatter)\nlogger.addHandler(file_handler)\n\n\nif len(fcst_lead_list[0]) < 2:\n logger.warning(\"Must provide more than one forecast lead to \"\n \"plot lead average\")\n sys.exit(0)\n\noutput_data_dir = os.path.join(output_base_dir, 'data')\noutput_imgs_dir = os.path.join(output_base_dir, 'imgs')\n# Model info\nmodel_info_list = list(\n zip(model_list,\n model_reference_name_list,\n model_obtype_list,\n )\n)\nnmodels = len(model_info_list)\n# Plot info\nplot_info_list = list(\n itertools.product(*[fcst_lead_list, \n fcst_var_level_list, \n fcst_var_thresh_list])\n )\n# Date and time infomation and build title for plot\ndate_beg = os.environ[date_type+'_BEG']\ndate_end = os.environ[date_type+'_END']\ndate_plot_title = (\n date_type.title()+': '\n +str(datetime.datetime.strptime(date_beg, '%Y%m%d').strftime('%d%b%Y'))\n +'-'\n +str(datetime.datetime.strptime(date_end, '%Y%m%d').strftime('%d%b%Y'))\n)\nvalid_init_dict = {\n 'fcst_valid_hour_beg': fcst_valid_hour_list[0],\n 'fcst_valid_hour_end': fcst_valid_hour_list[-1],\n 'fcst_init_hour_beg': fcst_init_hour_list[0],\n 'fcst_init_hour_end': fcst_init_hour_list[-1],\n 'obs_valid_hour_beg': obs_valid_hour_list[0],\n 'obs_valid_hour_end': obs_valid_hour_list[-1],\n 'obs_init_hour_beg': obs_init_hour_list[0],\n 'obs_init_hour_end': obs_init_hour_list[-1],\n 'valid_hour_beg': '',\n 'valid_hour_end': '',\n 'init_hour_beg': '',\n 'init_hour_end': ''\n}\nvalid_init_type_list = [ \n 'valid_hour_beg', 'valid_hour_end', 'init_hour_beg', 'init_hour_end'\n]\nfor vitype in valid_init_type_list:\n if (valid_init_dict['fcst_'+vitype] != '' \n and valid_init_dict['obs_'+vitype] == ''):\n valid_init_dict[vitype] = valid_init_dict['fcst_'+vitype]\n elif (valid_init_dict['obs_'+vitype] != '' \n and valid_init_dict['fcst_'+vitype] == ''):\n valid_init_dict[vitype] = valid_init_dict['obs_'+vitype]\n if valid_init_dict['fcst_'+vitype] == '':\n if 'beg' in vitype:\n valid_init_dict['fcst_'+vitype] = '000000'\n elif 'end' in vitype:\n valid_init_dict['fcst_'+vitype] = '235959'\n if valid_init_dict['obs_'+vitype] == '':\n if 'beg' in vitype:\n valid_init_dict['obs_'+vitype] = '000000'\n elif 'end' in vitype:\n valid_init_dict['obs_'+vitype] = '235959'\n if valid_init_dict['fcst_'+vitype] == valid_init_dict['obs_'+vitype]:\n valid_init_dict[vitype] = valid_init_dict['fcst_'+vitype]\ntime_plot_title = ''\nfor vi in ['valid_hour', 'init_hour']:\n beg_hr = valid_init_dict[vi+'_beg']\n end_hr = valid_init_dict[vi+'_end']\n fcst_beg_hr = valid_init_dict['fcst_'+vi+'_beg']\n fcst_end_hr = valid_init_dict['fcst_'+vi+'_end']\n obs_beg_hr = valid_init_dict['obs_'+vi+'_beg']\n obs_end_hr = valid_init_dict['obs_'+vi+'_end']\n time_label = vi.split('_')[0].title()\n if beg_hr != '' and end_hr != '':\n if beg_hr == end_hr:\n time_plot_title+=', '+time_label+': '+beg_hr[0:4]+'Z'\n else:\n time_plot_title+=(\n ', '+time_label+': '+beg_hr[0:4]+'-'+end_hr[0:4]+'Z'\n )\n else:\n if fcst_beg_hr == fcst_end_hr:\n time_plot_title+=', Fcst '+time_label+': '+fcst_beg_hr[0:4]+'Z'\n else:\n time_plot_title+=(\n ', Fcst '+time_label+': '+fcst_beg_hr[0:4]+'-'\n +fcst_end_hr[0:4]+'Z'\n )\n if obs_beg_hr == obs_end_hr:\n time_plot_title+=', Obs '+time_label+': '+obs_beg_hr[0:4]+'Z'\n else:\n time_plot_title+=(\n ', Obs '+time_label+': '+obs_beg_hr[0:4]+'-'\n +obs_end_hr[0:4]+'Z'\n )\ndate_time_plot_title = date_plot_title+time_plot_title\n# Common plotting information and build title for plot\nif 'WV1' not in interp_mthd or interp_mthd != '':\n extra_plot_title = verif_grid+'-'+vx_mask\nelse:\n extra_plot_title = interp_mthd+', '+verif_grid+'-'+vx_mask\nif desc != '':\n extra_plot_title+=', Desc: '+desc\nif obs_lead != '':\n extra_plot_title+=', Obs Lead: '+obs_lead\nif interp_pnts != '':\n extra_plot_title+=', Interp. Pts.: '+interp_pnts\nif cov_thresh != '':\n extra_plot_title+=', Cov. Thresh:'+cov_thresh\nif alpha != '':\n extra_plot_title+=', Alpha: '+alpha\n\n# Start looping to make plots\nfor plot_info in plot_info_list:\n fcst_leads = plot_info[0]\n fcst_lead_timedeltas = np.full_like(fcst_leads, np.nan, dtype=float)\n for fcst_lead in fcst_leads:\n fcst_lead_idx = fcst_leads.index(fcst_lead)\n fcst_lead_timedelta = datetime.timedelta(\n hours=int(fcst_lead[:-4]),\n minutes=int(fcst_lead[-4:-2]),\n seconds=int(fcst_lead[-2:])\n ).total_seconds()\n fcst_lead_timedeltas[fcst_lead_idx] = float(fcst_lead_timedelta)\n fcst_lead_timedeltas_str = []\n for tdelta in fcst_lead_timedeltas:\n h = int(tdelta/3600)\n m = int((tdelta-(h*3600))/60)\n s = int(tdelta-(h*3600)-(m*60))\n if h < 100:\n tdelta_str = f\"{h:02d}\"\n else:\n tdelta_str = f\"{h:03d}\"\n if m != 0:\n tdelta_str+=f\":{m:02d}\"\n if s != 0:\n tdelta_str+=f\":{s:02d}\"\n fcst_lead_timedeltas_str.append(tdelta_str)\n fcst_var_level = plot_info[1]\n obs_var_level = obs_var_level_list[\n fcst_var_level_list.index(fcst_var_level)\n ]\n fcst_var_thresh = plot_info[2]\n obs_var_thresh = obs_var_thresh_list[\n fcst_var_thresh_list.index(fcst_var_thresh)\n ]\n fcst_var_thresh_symbol, fcst_var_thresh_letter = plot_util.format_thresh(\n fcst_var_thresh\n )\n obs_var_thresh_symbol, obs_var_thresh_letter = plot_util.format_thresh(\n obs_var_thresh\n )\n # Build plot title for variable info\n fcst_var_plot_title = 'Fcst: '+fcst_var_name+' '+fcst_var_level\n obs_var_plot_title = 'Obs: '+obs_var_name+' '+obs_var_level\n if 'WV1' in interp_mthd:\n fcst_var_plot_title+=' '+interp_mthd\n obs_var_plot_title+=' '+interp_mthd \n if fcst_var_thresh != '':\n fcst_var_plot_title+=' '+fcst_var_thresh\n if obs_var_thresh != '':\n obs_var_plot_title+=' '+obs_var_thresh\n if fcst_var_units == '':\n fcst_var_units_list = []\n else:\n fcst_var_units_list = fcst_var_units.split(', ')\n if obs_var_units == '':\n obs_var_units_list = []\n else:\n obs_var_units_list = obs_var_units.split(', ')\n logger.info(\"Working on forecast lead averages \"\n +\"for forecast variable \"+fcst_var_name+\" \"+fcst_var_level+\" \"\n +fcst_var_thresh)\n # Set up base name for file naming convention for lead averages files,\n # and output data and images\n base_name = date_type.lower()+date_beg+'to'+date_end\n if (valid_init_dict['valid_hour_beg'] != ''\n and valid_init_dict['valid_hour_end'] != ''):\n base_name+=(\n '_valid'+valid_init_dict['valid_hour_beg'][0:4]\n +'to'+valid_init_dict['valid_hour_end'][0:4]+'Z'\n )\n else:\n base_name+=(\n '_fcst_valid'+valid_init_dict['fcst_valid_hour_beg'][0:4]\n +'to'+valid_init_dict['fcst_valid_hour_end'][0:4]+'Z'\n +'_obs_valid'+valid_init_dict['obs_valid_hour_beg'][0:4]\n +'to'+valid_init_dict['obs_valid_hour_end'][0:4]+'Z'\n )\n if (valid_init_dict['init_hour_beg'] != ''\n and valid_init_dict['init_hour_end'] != ''):\n base_name+=(\n '_init'+valid_init_dict['init_hour_beg'][0:4]\n +'to'+valid_init_dict['init_hour_end'][0:4]+'Z'\n )\n else:\n base_name+=(\n '_fcst_init'+valid_init_dict['fcst_init_hour_beg'][0:4]\n +'to'+valid_init_dict['fcst_init_hour_end'][0:4]+'Z'\n +'_obs_init'+valid_init_dict['obs_init_hour_beg'][0:4]\n +'to'+valid_init_dict['obs_init_hour_end']+'Z'\n )\n base_name+=(\n '_fcst_lead_avgs'\n +'_fcst'+fcst_var_name+fcst_var_level\n +fcst_var_thresh_letter.replace(',', '_')+interp_mthd\n +'_obs'+obs_var_name+obs_var_level\n +obs_var_thresh_letter.replace(',', '_')+interp_mthd\n +'_vxmask'+vx_mask\n )\n if desc != '':\n base_name+='_desc'+desc\n if obs_lead != '':\n base_name+='_obs_lead'+obs_lead\n if interp_pnts != '':\n base_name+='_interp_pnts'+interp_pnts\n if cov_thresh != '':\n cov_thresh_symbol, cov_thresh_letter = plot_util.format_thresh(\n cov_thresh\n )\n base_name+='_cov_thresh'+cov_thresh_letter.replace(',', '_')\n if alpha != '':\n base_name+='_alpha'+alpha\n for stat in stats_list:\n logger.debug(\"Working on \"+stat)\n stat_plot_name = plot_util.get_stat_plot_name(logger, stat)\n if (stat == 'fbar_obar' or stat == 'orate_frate'\n or stat == 'baser_frate'):\n avg_file_cols = ['LEADS', 'FCST_UNITS', 'OBS_UNITS',\n 'VALS', 'OBS_VALS']\n else:\n avg_file_cols = ['LEADS', 'FCST_UNITS', 'OBS_UNITS', 'VALS']\n avg_cols_to_array = avg_file_cols[3:]\n CI_file_cols = ['LEADS', 'CI_VALS']\n CI_bar_max_widths = np.append(\n np.diff(fcst_lead_timedeltas),\n fcst_lead_timedeltas[-1]-fcst_lead_timedeltas[-2]\n )/1.5\n CI_bar_min_widths = np.append(\n np.diff(fcst_lead_timedeltas),\n fcst_lead_timedeltas[-1]-fcst_lead_timedeltas[-2]\n )/nmodels\n CI_bar_intvl_widths = (\n (CI_bar_max_widths-CI_bar_min_widths)/nmodels\n )\n # Reading in model lead average files produced from plot_time_series.py\n logger.info(\"Reading in model data\")\n for model_info in model_info_list:\n model_num = model_info_list.index(model_info) + 1\n model_idx = model_info_list.index(model_info)\n model_name = model_info[0]\n model_plot_name = model_info[1]\n model_obtype = model_info[2]\n model_avg_data = np.empty(\n [len(avg_cols_to_array), len(fcst_leads)]\n )\n model_avg_data.fill(np.nan)\n# lead_avg_filename = (\n# stat+'_'\n# +model_plot_name+'_'+model_obtype+'_'\n# +base_name\n# +'.txt'\n# )\n# lead_avg_file = os.path.join(output_base_dir, 'data',\n# lead_avg_filename)\n model_stat_template = dump_row_filename_template\n string_sub_dict = {\n 'model': model_name,\n 'model_reference': model_plot_name,\n 'obtype': model_obtype,\n 'fcst_lead': fcst_lead,\n 'fcst_level': fcst_var_level,\n 'obs_level': obs_var_level,\n 'fcst_thresh': fcst_var_thresh,\n 'obs_thresh': obs_var_thresh,\n }\n model_stat_file = do_string_sub(model_stat_template,\n **string_sub_dict)\n logger.debug(f\"FCST LEAD IS {fcst_lead}\")\n lead_avg_file = get_lead_avg_file(stat,\n model_stat_file,\n fcst_lead,\n output_base_dir)\n if os.path.exists(lead_avg_file):\n nrow = sum(1 for line in open(lead_avg_file))\n if nrow == 0:\n logger.warning(\"Model \"+str(model_num)+\" \"\n +model_name+\" with plot name \"\n +model_plot_name+\" file: \"\n +lead_avg_file+\" empty\")\n else:\n logger.debug(\"Model \"+str(model_num)+\" \"\n +model_name+\" with plot name \"\n +model_plot_name+\" file: \"\n +lead_avg_file+\" exists\")\n model_avg_file_data = pd.read_csv(\n lead_avg_file, sep=' ', header=None,\n names=avg_file_cols, dtype=str\n )\n model_avg_file_data_leads = (\n model_avg_file_data.loc[:]['LEADS'].tolist()\n )\n if model_avg_file_data.loc[0]['FCST_UNITS'] == '[NA]':\n fcst_var_units_plot_title = ''\n else:\n fcst_var_units_plot_title = (\n model_avg_file_data.loc[0]['FCST_UNITS']\n )\n if model_avg_file_data.loc[0]['OBS_UNITS'] == '[NA]':\n obs_var_units_plot_title = ''\n else:\n obs_var_units_plot_title = (\n model_avg_file_data.loc[0]['OBS_UNITS']\n )\n for fcst_lead in fcst_leads:\n fcst_lead_idx = fcst_leads.index(fcst_lead)\n if fcst_lead in model_avg_file_data_leads:\n model_fcst_lead_idx = (\n model_avg_file_data_leads.index(fcst_lead)\n )\n for col in avg_cols_to_array:\n col_idx = avg_cols_to_array.index(col)\n model_avg_file_data_col = (\n model_avg_file_data.loc[:][col].tolist()\n )\n if (model_avg_file_data_col[model_fcst_lead_idx]\n != '--'):\n model_avg_data[col_idx, fcst_lead_idx] = (\n float(model_avg_file_data_col \\\n [model_fcst_lead_idx])\n ) \n else:\n logger.warning(\"Model \"+str(model_num)+\" \"\n +model_name+\" with plot name \"\n +model_plot_name+\" file: \"\n +lead_avg_file+\" does not exist\")\n# CI_filename = (\n# stat+'_'\n# +model_plot_name+'_'+model_obtype+'_'\n# +base_name\n# +'_CI_'+ci_method+'.txt'\n# )\n# CI_file = os.path.join(output_base_dir, 'data', CI_filename)\n CI_file = get_ci_file(stat,\n model_stat_file,\n fcst_lead,\n output_base_dir,\n ci_method)\n\n model_CI_data = np.empty(len(fcst_leads))\n model_CI_data.fill(np.nan)\n if ci_method != 'NONE':\n if (stat == 'fbar_obar' or stat == 'orate_frate'\n or stat == 'baser_frate'):\n diff_from_avg_data = model_avg_data[1,:]\n if os.path.exists(CI_file):\n nrow = sum(1 for line in open(CI_file))\n if nrow == 0:\n logger.warning(\"Model \"+str(model_num)+\" \"\n +model_name+\" with plot name \"\n +model_plot_name+\" file: \"\n +CI_file+\" empty\")\n else:\n logger.debug(\"Model \"+str(model_num)+\" \"\n +model_name+\" with plot name \"\n +model_plot_name+\" file: \"\n +CI_file+\" exists\")\n model_CI_file_data = pd.read_csv(\n CI_file, sep=' ', header=None,\n names=CI_file_cols, dtype=str\n )\n model_CI_file_data_leads = (\n model_CI_file_data.loc[:]['LEADS'].tolist()\n )\n model_CI_file_data_vals = (\n model_CI_file_data.loc[:]['CI_VALS'].tolist()\n )\n for fcst_lead in fcst_leads:\n fcst_lead_idx = (\n fcst_leads.index(fcst_lead)\n )\n if fcst_lead in model_CI_file_data_leads:\n model_CI_file_data_lead_idx = (\n model_CI_file_data_leads.index(\n fcst_lead\n )\n )\n if (model_CI_file_data_vals[fcst_lead_idx]\n != '--'):\n model_CI_data[fcst_lead_idx] = (\n float(model_CI_file_data_vals \\\n [fcst_lead_idx])\n )\n else:\n logger.warning(\"Model \"+str(model_num)+\" \"\n +model_name+\" with plot name \"\n +model_plot_name+\" file: \"\n +CI_file+\" does not exist\")\n else:\n if model_num == 1:\n diff_from_avg_data = model_avg_data[0,:]\n else:\n if os.path.exists(CI_file):\n nrow = sum(1 for line in open(CI_file))\n if nrow == 0:\n logger.warning(\"Model \"+str(model_num)+\" \"\n +model_name+\" with \"\n +\"plot name \"\n +model_plot_name+\" \"\n +\"file: \"+CI_file+\" empty\")\n else:\n logger.debug(\"Model \"+str(model_num)+\" \"\n +model_name+\" with \"\n +\"plot name \"\n +model_plot_name+\" \"\n +\"file: \"+CI_file+\" exists\")\n model_CI_file_data = pd.read_csv(\n CI_file, sep=' ', header=None,\n names=CI_file_cols, dtype=str\n )\n model_CI_file_data_leads = (\n model_CI_file_data.loc[:]['LEADS'] \\\n .tolist()\n )\n model_CI_file_data_vals = (\n model_CI_file_data.loc[:]['CI_VALS'] \\\n .tolist()\n )\n for fcst_lead in fcst_leads:\n fcst_lead_idx = (\n fcst_leads.index(fcst_lead)\n )\n if fcst_lead in model_CI_file_data_leads:\n model_CI_file_data_lead_idx = (\n model_CI_file_data_leads.index(\n fcst_lead\n )\n )\n if (model_CI_file_data_vals \\\n [fcst_lead_idx]\n != '--'):\n model_CI_data[fcst_lead_idx] = (\n float(model_CI_file_data_vals \\\n [fcst_lead_idx])\n )\n else:\n logger.warning(\"Model \"+str(model_num)+\" \"\n +model_name+\" with plot name \"\n +model_plot_name+\" file: \"\n +CI_file+\" does not exist\")\n if model_num == 1:\n fig, (ax1, ax2) = plt.subplots(2,1,figsize=(10,12),\n sharex=True)\n ax1.grid(True)\n ax1.tick_params(axis='x', pad=15)\n ax1.set_xticks(fcst_lead_timedeltas)\n ax1.set_xticklabels(fcst_lead_timedeltas_str)\n ax1.set_xlim([fcst_lead_timedeltas[0],\n fcst_lead_timedeltas[-1]])\n ax1.tick_params(axis='y', pad=15)\n ax1.set_ylabel(average_method.title(), labelpad=30)\n ax2.grid(True)\n ax2.tick_params(axis='x', pad=15)\n ax2.set_xlabel('Forecast Lead', labelpad=30)\n ax2.tick_params(axis='y', pad=15)\n ax2.set_ylabel('Difference', labelpad=30)\n boxstyle = matplotlib.patches.BoxStyle('Square', pad=0.25)\n props = {'boxstyle': boxstyle,\n 'facecolor': 'white',\n 'linestyle': 'solid',\n 'linewidth': 1,\n 'edgecolor': 'black',}\n ax2.text(0.7055, 1.05, 'Note: differences outside the '\n +'outline bars are significant\\n at the 95% '\n +'confidence interval', ha='center', va='center',\n fontsize=10, bbox=props, transform=ax2.transAxes)\n if (stat == 'fbar_obar' or stat == 'orate_frate'\n or stat == 'baser_frate'):\n ax1.plot(fcst_lead_timedeltas, model_avg_data[1,:],\n color='#888888',\n ls='-', linewidth=2.0,\n marker='o', markersize=7,\n label='obs',\n zorder=4)\n ax2.plot(fcst_lead_timedeltas,\n np.zeros_like(fcst_lead_timedeltas),\n color='#888888',\n ls='-', linewidth=2.0,\n zorder=4)\n ax2.plot(fcst_lead_timedeltas,\n model_avg_data[0,:] - diff_from_avg_data,\n color=colors[model_idx],\n ls='-', linewidth=2.0,\n marker='o', markersize=7,\n zorder=(nmodels-model_idx)+4)\n else:\n ax2.plot(fcst_lead_timedeltas,\n np.zeros_like(fcst_lead_timedeltas),\n color='black',\n ls='-', linewidth=2.0,\n zorder=4)\n ax1.plot(fcst_lead_timedeltas, model_avg_data[0,:],\n color=colors[model_idx],\n ls='-', linewidth=2.0,\n marker='o', markersize=7,\n label=model_plot_name,\n zorder=(nmodels-model_idx)+4)\n else:\n ax1.plot(fcst_lead_timedeltas, model_avg_data[0,:],\n color=colors[model_idx],\n ls='-', linewidth=2.0,\n marker='o', markersize=7,\n label=model_plot_name,\n zorder=(nmodels-model_idx)+4)\n ax2.plot(fcst_lead_timedeltas, \n model_avg_data[0,:] - diff_from_avg_data,\n color=colors[model_idx],\n ls='-', linewidth=2.0,\n marker='o', markersize=7,\n zorder=(nmodels-model_idx)+4)\n ax2.bar(fcst_lead_timedeltas, 2*np.absolute(model_CI_data),\n bottom=-1*np.absolute(model_CI_data),\n width=CI_bar_max_widths-(CI_bar_intvl_widths*model_idx),\n color='None', edgecolor=colors[model_idx], linewidth=1.5)\n fig.suptitle(stat_plot_name+'\\n'\n +fcst_var_plot_title+' '+fcst_var_units_plot_title\n +', '+obs_var_plot_title+' '+obs_var_units_plot_title+'\\n'\n +extra_plot_title+'\\n'\n +date_time_plot_title,\n fontsize=14, fontweight='bold')\n if (stat == 'fbar_obar' or stat == 'orate_frate'\n or stat == 'baser_frate'):\n ax1.legend(bbox_to_anchor=(0.0, 1.01, 1.0, .102), loc=3,\n ncol=nmodels+1, fontsize='13',\n mode='expand', borderaxespad=0.)\n else:\n ax1.legend(bbox_to_anchor=(0.0, 1.01, 1.0, .102), loc=3,\n ncol=nmodels, fontsize='13',\n mode='expand', borderaxespad=0.)\n savefig_imagename = stat+'_'+base_name+'.png'\n savefig_image = os.path.join(output_base_dir, 'images',\n savefig_imagename)\n logger.info(\"Saving image as \"+savefig_image)\n plt.savefig(savefig_image, bbox_inches='tight')\n plt.close()\n","sub_path":"ush/plotting_scripts/plot_lead_average.py","file_name":"plot_lead_average.py","file_ext":"py","file_size_in_byte":29580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"313590942","text":"\n\nfrom xai.brain.wordbase.nouns._fiat import _FIAT\n\n#calss header\nclass _FIATS(_FIAT, ):\n\tdef __init__(self,): \n\t\t_FIAT.__init__(self)\n\t\tself.name = \"FIATS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"fiat\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_fiats.py","file_name":"_fiats.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"368733183","text":"from __future__ import unicode_literals\nimport numpy as np\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\nimport argparse\n\n# Parse parameters\nparser = argparse.ArgumentParser(description='Warte nicht, plotte rasch!')\nparser.add_argument('-k', '--k', help=\"parameter K\", default=1.5, type = float)\nparser.add_argument('-r', '--res', help=\"Points per Axis\", default=30, type = int)\nparser.add_argument('-i', '--iters', help=\"Iterations\", default=500, type = int)\nargs = parser.parse_args()\n\nk = args.k\nres = args.res\niters = args.iters\n\n# Definition of the map, expecting arraylike x and p at time n\ndef standard(x,p):\n\txn = (x + p)%1\n\tpn = p + k/(2*np.pi) * np.sin(2*np.pi*xn)\n\treturn xn, pn\n\nx0 = np.linspace(0,1,2*res)\np0 = np.linspace(-1,1,res)\n\nx, p = np.meshgrid(x0,p0)\n\nfor i in np.arange(0,iters,1):\n\tx, p = standard(x,p)\n\tplt.scatter(x,p, marker = \".\", s = 0.01, alpha = 0.6, color = \"0.0\")\n\nplt.axis([0,1,-1.2,1.2])\nplt.show()\n","sub_path":"ex7/standard.py","file_name":"standard.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"286786330","text":"\"\"\"Add tweet count to users\n\nRevision ID: 2d1cfa8a385d\nRevises: f25da7d345cc\nCreate Date: 2017-01-30 22:57:07.970483\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '2d1cfa8a385d'\ndown_revision = 'f25da7d345cc'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.add_column('users', sa.Column('tweet_count', sa.Integer, nullable=False, server_default='0'))\n\n\ndef downgrade():\n op.drop_column('users', 'tweet_count')\n","sub_path":"alembic/versions/2d1cfa8a385d_add_tweet_count_to_users.py","file_name":"2d1cfa8a385d_add_tweet_count_to_users.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"648846345","text":"import threading\nimport queue\nimport numpy as np \n\ndef task(args):\n print(args)\n args[0]=33\n \n\ndef main():\n args=np.array([1,2,3])\n t=threading.Thread(target=task,args=args)\n t.start()\n\nif __name__ == '__main__':\n main()\n","sub_path":"thread/quethread.py","file_name":"quethread.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"518338982","text":"\n# wanzixi2.py\n\n\n# 2.写一个类,Fibonacci实现迭代器协议,此类的对象可以作为\n# 可迭代对象生成相应的斐波那契数\n# 1 1 2 3 4 5 8...\n\n# 提示:可以用一个类实现,也可以用两个类实现\n\n# class Fibonacci:\n# def __init__(self,n):\n# ...\n# def __iter__(self):\n# ...\n# def __next__\n\n# 实现如下操作:\n# for x in Fibonacci(10):\n# print(x)\n# L = [x for x in fibonacci(30)]\n# print(sum(Fibonacci(25)))\n# (需要实现迭代器协议)\n\n\n\n\nclass Fibonacci:\n L = [1,1]\n def __init__(self,n):\n self.number = n\n self.cur = 0 \n self.data = Fibonacci.L\n \n def __iter__(self):\n while len(self.data) < self.number:\n self.data.append(self.data[-1] + self.data[-2])\n print(\"__iter__方法被调用!\")\n return iter(self.data)\n\n \n def __next__(self):\n # '''有此方法的对象才叫迭代器,此方法一定要实现迭代器协议'''\n # # 如果self.cur已经超出了列表的索引范围就报迭代结束\n print(\"__next__方法被调用!\")\n # if self.cur >= self.number:\n # raise StopIteration\n # # 否则尚未迭代完成,需要返回数据\n # r = self.data[self.cur]\n # self.cur += 1 # 将当前值向后移动一个单位\n # return r\n return next(iter(self.data))\n\n\n\n# 实现如下操作:\nfor x in Fibonacci(10):\n print(x)\n# L = [x for x in Fibonacci(30)]\n# print(L)\n# print(sum(Fibonacci(25)))\n# (需要实现迭代器协议)\n# next(Fibonacci)\nit = Fibonacci(9)\nprint(next(it))\n\n","sub_path":"python语法/day19/exercise/wanzixi2.py","file_name":"wanzixi2.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"370868723","text":"import sys\nfrom PyQt4 import QtGui, QtCore\nfrom student_owe import Ui_Student_payment\nfrom PyQt4.QtSql import *\nfrom fee_print import Print_window\n\nclass Student_payment_window(QtGui.QMainWindow):\n def __init__(self):\n QtGui.QMainWindow.__init__(self)\n self.ui = Ui_Student_payment()\n self.ui.setupUi(self)\n self.conn()\n Teacher_query = QSqlQuery()\n Teacher_query.exec_(\"select Student_name from Student\")\n model = QSqlQueryModel()\n model.setQuery(Teacher_query)\n self.ui.Student_listView.setModel(model)\n self.ui.Statement_btn.setEnabled(False)\n self.ui.Search_btn.clicked.connect(self.search_student)\n self.ui.Statement_btn.clicked.connect(self.print_history)\n self.ui.Student_listView.clicked.connect(self.select_student)\n\n Term_query = QSqlQuery()\n Term_query.exec_(\"select Current_term from System where System_id = '1'\")\n Term_query.next()\n self.ui.cur_term = Term_query.value(0)\n\n self.ui.rates = []\n self.ui.time = []\n Rate_query = QSqlQuery()\n Rate_query.exec_(\"select Tuition_Rate, Tuition_Time from Tuition_Rates \")\n while Rate_query.next():\n self.ui.rates.append(float(Rate_query.value(0)))\n self.ui.time.append(float(Rate_query.value(1)))\n \n \n def get_rate(self, minitue):\n for i in range(len(self.ui.time)):\n if (minitue <= self.ui.time[i]):\n return self.ui.rates[i]\n return self.ui.rates[-1]\n \n def search_student(self):\n input_student_name = self.ui.Teacher_lineEdit.text()\n Student_query = QSqlQuery()\n Student_query.exec_(\"select Student_name from Student where Student_name like '%%%s%%'\" % input_student_name)\n model = QSqlQueryModel()\n model.setQuery(Student_query)\n self.ui.Student_listView.setModel(model)\n \n def print_history(self):\n self.ui.Statement_btn.setEnabled(True)\n Hours_query = QSqlQuery()\n Hours_query.exec_(\"select sum(TIME_TO_SEC(TIMEDIFF(C.Class_end_time, C.Class_time))) from Student as S, Student_Class as SC, Class as C\\\n where S.Student_id = SC.Student_id and SC.Class_id = C.Class_id and S.Student_name = '%s'\\\n and SC.Student_semester_taken = '%s'\" % (self.ui.name, self.ui.cur_term))\n class_query = QSqlQuery()\n\n class_query.exec_(\"select C.Class_name, TIME_TO_SEC(TIMEDIFF(C.Class_end_time, C.Class_time)) from Student as S, Student_Class as SC, Class as C where \\\n S.Student_id = SC.Student_id and SC.Class_id = C.Class_id and S.Student_name = '%s' \\\n and SC.Student_semester_taken = '%s'\" % (self.ui.name, self.ui.cur_term))\n\n class_name = []\n class_min = []\n while class_query.next():\n class_name.append(class_query.value(0))\n class_min.append(str(class_query.value(1)/60.0) + ' minutes')\n \n \n Hours_query.next()\n minutes = 0\n if not isinstance(Hours_query.value(0), QtCore.QPyNullVariant):\n minutes = int(Hours_query.value(0)) / 60\n\n\n Money = 0.0\n Money_query = QSqlQuery()\n Money_query.exec_(\"select sum(P.Amount_paid) from Student as S, Payment as P where S.Student_id = P.Student_id and \\\n S.Student_name = '%s' and P.Semester_paid = '%s'\" % (self.ui.name, self.ui.cur_term))\n\n Money_query.next()\n if not isinstance(Money_query.value(0), QtCore.QPyNullVariant):\n Money = float(Money_query.value(0))\n\n self.ui.print = Print_window(class_name, class_min, minutes, self.ui.name, self.ui.cur_term, Money, self.get_rate(minutes))\n self.ui.print.show()\n \n \n '''\n self.ui.history = Teacher_history_dialog(self.ui.name)\n self.ui.history.show()\n '''\n \n def select_student(self, index):\n #TODO\n #total hours\n self.ui.name = index.data()\n self.ui.Statement_btn.setEnabled(True)\n\n def conn(self):\n self.db = QSqlDatabase.addDatabase(\"QMYSQL\")\n self.db.setHostName(\"services1.mcs.sdsmt.edu\")\n self.db.setDatabaseName(\"db_dancesoft_f15\")\n self.db.setUserName(\"dancesoft_f15\")\n self.db.setPassword(\"DanceSoft\")\n return self.db.open()\n\n \n","sub_path":"together/student_owe_window.py","file_name":"student_owe_window.py","file_ext":"py","file_size_in_byte":4421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"22645774","text":"\"\"\"I called it so because I couldn't decide between 'blacklist' and 'whitelist'\"\"\"\nimport json\nimport os\nimport re\n\nfrom Levenshtein import distance # noqa\nfrom pyrogram import Client, filters\nfrom pyrogram.errors import SlowmodeWait\nfrom pyrogram.types import Message\n\nfrom app import app as app_, mod_group\nfrom db import Colorlist\nfrom util import normalize_uzbek\n\ncolorlist: list['Colorlist']\n\n\nasync def init():\n global colorlist\n colorlist = await Colorlist.all()\n print(colorlist)\n\n\nasync def on_message(app: Client, message: Message):\n text = ''.join(re.findall('[ a-z0-9]', normalize_uzbek(message.text)))\n for i in colorlist:\n if distance(i.text, text) <= 2:\n if i.is_black:\n if await try_blocking(app, message):\n await message.reply_text('Blacklisted message occured one more time.')\n return True\n return False\n\n\nasync def check_permissions(message: Message) -> bool:\n member = await message.chat.get_member(message.from_user.id)\n if member.can_restrict_members and member.can_delete_messages:\n return True\n else:\n await message.reply(\"You don't have enough permissions.\\n\"\n \"Permissions required: can_restrict_members, \"\n \"can_delete_messages.\")\n return True\n\n\nasync def try_blocking(app: Client, message: Message):\n if not check_permissions(message):\n return False\n try:\n await app.kick_chat_member(message.chat.id, message.from_user.id)\n await message.delete()\n await app.send_message(message.chat.id, 'Successfully blocked.')\n except Exception: # noqa\n await notify_no_perms(app, message)\n return False\n else:\n return True\n\n\nasync def notify_no_perms(app: Client, message: Message):\n text = '*Blacklist*\\nChat admin with restrict permission required in: ' \\\n f'@{message.chat.username}.'\n await app.send_message(mod_group, text)\n\n\n@app_.on_message(filters.regex('^!black$'))\nasync def on_black(app: Client, message: Message):\n if await add_to_list(app, message, True):\n await try_blocking(app, message.reply_to_message)\n\n\n@app_.on_message(filters.regex('^!white$'))\nasync def on_white(app: Client, message: Message):\n if not check_permissions(message):\n return\n await add_to_list(app, message, False)\n\n\nasync def add_to_list(app: Client, message: Message, is_black: bool):\n if message.reply_to_message is None or message.reply_to_message.text is None:\n await message.reply_text('Must reply to a text message!')\n return False\n text = message.reply_to_message.text\n if text in ('!black', '!white', '!list'):\n await message.reply_text('Cannot blacklist a command!')\n return False\n new = Colorlist(text=text, is_black=is_black)\n await new.save()\n colorlist.append(new)\n try:\n await message.reply('Added successfully.')\n except SlowmodeWait:\n await notify_no_perms(app, message)\n return False\n\n return True\n\n\n@app_.on_message(~filters.chat(mod_group) & filters.regex('^!list$'))\nasync def on_notmod_list(_, message):\n message.reply_text('Must be used in the mod group!')\n\n@app_.on_message(filters.chat(mod_group) & filters.regex('^!list$'))\nasync def on_list(_app: Client, message: Message):\n with open('tmp.json', 'w') as f:\n json.dump({'blacklist': [{'id': i.id, 'text': i.text}\n for i in colorlist if i.is_black],\n 'whitelist': [{'id': i.id, 'text': i.text}\n for i in colorlist if not i.is_black]}, f)\n with open('tmp.json', 'rb') as f:\n await message.reply_document(f)\n os.remove('tmp.json')\n","sub_path":"colorlist.py","file_name":"colorlist.py","file_ext":"py","file_size_in_byte":3757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"99172357","text":"#!/usr/bin/env python2\n\n\nclass Tile:\n\n '''Block class for background tiles'''\n\n def __init__(self, row, column, is_wall=True):\n self.row = row\n self.column = column\n self.is_wall = is_wall\n\n\nif __name__ == '__main__':\n tile = Tile(1, 1)\n print(tile.is_wall)\n","sub_path":"tile.py","file_name":"tile.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"380599652","text":"import yaml\nimport os\nimport datetime\nimport ipywidgets as widgets\nfrom ipywidgets import interactive\nfrom IPython.display import display\nimport sys\n\n\nclass POCS_devices_database(object):\n \"\"\"\n This class manages serial numbers and other information of multiple devices being used with POCS.\n It can be used to display ipython widgets to select the device information, and then create a .yaml\n config file that can be read and implemented by POCS.\n \"\"\"\n\n def __init__(self,\n device_info_master_directory='/var/huntsman-pocs/conf_files/',\n device_info_master_file='device_info_master.yaml',\n local_directory='/var/huntsman-pocs/conf_files/',\n archive_directory='/var/huntsman-pocs/conf_files/archive/',\n output_yaml_filename='huntsman.yaml'):\n \"\"\"\n Sets up the location to save all files, loads information off previous files, and gets the current\n datetime info for the archive filename.\n\n Args:\n device_info_master_directory : the file path of where the .yaml file that all the device info is in\n local_directory : the dir where the config file needs to be saved to be used by POCS\n archive_directory : the dir where the archive/version control of the config files are kept\n output_yaml_filename : the chosen filename of the local config file used by POCS\n \"\"\"\n self.local_directory = local_directory\n self.archive_directory = archive_directory\n self.device_info_master_directory = device_info_master_directory\n self.output_yaml_filename = output_yaml_filename\n self.device_info_master_file = device_info_master_file\n\n device_info_file = os.path.join(\n self.device_info_master_directory, self.device_info_master_file)\n try:\n with open(device_info_file, 'r') as file:\n self.data = yaml.load(file)\n except FileNotFoundError:\n sys.exit(\"Cannot find device information master file\")\n\n date_info = datetime.datetime.today()\n datetime_str = date_info.strftime('%Y_%m_%d_%H_%M')\n self.archive_filename = '{}_{}.{}'.format('huntsman', datetime_str, 'yaml')\n\n previous_file = os.path.join(self.local_directory, self.output_yaml_filename)\n # loading general data from the previous .yaml file used\n try:\n with open(previous_file, 'r') as file:\n self.data_dict = yaml.load(file)\n if self.data_dict is not None and 'cameras' in self.data_dict:\n del self.data_dict['cameras']\n except FileNotFoundError:\n self.data_dict = {}\n\n self.data_dict.update(\n {'cameras': {'hdr_mode': True, 'auto_detect': False, 'devices': [None]}})\n\n def add_device_widget(self, dummy_variable_for_widget):\n \"\"\"Function to add the details selected using the drop-down menu widgets to the 'data_dict'\n dictionary.\n The function is called by a widget in start_interface() and is then run when the user clicks\n on the widget button.\n\n Args:\n dummy_variable_for_widget : the widget needs an extra arg for some reason\n\n Output:\n Appends the data_dict dict with the information chosen from the device information widgets.\n\n \"\"\"\n\n additional_device = {'model': self.camera_type_chosen,\n 'port': self.camera_sn_chosen,\n 'filter_type': self.filter_ID_chosen,\n 'focuser': {'model': 'birger',\n 'port': self.birger_sn_chosen\n\n },\n 'lens': {'model': 'canon',\n 'port': self.lens_sn_chosen,\n 'name': self.lens_name_chosen,\n 'image_stabalisataion': self.lens_image_stabalisation_chosen},\n 'USB_hub_serial_number': self.USB_hub_SN_chosen,\n 'camera_into_serial_adaptor_port': self.camera_to_serial_port_chosen,\n 'serial_adaptor_into_USBhub_port': self.serial_to_USBhub_port_chosen,\n 'camera_into_USBhub_port': self.camera_to_USBhub_port_chosen\n }\n\n if self.data_dict['cameras']['devices'] == [None]:\n self.data_dict['cameras']['devices'] = [additional_device]\n else:\n self.data_dict['cameras']['devices'].append(additional_device)\n\n return self.data_dict\n\n def save_file(self, dummy_variable_for_widget):\n \"\"\"This function writes the 'data_dict' dictionary to a .yaml text file.\n The function is called by a widget in start_interface() and is run when the user clicks on the\n widget button.\n\n Args:\n dummy_variable_for_widget : the widget needs an extra arg for some reason\n\n Output:\n Writes the information in the dict into a .yaml file in two locations, as determined by the\n assign_local_dir() and assign_archive_dir methods.\n The default locations are:\n '/var/huntsman-pocs/conf_files/huntsman.yaml'\n for the local config file to be used by POCS\n\n and\n\n '/var/huntsman-pocs/conf_files/huntsman_archive/huntsman_YYYY_mm_dd_hh_MM.yaml'\n for the archive of all version of the config files, with the date it was created in\n the filename\n\n \"\"\"\n\n strOutFile1 = os.path.join(self.local_directory, self.output_yaml_filename)\n objFile1 = open(strOutFile1, \"w\")\n yaml.dump(self.data_dict, objFile1, default_flow_style=False, indent=4)\n objFile1.close()\n\n strOutFile = os.path.join(self.archive_directory, self.archive_filename)\n objFile = open(strOutFile, \"w\")\n yaml.dump(self.data_dict, objFile, default_flow_style=False, indent=4)\n objFile.close()\n\n def start_interface(self):\n \"\"\"This function runs all the code to generate the .yaml config files for the Huntsman-POCS system.\n It displays the Jupyter widgets which the user can interact with to write and save the config files.\n\n Files are saved in two locations, one for the local file that POCS will access,\n and the other is an archive of all previous config files which acts as a version control.\n By default, these locations are: (but can be changed using the arguments in the __init__ method)\n '/var/huntsman-pocs/conf_files/huntsman.yaml' for the local file.\n '/var/huntsman-pocs/conf_files/huntsman_archive/huntsman_YYYY_mm_dd_hh_MM.yaml' for the archive file.\n\n Steps for the user to follow:\n Select from the dropdown menus the information for one device set.\n Click 'Add new device set'.\n Select from the dropdown menus the information for the next device set.\n Click 'Add new device set'.\n Repeat until all device sets have been added.\n Click 'Save File' to write the .yaml file.\n\n Displays:\n Jupyter widgets of drop-down menus to select the device sets.\n These widgets are used to generate and save the .yaml config files.\n\n Output:\n A .yaml config file for Huntsman\n\n \"\"\"\n print(self.start_interface.__doc__)\n\n birger_sn = self.data['birger_SN']\n self.birger_serial_number = interactive(\n birger_sn_widget, birger_serial_number_displayed=birger_sn)\n camera_sn = self.data['camera_SN']\n self.camera_serial_number = interactive(\n camera_sn_widget, camera_serial_number_displayed=camera_sn)\n lens_sn = self.data['lens_SN']\n self.lens_serial_number = interactive(lens_sn_widget, lens_serial_number_displayed=lens_sn)\n filter_ID = self.data['filter_ID']\n self.filter_ID_code = interactive(filter_ID_widget, filter_ID_code_displayed=filter_ID)\n serial_into_USBhub = self.data['serial_into_USBhub_port']\n self.serial_into_USBhub_port = interactive(\n serial_to_usb_widget, serial_into_USBhub_port_displayed=serial_into_USBhub)\n camera_into_serial = self.data['camera_into_serial_port']\n self.camera_into_serial_port = interactive(\n camera_to_serial_widget, camera_into_serial_port_displayed=camera_into_serial)\n USBhub = self.data['USBhub_SN']\n self.USBhub_SN = interactive(usbhub_sn_widget, USBhub_SN_displayed=USBhub)\n camera_into_USBhub = self.data['camera_into_USBhub_port']\n self.camera_into_USBhub_port = interactive(\n camera_to_usb_widget, camera_into_USBhub_port_displayed=camera_into_USBhub)\n\n display(self.birger_serial_number)\n display(self.camera_serial_number)\n display(self.lens_serial_number)\n display(self.filter_ID_code)\n display(self.serial_into_USBhub_port)\n display(self.camera_into_serial_port)\n display(self.USBhub_SN)\n display(self.camera_into_USBhub_port)\n\n self.birger_sn_chosen = self.birger_serial_number.result\n self.camera_sn_chosen = self.camera_serial_number.result\n self.lens_sn_chosen = self.lens_serial_number.result\n self.filter_ID_chosen = self.filter_ID_code.result\n self.serial_to_USBhub_port_chosen = self.serial_into_USBhub_port.result\n self.camera_to_serial_port_chosen = self.camera_into_serial_port.result\n self.USB_hub_SN_chosen = self.USBhub_SN.result\n self.camera_to_USBhub_port_chosen = self.camera_into_USBhub_port.result\n\n self.camera_type_chosen = self.data['camera_type'][self.camera_sn_chosen]\n self.lens_name_chosen = self.data['lens_name'][self.lens_sn_chosen]\n self.lens_image_stabalisation_chosen = self.data['lens_image_stabalisation'][self.lens_sn_chosen]\n\n button1 = widgets.Button(description=\"Add new device set\")\n display(button1)\n button1.on_click(self.add_device_widget)\n\n button = widgets.Button(description=\"Save File\")\n display(button)\n button.on_click(self.save_file)\n\n\ndef birger_sn_widget(birger_serial_number_displayed):\n \"\"\"Function used to create Jupyter widget.\n It takes the parameter chosen from the widget and returns it such that it can be used as a variable.\n\n Args:\n birger_serial_number (str) : the serial number of the birger device as selected from the widget.\n\n Returns:\n The result of the widget; the chosen focuser serial number\n\n \"\"\"\n return birger_serial_number_displayed\n\n\ndef camera_sn_widget(camera_serial_number_displayed):\n \"\"\"Function used to create Jupyter widget.\n It takes the parameter chosen from the widget and returns it such that it can be used as a variable.\n\n Args:\n camera_serial_number (str) : the serial number of the camera device as selected from the widget.\n\n Returns:\n The result of the widget; the chosen camera serial number\n\n \"\"\"\n return camera_serial_number_displayed\n\n\ndef lens_sn_widget(lens_serial_number_displayed):\n \"\"\"Function used to create Jupyter widget.\n It takes the parameter chosen from the widget and returns it such that it can be used as a variable.\n\n Args:\n lens_serial_number (str) : the serial number of the lens device as selected from the widget.\n\n Returns:\n The result of the widget; the chosen lens serial number\n\n \"\"\"\n return lens_serial_number_displayed\n\n\ndef filter_ID_widget(filter_ID_code_displayed):\n \"\"\"Function used to create Jupyter widget.\n It takes the parameter chosen from the widget and returns it such that it can be used as a variable.\n\n Args:\n filter_ID_code (str) : the ID number of the lens as selected from the widget.\n\n Returns:\n The result of the widget; the chosen filter ID number\n\n \"\"\"\n return filter_ID_code_displayed\n\n\ndef serial_to_usb_widget(serial_into_USBhub_port_displayed):\n \"\"\"Function used to create Jupyter widget.\n It takes the parameter chosen from the widget and returns it such that it can be used as a variable.\n\n Args:\n serial_into_USBhub_port (str) : the port number of the USB Hub that the Serial Adaptor is plugged\n into as selected from the widget.\n\n Returns:\n The result of the widget; the chosen USB port number\n\n \"\"\"\n return serial_into_USBhub_port_displayed\n\n\ndef camera_to_serial_widget(camera_into_serial_port_displayed):\n \"\"\"Function used to create Jupyter widget.\n It takes the parameter chosen from the widget and returns it such that it can be used as a variable.\n\n Args:\n camera_into_serial_port (str) : the port number of the Serial Adaptor that the camera is plugged\n into as selected from the widget.\n\n Returns:\n The result of the widget; the chosen serial port number\n\n \"\"\"\n return camera_into_serial_port_displayed\n\n\ndef usbhub_sn_widget(USBhub_SN_displayed):\n \"\"\"Function used to create Jupyter widget.\n It takes the parameter chosen from the widget and returns it such that it can be used as a variable.\n\n Args:\n USBhub_SN (str) : the serial number of the USB Hub as selected from the widget.\n\n Returns:\n The result of the widget; the chosen USB Hub serial number\n\n \"\"\"\n return USBhub_SN_displayed\n\n\ndef camera_to_usb_widget(camera_into_USBhub_port_displayed):\n \"\"\"Function used to create Jupyter widget.\n It takes the parameter chosen from the widget and returns it such that it can be used as a variable.\n\n Args:\n camera_into_USBhub_port (str) : the port number of the USB Hub that the camera is plugged into as\n selected from the widget.\n\n Returns:\n The result of the widget; the chosen USB port number\n\n \"\"\"\n return camera_into_USBhub_port_displayed\n","sub_path":"scripts/generating_yaml.py","file_name":"generating_yaml.py","file_ext":"py","file_size_in_byte":14015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"427635959","text":"from itertools import product, combinations_with_replacement, combinations\nimport os\n\ndef main():\n #logic_value = input(\"Введите значность логики:\")\n #var_counter = input(\"Введите число переменных:\")\n path = \"D:\\\\Vs code Projects\\\\Poly_sep\\\\func.txt\"\n output = []\n logic_value = 4\n var_counter = 2\n polynom_degree = 1\n output = x_input_generator(logic_value, var_counter, var_counter, output)\n #output.sort(key = lambda x: [x[j] for j in reversed(range(var_counter))])\n functions, func_id = function_dictionary_generator (output, path)\n polynomyal_sep_func_generator(polynom_degree, var_counter, logic_value, functions, func_id)\n\n\ndef x_input_generator (logic_value:int, var_counter: int, counter_etalon: int, output, prefix=None):\n \"\"\" Функция генерирует значения переменных для дискрутных функций по значности логики и\n количеству переменных\n \"\"\"\n prefix = prefix or []\n if var_counter == 0:\n if len(prefix) == counter_etalon:\n output.append(tuple(prefix))\n return output\n for digit in range(logic_value):\n prefix.append(digit)\n x_input_generator(logic_value, var_counter-1, counter_etalon, output, prefix)\n prefix.pop()\n return output\n\ndef function_dictionary_generator (var_combinations, function_values_path):\n \"\"\" Генератор словаря для дискретных функций\n \"\"\"\n discrete_functions = []\n with open (function_values_path) as func_values:\n func_id = []\n lines = func_values.readlines()\n for line in lines:\n func = {}\n func_values = line.split('#')[0].split(';')\n func_id.append(line.split('#')[1])\n n = len(var_combinations)\n for x in range(n): \n func[var_combinations[x]] = func_values[x]\n discrete_functions.append(func)\n #discrete_functions.append({x: y for x in var_combinations for y in line.split('#')[0].split(';')})\n return discrete_functions, func_id\n \ndef polynomyal_sep_func_generator (polynom_degree: int, var_counter: int, logic:int, discr_funcs, discr_funcs_id):\n \"\"\" Генератор функций полиномиального разделения\n \"\"\"\n iterator = []\n polynom_func = []\n for i in range(1, var_counter + 1):\n iterator.append(str(i))\n # Для булевых функций генерация без повторов тк x1*x1 эквивалентно x1\n if logic == 2:\n for i in range(polynom_degree):\n #for comb in product(iterator, repeat=i + 1):\n for comb in combinations(iterator, i + 1):\n eq = 'a' + ''.join(comb)\n term = [0 for x in range(var_counter)]\n for x in comb:\n term[int(x) - 1] = 1\n eq = eq + ' * x' + x\n polynom_func.append(term)\n print(eq)\n else:\n for i in range(polynom_degree):\n #for comb in product(iterator, repeat=i + 1):\n for comb in combinations_with_replacement(iterator, i + 1):\n eq = 'a' + ''.join(comb)\n term = [0 for x in range(var_counter)]\n for x in comb:\n term[int(x) - 1] = 1\n eq = eq + ' * x' + x\n polynom_func.append(term)\n print(eq)\n n = len(polynom_func)\n for func in range(len(discr_funcs)):\n inequalities_a = []\n inequalities_b = []\n for key, value in discr_funcs[func].items():\n coef = 1\n additional_thresholds = [0] * (logic - 1)\n if value == '0':\n cur_inequlity_a = []\n cur_inequlity_b = []\n for t in range(n):\n lenght_poly = len(polynom_func[t])\n for i in range(lenght_poly):\n if polynom_func[t][i] != 0:\n coef *= key[i]\n cur_inequlity_a.append(coef)\n coef = 1\n additional_thresholds [int(value)] = -1\n cur_inequlity_a += additional_thresholds\n cur_inequlity_b.append(0)\n inequalities_a.append(cur_inequlity_a)\n inequalities_b.append(cur_inequlity_b)\n elif value == str(logic - 1):\n cur_inequlity_a = []\n cur_inequlity_b = []\n for t in range(n):\n lenght_poly = len(polynom_func[t])\n for i in range(lenght_poly):\n if polynom_func[t][i] != 0:\n coef *= key[i]\n cur_inequlity_a.append(str(-1 * coef))\n coef = 1\n additional_thresholds [int(value) - 1] = 1\n cur_inequlity_a += additional_thresholds\n cur_inequlity_b.append(-1)\n inequalities_a.append(cur_inequlity_a)\n inequalities_b.append(cur_inequlity_b)\n else:\n additional_thresholds1 = [0] * (logic - 1)\n additional_thresholds2 = [0] * (logic - 1) \n cur_inequlity_a1 = []\n cur_inequlity_b1 = []\n cur_inequlity_a2 = []\n cur_inequlity_b2 = []\n for t in range(n):\n lenght_poly = len(polynom_func[t])\n for i in range(lenght_poly):\n if polynom_func[t][i] != 0:\n coef *= key[i]\n cur_inequlity_a1.append(coef)\n cur_inequlity_a2.append(-1 * coef)\n coef = 1\n additional_thresholds1 [int(value)] = -1\n additional_thresholds2 [int(value) - 1] = 1\n cur_inequlity_a1 += additional_thresholds1\n cur_inequlity_b1.append(0)\n cur_inequlity_a2 += additional_thresholds2\n cur_inequlity_b2.append(-1)\n inequalities_a.append(cur_inequlity_a1) \n inequalities_a.append(cur_inequlity_a2)\n inequalities_b.append(cur_inequlity_b1)\n inequalities_b.append(cur_inequlity_b2)\n with open(os.path.dirname(os.path.realpath(__file__)) + '\\\\' + discr_funcs_id[func] +'_A' + '.txt', 'w') as f:\n for i in inequalities_a:\n print(*i, file=f, sep = ';')\n with open(os.path.dirname(os.path.realpath(__file__)) + '\\\\'+ discr_funcs_id[func] +'_B' + '.txt', 'w') as f:\n for i in inequalities_b:\n print(*i, file=f)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"poly_sep.py","file_name":"poly_sep.py","file_ext":"py","file_size_in_byte":6805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"76062400","text":"import socket\n\n\ndef setup_server():\n echo_server = socket.socket(\n socket.AF_INET,\n socket.SOCK_STREAM,\n socket.IPPROTO_TCP)\n echo_server.bind(('127.0.0.1', 4444))\n echo_server.listen(1)\n return echo_server, echo_server.accept()\n\n\nif __name__ == '__main__':\n server, (conn, address) = setup_server()\n print('Received client connection for {}'.format(address))\n\n buffer_length = 16\n message_complete = False\n\n while not message_complete:\n part = conn.recv(buffer_length)\n print(part.decode())\n if len(part) < buffer_length:\n break\n\n message = 'The server received your message!'\n conn.sendall(message.encode())\n\n conn.close()\n server.close()\n","sub_path":"echo_server.py","file_name":"echo_server.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"637892209","text":"\nfrom django import forms\n\nfrom multiselectfield import MultiSelectFormField\nfrom backend.cache import get_client_warehouse_cache, get_client_cache\n\nfrom .app_settings import PICKUP_STATUS, PICKUP_DAY_CHOICES\nfrom deliverycenters.cache import get_center_cache, get_pin_cache\nfrom backend.models import Client\nfrom dvutils.router import get_connection_db\n\n\nclass PickupRequestForm(forms.Form):\n\n '''\n create new Pickup Request\n '''\n\n client_id = forms.CharField(widget=forms.HiddenInput(\n attrs={'width': 1, 'class': 'autoCompleteHidden'}))\n client = forms.CharField(label='Client',\n max_length=100, required=True,\n widget=forms.TextInput(attrs={\n 'placeholder': 'Client Name',\n 'class': 'autoComplete',\n 'autocomplete': 'off',\n 'data-url': '/backend/cl-acpl'}))\n pickup_location_id = forms.CharField(widget=forms.HiddenInput(\n attrs={'width': 1, 'class': 'autoCompleteHidden'}))\n pickup_location = forms.CharField(label='Pickup Location',\n max_length=100, required=True,\n widget=forms.TextInput(attrs={\n 'placeholder': 'Warehouse Location',\n 'class': 'autoComplete',\n 'autocomplete': 'off',\n 'data-url': '/backend/wh-acpl',\n 'id': \"id_client_location\"}))\n pickup_date = forms.DateField(\n widget=forms.DateInput(attrs={'class': 'datepicker',\n 'placeholder': 'Pickup Date'}))\n\n pickup_time = forms.TimeField(\n widget=forms.TimeInput(attrs={'class': 'timepicker',\n 'placeholder': 'Pickup Time'}))\n expected_package_count = forms.IntegerField(required=False)\n is_scheduled = forms.BooleanField(\n label='Schedule this pickup request? ', required=False)\n frequency = MultiSelectFormField(label='Scheduled Days',\n choices=PICKUP_DAY_CHOICES,\n required=False)\n end_date = forms.DateField(widget=forms.DateInput(\n attrs={'class': 'datepicker'}), required=False)\n\n def clean(self):\n cleaned_data = super(PickupRequestForm, self).clean()\n cl_name = cleaned_data.get('client')\n clwr = cleaned_data.get('pickup_location')\n try:\n client = Client.objects.using(get_connection_db()).get(name=cl_name)\n except:\n raise forms.ValidationError(\n \"You have mentioned wrong client name\")\n\n cleaned_data['waybill_prefix'] = client.waybill_prefix\n cleaned_data['allow_no_data'] = client.allow_no_data\n\n if cl_name:\n try:\n client = get_client_cache(cl_name)\n except ValueError:\n client = None\n if not client:\n raise forms.ValidationError(\n \"You have mentioned wrong client name\")\n elif client['name'] != cl_name:\n raise forms.ValidationError(\n \"You have mentioned wrong client name\")\n clientwarehouse = get_client_warehouse_cache(cl_name)\n if clwr not in clientwarehouse['clwr']:\n raise forms.ValidationError(\n \"Please select correct return address for {0} \\\n \".format(cl_name))\n # if not cleaned_data.get('expected_package_count') or \\\n # cleaned_data.get('expected_package_count') < 0:\n # cleaned_data[\"expected_package_count\"] = 0\n return cleaned_data\n\n\nclass BulkPickupRequestForm(forms.Form):\n\n '''Form to create bulk pickuprequests via file upload'''\n upload_file = forms.FileField(help_text='CSV file to be processed, keep it'\n ' < 2.5MB for best performance')\n\n\nclass ReportForm(forms.Form):\n '''Form to generate FM Reports'''\n\n def __init__(self, user, *args, **kwargs):\n super(ReportForm, self).__init__(*args, **kwargs)\n if not user.email or user.is_superuser:\n # Option to provide mail address if it does not exist for user\n # and option to send mail to multiple user by superuser\n self.fields['email'] = forms.EmailField(label='Email',\n required=False)\n\n center = forms.MultipleChoiceField(label='Delhivery Center',\n choices=[('', '')] +\n get_center_cache('code_name'),\n widget=forms.SelectMultiple(\n attrs={\n 'class': 'center'}))\n\n client = forms.CharField(label='Client',\n max_length=100,\n required=False,\n widget=forms.TextInput(attrs={\n 'placeholder': 'Client Name',\n 'class': 'autoComplete',\n 'autocomplete': 'off',\n 'data-url': '/backend/cl-acpl'}))\n\n start_date = forms.DateField(\n widget=forms.DateInput(attrs={'class': 'datepicker',\n 'placeholder': 'Start Date'}))\n\n end_date = forms.DateField(required=False,\n widget=forms.DateInput(\n attrs={'class': 'datepicker',\n 'placeholder': 'End Date'}))\n\n status = forms.MultipleChoiceField(\n choices=PICKUP_STATUS,\n widget=forms.CheckboxSelectMultiple)\n\n\nclass FMIncoming(forms.Form):\n '''Form for firstmile incoming'''\n client_id = forms.CharField(widget=forms.HiddenInput(\n attrs={'width': 1, 'class': 'autoCompleteHidden'}))\n client = forms.CharField(label='Client',\n max_length=100, required=True,\n widget=forms.TextInput(attrs={\n 'placeholder': 'Client Name',\n 'class': 'autoComplete',\n 'autocomplete': 'off',\n 'data-url': '/backend/cl-acpl'}))\n\n packages = forms.CharField(required=True,\n widget=forms.Textarea(attrs={\n 'placeholder': 'scan waybills here'\n }))\n\n\nclass FMSearchForm(forms.Form):\n \"\"\"\n Form for Firstmile Pickup searches\n \"\"\"\n def __init__ (self, *args, **kwargs):\n super(FMSearchForm, self).__init__(*args, **kwargs)\n #cyclic import fix\n from dvutils.cache import get_client_cache\n CLIENT_CHOICES = get_client_cache('name_name')\n self.fields['client'].choices = [(u'', u'None')] + CLIENT_CHOICES\n\n search_id = forms.CharField(required=False, label=\"Search Pickups\",\n help_text=\"Enter Pickup ID, separated with spaces.\")\n\n pin = forms.CharField(required=False, label=\"Pin-code\",\n help_text=\"pincode based search\")\n\n client = forms.ChoiceField(required=False, label=\"Client\", choices=[('', 'None')],\n help_text=\"Client level search for pickups\")\n\n def clean(self):\n cleaned_data = super(FMSearchForm, self).clean()\n pin = cleaned_data.get('pin')\n if pin:\n try:\n pin = int(pin)\n except ValueError:\n raise forms.ValidationError(\"Please check the pincode.\")\n pin_info = get_pin_cache(unicode(pin))\n\n if not pin_info:\n raise forms.ValidationError(\"Pin-code doesn't exist in system. \"\n \"Please check pin code\")\n\n return cleaned_data\n\n\nclass PickupRequestCreate(forms.Form):\n \"\"\"\n form for generation of pickup request of packages\n \"\"\"\n packages = forms.CharField(required=True,\n widget=forms.Textarea(attrs={\n 'placeholder': 'create pickup request for waybills here'\n }))\n\n","sub_path":"firstmile/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":8524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"254584856","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport urllib\nimport uuid\nimport requests\nimport json\nfrom functools import partial\n\nimport unittest\n\nfrom selenium.webdriver import DesiredCapabilities, Remote\n\nfrom tests.pages.account import Account\nfrom tests.pages.cloud_page import CloudPage\nfrom tests.pages.shared_page import SharedPage\n\n\ndef check_link(link):\n filepath = link.split('https://cloud.mail.ru/public/')[1]\n query_string = urllib.urlencode({'weblink': filepath})\n url = 'https://cloud.mail.ru/api/v2/file?{}'.format(query_string)\n resp = requests.get(url)\n decoded = json.JSONDecoder().decode(resp.content)\n return decoded\n\n\nclass CloudFileAccessTest(unittest.TestCase):\n NEW_FOLDER_NAME = 'new_folder' + str(uuid.uuid4())\n HOME_URL = 'https://cloud.mail.ru/home/'\n SHARED_PAGE_URL = 'https://cloud.mail.ru/shared/incoming/'\n INVALID_EMAIL = '``````\\\"@mail.ru'\n\n def _create_file_for_test(self, depth):\n for i in range(depth):\n self.cur_cloud_page.toolbars.create_new_folder()\n self.cur_cloud_page.new_folder_popup.create_new(self.NEW_FOLDER_NAME, self.HOME_URL +\n (self.NEW_FOLDER_NAME + '/') * i)\n\n def _delete_folder(self):\n self.cur_cloud_page = CloudPage(self.driver, '')\n self.cur_cloud_page.open()\n self.cur_cloud_page.datalist.choose_folder_by_name('/' + self.NEW_FOLDER_NAME)\n self.cur_cloud_page.toolbars.delete()\n self.cur_cloud_page.delete_popup.accept()\n\n def _grant_access_and_change_user(self):\n self.depth = 2\n self._create_file_for_test(depth=self.depth)\n self.driver.back()\n self.cur_cloud_page.toolbars.share()\n self.cur_cloud_page.share_popup.fill_name(self.other_user_email)\n self.cur_cloud_page.share_popup.choose_access_type('view_only')\n self.cur_cloud_page.share_popup.accept()\n self.cur_cloud_page.share_popup.close()\n self.cur_cloud_page.auth_block.logout()\n self.account.login(self.other_user_email, self.other_user_pass)\n\n self.shared_page = SharedPage(self.driver)\n self.shared_page.open()\n self.shared_page.close_annoying_adverts()\n self.shared_page.invitation_list.accept_by_name(self.NEW_FOLDER_NAME)\n self.shared_page.accept_popup.accept()\n self.shared_page.invitation_list.wait_till_accepted(self.NEW_FOLDER_NAME)\n self.cur_cloud_page = CloudPage(self.driver, self.NEW_FOLDER_NAME)\n self.cur_cloud_page.open()\n self.cur_cloud_page.ad.close()\n\n def _clear_after_change_user(self):\n self.cur_cloud_page.delete_popup.close()\n self.cur_cloud_page.auth_block.logout()\n self.account.login(self.email, self.password)\n self._delete_folder()\n\n def setUp(self):\n before_test_map = {\n 'test_deleted_file_link': partial(self._create_file_for_test, 1),\n 'test_access_to_root_folder': partial(self._create_file_for_test, 1),\n 'test_access_to_deep_folder': partial(self._create_file_for_test, 3),\n 'test_access_to_invalid_user': partial(self._create_file_for_test, 1),\n 'test_invalid_delete': self._grant_access_and_change_user,\n }\n\n browser = os.environ.get('BROWSER', 'CHROME')\n self.email = os.environ['EMAIL']\n self.password = os.environ['PASSWORD']\n self.other_user_email = os.environ['OTHER_USER_EMAIL']\n self.other_user_pass = os.environ['OTHER_USER_PASS']\n self.driver = Remote(\n command_executor='http://127.0.0.1:4444/wd/hub',\n desired_capabilities=getattr(DesiredCapabilities, browser).copy()\n )\n self.account = Account(self.driver)\n self.account.login(self.email, self.password, redirect=self.HOME_URL)\n self.cur_cloud_page = CloudPage(self.driver, '')\n self.cur_cloud_page.ad.close()\n before_test = before_test_map.get(self._testMethodName, None)\n if before_test is not None:\n before_test()\n\n def tearDown(self):\n after_test_map = {\n 'test_access_to_root_folder': self._delete_folder,\n 'test_access_to_deep_folder': self._delete_folder,\n 'test_access_to_invalid_user': self._delete_folder,\n 'test_invalid_delete': self._clear_after_change_user,\n }\n after_test = after_test_map.get(self._testMethodName, None)\n if after_test is not None:\n after_test()\n self.driver.quit()\n\n def test_public_link(self):\n # checks if public link to file is valid after it's creation\n self.cur_cloud_page.datalist.choose_first_file()\n self.cur_cloud_page.toolbars.get_link()\n link = self.cur_cloud_page.get_link_popup.get_link_value()\n decoded = check_link(link)\n self.assertEqual(decoded.get('status', requests.codes.not_found), requests.codes.ok)\n\n def test_public_link_revoke(self):\n # checks if the public link to file is still valid(doesn't return 404) after revoking access\n # (it shouldn't)\n self.cur_cloud_page.datalist.choose_first_file()\n self.cur_cloud_page.toolbars.get_link()\n link = self.cur_cloud_page.get_link_popup.get_link_value()\n self.cur_cloud_page.get_link_popup.close_access()\n decoded = check_link(link)\n self.assertEqual(decoded.get('status', requests.codes.not_found), requests.codes.not_found)\n\n def test_deleted_file_link(self):\n # checks if the public link is still valid after file removing\n # (it shouldn't)\n self.cur_cloud_page.toolbars.get_link()\n link = self.cur_cloud_page.get_link_popup.get_link_value()\n self.cur_cloud_page.get_link_popup.close_popup()\n self.cur_cloud_page.toolbars.delete()\n self.cur_cloud_page.delete_popup.accept()\n decoded = check_link(link)\n self.assertEqual(decoded.get('status', requests.codes.not_found), requests.codes.not_found)\n\n def test_access_to_root_folder(self):\n # tests if it is possible to grant access to folder which is in\n # root folder to concrete user\n share_button_active = self.cur_cloud_page.toolbars.is_share_button_active()\n self.assertTrue(share_button_active)\n\n def test_access_to_deep_folder(self):\n # tests if it is possible to grant access to folder which is in\n # folder deeper then root folder to concrete user\n share_button_active = self.cur_cloud_page.toolbars.is_share_button_active()\n self.assertTrue(share_button_active)\n\n def test_access_to_invalid_user(self):\n # tests if it is possible to grant access on to user whose name is definitely invalid\n self.cur_cloud_page.toolbars.share()\n self.cur_cloud_page.share_popup.fill_name(self.INVALID_EMAIL)\n self.cur_cloud_page.share_popup.accept()\n error_exists = self.cur_cloud_page.share_popup.is_error_exist()\n self.assertTrue(error_exists)\n\n def test_invalid_delete(self):\n # user is granted to view smth, he tries to delete it, should not succeed\n self.cur_cloud_page.datalist.choose_folder_by_name(('/' + self.NEW_FOLDER_NAME) * self.depth)\n self.cur_cloud_page.toolbars.delete()\n self.cur_cloud_page.delete_popup.accept()\n error_exists = self.cur_cloud_page.error_notification_exists()\n self.assertTrue(error_exists)\n","sub_path":"tests/file_access/file_access_test.py","file_name":"file_access_test.py","file_ext":"py","file_size_in_byte":7417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"223038413","text":"#Prints a transposition table for an affine cipher.\n#a must be coprime to m=26.\nimport fractions\nALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \ndecrypted_msg = []\n\ndef build_alpha_to_int_dict():\n output_dict = {}\n i = 0\n for letter in ALPHA:\n output_dict[ALPHA[i]] =i# ALPHA[i]\n i += 1\n return output_dict\n\ndef build_int_to_alpha_dict():\n output_dict = {}\n i = 0\n for letter in ALPHA:\n output_dict[i] = ALPHA[i]\n i += 1\n return output_dict\n\ndef decrypt(msg, a, b):\n int_to_letter = build_int_to_alpha_dict()\n letter_to_int = build_alpha_to_int_dict()\n decrypted_msg = []\n print(\"Decrypted message: \\n\")\n for letter in msg:\n val = 21*(letter_to_int[letter]-b)%26\n print(int_to_letter[val],end=\"\")\n decrypted_msg.append(int_to_letter[val])\n print(\"\\n\\n\")\n return decrypted_msg\n \ndef encrypt(msg,a,b):\n encrypted_msg = []\n print(\"Encrypted message:\\n\")\n for letter in msg:\n letter_to_int = build_alpha_to_int_dict()\n int_to_alpha_dict = build_int_to_alpha_dict()\n val = (a*letter_to_int[letter]+b)%26\n encrypted_msg.append(ALPHA[val])\n print(ALPHA[val],end=\"\")\n print(\"\\n\\n\")\n return encrypted_msg\n\ndef get_factor(number):\n i = 2\n while fractions.gcd(i,number) != 1:\n i += 1 \n return i\n\n\n# Pick the parameter a in encrypt/decrypt to be\n# gcd(a,26)=1\n# So there are multiple values of a that give the\n# same answer for a fixed b. Fascinating.\nprint(\"Test encryption/decryption from wikipedia\")\nprint(\"----------------------------------------\")\ntest = \"AFFINECIPHER\"\ntest_encrypted = encrypt(test,5,8)\ntest_decrypted = decrypt(test_encrypted,5,8)\nprint(\"\\n\\n\")\n\n# Pick b=5 because the message was repeated 5 times\nprint(\"Decrypt the first message from DCDARKNET\")\nfirst_msg = \"RXRQNOTRXSWXNZQOFGZZRPFCZUWXCFMTRQSZZUTNNZUTFWZMZWMTZGFIQCIZFRZOBMMV\"\nfirst_msg_decrypted = decrypt(first_msg,5,5)\n\n# Same paramters\nprint(\"Encrypt the second message from DCDARKNET\")\nprint(\"----------------------------------------\")\nsecond_msg_to_encode = \"skyria will retrieve you\"\nsecond_msg_to_encode_no_white_space = second_msg_to_encode.replace(\" \", \"\").upper()\nencoded_second_msg = encrypt(second_msg_to_encode_no_white_space,5,5)\n\n# Shift cipher?\n# Not yet solved\nprint(\"Decrypt the third message from DCDARKNET\")\nprint(\"----------------------------------------\")\nthird_msg = 'JOQHMAQBYZDSYYIEJWAPNTFDEF'\nthird_msg_decrypted = decrypt(third_msg,1,5)\n","sub_path":"affine_encrypt_decrypt.py","file_name":"affine_encrypt_decrypt.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"654272947","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/webvis/main.py\n# Compiled at: 2019-11-15 00:11:41\n# Size of source mod 2**32: 350 bytes\nimport trio, time\nwith open('./front/teet.t') as (f):\n a = f.read()\nfrom .VisWorker import Vis\n\ndef main():\n vis = Vis(ws_port=8000,\n vis_port=80)\n vis.show()\n N = [\n 42, 12]\n vis.vars['test'] = N\n while True:\n N[1] += 1\n N[0] *= 2\n time.sleep(0.4)\n\n\nif __name__ == '__main__':\n main()","sub_path":"pycfiles/pywebvis-0.0.1-py3.7/main.cpython-37.py","file_name":"main.cpython-37.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"25991499","text":"from mock import Mock\nfrom nose.tools import eq_\n\nfrom django.test import TestCase\n\nfrom us_ignite.challenges import forms\nfrom us_ignite.challenges.models import Challenge, Entry, EntryAnswer, Question\n\n\nclass TestGetEntryChoices(TestCase):\n\n def test_get_entry_choices_are_not_sensitive(self):\n choices = forms.get_entry_choices()\n eq_([i[0] for i in choices], [Entry.DRAFT, Entry.SUBMITTED])\n\n\nclass TestGetFieldName(TestCase):\n\n def test_field_name_is_valid(self):\n field_name = forms.get_field_name(3)\n eq_(field_name, 'question_3')\n\n\nclass TestGetChallengeForm(TestCase):\n\n def test_get_challenge_form(self):\n question_mock = Mock(spec=Question)()\n question_mock.id = 3\n question_mock.question = 'Question 3'\n question_mock.is_required = False\n challenge_mock = Mock(spec=Challenge)()\n challenge_mock.question_set.all.return_value = [question_mock]\n FormClass = forms.get_challenge_form(challenge_mock)\n form = FormClass()\n eq_(sorted(form.fields.keys()), ['question_3', 'status'])\n challenge_mock.question_set.all.assert_called_once()\n\n\nclass TestGetChallengeInitialData(TestCase):\n\n def test_data_is_extracted_successfully(self):\n answer_mock = Mock(spec=EntryAnswer)()\n answer_mock.question_id = 4\n answer_mock.answer = 'This will help society.'\n entry_mock = Mock(spec=Entry)()\n entry_mock.status = Entry.DRAFT\n entry_mock.entryanswer_set.all.return_value = [answer_mock]\n initial_data = forms.get_challenge_initial_data(entry_mock)\n eq_(initial_data, {\n 'status': Entry.DRAFT,\n 'question_4': 'This will help society.',\n })\n","sub_path":"us_ignite/challenges/tests/forms_tests.py","file_name":"forms_tests.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"510466734","text":"# --- Day 18: Duet ---\n# You discover a tablet containing some strange assembly code labeled simply \"Duet\". Rather than bother the sound card\n# with it, you decide to run the code yourself. Unfortunately, you don't see any documentation, so you're left to figure\n# out what the instructions mean on your own.\n#\n# It seems like the assembly is meant to operate on a set of registers that are each named with a single letter and that\n# can each hold a single integer. You suppose each register should start with a value of 0.\n#\n# There aren't that many instructions, so it shouldn't be hard to figure out what they do. Here's what you determine:\n#\n# - snd X plays a sound with a frequency equal to the value of X.\n# - set X Y sets register X to the value of Y.\n# - add X Y increases register X by the value of Y.\n# - mul X Y sets register X to the result of multiplying the value contained in register X by the value of Y.\n# - mod X Y sets register X to the remainder of dividing the value contained in register X by the value of Y\n# (that is, it sets X to the result of X modulo Y).\n# - rcv X recovers the frequency of the last sound played, but only when the value of X is not zero. (If it is zero, the\n# command does nothing.)\n# - jgz X Y jumps with an offset of the value of Y, but only if the value of X is greater than zero. (An offset of 2\n# skips the next instruction, an offset of -1 jumps to the previous instruction, and so on.)\n#\n# Many of the instructions can take either a register (a single letter) or a number. The value of a register is the\n# integer it contains; the value of a number is that number.\n#\n# After each jump instruction, the program continues with the instruction to which the jump jumped. After any other\n# instruction, the program continues with the next instruction. Continuing (or jumping) off either end of the program\n# terminates it.\n#\n# For example:\n#\n# set a 1\n# add a 2\n# mul a a\n# mod a 5\n# snd a\n# set a 0\n# rcv a\n# jgz a -1\n# set a 1\n# jgz a -2\n#\n# - The first four instructions set a to 1, add 2 to it, square it, and then set it to itself modulo 5, resulting in a\n# value of 4.\n# - Then, a sound with frequency 4 (the value of a) is played.\n# - After that, a is set to 0, causing the subsequent rcv and jgz instructions to both be skipped (rcv because a is 0,\n# and jgz because a is not greater than 0).\n# - Finally, a is set to 1, causing the next jgz instruction to activate, jumping back two instructions to another jump,\n# which jumps again to the rcv, which ultimately triggers the recover operation.\n#\n# At the time the recover operation is executed, the frequency of the last sound played is 4.\n#\n# What is the value of the recovered frequency (the value of the most recently played sound) the first time a rcv\n# instruction is executed with a non-zero value?\n#\nfrom collections import namedtuple\n\nInstruction = namedtuple('Instruction', 'op args')\n\n\ndef parse_arg(arg):\n try:\n return int(arg)\n except ValueError:\n return arg\n\n\ndef parse_instr(line):\n op, *args = line.split()\n return Instruction(op=op, args=[parse_arg(arg) for arg in args])\n\n\ndef load(register_file, arg):\n if type(arg) is int:\n return arg\n else:\n return register_file[arg]\n\n\ndef step(program, pc, rc, register_file):\n instr = program[pc]\n if instr.op == 'snd':\n rc = register_file[instr.args[0]]\n elif instr.op == 'set':\n arg = load(register_file, instr.args[1])\n register_file[instr.args[0]] = arg\n elif instr.op == 'add':\n arg = load(register_file, instr.args[1])\n register_file[instr.args[0]] += arg\n elif instr.op == 'mul':\n arg = load(register_file, instr.args[1])\n register_file[instr.args[0]] *= arg\n elif instr.op == 'mod':\n arg = load(register_file, instr.args[1])\n register_file[instr.args[0]] %= arg\n elif instr.op == 'rcv':\n x = load(register_file, instr.args[0])\n if x != 0:\n print('recovers ', rc)\n exit()\n elif instr.op == 'jgz':\n x = load(register_file, instr.args[0])\n if x > 0:\n offset = load(register_file, instr.args[1])\n pc += offset - 1\n\n return pc + 1, rc\n\n\ndef run(program):\n register_file = dict({chr(ord('a') + i): 0 for i in range(0, 26)})\n pc = 0\n rc = None\n while 0 <= pc < len(program):\n pc, rc = step(program, pc, rc, register_file)\n\n\ndef main():\n with open('day18.input.txt') as f:\n program = [parse_instr(line.strip()) for line in f.readlines()]\n run(program)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"day18_1.py","file_name":"day18_1.py","file_ext":"py","file_size_in_byte":4612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"39956153","text":"from file_importer import FileImporter\n\n# Get input\ninp = [list(map(int, y.split(\"-\"))) for y in [x.strip() for x in FileImporter.get_input(\"/../input/20a.txt\").split(\"\\n\")]]\ninp = sorted(inp, key=lambda x: x[0])\n\nmax0, max1 = inp[0][0], inp[0][1]\nallowed = 0\nfor i in inp:\n if i[0] > max0:\n max0 = i[0]\n\n if max0 > max1 + 1:\n allowed += 1\n \n if i[1] > max1:\n max1 = i[1]\n\nprint(allowed)","sub_path":"src/_20b.py","file_name":"_20b.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}