diff --git "a/6232.jsonl" "b/6232.jsonl" new file mode 100644--- /dev/null +++ "b/6232.jsonl" @@ -0,0 +1,770 @@ +{"seq_id":"327969242","text":"import os\n\n\ndirectory = r'E:\\PROGRAMMING\\HACKATHONS\\MCGILL_PHYSICS_2020\\SCRIPTS\\augmented'\n\nfor filename in os.listdir(directory):\n if filename.endswith('.txt'):\n base = os.path.splitext(filename)[0]\n os.rename(os.path.join(directory, filename), base + \".xml\")\n print(filename)","sub_path":"rename.py","file_name":"rename.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"189600790","text":"import torch\nimport numpy as np\nfrom PIL import Image\nimport torchvision.transforms as transforms\nfrom torch.autograd import Variable\nfrom torch.utils.data.dataset import Dataset\nfrom torch.utils.data import DataLoader\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport torch.nn.functional as F\nimport cv2\n\n\n\nrng = np.random.RandomState(2017)\n\n\ndef readFlow(name):\n if name.endswith('.pfm') or name.endswith('.PFM'):\n return readPFM(name)[0][:, :, 0:2]\n\n f = open(name, 'rb')\n\n header = f.read(4)\n if header.decode(\"utf-8\") != 'PIEH':\n raise Exception('Flow file header does not contain PIEH')\n\n width = np.fromfile(f, np.int32, 1).squeeze()\n height = np.fromfile(f, np.int32, 1).squeeze()\n flow = np.fromfile(f, np.float32, width * height * 2).reshape((height, width, 2 ))\n\n return flow.astype(np.float32)\n\n\n'''Just trying to normalized the data \ndef normalizedData(inTensor):\n mean = torch.tensor([0.0484, 0.0043])\n std = torch.tensor([0.4076, 0.0948])\n\n inTensor = (inTensor - mean) / std\n\n # # simple division Normalization\n # inTensor[inTensor > 20.0 ] = 20.0\n # inTensor[ inTensor < -20.0] = -20.0\n # inTensor = torch.div(inTensor, 20.0)\n return inTensor\n\n'''\n\n\ndef Normalize(tensor):\n mean = (0.0484, 0.0043)\n std = (0.4076, 0.0948)\n\n for t, m, s in zip(tensor, mean, std):\n t.sub_(m).div_(s)\n\n return tensor\n\n\ndef np_load_frame(filename, resize_height=256, resize_width=256):\n img = Image.open(filename)\n img_resized = img.resize((resize_width, resize_height),Image.ANTIALIAS)\n img_numpy = np.array(img_resized)\n img_numpy = img_numpy.astype(dtype=np.float32)\n img_numpy = (img_numpy / 127.5) - 1.0\n inImg = torch.from_numpy(img_numpy)\n\n return inImg.permute(2,0,1)\n\n\nclass Datainput(Dataset):\n\n def __init__(self, df):\n\n self.datafile = pd.read_csv(df)\n\n def __len__(self):\n return len(self.datafile)\n\n\n def __getitem__(self, idx):\n '''\n :param idx: pass the index of files\n :return: sample generated randomly\n '''\n\n # Reading Previous Optical flow\n frame1_path = self.datafile.iloc[idx,0]\n frame1 = np_load_frame(frame1_path)\n\n frame2_path = self.datafile.iloc[idx, 1]\n frame2 = np_load_frame(frame2_path)\n\n frame3_path = self.datafile.iloc[idx, 2]\n frame3 = np_load_frame(frame3_path)\n\n # for 4 previous frame\n frame4_path = self.datafile.iloc[idx,3]\n frame4 = np_load_frame(frame4_path)\n\n frame12 = torch.cat((frame1, frame2), 0)\n frame34 = torch.cat((frame3, frame4), 0)\n inputFrame = torch.cat((frame12,frame34),0)\n\n # target optical flow\n flow_path = self.datafile.iloc[idx,4]\n targetFlow = readFlow(flow_path)\n # targetFlow = Normalize(torch.from_numpy(targetFlow))\n targetFlow_tensor = torch.from_numpy(targetFlow)\n targetFlow_arranged = targetFlow_tensor.permute(2,0,1)\n\n\n sample = {'inputFrame': inputFrame.cuda(), 'targetFlow': targetFlow_arranged.cuda()}\n\n return sample\n\n#\n# # # # #\n# data_opt_img = Datainput('data/training_avenue.csv')\n# print(len(data_opt_img))\n#\n# train_loader = torch.utils.data.DataLoader(data_opt_img,batch_size=1, shuffle=True)\n#\n# for k, batch in enumerate(train_loader):\n# print(batch['inputFrame'].size(), batch['targetFlow'].size())\n# print(batch['inputFrame'].max(), batch['inputFrame'].min())\n# print(batch['targetFlow'].max(), batch['targetFlow'].min())\n#\n# if k == 0:\n# break\n\n # if k ==10:\n # break\n #\n\n\n\n\n\n#\n#\n# # Finding out the minimum and maximum value in the Optical flow tensor\n# min = 0\n# max = 0\n# for data in range(0, len(data_opt_img)):\n# inflow = data_opt_img[data]['inFlow']\n# print(\"Data Frame :{} Min:{} Max: {} \".format(data, torch.min(inflow).item(), torch.max(inflow).item()))\n#\n# # if max < torch.max(inflow).item():\n# # max = torch.max(inflow).item()\n# # if min > torch.min(inflow).item():\n# # min = torch.min(inflow).item()\n#\n# # break\n#\n#\n# # print(normValue)\n# # print(' Min value', min)\n# # print(' Max vavlue', max)\n# # print('##################################')\n# # #\n# if data == 100:\n# break\n# train_loader = torch.utils.data.DataLoader(data_opt_img,batch_size=10, shuffle=True)\n#\n# mean = 0.\n# std = 0.\n#\n# nb_samples = 0.\n#\n# for data in train_loader:\n# batch_samples = data['inFlow'].size()\n# print(batch_samples)\n#\n# break\n","sub_path":"unet/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"260690619","text":"# Perfect Table Maker: even the text file has collapsed with uneven tabs and spaces:\n# Code will allign and give a perfect csv file\nimport pandas as pd\nimport csv \n\n\n\n\ndata = pd.read_csv('srce.txt',sep=' ',header = None)\n\ndata.to_csv('source.csv')\ndata.to_csv('source1.csv')\n\n\n\nfin = csv.reader(open('srce.txt', 'rb'), delimiter='\\t')\nfout = open('source.csv', 'w')\nfor row in fin:\n fout.write(','.join(','.join(item.split()) for item in row) + '\\n')\n","sub_path":"Python/perfector.py","file_name":"perfector.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"14955400","text":"import unittest\nfrom Headerbar.get_xpath_func import get_xpath_string\nfrom selenium import webdriver\nfrom pyvirtualdisplay import Display\n\ndisplay = Display(visible=0, size=(1366, 768))\ndisplay.start()\n\nclass AssertLogoPresent(unittest.TestCase):\n def setUp(self):\n self.driver = webdriver.Firefox()\n self.driver.maximize_window()\n self.driver.get('https://www.lybrate.com/')\n def test_logoPresent(self):\n driver = self.driver\n logo_element = driver.find_element_by_xpath(get_xpath_string(\"NavigationBar\",\"Logo\"))\n\n if(logo_element.is_displayed() and logo_element.size is not None):\n print(\"Logo is displayed\")\n else:\n print('Logo is not displayed')\n\n def tearDown(self):\n self.driver.quit()\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"Headerbar/logo_detect.py","file_name":"logo_detect.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"574726666","text":"import csv, sys\nimport csv\nimport json\nimport pandas as pd\nfrom geopy.geocoders import Nominatim\ngeolocator = Nominatim()\n\ndf = pd.read_csv(\"geodata.csv\")\n\nLat = []\nLong = []\naddress = []\n\nfor index,row in df.iterrows():\n location = geolocator.geocode(row[\"Center State\"])\n Lat.append(location.raw['lat'])\n Long.append(location.raw['lon'])\n address.append(location.address)\n\nprint(Lat)\nprint(Long)\nprint(address)\n\nlf = pd.DataFrame(Lat, columns=[\"colummn\"])\nlf.to_csv('list.csv', index=False)\n","sub_path":"Group Project/organ - Copy.py","file_name":"organ - Copy.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"140811241","text":"\nimport random\nimport os\n\n# Variables\ndigitos= '0123456789'\nnumero= ''\nmuertos=0\nheridos=0\nintento= None\nintentos= []\nsalir = False\n\n\n# Presentacion\nos.system('clear')\n\nprint('______________________________________________')\nprint()\nprint(' Juego de Muertos y Heridos ')\nprint(' Consiste en adivinar el numero de 4 dígitos ')\nprint(' Tienes 15 oportunidades ')\nprint(' Pulsa Enter para comenzar ')\nprint()\nprint('______________________________________________')\n\ninput()\n\n# Gererar un número aleatorio de 4 dígitos\nwhile len(numero)<4:\n digito=random.choice(digitos)\n if digito not in numero:\n numero += digito\n\n\n# Bucle principal\nwhile True:\n os.system('clear')\n \n print('********************************')\n print(' MUERTOS Y HERIDOS ')\n print('********************************')\n print(' NUMERO - M - H ')\n print(' ------ - --------- ')\n\n # Imprimir intentos \n for i in range(len(intentos)):\n plantilla = '* {} - {} - {} *'\n print(plantilla.format(intentos[i][0],intentos[i][1],intentos[i][2]))\n \n # Si gana\n if numero == intento:\n print('* Has acertado. Has ganado *')\n print('*Lo has logrado en ', len(intentos), 'intentos *')\n break\n \n # Si pierde por limite de 15 intentos\n if len(intentos) >= 15:\n print('* Se acabaron los intentos. Has perdido *')\n print('* El numero era: ',numero, '*')\n break\n\n # Condiciones del intento del jugador: salir, 4 digitos, solo numeros, no repetidos\n while True:\n intento = input('=> Introduce un intento (\"q\" salir): ')\n if intento == \"q\":\n salir = True\n break \n elif len(intento) < 4 or len(intento)>4:\n print('Debe ser solo de 4 digitos')\n elif intento[0] not in digitos or intento[1] not in digitos or \\\n intento[2] not in digitos or intento[3] not in digitos:\n print('Solo números del 0 al 9')\n elif intento[0] == intento[1] or intento[0] == intento[2] or intento[0] == intento[3] or \\\n intento[1] == intento[2] or intento[1] == intento[3] or intento[2] == intento[3]:\n print('No se pueden repetir numeros')\n else:\n break\n\n # Salir del bucle principal\n if salir:\n print('El número era ',numero)\n break\n \n # Bucle para agregar los muertos y heridos del intento del jugador\n for i in range(4):\n if intento[i] in numero:\n if intento[i] == numero[i]:\n muertos +=1\n else:\n heridos +=1\n \n intentos.append([intento, muertos, heridos])\n muertos=0\n heridos=0\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"549693258","text":"from setuptools import setup, find_packages\n\nfrom eacheck import VERSION\n\ninstall_requires = [\n 'lxml>=4.0'\n]\n\ntests_require = []\n\nsetup(\n name=\"eacheck\",\n version=VERSION,\n description=\"Library to valida XML agains EruditArticle Schema. \",\n author=\"Érudit\",\n author_email=\"fabio.batalha@erudit.org\",\n maintainer=\"Fabio Batalha\",\n maintainer_email=\"fabio.batalha@erudit.org\",\n url=\"http://github.com/fabiobatalha/converter\",\n packages=find_packages(),\n include_package_data=True,\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"Intended Audience :: Developers\",\n \"Programming Language :: Python :: 3\"\n ],\n dependency_links=[],\n tests_require=tests_require,\n test_suite='tests',\n install_requires=install_requires,\n entry_points={\n 'console_scripts': [\n 'eacheck=eacheck.console_script:main'\n ]\n }\n)\n","sub_path":"pypi_install_script/eacheck-0.1.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"78290614","text":"from pyoo.things import Place, Player\nfrom pyoo.placeloader import interpreter_from_placeloader, PlaceLoader\nfrom pyoo.interpret import PyooVerbNotFound\nfrom pyoo.base import make_verb\n\n\nclass DescriptivePlace(Place):\n def handle_enter(self, player):\n super().handle_enter(player)\n self.do_look()\n\n @make_verb(\"look,l\", \"none\", \"none\", \"none\")\n def look(self, verb_callframe):\n self.do_look()\n\n def do_look(self):\n print(self.name)\n if isinstance(self.description, str):\n print(self.description)\n else:\n for line in self.description:\n print(line)\n\n\nloader = PlaceLoader(open(\"roomtest.txt\", \"r\"), DescriptivePlace)\nplayer = Player(\"player\")\ngame = interpreter_from_placeloader(loader)\nporch = game.lookup_global_object(\"Porch\")[0][1]\nrun = True\ngame.update()\ngame.handle_move(porch, player)\n\n# REPL\nif __name__ == \"__main__\":\n while run:\n cmd = \"\"\n try:\n cmd = input(\">\")\n except EOFError:\n run = False\n if cmd.startswith(\"quit\"):\n run = False\n else:\n try:\n game.interpret(cmd, player)\n except PyooVerbNotFound:\n print(\"I don't understand that.\")\n\n print(\"Bye!\")\n","sub_path":"testrooms.py","file_name":"testrooms.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"500907098","text":"# Importing the required libraries\r\nimport cv2\r\nimport numpy as np\r\n\r\ndef dummy(value): # just a dummy function to give as a parameter for the creation of trackbars\r\n\tpass\r\n\r\ncapture = cv2.VideoCapture(\"road_car_view.mp4\")\r\n# Creating a Window with a name\r\ncv2.namedWindow(\"HueSaturationValue Adjuster\")\r\n# Creating trackbars for the HueSaturationValue\r\n# For Lower HSV..\r\ncv2.createTrackbar(\"Lower_Hue\", \"HueSaturationValue Adjuster\", 0, 255, dummy) # for the Hue\r\ncv2.createTrackbar(\"Lower_Sat\", \"HueSaturationValue Adjuster\", 0, 255, dummy) # for the Saturation\r\ncv2.createTrackbar(\"Lower_Val\", \"HueSaturationValue Adjuster\", 0, 255, dummy) # for the Value\r\n# For Higher HSV\r\ncv2.createTrackbar(\"Higher_Hue\", \"HueSaturationValue Adjuster\", 0, 255, dummy) # for the Hue\r\ncv2.createTrackbar(\"Higher_Sat\", \"HueSaturationValue Adjuster\", 0, 255, dummy) # for the Saturation\r\ncv2.createTrackbar(\"Higher_Val\", \"HueSaturationValue Adjuster\", 0, 255, dummy) # for the Value\r\nwhile True: # Running the infinite loop\r\n\tret, colorFrame = capture.read()\r\n\tif ret is False: # What this does is... When the video is finished, it loads it again, so by this we can keep on running(it is as like as being in a infinite loop)\r\n\t\tcapture = cv2.VideoCapture(\"road_car_view.mp4\")\r\n\t\tcontinue\r\n\t\r\n\tgrayFrame = cv2.cvtColor(colorFrame, cv2.COLOR_BGR2GRAY) # converting into gray-scale as processing can be done easily {just for the purpose of detecting the white middle broken lines}\r\n\thsvFrame = cv2.cvtColor(colorFrame, cv2.COLOR_BGR2HSV) # Converting into HSV as to detect the side's yellow color lanes\r\n\t\r\n\t# Getting the H, S, V values from the trackbars\r\n\t# Getting the lower Hue, Saturation, Value values\r\n\tlowerHue = cv2.getTrackbarPos(\"Lower_Hue\", \"HueSaturationValue Adjuster\")\r\n\tlowerSat = cv2.getTrackbarPos(\"Lower_Sat\", \"HueSaturationValue Adjuster\")\r\n\tlowerVal = cv2.getTrackbarPos(\"Lower_Val\", \"HueSaturationValue Adjuster\")\r\n\t# Getting the higher Hue, Saturation, Value values\r\n\thigherHue = cv2.getTrackbarPos(\"Higher_Hue\", \"HueSaturationValue Adjuster\")\r\n\thigherSat = cv2.getTrackbarPos(\"Higher_Sat\", \"HueSaturationValue Adjuster\")\r\n\thigherVal = cv2.getTrackbarPos(\"Higher_Val\", \"HueSaturationValue Adjuster\")\r\n\t\r\n\tlower_hsv = np.array([lowerHue, lowerSat, lowerVal])\r\n\thigher_hsv = np.array([higherHue, higherSat, higherVal])\r\n\t\r\n\t# Getting the Road borders\r\n\tmaskedImage = cv2.inRange(hsvFrame, lower_hsv, higher_hsv)\r\n\t# Doing the bitwise_and operation, so as to keep only which is required and black the one which is not required\r\n\tresultantImage = cv2.bitwise_and(colorFrame, colorFrame, mask=maskedImage)\r\n\t\r\n\t# Displaying the Results\r\n\tcv2.imshow(\"Original Frame\", colorFrame)\r\n\tcv2.imshow(\"Final Detected Image\", resultantImage)\r\n\tcv2.imshow(\"Masked image\", maskedImage)\r\n\tcv2.imshow(\"HueSaturationValued image\", hsvFrame)\r\n\t\r\n\tif cv2.waitKey(40) == 27:\r\n\t\tlwr_vals = [lowerHue, lowerSat, lowerVal]\r\n\t\thigher_vals = [higherHue, higherSat, higherVal]\r\n\t\tprint(\"The final values are: \")\r\n\t\tprint(\"Lower HSV values : \",lwr_vals)\r\n\t\tprint(\"Higher HSV values : \", higher_vals)\r\n\t\tbreak\r\n\r\ncapture.release()\r\ncv2.destroyAllWindows()","sub_path":"Grounding_roots_of_core/Lesson_XX~by PySource-Road_lane_detection.py","file_name":"Lesson_XX~by PySource-Road_lane_detection.py","file_ext":"py","file_size_in_byte":3142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"162247399","text":"import unittest\nfrom trie import *\nfrom levenshtein import *\n\nclass Test(unittest.TestCase):\n def test_grep(self):\n for word in WORDS:\n trie.insert(word)\n l = Levenshtein()\n res = l.search('grup')\n self.assertEqual(res, 'grep')\n\n def test_ping(self):\n for word in WORDS:\n trie.insert(word)\n l = Levenshtein()\n res = l.search('pinh')\n self.assertEqual(res, 'ping')\n\n def test_ls(self):\n for word in WORDS:\n trie.insert(word)\n l = Levenshtein()\n res = l.search('lss')\n self.assertEqual(res, 'ls')","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"284482997","text":"\"\"\"\n\n Student : Shahreen Shahjahan Psyche\n Time : O(N*2^N)\n Space : O(N)\n\n This code ran for all the test cases in Leetcodee\n\n\n\"\"\"\n\nfrom typing import List\n\nclass Solution:\n def subsets(self, nums: List[int]) -> List[List[int]]:\n \n # edge case\n if not nums:\n return []\n \n # output array\n result = []\n # array that will be used to backtrack the subsets\n temp = []\n \n def helper(nums, pos, temp, result):\n \n # appending the current subset. Copying into a new array\n result.append(list(temp))\n \n # now starting from the current pos and creating the subset until wee reach the last of nums\n for i in range(pos, len(nums)):\n temp.append(nums[i])\n helper(nums, i+1, temp, result)\n temp.pop()\n \n \n helper(nums, 0, temp, result)\n \n return result","sub_path":"Problem1.py","file_name":"Problem1.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"136686044","text":"def is_board_full(board):\r\n for i in range(len(board)):\r\n if board[i] == \"-\":\r\n return\r\n for j in range(len(board)):\r\n board[j] = \"-\"\r\n print(\"TIE. NEW GAME\")\r\n display_board(board)\r\n return\r\n\r\n\r\ndef is_turn_valid(num,board):\r\n if(board[num] == \"-\"):\r\n return True;\r\n return False;\r\n\r\n\r\ndef display_board(board):\r\n print(board[0] + \"|\" + board[1] + \"|\" + board[2])\r\n print(board[3] + \"|\" + board[4] + \"|\" + board[5])\r\n print(board[6] + \"|\" + board[7] + \"|\" + board[8])\r\n\r\n\r\n","sub_path":"board_functions.py","file_name":"board_functions.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"267137171","text":"n = 18\ncount = 9\nprint('You have 9 trials to guess the number')\nfor i in range(1,10):\n num1 = int(input('Guess the number between the range of 10 to 20 : '))\n if (num1 <= 14):\n print('Increase your number by a more difference')\n count = count - 1\n print('Number of guesses left : ',count)\n elif (15<=num1<=17):\n print('Increase your number by a small difference')\n count = count - 1\n print('Number of guesses left : ',count)\n elif (num1 == n):\n print('Congratulations! You have guess the correct number.')\n break\n elif (num1 >n and num1<21):\n print('Decrease your number by a small difference')\n count = count - 1\n print('Number of guesses left : ',count)\nwhile (count == 0):\n print('Game Over! Better Luck Next Time.')\n break\n","sub_path":"guess_the_number.py","file_name":"guess_the_number.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"389472365","text":"# coding:utf8\n__author__ = '613108'\nimport sys\nfrom ms_spider_fw.downLoad.DownLoader import DownLoader\nfrom pyquery import PyQuery as pq\n\nreload(sys)\n# noinspection PyUnresolvedReferences\nsys.setdefaultencoding('utf8')\n\n\ndef brandList():\n DL = DownLoader('http://www.xiu.com/brand.html')\n src = DL.selenium()\n d = pq(src)\n text = d.find('li>dl>dd>a').my_text()\n res = []\n for item in text:\n res.extend(item.split('/'))\n res = map(lambda x: x.replace(' ', ''), res)\n return res\n","sub_path":"luxury_project/luxuryBrand/brandList.py","file_name":"brandList.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"242522800","text":"#!/usr/bin/env python3\nimport os\nimport socket\nimport re\nimport sys\nimport time\nimport shutil\nimport inotify.adapters\nfrom datetime import datetime\nfrom sh import which\nfrom avatar2 import archs, Avatar, GDBTarget\nfrom utils import (\n get_base,\n get_arch,\n all_regs,\n REQUEST_FOLDER,\n STATE_FOLDER,\n REJECTED_ENDING,\n)\n\nGDB_PATH = which(\"gdb\")\n\n\ndef dump(workdir, target, base_address):\n mem = target.read_memory(base_address, 0x1000, raw=True)\n with open(\n os.path.join(workdir, STATE_FOLDER, \"{0:016x}\".format(base_address)), \"wb\"\n ) as f:\n f.write(mem)\n print(\"[*] {}: Dumped 0x{:016x}\".format(datetime.now(), base_address))\n\n\ndef forward_requests(target, workdir, requests_path, output_path):\n filenames = os.listdir(requests_path)\n while len(filenames):\n for filename in filenames:\n base_address = get_base(int(filename, 16))\n try:\n print(\n \"[+] {}: Received request for {:016x}\".format(\n datetime.now(), base_address\n )\n )\n if not os.path.isfile(os.path.join(output_path, str(base_address))):\n dump(workdir, target, base_address)\n # we should restart afl now\n except KeyboardInterrupt as ex:\n print(\"cya\")\n exit(0)\n except Exception as e:\n print(\n \"Could not get memory region at {}: {} (Found mem corruption?)\".format(\n hex(base_address), repr(e)\n )\n )\n with open(\n os.path.join(\n output_path, \"{:016x}{}\".format(base_address, REJECTED_ENDING)\n ),\n \"a\",\n ) as f:\n f.write(repr(e))\n os.remove(os.path.join(requests_path, filename))\n filenames = os.listdir(requests_path)\n\n\ndef main(\n workdir,\n module=None,\n breakoffset=None,\n breakaddress=None,\n reset_state=True,\n arch=\"x64\",\n gdb_port=1234,\n gdb_host=\"localhost\",\n):\n request_path = os.path.join(workdir, REQUEST_FOLDER)\n output_path = os.path.join(workdir, STATE_FOLDER)\n\n if arch != \"x64\":\n raise (\"Unsupported arch\")\n if reset_state:\n try:\n shutil.rmtree(output_path)\n except:\n pass\n try:\n os.makedirs(output_path, exist_ok=True)\n except:\n pass\n\n if module:\n if breakaddress is not None:\n raise (\"Breakaddress and module supplied. They are not compatible.\")\n if breakoffset is None:\n raise (\"Module but no breakoffset specified. Don't know where to break.\")\n\n mem_addr = os.popen(\"./get_mod_addr.sh \" + module).readlines()\n try:\n mem_addr = int(mem_addr[0], 16)\n except ValueError as ex:\n print(\n \"Error decoding module addr. Either module {} has not been loaded or something went wrong with ssh ({})\".format(\n module, ex\n )\n )\n exit(-1)\n print(\"Module \" + module + \" is at memory address \" + hex(mem_addr))\n breakaddress = hex(mem_addr + breakoffset)\n else:\n breakaddress = hex(breakaddress)\n\n avatar = Avatar(\n arch=get_arch(arch), output_directory=os.path.join(workdir, \"avatar\")\n )\n target = avatar.add_target(\n GDBTarget, gdb_ip=gdb_host, gdb_port=gdb_port, gdb_executable=GDB_PATH\n )\n target.init()\n\n target.set_breakpoint(\"*{}\".format(breakaddress))\n print(\"[*] Breakpoint set at {}\".format(breakaddress))\n print(\"[+] waiting for bp hit...\")\n target.cont()\n target.wait()\n\n print(\"[+] hit! dumping registers and memory\")\n\n # dump registers\n for reg in all_regs(get_arch(arch)):\n written = True\n reg_file = os.path.join(output_path, reg)\n with open(reg_file, \"w\") as f:\n try:\n val = target.read_register(reg)\n if isinstance(val, list):\n # Avatar special registers (xmm, ...)\n i32list = val\n val = 0\n for shift, i32 in enumerate(i32list):\n val += i32 << (shift * 32)\n f.write(str(val))\n except Exception as ex:\n # print(\"Ignoring {}: {}\".format(reg, ex))\n written = False\n if not written:\n os.unlink(reg_file)\n\n if not os.path.isdir(request_path):\n print(\"[+] Creating request folder\")\n os.mkdir(request_path)\n\n forward_requests(target, workdir, request_path, output_path)\n print(\"[*] Initial dump complete. Listening for requests from ./harness.py.\")\n\n i = inotify.adapters.Inotify()\n # only readily written files\n i.add_watch(request_path, mask=inotify.constants.IN_CLOSE_WRITE)\n for event in i.event_gen(yield_nones=False):\n # print(\"Request: \", event)\n forward_requests(target, workdir, request_path, output_path)\n\n print(\"[*] Exiting probe_wrapper (keyboard interrupt)\")\n\n\nif __name__ == \"__main__\":\n import config\n\n main(\n module=config.MODULE,\n breakoffset=config.BREAKOFFSET,\n breakaddress=config.BREAKADDR,\n workdir=config.WORKDIR,\n arch=config.ARCH,\n gdb_port=config.GDB_PORT,\n gdb_host=config.GDB_HOST,\n )\n","sub_path":"probe_wrapper.py","file_name":"probe_wrapper.py","file_ext":"py","file_size_in_byte":5471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"346362062","text":"import matplotlib.pyplot as plt\nfrom matplotlib import colors\n\nimport time, numpy, sys, PIL\n\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\ndef keyWait():\n input(\"Press Enter to continue...\")\n\ndef printResult(result):\n index = [32, 64, 128, 256]\n plt.close()\n cnt = 0\n for x in result:\n plt.plot(x, label=str(index[cnt]))\n plt.xlim(0,100)\n # plt.show()\n plt.savefig('batch')\ndef printFPS(step):\n now = time.clock()\n timeElapsed = now - printFPS.lastTime\n stepsDone = step - printFPS.lastStep\n\n eprint(\"FPS:\", stepsDone / timeElapsed)\n\n printFPS.lastTime = now\n printFPS.lastStep = step\n\nprintFPS.lastTime = time.clock()\nprintFPS.lastStep = 0\n\ndef displayBrain(brain, res=25): \n mapV, mapA = mapBrain(brain, res)\n\n plt.close()\n plt.show() \n\n fig = plt.figure(figsize=(5,7))\n fig.add_subplot(211)\n\n plt.imshow(mapV)\n plt.colorbar(orientation='vertical')\n\n fig.add_subplot(212)\n\n cmap = colors.ListedColormap(['yellow', 'blue', 'white', 'red'])\n bounds=[-1.5,-0.5,0.5,1.5,2.5]\n norm = colors.BoundaryNorm(bounds, cmap.N)\n\n plt.imshow(mapA, cmap=cmap, norm=norm) \n cb = plt.colorbar(orientation='vertical', ticks=[-1,0,1,2])\n\n plt.pause(0.001)\n\ndef mapBrain(brain, res):\n mapV = numpy.zeros( (2 * res, 2 * res) )\n mapA = numpy.zeros( (2 * res, 2 * res) )\n\n for i1 in range(2 * res):\n for i2 in range(2 * res):\n s = numpy.array( [ (i1 - res) / res, (i2 - res) / res ] )\n mapV[i1, i2] = numpy.amax(brain.predictOne(s))\t# TODO: more efficient to predict all at once\n mapA[i1, i2] = numpy.argmax(brain.predictOne(s))\n\n return (mapV, mapA)\n\ndef showImage(imgData):\n img = PIL.Image.fromarray(imgData)\n img.show()\n\nclass SumTree:\n write = 0\n\n def __init__(self, capacity):\n self.capacity = capacity\n self.tree = numpy.zeros( 2*capacity - 1 )\n self.data = numpy.zeros( capacity, dtype=object )\n\n def _propagate(self, idx, change):\n parent = (idx - 1) // 2\n\n self.tree[parent] += change\n\n if parent != 0:\n self._propagate(parent, change)\n\n def _retrieve(self, idx, s):\n left = 2 * idx + 1\n right = left + 1\n\n if left >= len(self.tree):\n return idx\n\n if s <= self.tree[left]:\n return self._retrieve(left, s)\n else:\n return self._retrieve(right, s-self.tree[left])\n\n def total(self):\n return self.tree[0]\n\n def add(self, p, data):\n idx = self.write + self.capacity - 1\n\n self.data[self.write] = data\n self.update(idx, p)\n\n self.write += 1\n if self.write >= self.capacity:\n self.write = 0\n\n def update(self, idx, p):\n change = p - self.tree[idx]\n\n self.tree[idx] = p\n self._propagate(idx, change)\n\n def get(self, s):\n idx = self._retrieve(0, s)\n dataIdx = idx - self.capacity + 1\n\n return (idx, self.tree[idx], self.data[dataIdx])\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"271903645","text":"from word2vec.cbow.pytorch.softmax import const\nimport re\nimport random\nimport numpy as np\nimport nltk\nimport jieba\nimport collections\nfrom collections import defaultdict, Counter\n\n\ndef rm_sign(string):\n string = re.sub(\"[\\.\\!_,\\$\\(\\)\\\"\\'\\]\\[!!\\?,。?、~@#¥……&]+\", \"\", string)\n return string\n\n\ndef load_data(corpus_dir='../../../corpus/articles.txt'):\n with open(corpus_dir, 'r') as f:\n for line in f:\n line = line.strip()\n if len(line) == 0:\n continue\n yield jieba.lcut(rm_sign(line))\n\n\nclass Corpus(object):\n def __init__(self, data):\n flatten = lambda l: [item.lower() for sublist in l for item in sublist]\n word_count = Counter(flatten(data)).most_common()\n self.word2idx = {const.U_TOKEN: 0}\n self.n_words = 1\n for word, _ in word_count:\n self.word2idx[word] = self.n_words\n self.n_words += 1\n self.idx2word = dict(zip(self.word2idx.values(), self.word2idx.keys()))\n self.vocab = list(self.word2idx.keys())\n\n # @return batch data\n # @generator\n def batch_data(self):\n batch_size = const.BATCH_SIZE * const.WIN_SIZE\n data = self.vocab\n data_index = 0\n assert batch_size % const.WIN_SIZE == 0\n assert const.WIN_SIZE <= 2 * const.SKIP_WIN\n\n batch = np.ndarray(shape=(batch_size), dtype=np.int32)\n labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)\n span = 2 * const.SKIP_WIN + 1 # [ const.SKIP_WIN target const.SKIP_WIN ]\n buffers = collections.deque(maxlen=span)\n\n for _ in range(span):\n buffers.append(data[data_index])\n data_index = (data_index + 1) % len(data)\n\n for i in range(batch_size // const.WIN_SIZE):\n\n target = const.SKIP_WIN # target label at the center of the buffers\n targets_to_avoid = [const.SKIP_WIN]\n for j in range(const.WIN_SIZE):\n while target in targets_to_avoid:\n target = random.randint(0, span - 1)\n targets_to_avoid.append(target)\n batch[i * const.WIN_SIZE + j] = self.var_word(buffers[const.SKIP_WIN])[0]\n labels[i * const.WIN_SIZE + j, 0] = self.var_word(buffers[target])[0]\n buffers.append(data[data_index])\n data_index = (data_index + 1) % len(data)\n\n label_CBOW = []\n context_CBOW = []\n for i in range(0, len(batch), const.WIN_SIZE):\n label_CBOW.append(batch[i])\n context_CBOW.append([l[0] for l in labels[i:i + const.WIN_SIZE]])\n return np.array(context_CBOW), np.array(label_CBOW).reshape(batch_size // const.WIN_SIZE, 1)\n\n # @input sentence [w1, w2, ... , wn]\n def var_sentence(self, sentence):\n idxs = list(map(lambda w: self.word2idx[w] if w in self.vocab else self.word2idx[const.U_TOKEN], sentence))\n return idxs\n\n # @input word\n def var_word(self, word):\n idx = [self.word2idx[const.U_TOKEN]]\n if word in self.word2idx:\n idx = [self.word2idx[word]]\n return idx\n","sub_path":"word2vec/cbow/pytorch/softmax/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":3115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"633961642","text":"import decimal\nfrom dateutil.parser import parse\nfrom optparse import OptionValueError\nfrom django.contrib.humanize.templatetags import humanize\nfrom django.utils import timezone\n\n\nclass FormattingHelpers(object):\n\n @staticmethod\n def price(price):\n return u'${0}'.format(\n humanize.intcomma(\n decimal.Decimal(price).quantize(\n decimal.Decimal('0.00'))))\n\n @staticmethod\n def hours(time):\n return u'{0}'.format(\n time.quantize(\n decimal.Decimal('0.00'),\n rounding=decimal.ROUND_UP))\n\n @staticmethod\n def verify_input_date(option, opt, value, parser):\n try:\n setattr(parser.values,\n option.dest,\n parse(value,\n yearfirst=True).replace(\n tzinfo=timezone.get_default_timezone()))\n except Exception:\n raise OptionValueError('invalid date format, must be yyyy-mm-dd')\n if (getattr(parser.values,\n option.dest) >= timezone.now().replace(hour=0,\n minute=0,\n second=0,\n microsecond=0)):\n raise OptionValueError('date must be in the past')\n","sub_path":"project_billing/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"275347000","text":"from debugsqlalchemy import db\nfrom models import Person, Pet\ndb.drop_all()\ndb.create_all()\nkathiravan = Person(name=\"Kathiravan\")\ndb.session.add(kathiravan)\ndb.session.commit()\nmichelle = Person(name=\"Michelle\")\ndb.session.add(michelle)\ndb.session.commit()\n\njhujhu = Pet(name=\"JhuJhu\", owner=kathiravan)\nbabblu = Pet(name='Bablu', owner=kathiravan)\n\nspot = Pet(name=\"Spot\", owner = michelle)\ndb.session.commit()","sub_path":"sqlalchemy-relationships/setup_debugsqlalchemy.py","file_name":"setup_debugsqlalchemy.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"172822253","text":"#!/usr/bin/env python\nfrom unittest import main, TestCase\nfrom assert_is import not_, ok_\nfrom datetimecls import datetimecls \n\nclass Test(TestCase):\n def test_today(self):\n td=datetimecls.now()\n not_(td.yesterday)\n ok_(td.today)\n not_(td.tomorrow)\n\nif __name__ == \"__main__\": # pragma: no cover\n main()","sub_path":"tests/test_today.py","file_name":"test_today.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"46024789","text":"#Tim Pauley\n#Assignment 05, \n#Feb 10 2019\n#Update Feb 20 2019\n\n'''\nAssignment Description\n\nRequirements:\n\n1. As a HP Norton customer I want to see a list of all products available for \nrent so that I can make a rental choice.\n\n2. As a HP Norton salesperson I want to see a list of all of the different \nproducts, showing product ID, description, product type and quantity \navailable.\n\n3. As a HP Norton salesperson I want to see a list of the names and contact\ndetails (address, phone number and email) of all customers who have \nrented a certain product.\n\nHere is what you need to do:\n\n1. Create a product database with attributes that reflect the contents of the \ncsv file.\n\n2. Import all data in the csv files into your MongoDB implementation.\n\n3. Write queries to retrieve the product data.\n\n4. Write a query to integrate customer and product data.\n'''\n\n\"\"\"\nLesson 05 Assignment\nMongoDB\n\"\"\"\n\nimport csv\nimport os\nimport pymongo\n\n# pylint: disable-msg=line-too-long\n# pylint: disable-msg=invalid-name\n# pylint: disable-msg=redefined-outer-name\n\n\nclass MongoDBConnection:\n \"\"\"\n Creates a MongoDB Connection\n \"\"\"\n def __init__(self, host='127.0.0.1', port=27017):\n self.host = host\n self.port = port\n self.connection = None\n\n def __enter__(self):\n self.connection = pymongo.MongoClient(self.host, self.port)\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.connection.close()\n\n\ndef print_mdb_collection(collection_name):\n \"\"\"\n Prints documents in a collection.\n :param collection_name: collection\n :return:\n \"\"\"\n for doc in collection_name.find():\n print(doc)\n\n\ndef _import_csv(filename):\n \"\"\"\n Returns a list of dictionaries. One dictionary for each row of data in a csv file.\n :param filename: csv file\n :return: list of dictionaries\n \"\"\"\n\n with open(filename, newline=\"\") as csvfile:\n dict_list = []\n\n csv_data = csv.reader(csvfile)\n\n headers = next(csv_data, None) # Save the first line as the headers\n\n if headers[0].startswith(\"\"): # Check for weird formatting\n headers[0] = headers[0][3:]\n\n for row in csv_data:\n row_dict = {}\n\n for index, column in enumerate(headers):\n row_dict[column] = row[index]\n\n dict_list.append(row_dict)\n\n return dict_list\n\n\ndef _add_bulk_data(collection, directory_name, filename):\n file_path = os.path.join(directory_name, filename)\n\n try:\n collection.insert_many(_import_csv(file_path), ordered=False)\n return 0\n\n except pymongo.errors.BulkWriteError as bwe:\n print(bwe.details)\n return len(bwe.details[\"writeErrors\"])\n\n\ndef import_data(db, directory_name, products_file, customers_file, rentals_file):\n \"\"\"\n Takes a directory name and three csv files as input. Creates and populates a new MongoDB.\n :param db: MongoDB\n :param directory_name: directory name for files. Use \"\" for current directory.\n :param products_file: csv file with product data\n :param customers_file: csv file with customer data\n :param rentals_file: csv file with rentals data\n :return: Tuple with record count for products, customers, rentals added (in that order) and\n tuple with count of errors that occurred for products, customers, rentals (in that order).\n \"\"\"\n\n products = db[\"products\"]\n products_errors = _add_bulk_data(products, directory_name, products_file)\n\n customers = db[\"customers\"]\n customers_errors = _add_bulk_data(customers, directory_name, customers_file)\n\n rentals = db[\"rentals\"]\n rentals_errors = _add_bulk_data(rentals, directory_name, rentals_file)\n\n record_count = (db.products.count_documents({}), db.customers.count_documents({}), db.rentals.count_documents({}))\n\n error_count = (products_errors, customers_errors, rentals_errors)\n\n return record_count, error_count\n\n\ndef show_available_products(db):\n \"\"\"\n Returns a dictionary for each product listed as available.\n :param db: MongoDB\n :return: Dictionary with product_id, description, product_type, quantity_available.\n \"\"\"\n\n available_products = {}\n\n for product in db.products.find():\n if int(product[\"quantity_available\"]) > 0:\n\n product_dict = {\"description\": product[\"description\"],\n \"product_type\": product[\"product_type\"],\n \"quantity_available\": product[\"quantity_available\"]}\n\n available_products[product[\"product_id\"]] = product_dict\n\n return available_products\n\n\ndef show_rentals(db, product_id):\n \"\"\"\n Returns a dictionary with user information from users who have rented products matching the product_id.\n :param db: MongoDB\n :param product_id: product id\n :return: user_id, name, address, phone_number, email\n \"\"\"\n\n customer_info = {}\n\n for rental in db.rentals.find():\n if rental[\"product_id\"] == product_id:\n customer_id = rental[\"user_id\"]\n\n customer_record = db.customers.find_one({\"user_id\": customer_id})\n\n customer_dict = {\"name\": customer_record[\"name\"],\n \"address\": customer_record[\"address\"],\n \"phone_number\": customer_record[\"phone_number\"],\n \"email\": customer_record[\"email\"]}\n\n customer_info[customer_id] = customer_dict\n\n return customer_info\n\n\ndef clear_data(db):\n \"\"\"\n Delete data in MongoDB.\n :param db: MongoDB\n :return: Empty MongoDB.\n \"\"\"\n db.products.drop()\n db.customers.drop()\n db.rentals.drop()\n\n\nif __name__ == \"__main__\":\n mongo = MongoDBConnection()\n\n with mongo:\n print(\"Opening a MongoDB.\\n\")\n db = mongo.connection.media\n\n print(\"Importing data for products, customers, and rentals.\\n\")\n import_data(db, \"\", \"products.csv\", \"customers.csv\", \"rentals.csv\")\n\n print(\"Showing available products:\")\n print(show_available_products(db))\n\n print(\"\\nShowing rental information for prd005:\")\n print(show_rentals(db, \"prd005\"))\n\n print(\"\\nClearing data from database.\")\n clear_data(db)\n","sub_path":"students/TimPauley/session05/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":6217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"247033585","text":"from skimage.feature import local_binary_pattern\nfrom PIL import Image\nimport numpy as np\n\n# settings\nneighbors = 8 # ?\nradius = 2 # ?\nmethod = 'nri_uniform' # ?\nregions_num = [6, 10] # ? component-based\nface_size = [150, 170]\n\ndef lbp(filename):\n '''\n Extract the local binary pattern from image of filename\n :param filename: \n filename - the path to face image (detected, aligned and cropped)\n :return: \n feature - matrix where row is\n '''\n image = Image.open(filename).convert('L')\n imarray = np.array(image)\n\n # divide into regions\n [per_width, per_height] = [int(face_size[0]/regions_num[0]), int(face_size[1]/regions_num[1])]\n regions = [ imarray[r*per_height:(r+1)*per_height, c*per_width:(c+1)*per_width] for c in range(regions_num[0]) for r in range(regions_num[1])]\n\n patterns = [local_binary_pattern(region, neighbors, radius, method) for region in regions]\n\n bin_range = int(np.ceil(np.max(patterns)))\n hists = [ np.histogram(pattern.ravel(), bins=bin_range)[0] for pattern in patterns] # ? normalize\n return np.vstack(hists) # row - region , column - label","sub_path":"feature_extraction/LBP/LBP.py","file_name":"LBP.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"554014677","text":"# coding: UTF-8\nPOINT_SIZE = 10\nP_SIZE = 100\nQ_SIZE = 100\nSLEEP_SIZE = 0\nM_RATE = 0.05\n\nfrom Tkinter import *\nfrom random import Random\nimport my_module\nimport random\nimport time\nfrom math import sqrt\n\ndef numeric_compare(x,y):\n return int(my_module.distance(point_table,x)-my_module.distance(point_table,y))\n\npoint_table = []\npoint_table = [[100,300],[160,400],[600,130],[730,70],[130,600],[400,500],[800,300],[410,50],[90,190]]\n'''\nf = open('point_table.txt','r')\nfor line in f:\n line = line.strip()\n point = line.split(',')\n point[0] = int(point[0])\n point[1] = int(point[1])\n point_table.append(point)\n'''\nroot = Tk()\nc0 = Canvas(root, width=1000, height=1000)\nfor point in point_table:\n c0.create_oval(point[0]-POINT_SIZE/2, point[1]-POINT_SIZE/2, point[0]+POINT_SIZE/2, point[1]+POINT_SIZE/2, fill=\"red\")\n\ngeneration = 0\nr = Random()\np_path = []\nfor x in range(P_SIZE):\n c = range(len(point_table))\n r.shuffle(c)\n p_path.append(c)\n\nwhile True:\n generation += 1\n q_path = []\n for x in range(Q_SIZE):\n r1 = random.randint(0,P_SIZE-1)\n r2 = random.randint(0,P_SIZE-1)\n offspring = my_module.one_cross(my_module.order(p_path[r1]),my_module.order(p_path[r2]))\n q_path.append(my_module.path(offspring))\n\n for x in range(Q_SIZE):\n for gene in range(len(point_table)):\n ran = random.random()\n if ran < M_RATE:\n r1 = random.randint(0, len(point_table)-1)\n q_path[x][gene],q_path[x][r1] = q_path[x][r1],q_path[x][gene]\n\n pq_path = sorted(p_path+q_path, cmp=numeric_compare)\n p_path = []\n\n p_path.append(pq_path.pop(0))\n while len(p_path) <= P_SIZE:\n r1 = random.randint(0, len(pq_path)-1)\n r2 = random.randint(0, len(pq_path)-1)\n if r1 <= r2:\n p_path.append(pq_path.pop(r1))\n else:\n p_path.append(pq_path.pop(r2))\n\n time.sleep(SLEEP_SIZE)\n\n c0.create_text(200, 30, text = str(generation)+\"世代目:総距離\"+str(my_module.distance(point_table,p_path[0])), font = (\"FixedSys\",14), tags = \"lines\")\n\n for x in range(len(point_table)-1):\n c0.create_line(point_table[p_path[0][x]][0], point_table[p_path[0][x]][1],point_table[p_path[0][x+1]][0], point_table[p_path[0][x+1]][1], tags = \"lines\")\n\n c0.create_line(point_table[p_path[0][-1]][0], point_table[p_path[0][-1]][1],point_table[p_path[0][0]][0], point_table[p_path[0][0]][1], tags = \"lines\")\n c0.pack()\n c0.update()\n c0.delete(\"lines\")\n print(p_path[0])\n if generation == 100:\n break\nroot.mainloop()\n","sub_path":"ga.py","file_name":"ga.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"598618432","text":"import os\nclear = lambda: os.system('clear')\nclear()\n\nimport re\n\ndata = \"Hello, world!\"\nexp = \"Hello\"\nprint(data)\noutput = input('{} >>> '.format(exp))\nregex = re.compile(output)\nmo = regex.search(data).group()\nprint(mo)","sub_path":"lesson125.py","file_name":"lesson125.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"71722047","text":"from flask import Flask, render_template, url_for, request\nimport requests\n\napp = Flask('app2')\n\nkey_list = [\"id\", \"location\", \"alive\", \"lastupdate\"] # A list of keys of relevant incoming JSON data.\napi_url = 'http://127.0.0.1:4000' # The url of the Beehive API.\n\n\n@app.route('/')\ndef dashboard():\n \"\"\"\n\n Update Argument Parsing!\n\n This function is a route to the dashboard homepage, and calls all of the functions necessary for rendering the\n data table.\n :return: An HTML template that replaces a Jinja block with the HTML table generated in DASHTABLE.\n The DASHTABLE parameter in the return statement connects the Jinja block in 'dashboard.html' to the HTML\n generated in the DASHTABLE function.\n \"\"\"\n\n\n # http://127.0.0.1:5000/?location=chicago&status=alive\n location = str(request.args.get('location'))\n status = str(request.args.get('status'))\n table = dashtable(apirequest(api_url), location, status)\n # print(apirequest(\"http://10.10.10.137:7000/nodeApi\"))\n return render_template('dashboard.html', dashtable=table)\n\n\ndef apirequest(url):\n \"\"\"\n This function sends a request to an api, and then converts the received data into JSON.\n :param url: The url of the chosen api.\n :return: The received data in JSON format.\n \"\"\"\n req = requests.get(url)\n json_data = req.json()\n return json_data\n\n\ndef dashtable(data, argloc, argstat):\n \"\"\"\n\n Update new parameters!\n\n This function generates a table based on the data received from the api.\n The table headers must be updated manually to match any new figures.\n :param data: This is JSON data passed in the DASHBOARD function from the APIREQUEST function.\n :param argloc: location arg\n :param argstat: status arg\n :return: A string of HTML code that generates a readable table of data.\n \"\"\"\n\n print(argloc)\n print(argstat)\n testData = data\n tbl = []\n\n # This section generates the table headers.\n # This must be manually updated when new columns are to be introduced.\n tbl.append(\"
\")')\n print(\"2. Launch the Rich Presence (Requires /tokens folder)\")\n print(\"3. Delete your Credentials\")\n print(\"4. Exit\")\n print(\"------------------------------------------------------------------------------------------------------------------------\")\n print(\"Current Build: 0.3.3\")\n print(\"------------------------------------------------------------------------------------------------------------------------\")\n selection = int(input(\"Select from list: \"))\n return selection\n\ndef splashScreen():\n \"\"\"Creates a Screen to show the devs and other program info.\n \"\"\"\n clear()\n print(\"------------------------------------------------------------------------------------------------------------------------\")\n print(\"Halo: MCC Rich Presence\")\n print(\"------------------------------------------------------------------------------------------------------------------------\")\n print(\"Created by kay-el-zed, Gurrman375D.\")\n print(\"Maintained by Gurrman375D.\")\n print(\"------------------------------------------------------------------------------------------------------------------------\")\n print(\"Current Build: 0.3.3\")\n print(\"------------------------------------------------------------------------------------------------------------------------\")\n sleep(5)\n clear()\n\n \nif __name__ == \"__main__\":\n system('color 2')\n try:\n ctypes.windll.kernel32.SetConsoleTitleW(\"Halo Master Chief Collection Rich Presence\")\n main()\n except KeyboardInterrupt as e:\n print(e)\n sleep(1)\n clear()\n print(\"Manually Close the App\")\n optionUI()","sub_path":"ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":3694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"426582849","text":"# Copyright 2015 IBM Corp.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport os\n\nfrom oslo_log import log as logging\n\nfrom trove.guestagent.datastore.experimental.couchdb import service\nfrom trove.guestagent.datastore import manager\nfrom trove.guestagent import volume\n\n\nLOG = logging.getLogger(__name__)\n\n\nclass Manager(manager.Manager):\n \"\"\"\n This is CouchDB Manager class. It is dynamically loaded\n based off of the datastore of the Trove instance.\n \"\"\"\n\n def __init__(self):\n self.appStatus = service.CouchDBAppStatus()\n self.app = service.CouchDBApp(self.appStatus)\n super(Manager, self).__init__('couchdb')\n\n @property\n def status(self):\n return self.appStatus\n\n def do_prepare(self, context, packages, databases, memory_mb, users,\n device_path, mount_point, backup_info,\n config_contents, root_password, overrides,\n cluster_config, snapshot):\n \"\"\"This is called from prepare in the base class.\"\"\"\n self.app.install_if_needed(packages)\n if device_path:\n self.app.stop_db()\n device = volume.VolumeDevice(device_path)\n # unmount if device is already mounted\n device.unmount_device(device_path)\n device.format()\n if os.path.exists(mount_point):\n device.migrate_data(mount_point)\n device.mount(mount_point)\n LOG.debug('Mounted the volume (%s).' % device_path)\n self.app.start_db()\n self.app.change_permissions()\n self.app.make_host_reachable()\n\n def stop_db(self, context, do_not_start_on_reboot=False):\n \"\"\"\n Stop this CouchDB instance.\n This method is called when the guest agent\n gets a stop message from the taskmanager.\n \"\"\"\n LOG.debug(\"Stopping the CouchDB instance.\")\n self.app.stop_db(do_not_start_on_reboot=do_not_start_on_reboot)\n\n def restart(self, context):\n \"\"\"\n Restart this CouchDB instance.\n This method is called when the guest agent\n gets a restart message from the taskmanager.\n \"\"\"\n LOG.debug(\"Restarting the CouchDB instance.\")\n self.app.restart()\n\n def start_db_with_conf_changes(self, context, config_contents):\n LOG.debug(\"Starting CouchDB with configuration changes.\")\n self.app.start_db_with_conf_changes(config_contents)\n","sub_path":"trove/guestagent/datastore/experimental/couchdb/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"141985131","text":"# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport time\nfrom statistics import mean\nfrom typing import Iterator\n\nimport torch\nfrom torch.utils.data import DataLoader, IterableDataset\n\nfrom pytorch_lightning import LightningModule, Trainer\nfrom pytorch_lightning.utilities.types import STEP_OUTPUT\nfrom tests.helpers.runif import RunIf\n\n\ndef count_cycles_per_ms() -> float:\n \"\"\"\n Measure and return approximate number of cycles per millisecond for torch.cuda._sleep\n\n Copied from: github.com/pytorch/pytorch/blob/master/test/test_cuda.py\n \"\"\"\n\n def measure() -> float:\n start = torch.cuda.Event(enable_timing=True)\n end = torch.cuda.Event(enable_timing=True)\n start.record()\n torch.cuda._sleep(1000000)\n end.record()\n end.synchronize()\n cycles_per_ms = 1000000 / start.elapsed_time(end)\n return cycles_per_ms\n\n # Get 10 values and remove the 2 max and 2 min and return the avg.\n # This is to avoid system disturbance that skew the results, e.g.\n # the very first cuda call likely does a bunch of init, which takes\n # much longer than subsequent calls.\n #\n # Tested on both Tesla V100, Quadro GP100, Titan RTX, RTX 3090 GPUs\n # and seems to return stable values. Therefore, we enable caching\n # using lru_cache decorator above.\n num = 10\n vals = []\n for _ in range(num):\n vals.append(measure())\n vals = sorted(vals)\n return mean(vals[2 : num - 2])\n\n\n_CYCLES_PER_MS = int(count_cycles_per_ms()) if torch.cuda.is_available() else 0\n_BATCH_SIZE = 128\n_EMB_SZ = 100\n_EMB_DIM = 64\n\n\nclass RandomSparseDataset(IterableDataset):\n def __init__(self, emb_dim: int, batch_size: int, count: int) -> None:\n self.emb_dim = emb_dim\n self.batch_size = batch_size\n self.count = count\n\n def __iter__(self):\n for _ in range(self.count):\n yield torch.randint(self.emb_dim, [self.batch_size])\n\n\nclass ToyDLRMModel(LightningModule):\n \"\"\"\n A toy model for mimicking the communication overhead of sharded embedding\n modules in DLRM models.\n\n DLRM models can be trained in a DDP-like fashion, where each trainer\n receives different batches (embedding indices in this example). Since the\n embeddings are sharded across trainers, the lookup process involves (1)\n routing the indices to the trainer that possesses the corresponding\n embeddings (2) performing local lookup (3) routing the embedding lookup\n result back.\n\n The toy model doesn't actually performs index/result routing. It simply\n uses torch.cuda._sleep() to mimic the cost of the communication op (i.e.\n a2a).\n \"\"\"\n\n def __init__(self):\n super().__init__()\n self.automatic_optimization = False\n self.local_embedding = torch.nn.Embedding(_EMB_SZ, _EMB_DIM)\n\n def _route_indices(self, batch: torch.Tensor, non_blocking=False):\n \"\"\"\n This can be parallelized across different batches since it's model\n weight independent.\n\n Why not run this in dataloader/datamodule?\n - The routing logic depends on how model is sharded\n - Putting this in data preprocessor changes the semantic of the model\n \"\"\"\n torch.cuda._sleep(_CYCLES_PER_MS * 1_000)\n if not non_blocking:\n torch.cuda.synchronize()\n return batch\n\n def _route_result(self, result: torch.Tensor, non_blocking=False):\n torch.cuda._sleep(_CYCLES_PER_MS * 1_000)\n if not non_blocking:\n torch.cuda.synchronize()\n return result\n\n def forward(self, indices: torch.Tensor):\n local_indices = self._route_indices(indices)\n result = self.local_embedding(local_indices)\n return self._route_result(result)\n\n def training_step(self, batch: torch.Tensor, batch_idx: int) -> STEP_OUTPUT:\n return self.forward(batch)\n\n def configure_optimizers(self):\n return torch.optim.SGD(self.local_embedding.parameters(), lr=0.1)\n\n def train_dataloader(self):\n return DataLoader(RandomSparseDataset(_EMB_DIM, _BATCH_SIZE, 5))\n\n\nclass AsyncToyDLRMModel(ToyDLRMModel):\n def __init__(self):\n super().__init__()\n self.comm_stream = torch.cuda.Stream()\n self.batch_i = None\n self.batch_i_ready = torch.cuda.Event()\n\n def training_step(self, dataloader_iter: Iterator) -> STEP_OUTPUT:\n if self.batch_i is None:\n self.batch_i = next(dataloader_iter)\n with torch.cuda.stream(self.comm_stream):\n self._route_indices(self.batch_i, non_blocking=True)\n self.batch_i_ready.record()\n\n # Invariant: the routing for batch[i] has been kicked off\n is_last = False\n batch_ip1 = None\n batch_ip1_ready = torch.cuda.Event()\n try:\n batch_ip1 = next(dataloader_iter)\n with torch.cuda.stream(self.comm_stream):\n self._route_indices(batch_ip1, non_blocking=True)\n batch_ip1_ready.record()\n except StopIteration:\n is_last = True\n\n self.batch_i_ready.wait()\n\n result = self.local_embedding(self.batch_i)\n self._route_result(result)\n\n self.batch_i = batch_ip1\n self.batch_i_ready = batch_ip1_ready\n\n return {\"is_last\": is_last}\n\n\n@RunIf(min_gpus=1)\ndef test_inter_batch_parallelism(tmpdir):\n \"\"\"\n Verify the speedup of a simple inter-batch parallelization use case enabled\n by exposing `dataloader_iter` to `training_step`.\n \"\"\"\n begin_time = time.time()\n m = AsyncToyDLRMModel()\n trainer = Trainer(max_epochs=1, default_root_dir=tmpdir)\n trainer.fit(m)\n async_duration = time.time() - begin_time\n\n begin_time = time.time()\n m = ToyDLRMModel()\n trainer = Trainer(max_epochs=1, default_root_dir=tmpdir)\n trainer.fit(m)\n sync_duration = time.time() - begin_time\n\n # We expect 2x speedup. However, we only assert that the async\n # training_step is faster in order to avoid flaky tests\n assert async_duration < sync_duration, \"Expect `AsyncToyDLRMModel` to train faster than `ToyDLRMModel`.\"\n","sub_path":"tests/loops/test_inter_batch_parallelism.py","file_name":"test_inter_batch_parallelism.py","file_ext":"py","file_size_in_byte":6647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"128638608","text":"import json\nimport os\nimport time\n\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom andrewtfesta.settings import CONTENT_ROOT\n\n\ndef get_content_dict(page_name: str, section_name: str) -> dict:\n content_fname = os.path.join(CONTENT_ROOT, page_name, '{}.{}'.format(section_name, 'json'))\n if not os.path.isfile(content_fname):\n content_dict = ['Unable to locate {} {} information at: {}'.format(section_name, page_name, content_fname)]\n else:\n with open(content_fname, 'r+', encoding='utf8') as cfile:\n content_dict = json.load(cfile)\n return content_dict\n\n\ndef approach(request):\n time_stamp = time.strftime('%b %d, %Y, %H:%M:%S', time.gmtime())\n\n approach_sections = get_content_dict('thesis', 'approach')\n render_dict = {\n 'page_title': 'Approach',\n 'sections': approach_sections\n }\n return render(request, 'thesis/approach.html', render_dict)\n\n\ndef architecture(request):\n time_stamp = time.strftime('%b %d, %Y, %H:%M:%S', time.gmtime())\n\n architecture_sections = get_content_dict('thesis', 'architecture')\n render_dict = {\n 'page_title': 'Architecture',\n 'sections': architecture_sections\n }\n return render(request, 'thesis/architecture.html', render_dict)\n\n\ndef background(request):\n time_stamp = time.strftime('%b %d, %Y, %H:%M:%S', time.gmtime())\n\n background_sections = get_content_dict('thesis', 'background')\n render_dict = {\n 'page_title': 'Background',\n 'sections': background_sections\n }\n return render(request, 'thesis/background.html', render_dict)\n\n\ndef index(request):\n time_stamp = time.strftime('%b %d, %Y, %H:%M:%S', time.gmtime())\n\n index_sections = get_content_dict('thesis', 'index')\n render_dict = {\n 'page_title': 'Data Representation for Motor Imagery Classification',\n 'sections': index_sections\n }\n return render(request, 'thesis/index.html', render_dict)\n\n\ndef tasks(request):\n time_stamp = time.strftime('%b %d, %Y, %H:%M:%S', time.gmtime())\n\n task_sections = get_content_dict('thesis', 'tasks')\n render_dict = {\n 'page_title': 'Tasks',\n 'sections': task_sections\n }\n return render(request, 'thesis/tasks.html', render_dict)\n\n\ndef timeline(request):\n time_stamp = time.strftime('%b %d, %Y, %H:%M:%S', time.gmtime())\n\n timeline_sections = get_content_dict('thesis', 'timeline')\n render_dict = {\n 'page_title': 'Timeline',\n 'sections': timeline_sections\n }\n\n return render(request, 'thesis/timeline.html', render_dict)\n\n\ndef updates(request):\n time_stamp = time.strftime('%b %d, %Y, %H:%M:%S', time.gmtime())\n\n updates_sections = get_content_dict('thesis', 'updates')\n render_dict = {\n 'page_title': 'Updates',\n 'sections': updates_sections\n }\n\n return render(request, 'thesis/updates.html', render_dict)\n","sub_path":"thesis/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"478698040","text":"import threading\nfrom threading import Timer\nimport random\nimport time\n\nfrom datetime import datetime, timedelta\n\nfrom configparser import ConfigParser\n\nfrom trading.esssencial.logger import log\nfrom trading.esssencial.api import Poloniex\nfrom trading.model.order import Order\nfrom trading.model.trade_currency import TradeCurrency\nfrom trading.model.data_source import BacktestDataSource,LiveDataSource\nfrom trading import ITradeAlgorithm, ANN, SniperBacktest, MACD, MyTradeAlgorithm, SimpleStrategy\n\napi_key = ''\napi_secret = ''\n\nupdate_interval = 0\n\ntrade_currencies = []\n\nlock = threading.Lock()\n\nmain_percent = 'main_percent'\nalt_percent = 'alt_percent'\nmin_buy_profit = 'min_buy_profit'\nmin_sell_profit = 'min_sell_profit'\nnew_order_threshold = 'new_order_threshold'\nmin_main = 'min_main'\nmin_alt = 'min_alt'\ntrading_history = 'trading_history'\ninitial_buy_rate = 'initial_buy_rate'\ninitial_sell_rate = 'initial_sell_rate'\nann_order_size = 'ann_order_size'\nann_threshold = 'ann_threshold'\n\n\ndef load_defaults(cfg, currency):\n dft_tc = TradeCurrency(currency_pair='',\n main_percent=float(cfg[currency][main_percent]) / 100.0,\n alt_percent=float(cfg[currency][alt_percent]) / 100.0,\n min_buy_profit=float(cfg[currency][min_buy_profit]) / 100.0,\n min_sell_profit=float(cfg[currency][min_sell_profit]) / 100.0,\n new_order_threshold=float(cfg[currency][new_order_threshold]) / 100.0,\n min_main=float(cfg[currency][min_main]),\n min_alt=float(cfg[currency][min_alt]),\n trading_history_in_minutes=float(cfg[currency][trading_history]),\n initial_buy_rate=float(cfg[currency][initial_buy_rate]),\n initial_sell_rate=float(cfg[currency][initial_sell_rate]),\n ann_order_size=float(cfg[currency][ann_order_size]),\n ann_threshold=float(cfg[currency][ann_threshold]))\n return dft_tc\n\n\ndef load_custom(cfg, dft_tc, pair):\n # initialize with defaults\n tc = TradeCurrency.from_tc(dft_tc)\n tc.currency_pair = pair\n\n # custom values\n if pair in cfg:\n tc.main_percent = float(cfg[pair][main_percent]) / 100 if main_percent in cfg[pair] else tc.main_percent\n tc.alt_percent = float(cfg[pair][alt_percent]) / 100.0 if alt_percent in cfg[pair] else tc.alt_percent\n tc.min_buy_profit = float(cfg[pair][min_buy_profit]) / 100.0 if min_buy_profit in cfg[pair] else tc.min_buy_profit\n tc.min_sell_profit = float(cfg[pair][min_sell_profit]) / 100.0 if min_sell_profit in cfg[pair] else tc.min_sell_profit\n tc.new_order_threshold = float(cfg[pair][new_order_threshold]) / 100.0 if new_order_threshold in cfg[pair] else tc.new_order_threshold\n tc.min_main = float(cfg[pair][min_main] if min_main in cfg[pair] else tc.min_main)\n tc.min_alt = float(cfg[pair][min_alt] if min_alt in cfg[pair] else tc.min_alt)\n tc.trading_history_in_minutes = float(cfg[pair][trading_history] if trading_history in cfg[pair] else tc.trading_history_in_minutes)\n tc.initial_buy_rate = float(cfg[pair][initial_buy_rate] if initial_buy_rate in cfg[pair] else tc.initial_buy_rate)\n tc.initial_sell_rate = float(cfg[pair][initial_sell_rate] if initial_sell_rate in cfg[pair] else tc.initial_sell_rate)\n tc.ann_order_size = float(cfg[pair][ann_order_size] if ann_order_size in cfg[pair] else tc.ann_order_size)\n tc.ann_threshold = float(cfg[pair][ann_threshold] if ann_threshold in cfg[pair] else tc.ann_threshold)\n\n return tc\n\n\ndef load_config():\n global api_key, api_secret, update_interval, trade_currencies\n\n cfg = ConfigParser()\n cfg.read('config.cfg')\n\n api_key = cfg['API']['key']\n api_secret = cfg['API']['secret']\n\n update_interval = float(cfg['PROCESS']['update_interval']) * 60\n\n btc_pairs = cfg['CURRENCY']['btc_pairs'].split(',') if 'btc_pairs' in cfg['CURRENCY'] else []\n usdt_pairs = cfg['CURRENCY']['usdt_pairs'].split(',') if 'usdt_pairs' in cfg['CURRENCY'] else []\n\n dft_tc_btc = load_defaults(cfg, 'BTC')\n dft_tc_usdt = load_defaults(cfg, 'USDT')\n\n for pair in btc_pairs:\n trade_currencies.append(load_custom(cfg, dft_tc_btc, pair))\n\n for pair in usdt_pairs:\n trade_currencies.append(load_custom(cfg, dft_tc_usdt, pair))\n\n\ndef update_loop(algorithm):\n with lock:\n assert isinstance(algorithm, ITradeAlgorithm)\n try:\n algorithm.update()\n try_again = False\n except Exception as e:\n log('An error occurred: ' + str(e.args), True)\n try_again = True\n\n if try_again:\n loop = Timer(random.randint(1, 10), update_loop, [algorithm])\n loop.start()\n else:\n loop = Timer(update_interval + random.randint(1, 10), update_loop, [algorithm])\n loop.start()\n\n\ndef main():\n try:\n load_config()\n\n template = \"{0:20}{1:>15}\\t\\t\\t{2:33}\"\n print('initializing')\n poloniex = Poloniex(api_key, api_secret)\n\n offset = 60 * 24 * 2 #2 Days Offset\n start = datetime.now() - timedelta(days=31)\n\n #MODE: 'BACKTEST' 'LIVE'\n mode = 'BACKTEST'\n\n for currency in trade_currencies:\n total_profit = 0\n\n if mode == 'LIVE':\n for currency in trade_currencies:\n source = LiveDataSource(currency, poloniex, start, offset, update_interval / 60)\n algorithm = SimpleStrategy(source, offset)\n update_loop(algorithm)\n time.sleep(10)\n if mode == 'BACKTEST':\n print('\\n\\nBackTest Mode - Gathering Data for ' + currency.currency_pair)\n source = BacktestDataSource(currency, poloniex, start, offset, update_interval / 60)\n algorithm = SimpleStrategy(source, offset)\n\n #source.plot_result()\n\n print('Updating... ' + currency.currency_pair)\n print(template.format('Initial Balances:', '$' + \"{0:.2f}\".format(source.main_balance), str(source.alt_balance)))\n while algorithm.update():\n continue\n total_main = 0\n total_alt = 0\n total_fee = 0\n total_trades = algorithm.winning_trades + algorithm.losing_trades\n accuracy = (abs(algorithm.winning_trades - algorithm.losing_trades) / total_trades) * 100 if total_trades > 0 else 0\n for order in algorithm.data_source.orders:\n assert isinstance(order, Order)\n total_main += abs(order.total)\n total_alt += abs(order.amount)\n total_fee += order.fee\n\n main_profit = algorithm.data_source.main_balance - algorithm.data_source.main_balance_init\n alt_profit = algorithm.data_source.alt_balance - algorithm.data_source.alt_balance_init\n highest_bid = float(poloniex.returnTicker()[currency.currency_pair]['highestBid'])\n profit = (alt_profit * highest_bid) + main_profit\n total_profit += profit\n\n print(template.format('Final Balances:', '$' + \"{0:.2f}\".format(algorithm.data_source.main_balance), str(algorithm.data_source.alt_balance)))\n print(template.format('Difference:', '$' + \"{0:.2f}\".format(main_profit), str(alt_profit)))\n print(template.format('Total Moved:', '$' + \"{0:.2f}\".format(total_main), str(total_alt)))\n print(template.format('Accuracy: ' , '%' + \"{0:.2f}\".format(accuracy), str(total_alt)))\n print(template.format('Fees:' , '$' + \"{0:.2f}\".format(total_fee), str(total_alt)))\n print(template.format('Winning Trades:' , str(algorithm.winning_trades), str(total_alt)))\n print(template.format('Losing Trades:' , str(algorithm.losing_trades), str(total_alt)))\n print(template.format('Profit:' , '$' + \"{0:.2f}\".format(profit), str(total_alt)))\n print(template.format('Total Profit:', '$' + \"{0:.2f}\".format(profit), str(total_profit)))\n\n except KeyboardInterrupt:\n quit()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tradingbot.py","file_name":"tradingbot.py","file_ext":"py","file_size_in_byte":8376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"491027302","text":"from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType\r\nimport vk_api\r\nimport random\r\nfrom datetime import datetime\r\n\r\nimport parser_daimond\r\nimport parser_advance\r\n\r\ntoken = ''\r\n\r\nvk_session = vk_api.VkApi(token = token)\r\n\r\nsession_api = vk_session.get_api()\r\n\r\nid_group = 185787449\r\n\r\nlongpoll = VkBotLongPoll(vk_session, id_group)\r\n\r\ndef send_message(session_api, peer_id, message):\r\n session_api.messages.send(peer_id = peer_id, message = message, random_id = random.randint(-99999,+99999))\r\n\r\ndef get_online(session_api, peer_id):\r\n return session_api.users.get(peer_id=peer_id, fields='online')[0]\r\n\r\nfor event in longpoll.listen():\r\n if event.type == VkBotEventType.MESSAGE_NEW:\r\n\r\n max_member = session_api.messages.getConversationMembers(peer_id = event.obj.peer_id)['count']-1\r\n print('Участников: ' + str(max_member))\r\n\r\n if event.obj.peer_id != event.obj.from_id:\r\n\r\n # members_list = session_api.messages.getConversationMembers(peer_id=event.obj.peer_id)\r\n #\r\n # sender_name = list(filter(lambda name: name['id'] == event.obj.from_id, [name for name in session_api.messages.getConversationMembers(peer_id=event.obj.peer_id, fields='profiles')['profiles']]))[0]\r\n #\r\n # last_and_ferst_name = str(sender_name['first_name']) + ' ' +str(sender_name['last_name'])\r\n #\r\n # send_message(session_api,peer_id=event.obj.peer_id, message='@.id{0}({1})'.format(event.obj.from_id,last_and_ferst_name) +'\\nУчастников беседы: ' + str(max_member))\r\n #\r\n # print(event.obj)\r\n\r\n if event.obj.text == '/help':\r\n text = 'Доступные команды:\\n\\n' \\\r\n '/help - Команды Бота\\n' \\\r\n '/online - Показывает онлайн на сервере Paradox RP\\n' \\\r\n '/ \\n' \\\r\n '/ \\n'\r\n send_message(session_api, peer_id=event.obj.peer_id, message=text)\r\n\r\n\r\n if event.obj.text == '/online':\r\n text = ''\r\n for i in range(max_member):\r\n print('i = ',i)\r\n\r\n id = session_api.messages.getConversationMembers(peer_id=event.obj.peer_id)['profiles'][i]['id']\r\n print('ID = ',id)\r\n\r\n name = session_api.users.get(user_ids = id)[0]\r\n print('Объект по ID: ',name)\r\n\r\n operation_name = name['first_name'] + ' ' +name['last_name']\r\n print('Преобразование в Имя: ',operation_name)\r\n\r\n text = text + '\\n' +str(operation_name)\r\n\r\n print('============================================================')\r\n\r\n print('Участники:' + text)\r\n\r\n send_message(session_api, peer_id=event.obj.peer_id, message='Участники:{0}'.format(text))\r\n\r\n if event.obj.text == '/test':\r\n send_message(session_api, peer_id=event.obj.peer_id, message=str(parser_daimond.result))\r\n send_message(session_api, peer_id=event.obj.peer_id, message=str(parser_advance.result))\r\n\r\n\r\n\r\n\r\n","sub_path":"VK_BOT.py","file_name":"VK_BOT.py","file_ext":"py","file_size_in_byte":3272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"70456777","text":"from django.db import models\nfrom django.utils.translation import ugettext as _\nfrom plus import utilplus, modelplus\n\n\nclass Arquivo(models.Model):\n\t'''\n\tGuarda arquivos .csv e .pdf\n\t'''\n\tnome = models.CharField(max_length=64, unique=True, verbose_name='Nome')\n\tarquivo = modelplus.FileField(\tupload_to='arquivos/',\n\t\t\t\t\t\t\t\t\tcontent_types=['application/vnd.ms-excel', 'text/csv', 'application/pdf'],\n\t\t\t\t\t\t\t\t\tmax_upload_size=33554432,\n\t\t\t\t\t\t\t\t\tverbose_name=_('Arquivo'),\n\t\t\t\t\t\t\t\t\thelp_text=_('Tipos de Arquivos: .pdf .csv. Tamanho Máximo: 32MB'))\n\n\tclass Meta:\n\t\tverbose_name = _('Arquivo')\n\t\tverbose_name_plural = _('Arquivos')\n\n\tdef __str__(self):\n\t\treturn '{nome:s}'.format(nome=self.nome)\n\n\tdef clean(self, *args, **kwargs):\n\t\t# Renomeia o arquivo\n\t\tif self.arquivo:\n\t\t\tif self.id is None:\n\t\t\t\text = utilplus.get_file_extension(self.arquivo)\n\t\t\t\tself.arquivo.name = utilplus.unique_name(extension=ext)\n\t\t\telse:\n\t\t\t\tarquivo = Arquivo.objects.get(id=self.id)\n\t\t\t\tif self.arquivo != arquivo.arquivo:\n\t\t\t\t\text = utilplus.get_file_extension(self.arquivo)\n\t\t\t\t\tself.arquivo.name = utilplus.unique_name(extension=ext)\n\n\t\treturn super(Arquivo, self).clean(*args, **kwargs)\n","sub_path":"transpsesisenai/apps/repo/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"247889175","text":"# \n\"\"\"\nВыгружает произвольный файл по FTP в двоичном режиме.\nИспользует анонимный доступ к ftp, если функции не был передан\nкортеж user=(имя, пароль) аргументов.\n\"\"\"\n\nimport ftplib\n\ndef putfile(file, site, dir, user=(), *, verbose=True):\n \"\"\"\n выгружает произвольный файл по FTP на сайт/каталог, используя анонимный\n доступ или дейст��ительную учетную запись, двоичный режим передачи\n \"\"\"\n if verbose: print('Uploading', file)\n local = open(file, 'rb') # локальный файл с тем же именем\n remote = ftplib.FTP(site) # соединиться с FTP-сайтом\n remote.login(*user) # анонимная или действительная учетная запись\n remote.cwd(dir)\n remote.storbinary('STOR ' + file, local, 1024)\n remote.quit()\n local.close()\n if verbose: print('Upload done.')\n","sub_path":"3/ftp/putfile_through_ftp.py","file_name":"putfile_through_ftp.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"215245740","text":"__author__ = 'Administrator'\n\nfrom collections import namedtuple,deque,defaultdict,OrderedDict,Counter\n\n#namedtuple是一个函数,它用来创建一个自定义的tuple对象,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。\nPointValues = namedtuple('pointvalues',['x','y'])\npv = PointValues(1,2)\nprint('pv.x is : ',pv.x,' and pv.y is : ',pv.y)\n#print('type(PointValues) is : ',type(PointValues))\n\n#使用list存储数据时,按索引访问元素很快,但是插入和删除元素就很慢了,因为list是线性存储,数据量大的时候,插入和删除效率很低。\n#deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈:\nq = deque(['a', 'b', 'c'])\nq.append('x')\nq.appendleft('y')\nprint(q)\n\n#使用dict时,如果引用的Key不存在,就会抛出KeyError。如果希望key不存在时,返回一个默认值,就可以用defaultdict:\ndd = defaultdict(lambda: 'N/A')\ndd['key1'] = 'abc'\nprint(\"dd['key1'] is : \",dd['key1']) # key1存在\nprint(\"dd['key2'] is : \",dd['key2']) # key1存在\n\n#使用dict时,Key是无序的。在对dict做迭代时,我们无法确定Key的顺序。如果要保持Key的顺序,可以用OrderedDict:\nd = dict([('a', 1), ('b', 2), ('c', 3)])\nprint('non orderedDict is : ',d)\nod = OrderedDict([('a', 1), ('b', 2), ('c', 3)])\nprint('used orderdDict is : ',od)\n\n#Counter是一个简单的计数器,例如,统计字符出现的个数\ncounters = Counter()\nfor ch in 'programming':\n counters[ch] = counters[ch] + 1\nprint(counters)\n","sub_path":"src/fundamental/basic/handleCollections.py","file_name":"handleCollections.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"315192919","text":"from authzed.api.v1 import (\n Client,\n ObjectReference,\n Relationship,\n RelationshipUpdate,\n SubjectReference,\n WriteRelationshipsRequest,\n)\nfrom grpcutil import bearer_token_credentials\n\nclient = Client(\n \"grpc.authzed.com:443\",\n bearer_token_credentials(\"t_your_token_here_1234567deadbeef\"),\n)\n\nresp = client.WriteRelationships(\n WriteRelationshipsRequest(\n updates=[\n # Emilia is a Writer on Post 1\n RelationshipUpdate(\n operation=RelationshipUpdate.Operation.OPERATION_CREATE,\n relationship=Relationship(\n resource=ObjectReference(object_type=\"blog/post\", object_id=\"1\"),\n relation=\"writer\",\n subject=SubjectReference(\n object=ObjectReference(\n object_type=\"blog/user\",\n object_id=\"emilia\",\n )\n ),\n ),\n ),\n # Beatrice is a Reader on Post 1\n RelationshipUpdate(\n operation=RelationshipUpdate.Operation.OPERATION_CREATE,\n relationship=Relationship(\n resource=ObjectReference(object_type=\"blog/post\", object_id=\"1\"),\n relation=\"reader\",\n subject=SubjectReference(\n object=ObjectReference(\n object_type=\"blog/user\",\n object_id=\"beatrice\",\n )\n ),\n ),\n ),\n ]\n )\n)\n","sub_path":"examples/v1/write_relationships.py","file_name":"write_relationships.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"49051307","text":"#!/usr/bin/env python\nimport re\nimport cv2\nimport argparse\nimport numpy as np\nfrom pathlib import Path\n\n\nGRID_WIDTH = 29.8 # mm\nGRID_COLS = 13\nGRID_ROWS = 6\nGRID_NUM = GRID_COLS * GRID_ROWS\n\n\ndef execute(dn_rgb_img: Path, dn_rgb_txt: Path, dn_calib: Path):\n if not dn_rgb_txt.exists() or not dn_rgb_txt.is_dir():\n dn_rgb_txt.mkdir()\n\n # load images\n fp_rgb_img_list = [p for p in dn_rgb_img.glob(\"*\") if re.search(\".*(jpg|JPG|png|PNG)\", str(p))]\n fp_rgb_img_list = sorted(fp_rgb_img_list)\n\n # prepare 3D points\n obj_coords = np.zeros((1, GRID_COLS * GRID_ROWS, 3), np.float32)\n obj_coords[0, :, :2] = np.mgrid[0:GRID_COLS, 0:GRID_ROWS].T.reshape(-1, 2) * GRID_WIDTH\n\n objpoints = []\n imgpoints = []\n\n print(\"----- Circle Grid Detection -----\")\n for fp_rgb_img in fp_rgb_img_list:\n print(\"{}\".format(fp_rgb_img))\n rgb_img = cv2.imread(str(fp_rgb_img), cv2.IMREAD_GRAYSCALE)\n rgb_img = rgb_img.astype(np.uint8)\n\n # detect circle grid centers\n params = cv2.SimpleBlobDetector_Params()\n params.filterByArea = True\n params.minArea = 10 ** 2\n params.maxArea = 100 ** 2\n params.filterByColor = True\n params.minThreshold = 0\n params.maxThreshold = 192\n params.filterByCircularity = True\n params.filterByInertia = False\n params.filterByConvexity = True\n detector = cv2.SimpleBlobDetector_create(params)\n detect_flags = cv2.CALIB_CB_SYMMETRIC_GRID + cv2.CALIB_CB_CLUSTERING\n is_found, centers = cv2.findCirclesGrid(rgb_img, (GRID_COLS, GRID_ROWS), detect_flags, blobDetector=detector)\n\n # check if centers are valid or not\n if not is_found or centers is None or len(centers) != GRID_NUM:\n print(\"- FAILED\")\n continue\n\n # convert to color image format\n rgb_img = cv2.cvtColor(rgb_img, cv2.COLOR_GRAY2RGB)\n cv2.drawChessboardCorners(rgb_img, (GRID_COLS, GRID_ROWS), centers, True)\n center_coords = []\n for i, corner in enumerate(centers):\n cv2.putText(rgb_img, str(i), (int(corner[0][0]) + 2, int(corner[0][1]) - 2),\n cv2.FONT_HERSHEY_PLAIN, 2, (255, 255, 255), 2)\n center_coords.append((corner[0][0], corner[0][1]))\n\n objpoints.append(obj_coords)\n imgpoints.append(centers)\n\n cv2.imwrite(str(dn_rgb_txt / fp_rgb_img.name), rgb_img)\n np.savetxt(str(dn_rgb_txt / (fp_rgb_img.stem + \".txt\")), np.array(center_coords))\n\n # convert to grayscale image format\n calib_flags = cv2.CALIB_FIX_K2 + cv2.CALIB_FIX_K3 + cv2.CALIB_FIX_TANGENT_DIST\n criteria_flags = (cv2.TERM_CRITERIA_MAX_ITER + cv2.TERM_CRITERIA_EPS, 1000, 1e-12)\n\n # dummy input (these initial values won't be used because cv2.CALIB_USE_INTRINSIC_GUESS is not specified)\n camera_matrix = np.zeros((3, 3))\n dist_params = np.zeros((5, 1))\n rmse, camera_matrix, dist_params, rvecs, tvecs \\\n = cv2.calibrateCamera(objpoints, imgpoints, (rgb_img.shape[1], rgb_img.shape[0]),\n camera_matrix, dist_params, flags=calib_flags, criteria=criteria_flags)\n print(\"\")\n\n print(\"----- Calibration Results -----\")\n print(\"RMSE:\")\n print(rmse)\n print(\"K:\")\n print(camera_matrix)\n print(\"D:\")\n print(dist_params.T)\n print(\"\")\n\n print(\"----- Undistortion of Calibration Images -----\")\n\n if not dn_calib.exists() or not dn_calib.is_dir():\n dn_calib.mkdir()\n\n np.savetxt(dn_calib / \"camera_matrix.txt\", camera_matrix)\n np.savetxt(dn_calib / \"dist_params.txt\", dist_params)\n\n # create a new optimal camera matrix\n new_camera_matrix, _ = cv2.getOptimalNewCameraMatrix(camera_matrix, dist_params,\n (rgb_img.shape[1], rgb_img.shape[0]), 1.0)\n remap = cv2.initUndistortRectifyMap(camera_matrix, dist_params, np.eye(3), new_camera_matrix,\n (rgb_img.shape[1], rgb_img.shape[0]), cv2.CV_32FC1)\n for fp_rgb_img in fp_rgb_img_list:\n rgb_img = cv2.imread(str(fp_rgb_img), cv2.IMREAD_COLOR)\n rgb_img = rgb_img.astype(np.uint8)\n rgb_img = cv2.remap(rgb_img, remap[0], remap[1], cv2.INTER_AREA)\n fp_rgb_img_undist = dn_rgb_txt / (\"undist_\" + fp_rgb_img.name)\n print(f\"- {fp_rgb_img_undist}\")\n cv2.imwrite(str(fp_rgb_img_undist), rgb_img)\n print(\"\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Calibration script for a perspective camera\")\n parser.add_argument(\"dp_rgb_img\", type=Path, help=\"directory of RGB images\")\n parser.add_argument(\"dp_rgb_txt\", type=Path, help=\"directory of circle detection output\")\n parser.add_argument(\"dp_calib\", type=Path, help=\"directory of calibration output\")\n args = parser.parse_args()\n\n execute(args.dp_rgb_img, args.dp_rgb_txt, args.dp_calib)\n","sub_path":"calib_perspective.py","file_name":"calib_perspective.py","file_ext":"py","file_size_in_byte":4895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"331226854","text":"import psycopg2\nimport sys\nfrom gym.envs.postgres_idx_advisor.envs.Utils import Utils\nfrom gym.envs.postgres_idx_advisor.envs.Constants import Constants\nfrom pglast import Node, parse_sql\nimport re\nimport numpy as np\nimport json\n\nclass PostgresQueryHandler:\n # attribute which will hold the postgres connection\n connection = None\n connectionDefault = None\n hypo_indexes_dict = dict()\n\n @staticmethod\n def __get_connection():\n # create connection only if it is not done before\n if PostgresQueryHandler.connection is None:\n # connect to postgres\n try:\n # read database config from config file\n database_config = Utils.read_config_data(Constants.CONFIG_DATABASE)\n # connect to postgres\n PostgresQueryHandler.connection = psycopg2.connect(database=database_config[\"dbname\"],\n user=database_config[\"user\"],\n password=database_config[\"password\"],\n host=database_config[\"host\"],\n port=database_config[\"port\"])\n PostgresQueryHandler.connection.autocommit = True\n # capture connection exception\n except psycopg2.OperationalError as exception:\n print('Unable to connect to postgres \\n Reason: {0}').format(str(exception))\n # exit code\n sys.exit(1)\n else:\n cursor = PostgresQueryHandler.connection.cursor()\n # Print PostgreSQL version\n cursor.execute(\"SELECT version();\")\n record = cursor.fetchone()\n print(\"***You are connected to below Postgres database*** \\n \", record, \"\\n\")\n return PostgresQueryHandler.connection\n\n @staticmethod\n def __get_default_connection():\n if PostgresQueryHandler.connectionDefault is None:\n # connect to postgres\n try:\n # read database config from config file\n database_config = Utils.read_config_data(Constants.CONFIG_DATABASE)\n # connect to postgres\n PostgresQueryHandler.connectionDefault = psycopg2.connect(database=database_config[\"dbname\"],\n user=database_config[\"user\"],\n password=database_config[\"password\"],\n host=database_config[\"host\"],\n port=database_config[\"port\"])\n PostgresQueryHandler.connectionDefault.autocommit = True\n # capture connection exception\n except psycopg2.OperationalError as exception:\n print('Unable to connect to postgres \\n Reason: {0}').format(str(exception))\n # exit code\n sys.exit(1)\n else:\n cursor = PostgresQueryHandler.connectionDefault.cursor()\n # Print PostgreSQL version\n cursor.execute(\"SELECT version();\")\n record = cursor.fetchone()\n print(\"***You are connected to below Postgres database*** \\n \", record, \"\\n\")\n return PostgresQueryHandler.connectionDefault\n\n @staticmethod\n def execute_select_query(query: str, load_index_advisor: bool = False, get_explain_plan: bool = False):\n #cursor = PostgresQueryHandler.__get_connection().cursor()\n if load_index_advisor:\n print('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$')\n cursor = PostgresQueryHandler.__get_connection().cursor()\n cursor.execute(Constants.CREATE_EXTENSION)\n cursor.execute(Constants.LOAD_PG_IDX_ADVISOR)\n cursor = PostgresQueryHandler.__get_connection().cursor()\n else:\n print('################################')\n cursor = PostgresQueryHandler.__get_default_connection().cursor()\n cursor.execute(Constants.DROP_PG_IDX_ADVISOR)\n if get_explain_plan:\n query = Constants.QUERY_EXPLAIN_PLAN.format(query)\n cursor.execute(query)\n returned_rows = cursor.fetchall()\n\n #PostgresQueryHandler.check_hypo_indexes()\n\n cursor.close()\n return returned_rows\n\n @staticmethod\n def get_table_row_count(table_name):\n cursor = PostgresQueryHandler.__get_connection().cursor()\n cursor.execute(Constants.QUERY_FIND_NUMBER_OF_ROWS.format(table_name))\n returned_count = cursor.fetchone()\n cursor.close()\n return returned_count[0]\n\n @staticmethod\n def execute_count_query(query):\n cursor = PostgresQueryHandler.__get_connection().cursor()\n cursor.execute(query)\n returned_count = cursor.fetchone()\n cursor.close()\n return returned_count[0]\n\n @staticmethod\n def execute_select_query_and_get_row_count(query):\n cursor = PostgresQueryHandler.__get_connection().cursor()\n # trim whitespaces and add wrapper query to get count of rows i.e select count(*) from () table1\n query_to_execute = ' '.join(query.strip().replace('\\n', ' ').lower().split())\n query_to_execute = \"Select count(*) from (\" + query_to_execute + \" ) table1\"\n cursor.execute(query_to_execute)\n returned_count = cursor.fetchone()\n cursor.close()\n return returned_count\n\n @staticmethod\n def create_hypo_index(table_name, col_name):\n key = table_name + Constants.MULTI_KEY_CONCATENATION_STRING + col_name\n # create hypo index if it is not already present\n if key not in PostgresQueryHandler.hypo_indexes_dict:\n cursor = PostgresQueryHandler.__get_default_connection().cursor()\n #print('setting index', table_name, col_name)\n # replace placeholders in the create hypo index query with table name and column name\n cursor.execute(Constants.QUERY_CREATE_HYPO_INDEX.format(table_name, col_name))\n returned_index_id = cursor.fetchone()\n cursor.close()\n PostgresQueryHandler.hypo_indexes_dict[key] = returned_index_id[0]\n\n @staticmethod\n def remove_hypo_index(table_name, col_name):\n key = table_name + Constants.MULTI_KEY_CONCATENATION_STRING + col_name\n # check whether index is already present\n if key in PostgresQueryHandler.hypo_indexes_dict:\n cursor = PostgresQueryHandler.__get_connection().cursor()\n # retrieve index id from dict and replace the place holder with index id\n cursor.execute(Constants.QUERY_REMOVE_HYPO_INDEX.format(PostgresQueryHandler.hypo_indexes_dict.get(key, 0)))\n cursor.close()\n PostgresQueryHandler.hypo_indexes_dict.pop(key, None)\n\n @staticmethod\n def remove_all_hypo_indexes():\n cursor = PostgresQueryHandler.__get_default_connection().cursor()\n cursor.execute(Constants.QUERY_REMOVE_ALL_HYPO_INDEXES)\n print(cursor.fetchall())\n cursor.close()\n\n @staticmethod\n def get_where_clause_list_for_query(query: str):\n query_tree = Node(parse_sql(query))\n for tre in query_tree:\n for node in tre.stmt.whereClause:\n print(str(node))\n\n @staticmethod\n def check_hypo_indexes():\n cursor = PostgresQueryHandler.__get_default_connection().cursor()\n cursor.execute(Constants.QUERY_CHECK_HYPO_INDEXES)\n print(cursor.fetchall())\n cursor.close()\n\n @staticmethod\n def add_query_cost_suggested_indexes(result):\n #PostgresQueryHandler.check_hypo_indexes()\n explain_plan = ' \\n'.join(map(str, result))\n # extract cost\n print(explain_plan)\n cost_pattern = \"cost=(.*)row\"\n cost_match = re.search(cost_pattern, explain_plan)\n if cost_match is not None:\n cost_query = cost_match.group(1).split('..')[-1]\n return float(cost_query)\n\n @staticmethod\n def get_observation_space(queries_list):\n observation_space = np.array(np.ones((8,61)))\n observation_space[0,:] = np.array((np.zeros((61,))))\n action_space = PostgresQueryHandler.read_json_action_space()\n for query_number in range(len(queries_list)):\n for key, value in queries_list[query_number].where_clause_columns_query.items():\n print(key + ' : ' + value + ' : ' + str(\n queries_list[query_number].selectivity_for_where_clause_columns[key]) + ' : ' + str(queries_list[query_number].query_cost_without_index))\n table_name, col_name = key.split(Constants.MULTI_KEY_CONCATENATION_STRING)\n print(key, table_name, col_name)\n selectivity_index = action_space[(table_name + \".\" + col_name).upper()]\n print(selectivity_index)\n observation_space[query_number+1, selectivity_index] = queries_list[query_number].selectivity_for_where_clause_columns[key]\n return observation_space\n\n @staticmethod\n def read_json_action_space():\n with open('../index_action_space.json') as json_file:\n action_space = json.load(json_file)\n return action_space","sub_path":"envs/PostgresQueryHandler.py","file_name":"PostgresQueryHandler.py","file_ext":"py","file_size_in_byte":9412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"269711279","text":"#encoding:utf-8\r\nimport re\r\nfrom nltk.stem.snowball import SnowballStemmer\r\nimport nltk\r\nnltk.download(\"stopwords\")\r\nfrom nltk.corpus import stopwords\r\n\r\nreplacement = {\r\n \"aren't\" : \"are not\",\r\n \"can't\" : \"cannot\",\r\n \"couldn't\" : \"could not\",\r\n \"didn't\" : \"did not\",\r\n \"doesn't\" : \"does not\",\r\n \"don't\" : \"do not\",\r\n \"hadn't\" : \"had not\",\r\n \"hasn't\" : \"has not\",\r\n \"haven't\" : \"have not\",\r\n \"he'd\" : \"he would\",\r\n \"he'll\" : \"he will\",\r\n \"he's\" : \"he is\",\r\n \"i'd\" : \"I would\",\r\n \"i'll\" : \"I will\",\r\n \"i'm\" : \"I am\",\r\n \"isn't\" : \"is not\",\r\n \"it's\" : \"it is\",\r\n \"it'll\":\"it will\",\r\n \"i've\" : \"I have\",\r\n \"let's\" : \"let us\",\r\n \"mightn't\" : \"might not\",\r\n \"mustn't\" : \"must not\",\r\n \"shan't\" : \"shall not\",\r\n \"she'd\" : \"she would\",\r\n \"she'll\" : \"she will\",\r\n \"she's\" : \"she is\",\r\n \"shouldn't\" : \"should not\",\r\n \"that's\" : \"that is\",\r\n \"there's\" : \"there is\",\r\n \"they'd\" : \"they would\",\r\n \"they'll\" : \"they will\",\r\n \"they're\" : \"they are\",\r\n \"they've\" : \"they have\",\r\n \"we'd\" : \"we would\",\r\n \"we're\" : \"we are\",\r\n \"weren't\" : \"were not\",\r\n \"we've\" : \"we have\",\r\n \"what'll\" : \"what will\",\r\n \"what're\" : \"what are\",\r\n \"what's\" : \"what is\",\r\n \"what've\" : \"what have\",\r\n \"where's\" : \"where is\",\r\n \"who'd\" : \"who would\",\r\n \"who'll\" : \"who will\",\r\n \"who're\" : \"who are\",\r\n \"who's\" : \"who is\",\r\n \"who've\" : \"who have\",\r\n \"won't\" : \"will not\",\r\n \"wouldn't\" : \"would not\",\r\n \"you'd\" : \"you would\",\r\n \"you'll\" : \"you will\",\r\n \"you're\" : \"you are\",\r\n \"you've\" : \"you have\",\r\n \"'re\": \" are\",\r\n \"wasn't\": \"was not\",\r\n \"we'll\":\" will\",\r\n \"tryin'\":\"trying\",\r\n}\r\n\r\nstemmer = SnowballStemmer(\"english\")\r\nstopwords_en = set(stopwords.words('english'))\r\n\r\n# now build a custom tokenizer based on these\r\n__tokenization_pattern = r'''(?x) # set flag to allow verbose regexps\r\n \\$?\\d+(?:\\.\\d+)?%? # currency and percentages, e.g. $12.40, 82%\r\n | (?:[A-Z]\\.)+ # abbreviations, e.g. U.S.A.\r\n | \\w+(?:-\\w+)* # words with optional internal hyphens\r\n | \\.\\.\\. # ellipsis\r\n | [][.,;\"'?():_`-] # these are separate tokens; includes ], [\r\n '''\r\n\r\ntokenizer = nltk.tokenize.regexp.RegexpTokenizer(__tokenization_pattern)\r\n\r\nclass EnglishPreProcessor(object):\r\n def __init__(self,min_len = 2,stopwords_path = None):\r\n self.min_len = min_len\r\n\r\n def preprocessor(self,sentence):\r\n '''\r\n turns text into tokens after tokenization, stemming, stop words removal\r\n imput:\r\n - text: document to process\r\n output: =>\r\n - tokens: list of tokens after tokenization, stemming, stop words removal\r\n '''\r\n stems = []\r\n tokens = tokenizer.tokenize(sentence.lower())\r\n\r\n for token in tokens:\r\n if token.isalpha() and token not in stopwords_en:\r\n stems.append(str(stemmer.stem(token)))\r\n if not stems:\r\n for token in tokens:\r\n if token not in stopwords_en:\r\n stems.append(str(stemmer.stem(token)))\r\n return stems\r\n\r\n\r\n def clean_length(self,sentence):\r\n '''\r\n 去除长度小于min_len的文本\r\n :param sentence:\r\n :return:\r\n '''\r\n if len([x for x in sentence]) >= self.min_len:\r\n return sentence\r\n\r\n def replace(self,sentence):\r\n '''\r\n 一些特殊缩写替换\r\n :param sentence:\r\n :return:\r\n '''\r\n # Replace words like gooood to good\r\n sentence = re.sub(r'(\\w)\\1{2,}', r'\\1\\1', sentence)\r\n # Normalize common abbreviations\r\n words = sentence.split(' ')\r\n words = [replacement[word] if word in replacement else word for word in words]\r\n sentence_repl = \" \".join(words)\r\n return sentence_repl\r\n\r\n def remove_website(self,sentence):\r\n '''\r\n 处理网址符号\r\n :param sentence:\r\n :return:\r\n '''\r\n sentence_repl = sentence.replace(r\"http\\S+\", \"\")\r\n sentence_repl = sentence_repl.replace(r\"https\\S+\", \"\")\r\n sentence_repl = sentence_repl.replace(r\"http\", \"\")\r\n sentence_repl = sentence_repl.replace(r\"https\", \"\")\r\n return sentence_repl\r\n\r\n def remove_name_tag(self,sentence):\r\n # Remove name tag\r\n sentence_repl = sentence.replace(r\"@\\S+\", \"\")\r\n return sentence_repl\r\n\r\n def remove_time(self,sentence):\r\n '''\r\n 特殊数据处理\r\n :param sentence:\r\n :return:\r\n '''\r\n # Remove time related text\r\n sentence_repl = sentence.replace(r'\\w{3}[+-][0-9]{1,2}\\:[0-9]{2}\\b', \"\") # e.g. UTC+09:00\r\n sentence_repl = sentence_repl.replace(r'\\d{1,2}\\:\\d{2}\\:\\d{2}', \"\") # e.g. 18:09:01\r\n sentence_repl = sentence_repl.replace(r'\\d{1,2}\\:\\d{2}', \"\") # e.g. 18:09\r\n # Remove date related text\r\n # e.g. 11/12/19, 11-1-19, 1.12.19, 11/12/2019\r\n sentence_repl = sentence_repl.replace(r'\\d{1,2}(?:\\/|\\-|\\.)\\d{1,2}(?:\\/|\\-|\\.)\\d{2,4}', \"\")\r\n # e.g. 11 dec, 2019 11 dec 2019 dec 11, 2019\r\n sentence_repl = sentence_repl.replace(\r\n r\"([\\d]{1,2}\\s(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)|(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\\s[\\d]{1,2})(\\s|\\,|\\,\\s|\\s\\,)[\\d]{2,4}\",\r\n \"\")\r\n # e.g. 11 december, 2019 11 december 2019 december 11, 2019\r\n sentence_repl = sentence_repl.replace(\r\n r\"[\\d]{1,2}\\s(january|february|march|april|may|june|july|august|september|october|november|december)(\\s|\\,|\\,\\s|\\s\\,)[\\d]{2,4}\",\r\n \"\")\r\n return sentence_repl\r\n\r\n def remove_breaks(self,sentence):\r\n # Remove line breaks\r\n sentence_repl = sentence.replace(\"\\r\", \"\")\r\n sentence_repl = sentence_repl.replace(\"\\n\", \"\")\r\n sentence_repl = re.sub(r\"\\\\n\\n\", \".\", sentence_repl)\r\n return sentence_repl\r\n\r\n def remove_ip(self,sentence):\r\n # Remove phone number and IP address\r\n sentence_repl = sentence.replace(r'\\d{8,}', \"\")\r\n sentence_repl = sentence_repl.replace(r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}', \"\")\r\n return sentence_repl\r\n\r\n def adjust_common(self,sentence):\r\n # Adjust common abbreviation\r\n sentence_repl = sentence.replace(r\" you re \", \" you are \")\r\n sentence_repl = sentence_repl.replace(r\" we re \", \" we are \")\r\n sentence_repl = sentence_repl.replace(r\" they re \", \" they are \")\r\n sentence_repl = sentence_repl.replace(r\"@\", \"at\")\r\n return sentence_repl\r\n\r\n\r\n def full2half(self,sentence):\r\n '''\r\n 全角转化为半角\r\n :param sentence:\r\n :return:\r\n '''\r\n ret_str = ''\r\n for i in sentence:\r\n if ord(i) >= 33 + 65248 and ord(i) <= 126 + 65248:\r\n ret_str += chr(ord(i) - 65248)\r\n else:\r\n ret_str += i\r\n return ret_str\r\n\r\n def remove_stopword(self,sentence):\r\n '''\r\n 去除停用词\r\n :param sentence:\r\n :return:\r\n '''\r\n words = sentence.split()\r\n x = [word for word in words if word not in self.stopwords]\r\n return \" \".join(x)\r\n\r\n # 主函数\r\n def __call__(self, sentence):\r\n x = sentence\r\n x = self.preprocessor(x)\r\n return x\r\n","sub_path":"pybert/preprocessing/preprocessor.py","file_name":"preprocessor.py","file_ext":"py","file_size_in_byte":7442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"460243950","text":"from pylgbst import *\nfrom pylgbst.hub import MoveHub\nfrom pylgbst.peripherals import *\nfrom robot import *\nfrom time import sleep\n\nBTN_FORWARD=19\nBTN_BACKWARD=26\n\nlogging.basicConfig(level = logging.WARN)\nlog = logging.getLogger(\"test\")\n\nmac=\"00:16:53:B2:30:37\"\nconn = get_connection_bluegiga(hub_mac=mac)\n\nprint(\"Connected.\")\n\nrobot = Robot(conn)\nrobot.addButton(BTN_BACKWARD)\nrobot.addButton(BTN_FORWARD)\nrobot.setInvert(False)\n\n#################################################################\nmoving = False\nisWhite = False\nisRed = False\n\ndef callback(color, distance):\n print(color)\n\n global isRed\n global isWhite\n if color == COLOR_RED:\n isRed=True\n isWhite = False\n elif color == COLOR_WHITE:\n isWhite = True\n isRed = False\n else:\n isRed = False\n isWhite = False\n\nrobot.setSensorCallback(callback)\n\ntry:\n while True:\n\n if robot.isButtonPressed(BTN_FORWARD):\n moving=True\n\n if robot.isButtonPressed(BTN_BACKWARD):\n moving = False\n\n\n step=0.2\n if moving:\n if isRed:\n robot.motor_AB.timed(step, 0.7, -0.3)\n robot.motor_AB.timed(step, 0.5) # FORWARD\n #robot.turn(LEFT)\n elif isWhite:\n robot.motor_AB.timed(step, -0.3, 0.7)\n robot.motor_AB.timed(step, 0.5) # FORWARD\n #robot.turn(RIGHT)\n else:\n robot.motor_AB.timed(step, 0.5)\n print(\"FORWARD\")\n\n sleep(0.1)\n\nfinally:\n robot.say(\"Goodbye\")\n GPIO.cleanup()\n\n","sub_path":"robot3_color_sensor.py","file_name":"robot3_color_sensor.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"124817005","text":"\"\"\"\n\nThe hashing and sha stuff\n\n\"\"\"\n\nfrom Crypto.Hash import SHA256\nfrom Crypto.PublicKey import RSA\nfrom Crypto.Signature import PKCS1_v1_5\n\nfrom util import insertBytes\n\n\ndef createRRSetData(rr_set, rrsig_record, domain):\n \"\"\"\n Puts together data for an RRSet and computes hash\n https://tools.ietf.org/html/rfc4034#section-3.1.8.1\n :param rr_set: The RRset\n :param rrsig_record: The RRSIG record\n :param domain: The domain name of the RRSIG\n :return: The data ready for verification\n \"\"\"\n data = rrsig_record.type_covered.to_bytes(2, 'big') + \\\n rrsig_record.algorithm.to_bytes(1, 'big') + rrsig_record.labels.to_bytes(1, 'big') + \\\n rrsig_record.orig_ttl.to_bytes(4, 'big') + rrsig_record.expiration + \\\n rrsig_record.inception + rrsig_record.tag.to_bytes(2, 'big') + \\\n rrsig_record.signer_name\n\n for rr in rr_set:\n data += RRSignableData(rr, domain, rrsig_record.orig_ttl)\n\n return data\n\n\ndef createDSRecord(dnskey, domain):\n \"\"\"\n A DS record is just the hash of a public key. Uses SHA256\n :param dnskey: The DNSKEY record\n :param domain: The domain name\n :return: The SHA256 hash of the DNSKEY record\n \"\"\"\n data = formatName(domain)\n\n data += dnskey.rdata\n\n hasher = SHA256.new()\n hasher.update(data)\n return hasher.digest()\n\n\ndef formatName(name):\n \"\"\"\n Puts a domain name into that form DNS loves so much\n :param name: A domain name string\n :return: The name formatting for verification use\n \"\"\"\n name_bytes = bytearray(len(name) + 2)\n i = 0\n for domain in name.split('.'):\n name_bytes[i] = len(domain)\n i += 1\n insertBytes(name_bytes, domain.encode('utf-8', 'strict'), i)\n i += len(domain)\n name_bytes[i] = 0\n return name_bytes\n\n\ndef RRSignableData(rr, owner, orig_ttl):\n \"\"\"\n This will take a RR and return the bytes to be used in signing\n # RFC on signiture calculation: https://tools.ietf.org/html/rfc4034#section-3.1\n\n owner is the domain owner (EX: 'example.com', 'com'). This TECHNICALLY should\n be in the rr, but we never figured out the pointer name storage thing\n :param rr: The Resource record\n :param owner: The owner of the RR\n :param orig_ttl: original TTL from RRSIG record\n :return: The data set for verification\n \"\"\"\n formatted_owner = formatName(owner)\n return formatted_owner + rr.type.to_bytes(2, 'big') + rr.clazz.to_bytes(2, 'big') + \\\n orig_ttl.to_bytes(4, 'big') + rr.rdata_len.to_bytes(2, 'big') + rr.rdata\n\n\ndef verify_signature(signature, key, recordset):\n \"\"\"\n Verifies a signature\n :param signature: The signature\n :param key: The key\n :param recordset: The recordset to verify\n :return: True if verified, false otherwise\n \"\"\"\n expo, mod = get_expo_and_mod(key)\n constructed_key = RSA.construct((mod, expo))\n cipher = PKCS1_v1_5.new(constructed_key)\n return cipher.verify(SHA256.new(recordset), signature)\n\n\ndef get_expo_and_mod(dnskey):\n \"\"\"\n Gets the exponent and modulus from a DNSKEY record\n :param dnskey: The DNSKEY record\n :return: Tuples of (exponent, modulus)\n \"\"\"\n data = bytearray(dnskey.key)\n cursor = 1\n expo_len = int.from_bytes([data[0]], 'big')\n if expo_len == 0:\n expo_len = int.from_bytes(data[1:3], 'big')\n cursor = 3\n expo = int.from_bytes(data[cursor:cursor + expo_len], 'big')\n cursor += expo_len\n mod = int.from_bytes(data[cursor:], 'big')\n return expo, mod\n","sub_path":"crypto.py","file_name":"crypto.py","file_ext":"py","file_size_in_byte":3522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"292584173","text":"\nimport microfabrication_functions as mfc\nimport microfabrication_constant as mconst\nimport time as time\nimport sys\nimport os as os\nimport sdl2.ext \nimport sdl2.sdlimage\n#os.environ[\"PYSDL2_DLL_PATH\"] = \"/Users/vishwanathan/Desktop/UM-2/undergrad_research/PySDL2-0.9.5\"\nRESOURCES = sdl2.ext.Resources(__file__, mconst.IMAGE_PATH)\nimage_list = mfc\nimage_filelist = mfc.read_files(mconst.IMAGE_PATH)\nsdl2.ext.init()\nwindow = sdl2.ext.Window(\"Hello World!\", size=(1000, 1000))\nwindow.show()\n#sdl2.SDL_SetWindowFullscreen(window, 1, flags = sdl2.SDL_WINDOW_FULLSCREEN_DESKTOP)\n\n\nfactory = sdl2.ext.SpriteFactory(sdl2.ext.SOFTWARE)\n\n\nspritelist =[]\n\nfor filename in image_filelist :\n sprite = factory.from_image(RESOURCES.get_path(filename.original_filename))\n spritelist.append(sprite)\n\nspriterenderer = factory.create_sprite_render_system(window)\nprint(\"yoh\")\nprocessor = sdl2.ext.TestEventProcessor()\nprint(\"yeh\")\nprocessor.run(window)\nsdl2.ext.get_events()\nstart = time.time()\nprint(\"yuh\")\nfor sprite in spritelist:\n spriterenderer.render(sprite)\n sdl2.timer.SDL_Delay(50)\n\n \nend = time.time()\nprint(end-start)\n\n\nsdl2.ext.quit()\n\n\n\n\n\n\n\n\n\n\n","sub_path":"image_display.py","file_name":"image_display.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"335423714","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom scipy.optimize import leastsq\nimport weave\n\nimport sys\nimport scipy.io as sio\nimport neo\n\n#import GIF\n#from Experiment import *\n#from AEC_Badel import *\n\n###########################################################\n# Remove axis\n###########################################################\n\ndef removeAxis(ax, which_ax=['top', 'right']):\n\n for loc, spine in ax.spines.iteritems():\n if loc in which_ax:\n spine.set_color('none') # don't draw spine\n\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')\n\n\n###########################################################\n# Reprint\n###########################################################\ndef reprint(str):\n sys.stdout.write('%s\\r' % (str))\n sys.stdout.flush()\n\n\n###########################################################\n# Generate Ornstein-Uhlenbeck process\n###########################################################\n\ndef generateOUprocess(T=10000.0, tau=3.0, mu=0.0, sigma=1.0, dt=0.1):\n\n \"\"\"\n Generate an Ornstein-Uhlenbeck (stationnary) process with:\n - mean mu\n - intensity parameter sigma\n - temporal correlation tau (ms)\n The duration of the signal is specified by the input parameter T (in ms).\n The process is generated in discrete time with temporal resolution dt (in ms)\n \"\"\"\n\n T_ind = int(T/dt)\n\n white_noise = np.random.randn(T_ind)\n white_noise = white_noise.astype(\"double\")\n\n OU_process = np.zeros(T_ind)\n OU_process = OU_process.astype(\"double\")\n\n '''OU_k1 = dt / tau\n OU_k2 = np.sqrt(dt / tau)\n for t in xrange(T_ind-1) :\n OU_process[t + 1] = OU_process[t] + (mu - OU_process[t]) * OU_k1 + sigma * OU_k2 * white_noise[t]\n '''\n\n code = \"\"\"\n\n #include \n\n int cT_ind = int(T_ind);\n float cdt = float(dt);\n float ctau = float(tau);\n float cmu = float(mu);\n float csigma = float(sigma);\n\n float OU_k1 = cdt / ctau ;\n float OU_k2 = sqrt(cdt/ctau) ;\n\n for (int t=0; t < cT_ind-1; t++) {\n OU_process[t+1] = OU_process[t] + (cmu - OU_process[t])*OU_k1 + csigma*OU_k2*white_noise[t] ;\n }\n\n \"\"\"\n\n vars = ['T_ind', 'dt', 'tau', 'sigma','mu', 'OU_process', 'white_noise']\n v = weave.inline(code,vars)\n\n return OU_process\n\n\ndef generateOUprocess_sinSigma(f=1.0, T=10000.0, tau=3.0, mu=0.0, sigma=1.0, delta_sigma=0.5, dt=0.1):\n\n \"\"\"\n Generate an Ornstein-Uhlenbeck process with time dependent standard deviation:\n - mean mu\n - sigma(t) = sigma*(1+delta_sigma*sin(2pift)), f in Hz\n - temporal correlation tau (ms)\n The duration of the signal is specified by the input parameter T (in ms).\n The process is generated in discrete time with temporal resolution dt (in ms)\n \"\"\"\n\n OU_process = generateOUprocess(T=T, tau=tau, mu=0.0, sigma=1.0, dt=dt)\n t = np.arange(len(OU_process))*dt\n\n sin_sigma = sigma*(1+delta_sigma*np.sin(2*np.pi*f*t*10**-3))\n\n I = OU_process*sin_sigma + mu\n\n return I\n\n\ndef generateOUprocess_sinMean(f=1.0, T=10000.0, tau=3.0, mu=0.2, delta_mu=0.5, sigma=1.0, dt=0.1):\n\n \"\"\"\n Generate an Ornstein-Uhlenbeck process with time dependent mean:\n - sigma\n - mu(t) = mu*(1+delta_mu*sin(2pift)), f in Hz\n - temporal correlation tau (ms)\n The duration of the signal is specified by the input parameter T (in ms).\n The process is generated in discrete time with temporal resolution dt (in ms)\n \"\"\"\n\n OU_process = generateOUprocess(T=T, tau=tau, mu=0.0, sigma=sigma, dt=dt)\n t = np.arange(len(OU_process))*dt\n\n sin_mu = mu*(1+delta_mu*np.sin(2*np.pi*f*t*10**-3))\n\n I = OU_process + sin_mu\n\n return I\n\n\n###########################################################\n# Functin to convert spike times in spike indices\n###########################################################\ndef timeToIndex(x_t, dt):\n\n x_t = np.array(x_t)\n x_i = np.array( [ int(np.round(s/dt)) for s in x_t ] )\n x_i = x_i.astype('int')\n\n return x_i\n\n\n###########################################################\n# Functions to perform exponential fit\n###########################################################\n\ndef multiExpEval(x, bs, taus):\n\n result = np.zeros(len(x))\n L = len(bs)\n\n for i in range(L) :\n result = result + bs[i] *np.exp(-x/taus[i])\n\n return result\n\n\ndef multiExpResiduals(p, x, y, d):\n bs = p[0:d]\n taus = p[d:2*d]\n\n return (y - multiExpEval(x, bs, taus))\n\n\n\ndef fitMultiExpResiduals(bs, taus, x, y) :\n x = np.array(x)\n y = np.array(y)\n d = len(bs)\n p0 = np.concatenate((bs,taus))\n plsq = leastsq(multiExpResiduals, p0, args=(x,y,d), maxfev=100000,ftol=0.00000001)\n p_opt = plsq[0]\n bs_opt = p_opt[0:d]\n taus_opt = p_opt[d:2*d]\n\n fitted_data = multiExpEval(x, bs_opt, taus_opt)\n\n ind = np.argsort(taus_opt)\n\n taus_opt = taus_opt[ind]\n bs_opt = bs_opt[ind]\n\n return (bs_opt, taus_opt, fitted_data)\n\n\n###########################################################\n# Get indices far from spikes\n###########################################################\n\ndef getIndicesFarFromSpikes(T, spikes_i, dt_before, dt_after, initial_cutoff, dt) :\n\n T_i = int(T/dt)\n flag = np.zeros(T_i)\n flag[:int(initial_cutoff/dt)] = 1\n flag[-1] = 1\n\n dt_before_i = int(dt_before/dt)\n dt_after_i = int(dt_after/dt)\n\n for s in spikes_i :\n flag[ max(s-dt_before_i,0) : min(s+dt_after_i, T_i) ] = 1\n\n selection = np.where(flag==0)[0]\n\n return selection\n\n\ndef getIndicesDuringSpikes(T, spikes_i, dt_after, initial_cutoff, dt) :\n\n T_i = int(T/dt)\n flag = np.zeros(T_i)\n flag[:int(initial_cutoff/dt)] = 1\n flag[-1] = 1\n\n dt_after_i = int(dt_after/dt)\n\n for s in spikes_i :\n flag[ max(s,0) : min(s+dt_after_i, T_i) ] = 1\n\n selection = np.where(flag>0.1)[0]\n\n return selection\n\n\n###########################################################\n# Load AEC data\n###########################################################\ndef load_AEC_data(filename):\n if filename.find('.mat') > 0:\n mat_contents = sio.loadmat(filename)\n analogSignalsAEC = mat_contents['analogSignals']\n timesAEC = mat_contents['times']\n timesAEC = timesAEC.reshape(timesAEC.size)\n lengthAEC = timesAEC[-1]\n voltage_traceAEC = analogSignalsAEC[0, 0, :]\n current_traceAEC = analogSignalsAEC[1, 0, :] - 5. # Correction for exp bias\n maxT = int((lengthAEC - 0.5) / (timesAEC[1] - timesAEC[0]))\n minT = int(0.5 / (timesAEC[1] - timesAEC[0]))\n current_traceAEC = current_traceAEC[minT:maxT]\n voltage_traceAEC = voltage_traceAEC[minT:maxT]\n timesAEC = timesAEC[minT:maxT] * 10. ** 3\n sampling_time = timesAEC[1] - timesAEC[0]\n elif filename.find('.abf') > 0:\n r = neo.io.AxonIO(filename=filename)\n bl = r.read_block()\n voltage_traceAEC = bl.segments[0].analogsignals[0].magnitude\n current_traceAEC = bl.segments[0].analogsignals[1].magnitude - 5.\n timesAEC = bl.segments[0].analogsignals[0].times.rescale('ms').magnitude\n lengthAEC = timesAEC[-1]\n sampling_time = timesAEC[1] - timesAEC[0]\n maxT = int((lengthAEC - 0.5) / sampling_time)\n minT = int(0.5 / sampling_time)\n current_traceAEC = current_traceAEC[minT:maxT]\n voltage_traceAEC = voltage_traceAEC[minT:maxT]\n return (sampling_time, voltage_traceAEC, current_traceAEC)\n\n\ndef load_training_data(filename):\n if filename.find('.mat') > 0:\n mat_contents = sio.loadmat(filename)\n analogSignals = mat_contents['analogSignals']\n voltage_trace = analogSignals[0,0,:]\n current_trace = analogSignals[1,0,:] - 5. #offset due to uncalibrated current\n times = mat_contents['times'];\n times = times.reshape(times.size)\n times = times*10.**3 #convert to ms\n sampling_time = times[1] - times[0]\n elif filename.find('.abf') > 0:\n r = neo.io.AxonIO(filename=filename)\n bl = r.read_block()\n voltage_trace = bl.segments[0].analogsignals[0].magnitude\n current_trace = bl.segments[0].analogsignals[1].magnitude - 5.\n times = bl.segments[0].analogsignals[0].times.rescale('ms').magnitude\n sampling_time = times[1] - times[0]\n return (sampling_time, voltage_trace, current_trace, times)\n\n\n##########################################################\n# Plotting training trace with forced spikes\n##########################################################\n'''\ndef plot_training_forced(filename_AEC, filename_training, filename_model):\n \"\"\"\n :param filename_training: training data file name (string)\n :param filename_model: name of the model (ending in .pck)\n :return: none\n \"\"\"\n # Load AEC data\n (sampling_timeAEC, voltage_traceAEC, current_traceAEC) = load_AEC_data(filename_AEC)\n\n experiment = Experiment('Experiment 1', sampling_timeAEC)\n experiment.setAECTrace(voltage_traceAEC, 10. ** -3, current_traceAEC, 10. ** -12,\n len(voltage_traceAEC) * sampling_timeAEC, FILETYPE='Array')\n\n # Load preprocessed training data set\n (sampling_time, voltage_trace, current_trace) = load_training_data(filename_training)\n experiment.addTrainingSetTrace(voltage_trace, 10 ** -3, current_trace, 10 ** -12,\n len(voltage_trace) * sampling_time, FILETYPE='Array')\n\n # Compensate traces\n myAEC = AEC_Badel(experiment.dt)\n\n # Define metaparametres\n myAEC.K_opt.setMetaParameters(length=150.0, binsize_lb=experiment.dt, binsize_ub=2.0, slope=30.0, clamp_period=1.0)\n myAEC.p_expFitRange = [3.0, 150.0]\n myAEC.p_nbRep = 15\n\n # Assign myAEC to experiment and compensate the voltage recordings\n experiment.setAEC(myAEC)\n experiment.performAEC()\n\n # Load model\n model = GIF.load(filename_model)\n\n # Simulate model\n (time, V_est, eta_sum_est) = model.simulateDeterministic_forceSpikes(current_trace, voltage_trace[0], experiment.trainingset_traces[0].spks)\n\n #Plot\n plt.plot(time, V_est, 'r-', label='V_$\\mathrm{est}$', lw=0.5)\n plt.plot(time, voltage_trace, 'k-', label='V__$\\mathrm{training}$', lw=0.5)\n plt.xlabel('Time (ms)')\n plt.ylabel('V (mV)')\n plt.xlim(4000, 4500)\n plt.savefig(filename_model[:-4] + '_training_forced.png')\n plt.close()\n'''\n","sub_path":"src/Tools.py","file_name":"Tools.py","file_ext":"py","file_size_in_byte":10470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"487052043","text":"from bs4 import BeautifulSoup\nimport requests\n\nwith open('simple.html') as html_file:\n soup = BeautifulSoup(html_file, 'lxml')\nprint(soup.prettify())\n\nmatch = soup.find('div', class_ = 'footer')\nmatch = match.find('p')\nprint(match.text)\n","sub_path":"example_1.py","file_name":"example_1.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"421768222","text":"from six.moves.urllib.request import urlopen\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nfrom scrapeTools import get_first_table\n\ndef nba_team_names():\n\ttable = get_first_table(\"https://www.foxsports.com/nba/standings?season=2018&seasonType=1&grouping=3&advanced=0\")\n\tdf = pd.read_html(str(table))[0]\n\treturn df[\"NBA\"]\n\ndef get_east_west():\n\ttable = get_first_table(\"https://www.foxsports.com/nba/standings?season=2018&seasonType=1&grouping=1&advanced=0\")\n\tdf = pd.read_html(str(table))[0]\n\teast = list(df.iterrows())[0:15]\n\twest = list(df.iterrows())[17:]\n\treturn east, west\n\ndef east_vs_west():\n\teast, west = get_east_west()\n\tWL =[0,0]\n\tfor index, row in east:\n\t\tteam_conf_rec = row['Conf'].split('-')\n\t\ttotal_wins = int(row['W'])\n\t\ttotal_losses = int(row['L'])\n\t\tWL[0] += total_wins - int(team_conf_rec[0])\n\t\tWL[1] += total_losses - int(team_conf_rec[1])\n\n\treturn \"East vs. West\\nRecord: \" + \"-\".join([str(i) for i in WL]) + \"\\nWPCT: \" + str(round(WL[0] / sum(WL), 3))\n\t","sub_path":"nbateams.py","file_name":"nbateams.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"562243947","text":"# -*- coding: utf-8 -*-\n'''\nTroisième étape : Destruction de la seam déterminée et décalage de l'image\n\nA ce stade, on dispose de : \n - une image à traiter\n - (Anthony) sa carte d'énergie\n - (Antoine) une fonction calculate_cost_matrix qui détermine une matrice des coûts de l'image\n - (Antoine) une fonction detect_seam utilisant la matrice de coûts, et qui retourne la seam verticale\n à enlever sous forme de tuple de coordonnées\n\nCe fichier permet de supprimer la seam calculée en deux étapes : \n - Destruction de la seam en décalant les pixels par dessus\n - Redimensionnement de l'image\n'''\n\nfrom PIL import Image\n\ndef remove_seam(im,seam):\n '''\n Cette fonction décale tous les pixels à droite du seam par dessus, la\n redimensionne et la retourne \n '''\n image = im.load()\n for elm in seam: #pour chaque element du seam (de la forme (x,y))\n for x in range (elm[0],im.size[0]-1): #pour chaque x \n image[x,elm[1]] = image[x+1,elm[1]]\n #final = resize(im,(im.size[0]-1,im.size[1]))\n box = (0,0,im.size[0]-1,im.size[1])\n im2 = im.crop(box) \n return im2 #l'image modifiée est retournée\n","sub_path":"seam_treatment.py","file_name":"seam_treatment.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"444815683","text":"import redis, time, random\n\nr = redis.Redis('localhost', 6379, socket_timeout=10)\n\n#r.execute_command('TS.CREATE', 'test-ts', 'retention', '60', 'labels', 'name', 'test')\n \nstart = time.time()\nend = start + 10\n#while time.time() < end:\nwhile True:\n r.execute_command('TS.ADD', 'test-ts', '*', random.uniform(0, 10))\n time.sleep(0.5)\n","sub_path":"TimeSeries/LoadTS.py","file_name":"LoadTS.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"367726339","text":"# \n# NaverNewsCrawler.py\n# Web crawling program for Naver News\n# Author : Ji-yong219\n# Project Start:: 2021.07.24\n# Last Modified from Ji-yong 2021.07.27\n#\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException, ElementNotInteractableException, StaleElementReferenceException\nimport datetime\nimport json\n\nfrom tqdm import trange\n\nfrom utils.util import *\nfrom crawlers.BaseCrawler import Crawler\n\nclass NaverCrawler(Crawler):\n chrome_options = None\n driver = None\n url_page_num = 0\n url = ''\n news_dic = {}\n news_queue = []\n\n # 생성자\n def __init__(self, driver_url, chrome_options):\n self.chrome_options = chrome_options\n \n self.driver_url = driver_url\n\n # 기사 링크 수집 메소드\n def crawlLinks(self, search, start_date, end_date):\n self.news_queue = []\n self.driver = webdriver.Chrome(self.driver_url, chrome_options=self.chrome_options)\n self.url_page_num = 0\n \n start_date_ = datetime.date(int(start_date[:4]), int(start_date[4:6]), int(start_date[6:]))\n end_date_ = datetime.date(int(end_date[:4]), int(end_date[4:6]), int(end_date[6:])) + datetime.timedelta(days=1)\n for date_ in daterange(start_date_, end_date_):\n self.url_page_num = 1\n\n while True:\n date__ = str(date_).replace('-', '.')\n date___ = str(date_).replace('-', '')\n self.url = f'https://search.naver.com/search.naver?where=news&sm=tab_pge&query={search}&sort=2&photo=0&field=0&pd=3&ds={date__}&de={date__}&mynews=0&office_type=0&office_section_code=0&news_office_checked=&nso=so:r,p:from{date___}to{date___},a:all&start={self.url_page_num}'\n \n \n print(f\"크롤링시작 URL:{self.url}\")\n self.driver.get(self.url)\n\n try:\n element = WebDriverWait(self.driver, 1).until(\n EC.presence_of_element_located((By.XPATH, '//*[@id=\"main_pack\"]/div[2]'))\n \n # class = 'api_noresult_wrap'\n )\n\n except TimeoutException:\n print(\"타임아웃\")\n \n break\n\n div, news = None, None\n\n div = self.driver.find_element_by_xpath('//*[@id=\"main_pack\"]/div[2]')\n\n if div.get_attribute('class') == 'api_noresult_wrap':\n break\n\n div = self.driver.find_element_by_xpath('//*[@id=\"main_pack\"]/section/div/div[2]/ul')\n\n news = div.find_elements_by_css_selector('a[class=\"info\"]')\n\n news = list(set(news))\n\n for i in range(len(news)):\n link = None\n\n link = news[i].get_attribute('href')\n\n if link is None or link == \"\":\n continue\n\n link = link.replace('\\n', '')\n # if link.startswith(\"https://news.naver.com/main/\") and link not in self.news_queue:\n if news[i].text == '네이버뉴스' and link not in self.news_queue:\n print(f'link : {link}')\n try:\n pass\n\n except ValueError as e:\n print(\"value Error\", e, link)\n\n else:\n link = link.replace(\"?f=o\", \"\")\n self.news_queue.append(link)\n\n self.url_page_num += 10\n\n with open(f'result/naver_news/urls_{search}_naver_{start_date}_{end_date}.json.txt', 'w', encoding='utf8') as f:\n f.writelines('\\n'.join(self.news_queue))\n\n self.news_queue = []\n self.driver.close()\n\n def crawlNews(self, search, start_date, end_date):\n self.news_queue = []\n news_dic = {}\n\n with open(f'result/naver_news/urls_{search}_naver_{start_date}_{end_date}.json.txt', 'r', encoding='utf8', newline='\\n') as f:\n for row in f.readlines():\n row = row.replace('\\n', '').replace('\\r', '')\n self.news_queue.append(row)\n\n self.driver = webdriver.Chrome(self.driver_url, chrome_options=self.chrome_options)\n \n \n\n for url in self.news_queue:\n count = 0\n print(f\"네이버뉴스 댓글 크롤링 시작 :{self.url}\")\n\n reply_texts = []\n\n self.driver.get(url)\n\n try:\n element = WebDriverWait(self.driver, 1).until(\n EC.presence_of_element_located((By.XPATH, '//*[@id=\"cbox_module\"]/div[2]/div[2]/ul/li[1]/span')) \n )\n\n except TimeoutException:\n print(\"타임아웃\")\n \n break\n\n div = self.driver.find_element_by_xpath('//*[@id=\"cbox_module_wai_u_cbox_content_wrap_tabpanel\"]')\n\n comment_count = self.driver.find_element_by_xpath('//*[@id=\"cbox_module\"]/div[2]/div[2]/ul/li[1]/span')\n\n if comment_count == '0':\n continue\n\n\n # date = self.driver.find_element_by_xpath('//*[@id=\"main_content\"]/div[1]/div[3]/div/span').text[:10].strip().replace('.', '')\n date = self.driver.find_element_by_css_selector('#main_content span[class=\"t11\"]').text[:10].strip().replace('.', '')\n if date not in news_dic.keys():\n news_dic[date] = []\n\n \n # all_comments_mode = div.find_element_by_xpath('//*[@id=\"cbox_module_wai_u_cbox_sort_option_tab2\"]')\n all_comments_mode = WebDriverWait(div, 2).until(EC.presence_of_element_located((By.XPATH, '//*[@id=\"cbox_module_wai_u_cbox_sort_option_tab2')) )\n all_comments_mode.click()\n\n safe_bot_mode1 = div.find_element_by_xpath('//*[@id=\"cbox_module\"]/div[2]/div[7]/a')\n safe_bot_mode1.click()\n safe_bot_mode2 = div.find_element_by_xpath('//*[@id=\"cleanbot_dialog_checkbox_cbox_module\"]')\n safe_bot_mode2.click()\n safe_bot_mode3 = div.find_element_by_xpath('/html/body/div[3]/div/div[2]/div[4]/button')\n safe_bot_mode3.click()\n\n while True:\n try:\n element = WebDriverWait(self.driver, 2).until(\n EC.presence_of_element_located((By.XPATH, '//*[@id=\"cbox_module\"]/div[2]/div[9]/a')) \n )\n \n more_btn = self.driver.find_element_by_xpath('//*[@id=\"cbox_module\"]/div[2]/div[9]/a')\n print(\"댓글 더보기 클릭\")\n more_btn.click()\n\n except TimeoutException:\n print(\"more 버튼 없음 타임아웃\")\n \n break\n\n except ElementNotInteractableException:\n print(\"more 버튼 없음\")\n \n break\n\n \n\n\n\n try:\n element = WebDriverWait(self.driver, 1).until(\n EC.presence_of_element_located((By.XPATH, '//*[@id=\"cbox_module\"]/div[2]/div[2]/ul/li[1]/span')) \n )\n\n except TimeoutException:\n print(\"타임아웃\")\n \n break\n\n div = self.driver.find_element_by_xpath('//*[@id=\"cbox_module_wai_u_cbox_content_wrap_tabpanel\"]')\n \n # comments = div.find_elements_by_xpath('//li[**starts-with(id,\"comment\")**]')\n comments = div.find_elements_by_css_selector('ul>li')\n reply_count = 0\n\n for i in range(len(comments)):\n comment = comments[i]\n this_class = comment.get_attribute('class')\n\n if \"comment_\" not in this_class:\n continue\n\n this_class = this_class.split(' ')[1]\n # print(f'this_class : {this_class}')\n\n is_exists_reply = True\n\n\n try:\n element = WebDriverWait(comment, 1).until(\n EC.presence_of_element_located((By.CSS_SELECTOR, f'a[class=\"u_cbox_btn_reply\"]')) \n )\n reply_count = element.text\n if element.text == \"답글0\":\n is_exists_reply = False\n\n except TimeoutException:\n print(\"답글 버튼 없음 타임아웃\")\n is_exists_reply = False\n\n \n try:\n text = WebDriverWait(comment, 1).until(EC.presence_of_element_located((By.CSS_SELECTOR , f'div[class=\"u_cbox_text_wrap\"]'))).text\n if text != \"작성자에 의해 삭제된 댓글입니다.\":\n reply_texts.append( text )\n count += 1\n print(f\"수집한 댓글 : {count}개\\t{text}\")\n except:\n print(\"댓 못가져와서 패스\")\n continue\n\n if is_exists_reply:\n count2 = 0\n reply_btn = comment.find_element_by_css_selector(f'a[class=\"u_cbox_btn_reply\"]')\n # reply_btn.click()\n reply_btn.send_keys(Keys.ENTER)\n \n while True:\n try:\n element = WebDriverWait(comment, 1).until(\n EC.presence_of_element_located((By.CSS_SELECTOR, f'a[class=\"u_cbox_btn_more\"]')) \n )\n \n more_btn2 = comment.find_element_by_css_selector(f'a[class=\"u_cbox_btn_more\"]')\n # print(\"답글 더보기 클릭\")\n more_btn2.send_keys(Keys.ENTER)\n\n except:\n # print(\"답글 더보기 버튼 없음 타임아웃\")\n break\n\n\n replys = []\n try:\n replys = WebDriverWait(reply, 1).until(EC.presence_of_element_located((By.CSS_SELECTOR , f'li[class=\"u_cbox_comment\"]')))\n except:\n pass\n\n for reply in replys:\n try:\n text = WebDriverWait(reply, 1).until(EC.presence_of_element_located((By.CSS_SELECTOR , 'span[class=\"u_cbox_contents\"] > p'))).text\n if text != \"작성자에 의해 삭제된 댓글입니다.\":\n reply_texts.append( text )\n count+=1\n count2+=1\n print(f\"수집한 댓글 : {count}개\\t{reply_count}개 중 {count2}개 수집\")\n\n except:\n print(\"답글 못가져와서 패스\")\n continue\n\n \n # reply_btn.send_keys(Keys.ENTER)\n # for i in reply_texts:\n # print(i)\n print(f'수집한 댓글 : {len(reply_texts)}')\n \n news_dic[date[0:8]].append(\n {\n url: {\n 'comments': reply_texts,\n 'emotions': []\n }\n }\n )\n\n self.driver.close()\n \n with open(f'result/naver_news/news_{search}_naver_{start_date}_{end_date}.json.txt', 'w', encoding='utf8') as f:\n json.dump(news_dic, f, indent=4, sort_keys=True, ensure_ascii=False)","sub_path":"crawlers/NaverNewsCrawler.py","file_name":"NaverNewsCrawler.py","file_ext":"py","file_size_in_byte":11905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"521677565","text":"# coding:utf-8\nimport tornado.web\nimport tornado.ioloop\nimport tornado.httpserver\nimport tornado.options\n\nimport os.path\nimport sqlite3\nimport datetime\nimport time\n\nimport common\nfrom tornado.options import define, options\nfrom tornado.escape import json_encode\n\nconn = sqlite3.connect('chatroom.db', timeout=1)\ncur = conn.cursor()\n\n\n# 用户信息修改\nclass ModifyHandler(tornado.web.RequestHandler):\n def get(self):\n self.set_status(403)\n self.finish()\n return\n\n def post(self):\n username = self.get_secure_cookie(\"username\")\n if username is None:\n self.redirect('/login')\n password = self.get_argument('password')\n rep_password = self.get_argument('rep_password')\n email = self.get_argument('email')\n phone = self.get_argument('phone')\n if password != rep_password:\n # self.write(\"两次密码输入不一致\")\n self.set_header(\"Access-Control-Allow-Origin\", \"*\")\n self.set_header('Content-Type', 'application/json; charset=UTF-8')\n self.write(json_encode({\"modify\": False, \"err\": 1}))\n self.finish()\n return\n conn.execute(\"UPDATE user SET password=?, email=?, phone=? WHERE username =? \",\n (password, email, phone, username))\n conn.commit()\n self.set_header(\"Access-Control-Allow-Origin\", \"*\")\n self.set_header('Content-Type', 'application/json; charset=UTF-8')\n self.write(json_encode({\"modify\": True}))\n self.finish()\n return\n\n\n# 管理员特权操作\n\n\nclass AdminHandler(tornado.web.RequestHandler):\n def get(self):\n cookie_user = self.get_secure_cookie(\"username\")\n if cookie_user is None:\n # self.redirect('/login')\n # self.set_status(403)\n # self.finish()\n self.render('login.html')\n return\n else:\n usertype = common.get_usertype(cookie_user)\n self.render(\"admin.html\", usertype=usertype,\n roomlist=common.getRoomList())\n return\n\n def post(self):\n username = self.get_secure_cookie('username')\n setvip_username = self.get_argument(\"username1\", None)\n cancelvip_username = self.get_argument(\"username2\", None)\n delete_username = self.get_argument(\"username3\", None)\n delete_roomname = self.get_argument(\"deleteRoomname\", None)\n create_roomname = self.get_argument(\"createRoomname\", None)\n cookie_user = self.get_secure_cookie(\"username\")\n\n if 2 != common.get_usertype(cookie_user):\n self.set_status(403)\n if setvip_username:\n conn.execute(\"UPDATE user SET usertype = 1 WHERE username = ? \", (\n setvip_username,))\n conn.commit()\n self.write(\"设置成功\")\n if cancelvip_username:\n conn.execute(\"UPDATE user SET usertype = 0 WHERE username = ? \", (\n cancelvip_username,))\n conn.commit()\n self.write(\"取消成功\")\n if delete_username:\n conn.execute(\"DELETE FROM user WHERE username = ? \",\n (delete_username,))\n conn.commit()\n self.write(\"删除成功\")\n if delete_roomname:\n if not self.check_is_userd(delete_roomname):\n usertype = common.get_usertype(username)\n self.write('聊天室不存在')\n return\n else:\n conn.execute(\"DELETE FROM room WHERE roomname = ? \", (\n delete_roomname,))\n conn.commit()\n self.write('聊天室删除成功')\n return\n if create_roomname:\n username = self.get_secure_cookie('username')\n # roomname被使用过\n if self.check_is_userd(create_roomname):\n usertype = common.get_usertype(username)\n self.write('同名聊天室已经存在')\n return\n\n cursor = conn.execute(\n \"SELECT userid FROM user WHERE username = ? \", (username,))\n for row in cursor:\n userid = row[0]\n # 创建\n conn.execute(\n \"INSERT INTO room (roomname, created_time, owner_id) VALUES(?, datetime('now'), ?)\",\n (create_roomname, userid))\n conn.commit()\n # self.redirect(\"/chatroom\")\n self.write('聊天室添加成功')\n self.finish()\n return\n\n def check_is_userd(self, roomname):\n cur.execute(\n \"SELECT roomname FROM room WHERE roomname = ? \", (roomname,))\n if cur.fetchall():\n return True\n return False\n\n\nif __name__ == '__main__':\n define(\"port\", default=8000, help=\"run on given port\", type=int)\n tornado.options.parse_command_line()\n app = tornado.web.Application(\n handlers=[(r'/modify', ModifyHandler)],\n template_path=os.path.join(os.path.dirname(__file__), \"templates\")\n )\n http_server = tornado.httpserver.HTTPServer(app)\n http_server.listen(options.port)\n tornado.ioloop.IOLoop.instance().start()\n","sub_path":"src/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":5197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"639587877","text":"\"\"\"\nTest Vanilla PG on standard environment, where state is (ob_dim) and action is continuous/discrete\n\n\"\"\"\n\nimport pprint\n\nimport numpy as np\nimport torch.optim\n\nimport torchlib.deep_rl.algorithm as algo\nimport torchlib.utils.random\nfrom torchlib import deep_rl\n\nif __name__ == '__main__':\n parser = algo.a2c.make_default_parser()\n args = vars(parser.parse_args())\n pprint.pprint(args)\n\n env_name = args['env_name']\n\n assert args['discount'] < 1.0, 'discount must be smaller than 1.0'\n torchlib.utils.random.set_global_seeds(args['seed'])\n\n print('Env {}'.format(env_name))\n\n if deep_rl.envs.is_ple_game(env_name) or deep_rl.envs.is_atari_env(env_name):\n if args['recurrent']:\n args['frame_history_len'] = 1\n else:\n args['frame_history_len'] = 4\n\n env = deep_rl.envs.make_env(env_name, args)\n\n policy_net = algo.a2c.get_policy_net(env, args)\n\n policy_optimizer = torch.optim.Adam(policy_net.parameters(), args['learning_rate'])\n\n if args['recurrent']:\n init_hidden_unit = np.zeros(shape=(args['hidden_size']), dtype=np.float32)\n else:\n init_hidden_unit = None\n\n agent = algo.a2c.A2CAgent(policy_net, policy_optimizer,\n init_hidden_unit=init_hidden_unit,\n nn_baseline=args['nn_baseline'],\n lam=args['gae_lambda'],\n max_grad_norm=args['max_grad_norm'],\n value_coef=args['value_coef'],\n initial_state_mean=args['initial_state_mean'],\n initial_state_std=args['initial_state_std'])\n\n max_path_length = args['ep_len'] if args['ep_len'] > 0 else None\n\n agent.train(args['exp_name'], env, args['n_iter'], args['discount'], args['batch_size'],\n max_path_length, logdir=None, seed=args['seed'])\n","sub_path":"examples/deep_rl/policy_gradient/a2c.py","file_name":"a2c.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"130814446","text":"from django.test import TestCase\nimport datetime\nfrom decimal import Decimal, InvalidOperation\nfrom django.core.exceptions import ValidationError\nfrom django.db import transaction\nfrom .. import models\nfrom .. import dbapi\nfrom ._check_model_count import check_model_count\n\ndef _all_in_category(cat):\n return models.Transaction.objects.filter(category=cat)\n\nclass TestCategoryDelete(TestCase):\n\n fixtures = ['test_categories']\n ex_list = (TypeError, ValueError, AssertionError, ValidationError,\n InvalidOperation, AttributeError)\n\n def setUp(self):\n dbapi.create_category('Replacement Category')\n dbapi.create_account(name='Test Account', is_budgeted=True,\n starting_balance=0)\n self.test_acct = models.Account.objects.get(name='Test Account')\n self.test_params = {'account': self.test_acct,\n 'date': datetime.date.today(),\n 'payee': 'Test Payee',\n 'memo': 'Test Memo',\n 'amount': Decimal('123.45')}\n self.target_cat = models.Category.objects.get(name='Test Category')\n self.replacement_cat = models.Category.objects.get(name='Replacement Category')\n\n def test_success_no_affected_transactions(self):\n dbapi.create_category('Unaffected Category')\n unaffected_cat = models.Category.objects.get(name='Unaffected Category')\n with check_model_count({models.Transaction: 3}):\n for _ in range(3):\n dbapi.create_transaction(category=unaffected_cat,\n **self.test_params)\n with check_model_count({models.Category: -1, models.Transaction: 0}):\n dbapi.delete_category(self.target_cat, self.replacement_cat)\n self.assertNotIn('Test Category', (cat.name for cat in\n models.Category.objects.all()))\n self.assertEqual(_all_in_category(unaffected_cat).count(), 3)\n self.assertEqual(_all_in_category(self.target_cat).count(), 0)\n self.assertEqual(_all_in_category(self.replacement_cat).count(), 0)\n\n def test_success_some_affected_transactions(self):\n dbapi.create_category('Unaffected Category')\n unaffected_cat = models.Category.objects.get(name='Unaffected Category')\n with check_model_count({models.Transaction: 6}):\n for _ in range(3):\n dbapi.create_transaction(category=unaffected_cat,\n **self.test_params)\n dbapi.create_transaction(category=self.target_cat,\n **self.test_params)\n with check_model_count({models.Category: -1, models.Transaction: 0}):\n dbapi.delete_category(self.target_cat, self.replacement_cat)\n self.assertEqual(_all_in_category(unaffected_cat).count(), 3)\n self.assertEqual(_all_in_category(self.target_cat).count(), 0)\n self.assertEqual(_all_in_category(self.replacement_cat).count(), 3)\n\n def test_fail_bad_target_category(self):\n with self.assertRaises(self.ex_list):\n dbapi.delete_category('BAD', self.replacement_cat)\n\n def test_fail_bad_replacement_category(self):\n with self.assertRaises(self.ex_list):\n dbapi.delete_category(self.target_cat, 'BAD')\n\n def test_fail_no_replacement_category(self):\n with self.assertRaises(self.ex_list):\n dbapi.delete_category(self.target_cat)\n\n def test_fail_special_replacement_category(self):\n # transaction.atomic() required here to avert a known Django bug\n # See https://code.djangoproject.com/ticket/21540\n with self.assertRaises(self.ex_list):\n with transaction.atomic():\n dbapi.delete_category(self.target_cat, dbapi.transfer_category())\n with self.assertRaises(self.ex_list):\n with transaction.atomic():\n dbapi.delete_category(self.target_cat, dbapi.starting_bal_category())\n\n def test_fail_special_category(self):\n # transaction.atomic() required here to avert a known Django bug\n # See https://code.djangoproject.com/ticket/21540\n with self.assertRaises(self.ex_list):\n with transaction.atomic():\n dbapi.delete_category(dbapi.transfer_category(), self.replacement_cat)\n with self.assertRaises(self.ex_list):\n with transaction.atomic():\n dbapi.delete_category(dbapi.starting_bal_category(), self.replacement_cat)\n","sub_path":"moneybin/ledger/tests/test_category_delete.py","file_name":"test_category_delete.py","file_ext":"py","file_size_in_byte":4567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"331524376","text":"import cv2 as cv\nimport numpy as np\n\nblank = np.zeros((500, 500, 3), dtype='uint8')\ncv.imshow('Blank', blank)\n\n#1. paint the image to a color\n# blank[:] = 0,255,0\n# cv.imshow('Green', blank) \n\n#2. paint a rectangle\ncv.rectangle(blank, (0,0), (250,250), (0,0,255), thickness=2)\ncv.imshow('Rectangle', blank)\n\n#3. draw a circle\ncv.circle(blank, (blank.shape[1]//2, blank.shape[0]//2), 40, (0, 255, 0), thickness=-1)\ncv.imshow('Circle', blank)\n\n#4. draw a line\ncv.line(blank, (0,0), (blank.shape[1]//2, blank.shape[0]//2), (255, 255, 0), thickness=3)\ncv.imshow('Line', blank)\n\n#5. Add text\ncv.putText(blank, 'Feedback', (250, 250), cv.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 1)\ncv.imshow('Text', blank)\n\ncv.waitKey(0)\n","sub_path":"draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"552113211","text":"def sequencia_fibonaci():\n \"\"\" sequencia fibonnaci com 47 termos \"\"\"\n anterior = 1\n sucessor = 2\n somaAS = 0\n fibonnaci = [0,1,1,2]\n\n n = 0\n while n <= 47:\n\n somaAS = anterior + sucessor\n anterior = sucessor\n sucessor = somaAS\n\n fibonnaci.append(somaAS)\n n += 1\n \n return fibonnaci\n\nentradas_usuario = []\ncount = 0\nwhile True:\n entradas_usuario.append(int(input()))\n if entradas_usuario[count] == 0:\n break\n count += 1\n\n\"\"\"\npara cada entrada do usuario, imprimir os valores da sequencia,\nde 0 ate o valor do elemento da lista de entrada.\n\"\"\"\nfor x in entradas_usuario:\n for y in range(0,x):\n if y == x-1:\n print(sequencia_fibonaci()[y],end='')\n else:\n print(sequencia_fibonaci()[y],end=' ')\n print()\n \n\n \n\n \n\n \n \n\n\n\n","sub_path":"fibonnaci.py","file_name":"fibonnaci.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"267742626","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 17 22:29:31 2016\n\n@author: youngwan\n\"\"\"\n\nimport os\nimport sys\nimport subprocess\nimport pandas as pd\n\n#matplotlib.use('Agg')\nimport matplotlib.pylab as plt\n\n#plt.style.use('ggplot')\ndef load_data(data_file, field_idx0, field_idx1):\n data = [[], []]\n with open(data_file, 'r') as f:\n for line in f:\n line = line.strip() \n if line[0] != '#':\n fields = line.split()\n data[0].append(float(fields[field_idx0].strip()))\n data[1].append(float(fields[field_idx1].strip()))\n return data\n\n\ncaffe_path = '/home/youngwan/caffe/'\n\n#model_log_path = caffe_path + sys.argv[1]\n#learning_curve_path = caffe_path + sys.argv[2]\n\n\n#model_log_path = caffe_path + 'jobs/New/KITTI/inception_v3/SSD_Inception_v3_4_preActRes_OriginASP_BN_ImageNet_pretrained_unFreezed300x300/KITTI_SSD_Inception_v3_4_preActRes_OriginASP_BN_ImageNet_pretrained_unFreezed300x300_2016-11-6-17:41:14.log'\n#model_log_path_2 = caffe_path + 'jobs/New/KITTI/inception_v3/SSD_Inception_v3_4_preActRes_basic_OriginASP_BN_No_pretrained_300x300/KITTI_SSD_Inception_v3_4_preActRes_basic_OriginASP_BN_No_pretrained_300x300_2016-11-14-23:26:29.log'\n\nmodel_log_path = caffe_path + 'jobs/New/KITTI/inception_v3/SSD_Inception_v3_4_preActRes_OriginASP_BN_ImageNet_pretrained_unFreezed_5th_300x300/KITTI_SSD_Inception_v3_4_preActRes_OriginASP_BN_ImageNet_pretrained_unFreezed_5th_300x300_2016-11-19-15:56:0.log'\nmodel_log_path_2 = caffe_path + 'jobs/New/KITTI/inception_v3/SSD_Inception_v3_4_preActRes_basic_OriginASP_BN_No_pretrained_4th300x300/KITTI_SSD_Inception_v3_4_preActRes_basic_OriginASP_BN_No_pretrained_4th300x300_2016-11-17-23:47:35.log'\nmodel_log_path_3 = caffe_path + 'jobs/New/KITTI/inception_v3/SSD_Inception_v3_4_preActRes_basic_OriginASP_BN_cifar_pretrained_3rd_300x300/KITTI_SSD_Inception_v3_4_preActRes_basic_OriginASP_BN_cifar_pretrained_3rd_300x300_2016-11-18-10:56:17.log'\nmodel_log_path_4 = caffe_path + 'jobs/New/KITTI/inception_v3/SSD_Inception_v3_4_preActRes_basic_OriginASP_BN_cifar100_pretrained_1st_300x300/KITTI_SSD_Inception_v3_4_preActRes_basic_OriginASP_BN_cifar100_pretrained_1st_300x300_2016-11-23-17:53:56.log'\n\nlearning_curve_path = caffe_path + 'jobs/figures/Total_dpi5000.png'\n\n\n#Get directory where the model logs is saved, and move to it\nmodel_log_dir_path = os.path.dirname(model_log_path)\nos.chdir(model_log_dir_path)\ncommand = caffe_path + 'tools/extra/parse_log.sh ' + model_log_path\nprocess = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)\nprocess.wait()\n#Read training and test logs\ntrain_log_path = model_log_path + '.train'\ntest_log_path = model_log_path + '.test'\ntrain_log = pd.read_csv(train_log_path, delim_whitespace=True)\ntest_log = pd.read_csv(test_log_path, delim_whitespace=True)\n\n\n\n\n#Parsing\n#train_data = load_data(train_log_path,1,3)\n#test_data = load_data(test_log_path,1,3)\n\n\ntrain_loss = train_log['TrainingLoss']\ntrain_iter = train_log['#Iters']\ntrain_lr = train_log['LearningRate']\ntest_iter = test_log['#Iters']\ntest_loss = test_log['TestLoss']\ntest_acc = test_log['TestAccuracy']\n#test_error = 1- test_accuracy\n\n\n'''\nMaking learning curve\n'''\nfig, ax1 = plt.subplots()\n\n#Plotting training and test losses\n#train_loss, = ax1.plot(train_log['#Iters'], train_log['TrainingLoss'], color='red',linewidth=2, alpha=.5)\n#test_loss, = ax1.plot(test_log['#Iters'], test_log['TestLoss'], linewidth=2, color='green')\n\n\ntrain_loss = plt.plot(train_iter,train_loss, label='Loss', color='red',linewidth=1)\n\n\nplt.xlabel('Iterations', fontsize=15)\nplt.ylabel('Loss', fontsize=15)\nplt.yscale('log')\nplt.tick_params(labelsize=10)\nplt.legend(bbox_to_anchor=(0.5, 1), loc=2, borderaxespad=0.)\n\n#Plotting Accuracy\nax2 = plt.twinx()\n#test_accuracy, = plt.plot(test_log['#Iters'], test_acc, label='Acc. ImageNet',linewidth=3, color='red', linestyle=':')\ntrain_lr, = plt.plot(test_log['#Iters'], train_lr, label='learning rate',linewidth=3, color='blue', linestyle=':')\n\nax2.set_ylim(ymin=0.00001, ymax=0.1)\nax2.set_ylabel('Accuracy', fontsize=15)\nax2.tick_params(labelsize=10)\nplt.legend(bbox_to_anchor=(0.03, 1), loc=2, borderaxespad=0.)\nplt.title('Training Curve', fontsize=18)\n\n#Saving learning curve\n#plt.savefig(learning_curve_path,dpi=2000)\nplt.show()\n\n\n'''\nDeleting training and test logs\n'''\ncommand = 'rm ' + train_log_path\nprocess = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)\nprocess.wait()\n\ncommand = command = 'rm ' + test_log_path\nprocess = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)\nprocess.wait()\n\n\n\n\n\n","sub_path":"learning_rate_plot.py","file_name":"learning_rate_plot.py","file_ext":"py","file_size_in_byte":4585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"605733795","text":"'''\n7/27/2018\ncreate hind leg set up\n\nnote:\n don't line foot jnt, knuck joint and toe joint in straight line\n'''\nfrom maya import cmds\n\nimport joint_utility as ju\nreload(ju)\nimport control_utility as cu\nreload(cu)\nimport math_utility as mu\nreload(mu)\n\nfrom leg_rig import legRig\n\n\nclass hindLegRig(legRig):\n def __init__(self, side=\"LF\", index=1, alias=\"HindLeg\", aliasList=[\"Hip\", \"Knee\", \"Ankle\", \"Foot\", \"Knuckle\", \"Toe\"], par=\"MD_Torso_01_Hip_Ctrl\", parJnt=\"MD_Torso_01_01_Out_Jnt\", \n ik=True, fk=True, stretch=True, squeeze=True, localScale=False, elbowLock=True, softIK=True, autoSmooth=True, bendy=(5, 5, 5),\n ikSpace=[\"World\", \"Master_Sub_Ctrl\", \"COG_Sub_Ctrl\"], pvSpace=[\"World\", \"Master_Sub_Ctrl\", \"COG_Sub_Ctrl\"], shortFoot=False):\n '''\n short foot(boolean): whether treat the foot as a single joint chain or adding a dividing joint in the middle\n '''\n super(hindLegRig, self).__init__(side=side, index=index, alias=alias, aliasList=aliasList, par=par, parJnt=parJnt, ik=ik, fk=fk, stretch=stretch, squeeze=squeeze, localScale=localScale,\n elbowLock=elbowLock, softIK=softIK, autoSmooth=autoSmooth, bendy=bendy[:2], ikSpace=ikSpace, pvSpace=pvSpace)\n\n #the initial ik fk status\n self.ikFk = 1 #as ik\n self.ikMatchCoordinate = True #whether to have the ik ctrl match the world coordinate\n\n self.proxyCtrls.update({\"Rear\": \"{0}_Rear_Proxy_Ctrl\".format(self.longAlias), \n \"ToeIK2\": self.proxyJnts[-1].replace(\"Proxy_Jnt\", \"IK_Sub_Proxy_Ctrl\"),\n \"KnuckleFK\": self.proxyJnts[-2].replace(\"Proxy_Jnt\", \"FK_Proxy_Ctrl\"),\n \"KnuckleIK\": self.proxyJnts[-2].replace(\"Proxy_Jnt\", \"IK_Proxy_Ctrl\"),\n \"BotBendy\": \"{0}_Bot_Bendy_Proxy_Ctrl\".format(self.longAlias),\n \"BotBendy2\": \"{0}_Bot_Bendy_02_Proxy_Ctrl\".format(self.longAlias)})\n\n self.ctrlShape.update({\"BotBendy\": {\"shape\": \"circle\", \"ax\": (1, 0, 0), \"p\": (0, 0, 0), \"sd\": [1, 1, 8]},\n \"BotBendy2\": {\"shape\": \"nail3\", \"ax\": (0, 0, -self.negDic[self.side]), \"p\": (0, 0, 0), \"s\": (0.6, 0.6, 0.6)},\n \"ToeIK2\": {\"shape\": \"trapezoid3\", \"ax\": (0, 1, 0), \"p\": (0, 0.5, 0), \"s\": (0.5, 0.5, 0.5)},\n \"KnuckleFK\": {\"shape\": \"circle\", \"ax\": (1, 0, 0), \"p\": (0, 0, 0), \"sd\": [1, 0.5, 8]},\n \"KnuckleIK\": {\"shape\": \"trapezoid3\", \"ax\": (0, 1, 0), \"p\": (0, 0.5, 0), \"s\": (0.5, 0.5, 0.5)},\n \"Rear\": {\"shape\": \"circle\", \"ax\": (1, 0, 0), \"p\": (0, 0, 0), \"sd\": [1, 0.8, 8]}})\n\n self.attrValue.update({\"botBendy\": bendy[2], \"shortFoot\": self.boolDic[shortFoot]})\n\n\n def createProxy(self, repositionIK=True):\n botBendy = self.attrValue[\"botBendy\"]\n del self.attrValue[\"botBendy\"]\n super(hindLegRig, self).createProxy()\n\n #reset foot ik ctrl's aim constraint up vector\n cmds.setAttr(\"{0}_Grp_aimConstraint1.upVector\".format(self.proxyCtrls[\"FootIK\"]), 1, 0, 0, type=\"double3\")\n cmds.setAttr(\"{0}_Grp_aimConstraint1.worldUpVector\".format(self.proxyCtrls[\"FootIK\"]), 1, 0, 0, type=\"double3\")\n\n cu.createCtrl(n=self.proxyCtrls[\"KnuckleFK\"], colorNo=self.colorDic[self.side], ctrlShape=self.ctrlShape[\"KnuckleFK\"], depth=1, lockAttrs=[\"t\", \"r\", \"s\", \"v\"])\n cmds.parentConstraint(self.proxyJnts[-2], \"{0}_Grp\".format(self.proxyCtrls[\"KnuckleFK\"]), mo=False)\n cmds.parent(\"{0}_Grp\".format(self.proxyCtrls[\"KnuckleFK\"]), self.proxyGrp)\n\n cu.createCtrl(n=self.proxyCtrls[\"KnuckleIK\"], colorNo=self.colorDic2[self.side], ctrlShape=self.ctrlShape[\"KnuckleIK\"], depth=1, lockAttrs=[\"r\", \"s\", \"v\"])\n cmds.parent(\"{0}_Grp\".format(self.proxyCtrls[\"KnuckleIK\"]), self.proxyGrp)\n cmds.pointConstraint(self.proxyJnts[-2], \"{0}_Grp\".format(self.proxyCtrls[\"KnuckleIK\"]), mo=False)\n cmds.aimConstraint(self.proxyJnts[-3], \"{0}_Grp\".format(self.proxyCtrls[\"KnuckleIK\"]), aim=(0, 0, -1), u=(0, 1, 0), wu=(0, 1, 0), wut=\"objectrotation\", wuo=self.proxyGrp)\n cmds.setAttr(\"{0}.tz\".format(self.proxyCtrls[\"KnuckleIK\"]), -0.5)\n\n #create toe ik sub ctrl \n cu.createCtrl(n=self.proxyCtrls[\"ToeIK2\"], colorNo=self.colorDic2[self.side], ctrlShape=self.ctrlShape[\"ToeIK2\"], depth=1, lockAttrs=[\"r\", \"s\", \"v\"])\n cmds.parent(\"{0}_Grp\".format(self.proxyCtrls[\"ToeIK2\"]), self.proxyGrp)\n cmds.pointConstraint(self.proxyJnts[4], \"{0}_Grp\".format(self.proxyCtrls[\"ToeIK2\"]), mo=False)\n cmds.aimConstraint(self.proxyJnts[-1], \"{0}_Grp\".format(self.proxyCtrls[\"ToeIK2\"]), aim=(0, 0, 1), u=(0, 1, 0), wu=(0, 1, 0), wut=\"objectrotation\", wuo=self.proxyGrp)\n cmds.setAttr(\"{0}.tz\".format(self.proxyCtrls[\"ToeIK2\"]), 0.5)\n\n #reset initial pose\n cmds.move(self.negDic[self.side]*2.5, 12, -7.5, self.proxyJnts[0], a=True)\n cmds.move(self.negDic[self.side]*7, 0, 0, self.proxyJnts[1], a=True, os=True)\n cmds.move(self.negDic[self.side]*6, 0, 0, self.proxyJnts[2], a=True, os=True)\n cmds.move(self.negDic[self.side]*2.5, 0, 3.8, self.proxyJnts[3], a=True, ls=True)\n cmds.move(self.negDic[self.side]*1.25, 0, -0.3, self.proxyJnts[4], a=True, os=True)\n cmds.move(self.negDic[self.side]*1.25, 0, 0, self.proxyJnts[5], a=True, os=True)\n\n cmds.rotate(0, -45*self.negDic[self.side], -90*self.negDic[self.side], self.proxyJnts[0], a=True, os=True)\n cmds.rotate(0, 90*self.negDic[self.side], 0, self.proxyJnts[1], a=True, os=True)\n cmds.rotate(0, -45*self.negDic[self.side], 0, self.proxyJnts[2], a=True, os=True)\n cmds.rotate(0, -90*self.negDic[self.side], 0, self.proxyJnts[3], a=True, os=True)\n\n cmds.xform(self.proxyCtrls[\"IKTilt\"], t=(self.negDic[self.side]*2.8, 0, 6.8), ro=(0, 0, 0), a=True, os=True)\n cmds.xform(self.proxyCtrls[\"IKTilt2\"], t=(self.negDic[self.side]*2.8, 0, 2.5), ro=(0, 0, 0), a=True, os=True)\n\n cmds.setAttr(\"{0}.ty\".format(self.proxyCtrls[\"PV\"]), 8)\n cmds.setAttr(\"{0}.tz\".format(self.proxyCtrls[\"FootIK\"]), -1.5)\n #cmds.setAttr(\"{0}.tz\".format(self.proxyCtrls[\"ToeIK2\"]), 1.5)\n\n if repositionIK:\n cmds.delete(\"{0}_Grp_pointConstraint1\".format(self.proxyCtrls[\"IK\"]))\n cmds.pointConstraint(self.proxyJnts[3], \"{0}_Grp\".format(self.proxyCtrls[\"IK\"]), mo=False)\n\n #add bottom bendy \n cu.createCtrl(n=self.proxyCtrls[\"BotBendy\"], colorNo=self.colorDic2[self.side], ctrlShape=self.ctrlShape[\"BotBendy\"], depth=1, lockAttrs=[\"t\", \"r\", \"s\", \"v\"])\n cmds.aimConstraint(self.proxyJnts[2], \"{0}_Grp\".format(self.proxyCtrls[\"BotBendy\"]), aim=(-self.negDic[self.side], 0, 0), u=(0, 1, 0), wut=\"objectrotation\", wu=(0, 1, 0), wuo=self.proxyJnts[2])\n cmds.pointConstraint(self.proxyJnts[2], self.proxyJnts[3], \"{0}_Grp\".format(self.proxyCtrls[\"BotBendy\"]))\n cmds.parent(\"{0}_Grp\".format(self.proxyCtrls[\"BotBendy\"]), self.proxyGrp)\n #add secondary bendy ctrl\n cu.createCtrl(n=self.proxyCtrls[\"BotBendy2\"], colorNo=self.colorDic2[self.side], ctrlShape=self.ctrlShape[\"BotBendy2\"], depth=1, lockAttrs=[\"t\", \"r\", \"s\", \"v\"])\n cmds.parent(\"{0}_Grp\".format(self.proxyCtrls[\"BotBendy2\"]), self.proxyCtrls[\"BotBendy\"])\n cmds.xform(\"{0}_Grp\".format(self.proxyCtrls[\"BotBendy2\"]), t=(0, 0, 0), ro=(90*self.negDic[self.side], 0, 0), os=True, a=True)\n if self.side == self.right:\n cmds.xform(\"{0}_Grp\".format(self.proxyCtrls[\"BotBendy2\"]), ro=(0, 0, 180), os=True, r=True) \n\n #rear ctrl\n cu.createCtrl(n=self.proxyCtrls[\"Rear\"], colorNo=self.colorDic2[self.side], ctrlShape=self.ctrlShape[\"Rear\"], depth=1, lockAttrs=[\"t\", \"r\", \"s\", \"v\"])\n cmds.parentConstraint(self.proxyJnts[2], \"{0}_Grp\".format(self.proxyCtrls[\"Rear\"]))\n cmds.parent(\"{0}_Grp\".format(self.proxyCtrls[\"Rear\"]), self.proxyGrp)\n\n #save bot bendy ctrl number:\n cmds.addAttr(self.proxyJnts[0], ln=\"botBendy\", at=\"long\", k=True)\n cmds.setAttr(\"{0}.botBendy\".format(self.proxyJnts[0]), botBendy)\n\n self.attrValue.update({\"botBendy\": botBendy})\n return True\n\n def copyCleanJointsChain(self, alias=\"Jnt\"):\n '''\n ducplicate the proxy chain, auto orient it and freeze the tranfrom\n overwrite this part from limbRig object\n input:\n alias(string): the new name alisa for the duplicated joint chain\n '''\n #create a bind joint chain\n jnts = ju.copyJointChain(self.proxyJnts, oldAlias=\"Proxy_Jnt\", newAlias=alias, freeze=False)\n\n aimAxisDic = {self.left : \"x\", self.right: \"-x\"}\n sideAxisDic = {self.left : \"y\", self.right: \"-y\"}\n ju.orientJointChain(jnts, aimAxis=aimAxisDic[self.side], sideAxis=sideAxisDic[self.side])\n\n #set prefered angle\n cmds.setAttr(\"{0}.preferredAngleY\".format(jnts[1]), self.negDic[self.side]*10)\n\n [cmds.setAttr(\"{0}.segmentScaleCompensate\".format(jnt), 0) for jnt in jnts]\n return jnts\n\n def createRig(self):\n if not super(hindLegRig, self).createRig():\n return False\n\n self.bindJnts.remove(self.resultJnts[2])\n cmds.sets(self.resultJnts[2], rm=\"{0}_Bind_Jnt_Set\".format(self.longAlias))\n return True\n\n def createBind(self):\n super(hindLegRig, self).createBind()\n\n #add angle offset joint\n midJnt = self.resultJnts[1]\n ankleJnt = self.resultJnts[2]\n footJnt = self.resultJnts[3]\n midStartJnt = midJnt.replace(\"Jnt\", \"Start_Jnt\")\n midEndJnt = midJnt.replace(\"Jnt\", \"End_Jnt\")\n\n #create a midStartJnt\n ankleStartJnt = cmds.duplicate(ankleJnt, po=True, n=ankleJnt.replace(\"Jnt\", \"Start_Jnt\"))[0]\n cmds.parent(ankleStartJnt, ankleJnt)\n \n cmds.aimConstraint(footJnt, ankleStartJnt, mo=False, aim=(self.negDic[self.side], 0, 0), u=(0, 1, 0), wut=\"objectrotation\", wu=(0, 1, 0), wuo=ankleJnt) \n cmds.disconnectAttr(\"{0}.t\".format(ankleJnt), \"{0}.t\".format(midEndJnt))\n cmds.pointConstraint(ankleStartJnt, midEndJnt)\n #reset knee start joint's aim target\n oAttrs = [\"translate\", \"rotatePivotTranslate\", \"parentMatrix[0]\", \"rotatePivot\"]\n iattrs = [\"target[0].targetTranslate\", \"target[0].targetRotateTranslate\", \"target[0].targetParentMatrix\", \"target[0].targetRotatePivot\"]\n for oAttr, iattr in zip(oAttrs, iattrs):\n if self.attrValue[\"autoSmooth\"]:\n cmds.connectAttr(\"{0}.{1}\".format(ankleStartJnt, oAttr), \"{0}_aimConstraint1.{1}\".format(midStartJnt.replace(\"Jnt\", \"Null\"), iattr), f=True)\n else:\n cmds.connectAttr(\"{0}.{1}\".format(ankleStartJnt, oAttr), \"{0}_aimConstraint1.{1}\".format(midStartJnt, iattr), f=True)\n\n #create a midEndJnt\n ankleEndJnt = cmds.duplicate(footJnt, po=True, n=ankleJnt.replace(\"Jnt\", \"End_Jnt\"))[0]\n cmds.setAttr(\"{0}.jointOrient\".format(ankleEndJnt), 0, 0, 0, type=\"double3\")\n cmds.connectAttr(\"{0}.t\".format(footJnt), \"{0}.t\".format(ankleEndJnt))\n cmds.connectAttr(\"{0}.s\".format(footJnt), \"{0}.s\".format(ankleEndJnt))\n cmds.aimConstraint(ankleStartJnt, ankleEndJnt, mo=False, aim=(-self.negDic[self.side], 0, 0), u=(0, 1, 0), wut=\"objectrotation\", wu=(0, 1, 0), wuo=footJnt) \n\n #create mid tweak ctrl\n rearCtrl = \"{0}_Rear_Ctrl\".format(self.longAlias)\n lockAttrs = [\"r\", \"v\"] if self.attrValue[\"localScale\"] else [\"r\", \"s\", \"v\"]\n cu.createCtrlFromProxy(n=rearCtrl, colorNo=self.colorDic2[self.side], proxyShape=\"default\", depth=1, lockAttrs=lockAttrs, pSet=\"default\")\n cmds.parentConstraint(ankleJnt, \"{0}_Grp\".format(rearCtrl), mo=False)\n cmds.scaleConstraint(ankleJnt, \"{0}_Grp\".format(rearCtrl))\n cmds.connectAttr(\"{0}.t\".format(rearCtrl), \"{0}.t\".format(ankleStartJnt))\n cmds.connectAttr(\"{0}.s\".format(rearCtrl), \"{0}.s\".format(ankleStartJnt))\n\n cmds.disconnectAttr(\"{0}.s\".format(ankleJnt), \"{0}.s\".format(midEndJnt))\n cmds.scaleConstraint(rearCtrl, midEndJnt)\n self.ctrls[\"Bendy\"][\"Rear\"] = rearCtrl\n cmds.parent(\"{0}_Grp\".format(rearCtrl), self.mainGrp)\n\n #add bot bendy\n newBindJnts = []\n if self.attrValue[\"botBendy\"] > 2:\n botBendyResults = self.createBendy(\"{0}_Bot\".format(self.longAlias), ankleStartJnt, ankleEndJnt, noOfJnts=self.attrValue[\"botBendy\"])\n botBendyCtrl = botBendyResults[0]\n self.ctrls[\"Bendy\"][\"BotBendy\"] = botBendyCtrl\n self.ctrls[\"Bendy\"][\"Bot\"] = botBendyResults[2]\n\n cmds.sets(ankleStartJnt, rm=\"{0}_Bind_Jnt_Set\".format(self.longAlias))\n cmds.sets(ankleEndJnt, rm=\"{0}_Bind_Jnt_Set\".format(self.longAlias))\n\n for jnt in botBendyResults[1]:\n self.bindJnts.insert(-3, jnt)\n newBindJnts.append(jnt)\n \n else:\n self.bindJnts.insert(-3, ankleStartJnt)\n self.bindJnts.insert(-3, ankleEndJnt)\n newBindJnts.append(ankleStartJnt)\n newBindJnts.append(ankleEndJnt)\n\n for jnt in newBindJnts:\n ju.labelJoint(jnt, displayAxis=True)\n ju.setJoint(jnt)\n \n return True\n\n def createIK(self, repositionIK=True):\n super(legRig, self).createIK()\n\n #delete the ik tip handle and the old end end joint\n cmds.delete(\"{0}_Tip_IKHandle\".format(self.longAlias))\n cmds.delete(\"{0}_{1}_IK_End_Jnt\".format(self.longAlias, self.aliasList[2]))\n\n #create new single chain ik handle for the foot and toe\n ikFootHandle = cmds.ikHandle(n=\"{0}_{1}_IKHandle\".format(self.longAlias, self.aliasList[3]), \n startJoint=self.ikJnts[2], endEffector=self.ikJnts[3], solver=\"ikSCsolver\")[0]\n\n ikKnuckleHandle = cmds.ikHandle(n=\"{0}_{1}_IKHandle\".format(self.longAlias, self.aliasList[4]), \n startJoint=self.ikJnts[3], endEffector=self.ikJnts[4], solver=\"ikSCsolver\")[0]\n\n ikToeHandle = cmds.ikHandle(n=\"{0}_{1}_IKHandle\".format(self.longAlias, self.aliasList[5]), \n startJoint=self.ikJnts[4], endEffector=self.ikJnts[5], solver=\"ikSCsolver\")[0]\n\n cmds.setAttr(\"{0}.v\".format(ikFootHandle), 0)\n cmds.setAttr(\"{0}.v\".format(ikKnuckleHandle), 0)\n cmds.setAttr(\"{0}.v\".format(ikToeHandle), 0)\n\n #get some position data\n self.footPos = cmds.xform(self.ikJnts[3], q=True, t=True, ws=True)\n self.knucklePos = cmds.xform(self.ikJnts[4], q=True, t=True, ws=True)\n toePos = cmds.xform(self.ikJnts[5], q=True, t=True, ws=True)\n upVec = mu.vPlus(toePos, self.footPos, \"-\")\n tiltOri = mu.vectorToAngle((0, 1, 0), upVec=upVec, sideVec=None, aimAxis=\"y\", upAxis=\"z\", sideAxis=None)\n\n #reset IK tilt ctrl's orientation--------------------------------------\n cmds.xform(\"{0}_Grp\".format(self.ikCtrls[\"Tilt\"]), ro=tiltOri, a=True, ws=True)\n\n #create the second IK tilt ctrl\n self.ikCtrls[\"Tilt2\"] = \"{0}_IK_Tilt_02_Ctrl\".format(self.longAlias)\n cu.createCtrlFromProxy(n=self.ikCtrls[\"Tilt2\"], colorNo=self.colorDic[self.side], proxyShape=\"default\", posObj=self.proxyCtrls[\"IKTilt2\"], depth=1, lockAttrs=[\"s\", \"v\"])\n cmds.xform(\"{0}_Grp\".format(self.ikCtrls[\"Tilt2\"]), ro=(0, 0, 0), a=True, ws=True)\n cmds.parent(\"{0}_Grp\".format(self.ikCtrls[\"Tilt2\"]), self.ikTiltOutputGrp)\n self.ikTiltOutputGrp2 = cmds.duplicate(self.ikCtrls[\"Tilt2\"], po=True, n=\"{0}_Output_Grp\".format(self.ikCtrls[\"Tilt2\"]))[0]\n cmds.connectAttr(\"{0}.r\".format(self.ikCtrls[\"Tilt2\"]), \"{0}.r\".format(self.ikTiltOutputGrp2))\n cmds.connectAttr(\"{0}.t\".format(self.ikCtrls[\"Tilt2\"]), \"{0}.scalePivot\".format(self.ikTiltOutputGrp2))\n cmds.connectAttr(\"{0}.t\".format(self.ikCtrls[\"Tilt2\"]), \"{0}.rotatePivot\".format(self.ikTiltOutputGrp2))\n #reset tilt controls orientation\n cmds.xform(\"{0}_Grp\".format(self.ikCtrls[\"Tilt2\"]), ro=tiltOri, a=True, ws=True)\n\n #create ctrl footik toe ik------------------------------------------------------\n self.ikCtrls[\"FootIK\"] = \"{0}_{1}_IK_Ctrl\".format(self.longAlias, self.aliasList[3])\n ikFootCtrlGrp = \"{0}_Grp\".format(self.ikCtrls[\"FootIK\"])\n cu.createCtrlFromProxy(n=self.ikCtrls[\"FootIK\"], colorNo=self.colorDic[self.side], proxyShape=\"default\", offset=True, posObj=self.proxyCtrls[\"FootIK\"], depth=1, lockAttrs=[\"t\", \"s\", \"v\"])\n\n self.ikCtrls[\"ToeIK\"] = \"{0}_{1}_IK_Ctrl\".format(self.longAlias, self.aliasList[5])\n ikToeCtrlGrp = \"{0}_Grp\".format(self.ikCtrls[\"ToeIK\"])\n cu.createCtrlFromProxy(n=self.ikCtrls[\"ToeIK\"], colorNo=self.colorDic[self.side], proxyShape=\"default\", offset=True, posObj=self.proxyCtrls[\"ToeIK\"], depth=1, lockAttrs=[\"t\", \"s\", \"v\"])\n\n cmds.xform(ikFootCtrlGrp, t=self.footPos, a=True, ws=True)\n cmds.xform(ikToeCtrlGrp, t=self.footPos, a=True, ws=True)\n cmds.parent(self.ikHandleGrp, self.ikCtrls[\"FootIK\"])\n cmds.parent(ikFootHandle, self.ikCtrls[\"FootIK\"])\n\n #add toe tip ctrl\n self.ikCtrls[\"ToeTip\"] = \"{0}_{1}_Tip_Ctrl\".format(self.longAlias, self.aliasList[-1])\n cu.createCtrlFromProxy(n=self.ikCtrls[\"ToeTip\"], colorNo=self.colorDic[self.side], proxyShape=\"default\", posObj=self.proxyJnts[5], depth=1, lockAttrs=[\"v\"])\n \n self.toeOffsetJnt = cmds.duplicate(self.ikJnts[-1], n=self.ikJnts[-1].replace(\"Jnt\", \"Offset_Jnt\"), po=True)[0]\n toePMA = cmds.createNode(\"plusMinusAverage\", n=\"{0}_ToeTip_PMA\".format(self.longAlias))\n defaultT = cmds.getAttr(\"{0}.t\".format(self.toeOffsetJnt))[0]\n cmds.setAttr(\"{0}.input3D[0]\".format(toePMA), defaultT[0], defaultT[1], defaultT[2], type=\"double3\")\n cmds.connectAttr(\"{0}.t\".format(self.ikCtrls[\"ToeTip\"]), \"{0}.input3D[1]\".format(toePMA))\n cmds.connectAttr(\"{0}.output3D\".format(toePMA), \"{0}.t\".format(self.toeOffsetJnt))\n cmds.connectAttr(\"{0}.r\".format(self.ikCtrls[\"ToeTip\"]), \"{0}.r\".format(self.toeOffsetJnt))\n cmds.connectAttr(\"{0}.s\".format(self.ikCtrls[\"ToeTip\"]), \"{0}.s\".format(self.toeOffsetJnt))\n\n cu.setControl(self.ikCtrls[\"FootIK\"], key=\"IK\")\n cu.setControl(self.ikCtrls[\"ToeIK\"], key=\"IK\")\n cu.setControl(self.ikCtrls[\"Tilt2\"], key=\"IK\")\n cu.setControl(self.ikCtrls[\"ToeTip\"], key=\"IK\")\n\n if not self.attrValue[\"shortFoot\"]:\n self.ikCtrls[\"KnuckleIK\"] = \"{0}_{1}_IK_Ctrl\".format(self.longAlias, self.aliasList[4])\n ikKnuckleCtrlGrp = \"{0}_Grp\".format(self.ikCtrls[\"KnuckleIK\"])\n cu.createCtrlFromProxy(n=self.ikCtrls[\"KnuckleIK\"], colorNo=self.colorDic2[self.side], proxyShape=\"default\", offset=True, posObj=self.proxyCtrls[\"KnuckleIK\"], depth=2, lockAttrs=[\"t\", \"s\", \"v\"])\n\n self.ikCtrls[\"ToeIK2\"] = \"{0}_{1}_IK_Sub_Ctrl\".format(self.longAlias, self.aliasList[5])\n ikToeCtrl2Grp = \"{0}_Grp\".format(self.ikCtrls[\"ToeIK2\"])\n cu.createCtrlFromProxy(n=self.ikCtrls[\"ToeIK2\"], colorNo=self.colorDic2[self.side], proxyShape=\"default\", offset=True, posObj=self.proxyCtrls[\"ToeIK2\"], depth=1, lockAttrs=[\"t\", \"s\", \"v\"])\n \n cmds.xform(ikKnuckleCtrlGrp, t=self.knucklePos, a=True, ws=True)\n cmds.xform(ikToeCtrl2Grp, t=self.knucklePos, a=True, ws=True)\n \n cmds.parent(ikKnuckleHandle, self.ikCtrls[\"KnuckleIK\"])\n cmds.parent(ikToeHandle, self.ikCtrls[\"ToeIK2\"])\n\n cmds.parent(ikKnuckleCtrlGrp, self.ikCtrls[\"ToeIK\"])\n cmds.parent(ikToeCtrl2Grp, self.ikCtrls[\"ToeIK\"])\n\n KnuckleRollGrp = cmds.group(em=True, n=\"{0}_{1}_Roll_Grp\".format(self.longAlias, self.aliasList[4]), p=self.ikTiltOutputGrp2)\n cmds.xform(KnuckleRollGrp, t=self.knucklePos, a=True, ws=True)\n cmds.parent(ikFootCtrlGrp, KnuckleRollGrp)\n\n KnuckleRollPivotGrp = cmds.group(em=True, n=\"{0}_{1}_Roll_Pivot_Grp\".format(self.longAlias, self.aliasList[4]), p=KnuckleRollGrp)\n cmds.parent(KnuckleRollPivotGrp, self.ikTiltOutputGrp2)\n KnuckleRollPivot = cmds.group(em=True, n=\"{0}_{1}_Roll_Pivot_Null\".format(self.longAlias, self.aliasList[4]), p=KnuckleRollPivotGrp)\n cmds.pointConstraint(self.ikCtrls[\"KnuckleIK\"], KnuckleRollPivot, mo=True)\n cmds.connectAttr(\"{0}.t\".format(KnuckleRollPivot), \"{0}.rotatePivot\".format(KnuckleRollGrp))\n cmds.connectAttr(\"{0}.t\".format(KnuckleRollPivot), \"{0}.scalePivot\".format(KnuckleRollGrp))\n\n cu.setControl(self.ikCtrls[\"KnuckleIK\"], key=\"IK\")\n cu.setControl(self.ikCtrls[\"ToeIK2\"], key=\"IK\")\n\n cmds.parent(\"{0}_Grp\".format(self.ikCtrls[\"ToeTip\"]), self.ikCtrls[\"ToeIK2\"])\n else:\n cmds.parent(ikKnuckleHandle, self.ikCtrls[\"ToeIK\"])\n cmds.parent(ikToeHandle, self.ikCtrls[\"ToeIK\"])\n cmds.parent(\"{0}_Grp\".format(self.ikCtrls[\"ToeTip\"]), self.ikCtrls[\"ToeIK\"])\n\n\n #adding additional attribute on foot rolling system ---------------------------------------------------------------------------------- \n footAttrs = [\"ballRoll\", \"ballTwist\", \"toeRoll\", \"toeTwist\", \"toeBend\", \"heelRoll\", \"heelTwist\", \"footRock\"]\n if not self.attrValue[\"shortFoot\"]:\n footAttrs.insert(1, \"ballRoll2\")\n footAttrs.insert(6, \"toeBend2\")\n\n [cmds.addAttr(self.ikCtrls[\"IK\"], ln=attr, at=\"double\", dv=0, k=True) for attr in footAttrs]\n\n #---toe---\n toeBendGrp = cmds.group(self.ikCtrls[\"ToeIK\"], n=\"{0}_Toe_Bend_Grp\".format(self.longAlias))\n cmds.xform(toeBendGrp, rp=(0, 0, 0), sp=(0, 0, 0), a=True, os=True)\n cmds.connectAttr(\"{0}.toeBend\".format(self.ikCtrls[\"IK\"]), \"{0}.rx\".format(toeBendGrp))\n\n toeRollTwistGrp = cmds.group(self.ikCtrls[\"Tilt\"], self.ikTiltOutputGrp, n=\"{0}_Toe_Roll_Grp\".format(self.longAlias))\n cmds.connectAttr(\"{0}.t\".format(self.ikCtrls[\"Tilt\"]), \"{0}.scalePivot\".format(toeRollTwistGrp))\n cmds.connectAttr(\"{0}.t\".format(self.ikCtrls[\"Tilt\"]), \"{0}.rotatePivot\".format(toeRollTwistGrp))\n cmds.connectAttr(\"{0}.toeRoll\".format(self.ikCtrls[\"IK\"]), \"{0}.rx\".format(toeRollTwistGrp))\n cmds.connectAttr(\"{0}.toeTwist\".format(self.ikCtrls[\"IK\"]), \"{0}.ry\".format(toeRollTwistGrp))\n\n #---foot---\n footRollGrp = cmds.group(self.ikCtrls[\"FootIK\"], n=\"{0}_Foot_Roll_Grp\".format(self.longAlias))\n cmds.xform(footRollGrp, rp=(0, 0, 0), sp=(0, 0, 0), a=True, os=True)\n cmds.connectAttr(\"{0}.ballRoll\".format(self.ikCtrls[\"IK\"]), \"{0}.rx\".format(footRollGrp))\n\n #---heel---\n heelRollTwistGrp = cmds.group(self.ikCtrls[\"Tilt2\"], self.ikTiltOutputGrp2, n=\"{0}_Heel_Roll_Grp\".format(self.longAlias))\n cmds.connectAttr(\"{0}.t\".format(self.ikCtrls[\"Tilt2\"]), \"{0}.scalePivot\".format(heelRollTwistGrp))\n cmds.connectAttr(\"{0}.t\".format(self.ikCtrls[\"Tilt2\"]), \"{0}.rotatePivot\".format(heelRollTwistGrp))\n cmds.connectAttr(\"{0}.heelTwist\".format(self.ikCtrls[\"IK\"]), \"{0}.ry\".format(heelRollTwistGrp))\n cmds.connectAttr(\"{0}.heelRoll\".format(self.ikCtrls[\"IK\"]), \"{0}.rx\".format(heelRollTwistGrp))\n\n #---footRock---\n innerPos = cmds.xform(self.proxyLoc[\"Inner\"], q=True, ws=True, t=True)\n outerPos = cmds.xform(self.proxyLoc[\"Outer\"], q=True, ws=True, t=True)\n innerGrp = cmds.group(em=True, n=\"{0}_Foot_Inner_Grp\".format(self.longAlias), p=self.ikTiltOutputGrp2)\n outerGrp = cmds.group(em=True, n=\"{0}_Foot_Outer_Grp\".format(self.longAlias), p=innerGrp)\n cmds.xform(innerGrp, t=innerPos, ws=True, a=True)\n cmds.xform(outerGrp, t=outerPos, ws=True, a=True)\n\n #ball twist\n footTwistGrp = cmds.group(em=True, n=\"{0}_Foot_Twist_Grp\".format(self.longAlias), p=outerGrp)\n cmds.xform(footTwistGrp, t=self.footPos, a=True, ws=True)\n cmds.parent(ikToeCtrlGrp, footTwistGrp)\n cmds.connectAttr(\"{0}.ballTwist\".format(self.ikCtrls[\"IK\"]), \"{0}.ry\".format(footTwistGrp))\n\n rockCond = cmds.createNode(\"condition\", n=\"{0}_Foot_Rock_Cond\".format(self.longAlias))\n cmds.setAttr(\"{0}.operation\".format(rockCond), 2)\n cmds.setAttr(\"{0}.colorIfFalseG\".format(rockCond), 0)\n [cmds.connectAttr(\"{0}.footRock\".format(self.ikCtrls[\"IK\"]), \"{0}.{1}\".format(rockCond, attr)) for attr in [\"firstTerm\", \"colorIfTrueG\", \"colorIfFalseR\"]]\n \n if self.side == self.right:\n cmds.connectAttr(\"{0}.outColorR\".format(rockCond), \"{0}.rz\".format(innerGrp))\n cmds.connectAttr(\"{0}.outColorG\".format(rockCond), \"{0}.rz\".format(outerGrp))\n else:\n cmds.connectAttr(\"{0}.outColorG\".format(rockCond), \"{0}.rz\".format(innerGrp))\n cmds.connectAttr(\"{0}.outColorR\".format(rockCond), \"{0}.rz\".format(outerGrp))\n\n if not self.attrValue[\"shortFoot\"]:\n cmds.parent(KnuckleRollGrp, footTwistGrp)\n cmds.parent(KnuckleRollPivotGrp, footTwistGrp)\n\n toeBend2Grp = cmds.group(self.ikCtrls[\"ToeIK2\"], n=\"{0}_Toe_Sub_Bend_Grp\".format(self.longAlias))\n cmds.xform(toeBend2Grp, rp=(0, 0, 0), sp=(0, 0, 0), a=True, os=True)\n cmds.connectAttr(\"{0}.toeBend2\".format(self.ikCtrls[\"IK\"]), \"{0}.rx\".format(toeBend2Grp))\n\n rollADL = cmds.createNode(\"addDoubleLinear\", n=\"{0}_{1}_Roll_ADL\".format(self.longAlias, self.aliasList[4]))\n cmds.connectAttr(\"{0}.rx\".format(self.ikCtrls[\"KnuckleIK\"]), \"{0}.input1\".format(rollADL))\n cmds.connectAttr(\"{0}.ballRoll2\".format(self.ikCtrls[\"IK\"]), \"{0}.input2\".format(rollADL))\n cmds.connectAttr(\"{0}.output\".format(rollADL), \"{0}.rx\".format(KnuckleRollGrp))\n cmds.connectAttr(\"{0}.ballRoll2\".format(self.ikCtrls[\"IK\"]), \"{0}_02_Grp.rx\".format(self.ikCtrls[\"KnuckleIK\"]))\n else:\n cmds.parent(ikFootCtrlGrp, footTwistGrp)\n\n #--------------------------------------------------------------------------------------------------------------------------------------------\n #add bot length\n cmds.addAttr(self.ikCtrls[\"IK\"], ln=\"botLength\", at=\"double\", dv=1, min=0.001, k=True)\n lengthMDL = cmds.createNode(\"multDoubleLinear\", n=\"{0}_Bot_Length_MDL\".format(self.longAlias))\n\n footLength = cmds.getAttr(\"{0}.tx\".format(self.ikJnts[3]))\n cmds.setAttr(\"{0}.input2\".format(lengthMDL), footLength)\n cmds.connectAttr(\"{0}.botLength\".format(self.ikCtrls[\"IK\"]), \"{0}.input1\".format(lengthMDL))\n cmds.connectAttr(\"{0}.output\".format(lengthMDL), \"{0}.tx\".format(self.ikJnts[3]))\n\n if self.side == self.left:\n lengthMDL2 = cmds.createNode(\"multDoubleLinear\", n=\"{0}_Bot_Length_inverse_MDL\".format(self.longAlias))\n cmds.setAttr(\"{0}.input2\".format(lengthMDL2), -1)\n cmds.connectAttr(\"{0}.output\".format(lengthMDL), \"{0}.input1\".format(lengthMDL2))\n cmds.connectAttr(\"{0}.output\".format(lengthMDL2), \"{0}.tz\".format(self.ikHandleGrp))\n else:\n cmds.connectAttr(\"{0}.output\".format(lengthMDL), \"{0}.tz\".format(self.ikHandleGrp))\n\n #change IK ctrl's position to foot jnt\n if repositionIK:\n IKTiltPos = cmds.xform(self.ikCtrls[\"Tilt\"], q=True, t=True, ws=True)\n\n cmds.xform(\"{0}_02_Grp\".format(self.ikCtrls[\"IK\"]), t=self.footPos, ws=True, a=True)\n cmds.xform(\"{0}_Grp\".format(self.ikCtrls[\"Tilt\"]), t=IKTiltPos, ws=True, a=True)\n cmds.xform(self.ikTiltOutputGrp, t=IKTiltPos, ws=True, a=True)\n\n #reset the offset value between ik ctrl and foot joint\n offset = self.getOffset(self.ikCtrls[\"IK\"], self.resultJnts[3])\n [cmds.setAttr('{0}.ikOffset{1}'.format(self.ikCtrls[\"IK\"], attr), l=False) for attr in [\"X\", \"Y\", \"Z\"]]\n cmds.setAttr('{0}.ikOffset'.format(self.ikCtrls[\"IK\"]), offset[0], offset[1], offset[2], type='double3')\n [cmds.setAttr('{0}.ikOffset{1}'.format(self.ikCtrls[\"IK\"], attr), l=True) for attr in [\"X\", \"Y\", \"Z\"]]\n\n #add additonal anim constraint for the foot ik ctrl\n aimGrp = cmds.group(em=True, n=\"{0}_AutoAim_Grp\".format(self.longAlias), p=outerGrp)\n cmds.xform(aimGrp, t=self.footPos, a=True, ws=True)\n cmds.aimConstraint(self.mainGrp, aimGrp, aim=(0, 0, -1), u=(1, 0, 0), wut=\"objectrotation\", wu=(1, 0, 0), wuo=footTwistGrp)\n\n if not self.attrValue[\"shortFoot\"]:\n aimBufferGrp = cmds.group(KnuckleRollGrp, KnuckleRollPivotGrp, n=\"{0}_AutoAim_02_Grp\".format(self.longAlias))\n else:\n aimBufferGrp = cmds.group(ikFootCtrlGrp, n=\"{0}_AutoAim_02_Grp\".format(self.longAlias))\n\n cmds.xform(aimBufferGrp, rp=(0, 0, 0), sp=(0, 0, 0), a=True, os=True)\n cmds.parent(aimBufferGrp, aimGrp) \n\n return True\n\n def createFK(self):\n super(hindLegRig, self).createFK()\n\n if self.attrValue[\"shortFoot\"]:\n cmds.parent(\"{0}_Grp\".format(self.ctrls[\"FK\"][-2]), \"{0}_Grp\".format(self.ctrls[\"FK\"][-4]))\n cmds.delete(self.ctrls[\"FK\"][-4])\n cmds.delete(\"{0}_Grp_parentConstraint1\".format(self.ctrls[\"FK\"][-4]))\n self.ctrls[\"FK\"].remove(self.ctrls[\"FK\"][-4])\n self.ctrls[\"FK\"].remove(self.ctrls[\"FK\"][-3])\n\n return True\n\n def mirrorProxy(self, mirrorJnt=True, mirrorShape=True):\n super(hindLegRig, self).mirrorProxy(mirrorJnt=mirrorJnt, mirrorShape=mirrorShape)\n\n if mirrorShape:\n sideDic = {self.left: self.right, self.right: self.left}\n for key in [\"BotBendy\", \"BotBendy2\", \"ToeIK2\", \"KnuckleIK\"]:\n ctrl = self.proxyCtrls[key]\n otherSideCtrl = ctrl.replace(self.side, sideDic[self.side])\n if cmds.objExists(otherSideCtrl):\n if key in [\"BotBendy\", \"BotBendy2\"]:\n cu.matchShape(ctrl, otherSideCtrl, flip=(1, 1, -1))\n else:\n cu.matchShape(ctrl, otherSideCtrl, flip=(-1, 1, 1))\n\n if key in [\"ToeIK2\", \"KnuckleIK\"]:\n t = cmds.getAttr(\"{0}.t\".format(otherSideCtrl))[0]\n cmds.setAttr(\"{0}.t\".format(ctrl), -t[0], t[1], t[2], type=\"double3\")\n\n","sub_path":"Rig_Module/hindLeg_rig.py","file_name":"hindLeg_rig.py","file_ext":"py","file_size_in_byte":30383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"568205533","text":"\"\"\"\n This spider is a Werkenineenhotel spider created on top of the ATSSpider\n scrapy crawl werkenineenhotel -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"https://www.werkenineenhotel.nl/hotel_vacatures_banen_bijbanen_stage/?distance=&company_group_id=&company_rating_id=&job_availability_id%5B%5D=&keyword=&company_type_id%5B%5D=3&job_type_id%5B%5D=&location=&search=1\"\n\n sampel seed url:\n https://www.werkenindehoreca.nl/horeca_vacatures_baan_bijbaan/?distance=&company_group_id=&company_rating_id=&job_availability_id%5B%5D=&keyword=&company_type_id%5B%5D=&job_type_id%5B%5D=&location=&search=Zoeken \n\n sample job url:\n https://www.werkenindehoreca.nl/vacature/bediening-bar-f-b/amsterdam/noord-holland/12109/\n\"\"\"\n\nfrom re import compile\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, ConvertDateString\nfrom brightcorp.lib.utils import extract_first\n\n\nclass Werkenineenhotel(ATSSpider):\n\n name = \"werkenineenhotel\"\n domain = ''\n Domain_Url = compile(r\"://www\\.(\\S+)\\.nl\")\n\n def __init__(self, *args, **kwargs):\n super(Werkenineenhotel, self).__init__(*args, **kwargs)\n\n self.domain = self.Domain_Url.search(self.start_urls[0])\n if self.domain:\n self.domain = self.domain.group(1)\n\n def parse(self, response):\n selector = Selector(response)\n if not self.expected_job_count_set:\n job_count = selector.xpath(\n '//b[@id=\"results_count\"]/text()').extract()\n if job_count:\n self.expected_job_count = job_count\n\n jobs = selector.xpath(\n '//div[@class=\"job_results\"]/div/a[@class=\"job_result\"]')\n for job in jobs:\n url = job.xpath('./@href').extract()\n if url:\n yield Request(\n callback=self.parse_job_callback(),\n meta={\n 'title': job.xpath(\n './span[@class=\"job_title\"]/text()').extract(),\n 'company': job.xpath(\n './span[@class=\"company_logo\"]/img/@alt'\n ).extract(),\n },\n url=url[0]\n )\n\n next_page_url = extract_first(\n selector.xpath('//a[@class=\"next_page\"]/@href')\n )\n if next_page_url:\n yield Request(\n callback=self.parse,\n url=next_page_url\n )\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n\n details_xpath = '//td[text()=\"%s\"]/following-sibling::td/text()'\n\n loader.add_xpath(\n 'description',\n '//h3[text()=\"Algemene informatie\"]/following-sibling::node()[following::div[@class=\"job_company_info adbox-white\"]]'\n )\n loader.add_xpath(\n 'date', details_xpath % \"Geplaatst op:\",\n ConvertDateString('%d-%m-%Y')\n )\n loader.add_xpath('jobtype', details_xpath % \"Dienstverband:\")\n loader.add_xpath('location', details_xpath % \"Locatie:\")\n\n loader.add_xpath(\n 'referencenumber', details_xpath % \"Referentie nr.:\",\n Prefix('%s-' % self.domain)\n )\n\n loader.add_value('company', response.meta.get('company'))\n loader.add_value('title', response.meta.get('title'))\n loader.add_value('url', response.url)\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/werkenineenhotel.py","file_name":"werkenineenhotel.py","file_ext":"py","file_size_in_byte":3606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"311149504","text":"'''Python SpinPapi client\n\n File: SpinPapiClient.py\n Author Tom Worster\n Copyright (c) 2012 Spinitron, LLC. All rights reserved.\n Redistribution and use in source and binary forms, with or without modification, are permitted\n \tprovided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice, this list of conditions\n \t\tand the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of\n \t\tconditions and the following disclaimer in the documentation and/or other materials provided\n \t\twith the distribution.\n * Neither the name of the Spinitron, LLC. nor the names of its contributors may be used to endorse\n \t\tor promote products derived from this software without specific prior written permission.\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR\n IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n '''\n\nimport hmac, hashlib, base64, sys, binascii \nfrom urllib.parse import quote\nfrom time import gmtime, strftime\nfrom operator import itemgetter\n\nclass SpinPapiClient:\n '''A SpinPapi client class.\n\n {@see http://spinitron.com/user-guide/pdf/SpinPapi-v2.pdf}\n NOTE: all SpinPapi client applications must cache result data. This\n class does not provide caching.\n '''\n\n def __init__(self, userid, secret, station=''):\n '''Client constructor.\n\n :param string userid: Authentication user ID issued by Spinitron\n :param string secret: Authentication secret issued by Spinitron\n :param string station: Station ID\n '''\n\n self.params = {}\n self.params['papiversion'] = '2'\n self.host = 'spinitron.com'\n self.url = '/public/spinpapi.php'\n self.params['papiuser'] = userid\n self.secret = secret\n self.params['station'] = station\n\n def query(self, params):\n '''Perform an uncached SpinPapi query.\n\n :param dict params: SpinPapi query parameters. At least method\n must be present in the dict.\n\n :return string: A complete signed query URL.\n '''\n\n # Add requested params to object default params\n all_params = self.params\n for key, val in params.items():\n all_params[key] = val\n\n # Add current GMT timestamp to params\n all_params['timestamp'] = strftime(\"%Y-%m-%dT%H:%M:%SZ\", gmtime())\n\n # Sort params alphabetically by dict key\n all_params = sorted(all_params.items(), key=itemgetter(0))\n\n # Build the urlencoded query in a list and join it with '&' chars\n the_query = []\n for key, val in all_params:\n the_query.append(quote(key) + '=' + quote(val))\n the_query = '&'.join(the_query)\n\n # Construct the query's HMAC signature.\n signature = bytes(self.host + '\\n' + self.url + '\\n' + the_query, 'utf-8')\n signature = hmac.new(self.secret, signature, hashlib.sha256)\n signature = signature.digest()\n signature = base64.b64encode(signature)\n signature = quote(signature, '')\n\n return ('http://' + self.host + self.url\n + '?' + the_query + '&signature=' + signature)\n","sub_path":"packages/SpinPapiClient.py","file_name":"SpinPapiClient.py","file_ext":"py","file_size_in_byte":3709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"466818494","text":"#!/usr/bin/env python\nimport requests\nimport xmlrpclib\nimport logging\nimport logging.handlers\n\n# Logging setup\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.DEBUG)\nhandler = logging.handlers.SysLogHandler(address = '/dev/log')\nformatter = logging.Formatter('%(module)s: %(message)s')\nhandler.setFormatter(formatter)\nlog.addHandler(handler)\n\n\n# Function to get the current IP address\ndef get_current_ip_address():\n url = 'http://ip.jsontest.com/'\n\n try:\n r = requests.get(url)\n except Exception as e:\n raise(e)\n\n if r.status_code == 200:\n if len(r.json()) > 0:\n return r.json()['ip']\n else:\n log.error('No data received back from the url \"{0}\"'.format(url))\n else:\n log.error('Invalid response code received. The received response code is \"{0}\"'.format(r.status_code))\n\n\n# Function to get the zone id\ndef get_zone_id_version(api, apiKey, zone_name):\n zone_list = api.domain.zone.list(apiKey)\n\n if len(zone_list) > 0:\n for zone in zone_list:\n if zone['name'] == zone_name:\n return zone['id'], zone['version']\n else:\n log.error('No items found in the zone list')\n\n\n# Function to get the A-Records from a zone\ndef get_a_records_from_zone(api, apiKey, zone_id, zone_version):\n record_list = api.domain.zone.record.list(apiKey, zone_id, zone_version)\n a_records = []\n\n if len(record_list) > 0:\n for record in record_list:\n if record['type'] == 'A':\n a_records.append(record)\n else:\n log.error('No records found in zone')\n\n return a_records\n\n\n# Function to check which records needs to be updated\ndef get_outdated_records(api, apiKey, current_ip_address, zone_id=0, zone_version=0):\n outdated_records = []\n\n if (zone_id == 0 and zone_version == 0):\n zone_id, zone_version = get_zone_id_version(api, apiKey, 'timmer.pro')\n\n a_records = get_a_records_from_zone(api, apiKey, zone_id, zone_version)\n\n for a_record in a_records:\n if a_record['value'] != current_ip_address:\n outdated_records.append(a_record)\n\n return outdated_records\n\n\n# Function to update the outdated records\ndef update_dns_zone(api, apiKey, zone_name, current_ip_address):\n updated_records = []\n\n # Get the current zone id version\n zone_id, zone_version = get_zone_id_version(api, apiKey, zone_name)\n\n # create a new version of the zone file\n new_zone_version = api.domain.zone.version.new(apiKey, zone_id)\n\n # Get the outdated records\n outdated_records = get_outdated_records(api, apiKey, current_ip_address, zone_id, new_zone_version)\n\n # Go through the outdated records\n for record in outdated_records:\n record_id = { 'id': record['id'] }\n data = { 'name': record['name'], 'type': record['type'], 'value': current_ip_address }\n\n # Update the record\n updated_records.append(api.domain.zone.record.update(apiKey, zone_id, new_zone_version, record_id, data))\n\n # If the number of outdated records is equal to the number of update records\n if len(outdated_records) == len(updated_records):\n # Set the new version as the current version\n api.domain.zone.version.set(apiKey, zone_id, new_zone_version)\n\n # Delete the old version\n api.domain.zone.version.delete(apiKey, zone_id, zone_version)\n log.info('Records updated for zone \"timmer.pro\", total {0} record(s) updated'.format(str(len(updated_records))))\n\n\n# If the script is called directly\nif __name__ == '__main__':\n current_ip_address = get_current_ip_address()\n #current_ip_address = '62.45.245.48'\n\n api = xmlrpclib.ServerProxy('https://rpc.gandi.net/xmlrpc/')\n apiKey = ''\n\n outdate_records = get_outdated_records(api, apiKey, current_ip_address)\n\n if len(outdate_records) > 0:\n update_dns_zone(api, apiKey, 'timmer.pro', current_ip_address)\n else:\n log.info('No records to be updated for zone \"timmer.pro\"')\n\n\n","sub_path":"DDNS.py","file_name":"DDNS.py","file_ext":"py","file_size_in_byte":3982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"406378966","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Notification',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('messageId', models.CharField(max_length=48)),\n ('topicArn', models.CharField(max_length=256)),\n ('subject', models.CharField(max_length=100)),\n ('message', models.TextField()),\n ('timestamp', models.DateTimeField()),\n ('status', models.CharField(default=b'PENDING', max_length=9, choices=[(b'PENDING', b'Pending'), (b'PROCESSED', b'Processed'), (b'ERROR', b'Error')])),\n ('modified', models.DateTimeField(auto_now=True)),\n ('errors', models.TextField(null=True, blank=True)),\n ],\n ),\n migrations.CreateModel(\n name='Subscription',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('topic', models.CharField(max_length=128)),\n ('messageId', models.CharField(max_length=48)),\n ('token', models.CharField(max_length=256, null=True, blank=True)),\n ('topicArn', models.CharField(max_length=256)),\n ('message', models.TextField()),\n ('subscribeURL', models.URLField(max_length=512, null=True, blank=True)),\n ('timestamp', models.DateTimeField()),\n ('signatureVersion', models.CharField(max_length=32, null=True, blank=True)),\n ('signature', models.TextField(null=True, blank=True)),\n ('signingCertURL', models.URLField(max_length=512, null=True, blank=True)),\n ('status', models.CharField(default=b'PENDING', max_length=7, choices=[(b'ACTIVE', b'Active'), (b'PENDING', b'Pending'), (b'RETIRED', b'Retired')])),\n ('modified', models.DateTimeField(auto_now=True)),\n ('errors', models.TextField(null=True, blank=True)),\n ],\n ),\n ]\n","sub_path":"sns/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"308452335","text":"# Revision 1.0 // PLEASE MAKE A COPY AND EDIT BEFORE MAKING CHANGES\r\n\r\nimport random\r\nimport math\r\n\r\n\r\nclass Sun:\r\n def __init__(self, seed):\r\n self.name = \"\"\r\n self.id = seed # int\r\n self.star_class = '' # Letter O, B, A, F, G, K, M\r\n self.mass = None # int, *10^26 kilograms\r\n self.temperature = None # Int, degrees kelvin\r\n self.radius = None # int, kilometers\r\n\r\n random.seed = self.id\r\n t_val = random.random() # Temp variable\r\n if t_val <= 0.0000003:\r\n self.star_class = 'O'\r\n self.mass = random.randrange(160000, 320000) # *10^26 kilograms\r\n self.radius = self.mass * 0.4125 # In Solar radii (6.975*10^5km)\r\n self.temperature = math.floor(4*math.pi*self.radius*self.radius * 42.6264386916 + 6666.67) # Kelvin (many thousands) The area of the sun multiplies by the gradient of the relationship between area and termperate for its class\r\n elif 0.0000003 < t_val <= 0.0013003:\r\n self.star_class = 'B'\r\n self.mass = random.randrange(21000, 160000) # *10^26 kilograms\r\n self.radius = self.mass * 0.345323741007 + 1.47842 # In Solar radii (6.975*10^5km)\r\n self.temperature = math.floor(4*math.pi*self.radius*self.radius * 39.4729521557 + 8392.86)\r\n elif 0.0013003 < t_val <= 0.0073003:\r\n self.star_class = 'A'\r\n self.mass = random.randrange(14000, 21000) # *10^26 kilograms\r\n self.radius = self.mass * 0.571428571429 + 0.6 # In Solar radii (6.975*10^5km)\r\n self.temperature = math.floor(4*math.pi*self.radius*self.radius * 155.424749113 + 3671.88)\r\n elif 0.0073003 < t_val <= 0.0373003:\r\n self.star_class = 'F'\r\n self.mass = random.randrange(10400, 14000) # *10^26 kilograms\r\n self.radius = self.mass * 0.694444444444 + 1.58333 # In Solar radii (6.975*10^5km)\r\n self.temperature = math.floor(4*math.pi*self.radius*self.radius * 187.24110952 + 2888.24)\r\n elif 0.0373003 < t_val <= 0.1133:\r\n self.star_class = 'G'\r\n self.mass = random.randrange(8000, 10400) # *10^26 kilograms\r\n self.radius = self.mass * 0.791666666667 + 0.326667 # In Solar radii (6.975*10^5km)\r\n self.temperature = math.floor(4*math.pi*self.radius*self.radius * 158.797648383 + 3360.94)\r\n elif 0.1133 < t_val <= 0.2343:\r\n self.star_class = 'K'\r\n self.mass = random.randrange(4500, 8000) # *10^26 kilograms\r\n self.radius = self.mass * 1.34615384615 + 0.365714 # In Solar radii (6.975*10^5km)\r\n self.temperature = math.floor(4*math.pi*self.radius*self.radius * 276.56674541 + 1997.03)\r\n else:\r\n self.star_class = 'M'\r\n self.mass = random.randrange(800, 4500) # *10^26 kilograms\r\n self.radius = self.mass * 1.75675675676 + -0.77973 # In Solar radii (6.975*10^5km)\r\n self.temperature = math.floor(4*math.pi*self.radius*self.radius * 212.206590789 + 2393.33)\r\n\r\n\r\nclass Planet:\r\n def __init__(self, seed, minimum_orbit, central_body):\r\n self.radius = None # Orbit radius\r\n self.p_type = None\r\n self.id = seed\r\n self.orbital_speed = None # How long it takes to orbit central body\r\n self.axis = None # Planets inclination relative to the orbital plane\r\n self.p_axis = None # Planet's axis tilt\r\n self.moons = None\r\n self.atmosphere = None\r\n self.temperature = None # Surface temperature\r\n self.mass = None\r\n self.p_radius = None # The base radius of the planet itself\r\n self.gravity = None # Gravitational pull at p_radius\r\n if minimum_orbit == 0 or minimum_orbit < 0 or minimum_orbit is None:\r\n minimum_orbit = central_body.radius * 1.05 + 0.5*central_body.radius\r\n self.radius = random.randrange(minimum_orbit, central_body.mass * 1000000000000000000000000000) # In Solar radii (6.975*10^5km) # Completely Arbitary, will need additional research but probably out of the scope of game\r\n random.seed = self.id\r\n t_val = random.random()\r\n if self.radius < central_body.radius * 300:\r\n if t_val <= 0.5:\r\n self.p_type = 'rock'\r\n else:\r\n self.p_type = 'gas'\r\n # Rocky or Gas (0% ice planet)\r\n if central_body.radius * 300 <= self.radius < central_body.radius * 700: # Semi habitable? Needs additional research\r\n if t_val <= 0.45:\r\n self.p_type = 'rock'\r\n elif 0.45 < t_val <= 0.8:\r\n self.p_type = 'gas'\r\n else:\r\n self.p_type = 'ice'\r\n # Rocky or Gas or ice (45% rocky, 35% gas, 20% ice\r\n else:\r\n if t_val <= 0.1:\r\n self.type = 'gas'\r\n if 0.1 < t_val <= 0.55:\r\n self.type = 'rock'\r\n else:\r\n self.type = 'ice'\r\n # Rocky or ice (~10% of gas, 45% other)\r\n self.orbital_speed = (2*math.pi*math.sqrt(self.radius*self.radius*self.radius))/(math.sqrt(6.67*10**-11)*math.sqrt(central_body.mass)) # How long it takes to orbit central body\r\n self.axis = random.randint(0, 10) # Planets inclination relative to the orbital plane\r\n self.p_axis = random.randrange(0, 90) # Planet's axis tilt in degrees from vertical\r\n self.p_radius = math.floor(random.randrange(900, 0.05 * central_body.radius)) # The base radius of the planet itself in km\r\n if self.p_type is 'gas':\r\n # gassy things\r\n self.mass = math.floor((4/3) * math.pi * self.p_radius**3 * random.randrange(0.9, 1.8)) # in kg\r\n self.atmosphere = None\r\n self.temperature = random.randint(800, 1400) # Surface temperature in kelvin\r\n if self.p_type is 'rock':\r\n # rocky things\r\n self.mass = math.floor((4/3) * math.pi * self.p_radius**3 * random.randrange(0.8, 1.1))\r\n self.atmosphere = random.randint(0, 1)\r\n if self.atmosphere == 1:\r\n self.temperature = random.randint(230, 380) # Surface temperature\r\n else:\r\n self.temperature = random.randint(125, 800)\r\n else:\r\n # icy things\r\n self.mass = math.floor((4/3) * math.pi * self.p_radius**3 * random.randrange(0.9, 1.1))\r\n self.atmosphere = random.randint(0, 1)\r\n if self.atmosphere == 1:\r\n self.temperature = random.randint(200, 270)\r\n else:\r\n self.temperature = random.randint(125, 270) # Surface temperature\r\n self.gravity = ((6.67*10**-11) * self.mass)/self.p_radius**2 # Gravitational pull at p_radius\r\n self.moons = {}\r\n for m in range(0, random.randint(0, 3)):\r\n self.moons[m] = Planet(self.id + 1, self.p_radius * 1.2, self)\r\n\r\n","sub_path":"solar_gen.py","file_name":"solar_gen.py","file_ext":"py","file_size_in_byte":6926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"168716441","text":"# File: ps_noise_sniffer.py\n# Description: Power Supply Noise Sniffer\n# Author: Mark Thoren (mark.thoren@analog.com)\n# Antoniu Miclaus (antoniu.miclaus@analog.com)\n#\n# Copyright 2018(c) Analog Devices, Inc.\n#\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# - Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# - Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in\n# the documentation and/or other materials provided with the\n# distribution.\n# - Neither the name of Analog Devices, Inc. nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n# - The use of this software may or may not infringe the patent rights\n# of one or more patent holders. This license does not release you\n# from the requirement that you obtain separate licenses from these\n# patent holders to use this software.\n# - Use of the software either in source or binary form, must be run\n# on or directly connected to an Analog Devices Inc. component.\n#\n# THIS SOFTWARE IS PROVIDED BY ANALOG DEVICES \"AS IS\" AND ANY EXPRESS OR\n# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, NON-INFRINGEMENT,\n# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n# IN NO EVENT SHALL ANALOG DEVICES BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, INTELLECTUAL PROPERTY RIGHTS, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n'''\nDerived from an example posted here:\nhttps://ez.analog.com/thread/99958-ad9361-libiio-api-python-binding\n\nA useful nugget for verifying throughput, from:\nhttps://wiki.analog.com/university/tools/pluto/devs/performance\nADALM-PLUTO Performance Metrics:\nData Throughput (USB)\n\nVia IIOD USB backend\niio_readdev -u usb:1.100.5 -b 100000 cf-ad9361-lpc | pv > /dev/null\n210GiB 1:19:51 [26,1MiB/s] [ <=> \n\nVia IIOD Network backend\niio_readdev -n 192.168.2.1 -b 100000 cf-ad9361-lpc | pv > /dev/null\n203MiB 0:00:10 [20,4MiB/s] [ <=> \n\n'''\n\nimport sys, os\nimport time\n\ntry:\n import tkinter as tk\n from tkinter import filedialog\n import tkinter.scrolledtext as tkscrolled\n\nexcept:\n print(\"Please install tkinter\")\ntry:\n import csv\nexcept:\n print(\"Please install csv\")\ntry:\n import pandas as pd\nexcept:\n print(\"Please install pandas\")\ntry:\n import numpy as np\nexcept:\n print(\"Please install numpy\")\n\ntry:\n import matplotlib.pyplot as plt\n from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg\nexcept:\n print(\"Please install matplotlib\")\n\ntry: \n import iio\nexcept:\n sys.path.append('C:/Users/fhurgoi/Documents/libiio-master/bindings/python') #add own path to python bindings\n import iio\n\ntry:\n import serial\nexcept:\n print(\"Please install pywin32\")\n\nimport plotly\nimport plotly.graph_objs as go\n\ntry:\n import scipy.signal\nexcept:\n pritn(\"Please install scipy\")\n\n#Error\nERROR = -1\n\n#Success\nSUCCESS = 0\n\n# channel name index mapping\n# for phy:\nTMP = 2\n\n# buffer length index mapping\nBUFLEN = 2 ** 17\n\n# ADRV9009 operational parameters\nN_BITS = 16\n\nTRXLO = 1000e6\n\nTX0BW = 225e6\nTX0FS = 245.76e6\nRX0BW = 100e6\nRX0FS = 122.88e6#122.88e6\n\nFREQ_BAND = 100e6\n\n#TX tone frequency \nTXDAC_FREQ = 10e6 #MHz\n \n#Center frequencies, start frequency, stop frequency index mapping\nCENTER_FREQ = 0\nSTART_FREQ = 1\nSTOP_FREQ = 2\n\ndirname = os.path.dirname(__file__)\n\n# Clear Plot and Message Log\ndef clr_content():\n txt1.delete('1.0', tk.END)\n a.cla()\n canvas.draw()\n \n# Setup Context\ndef connect_device():\n \n global phy_a, phy_b, txdac, rxadc, ctx\n \n try:\n #ctx = iio.Context('ip:10.50.1.210')\n ctx = iio.Context('ip:192.168.1.146')\n except:\n return ERROR\n \n phy_a = ctx.find_device(\"adrv9009-phy\") # Register control\n phy_b = ctx.find_device(\"adrv9009-phy-b\") # Register control\n txdac = ctx.find_device(\"axi-adrv9009-tx-hpc\") # TX/DAC Core in HDL for DMA (plus DDS)\n rxadc = ctx.find_device(\"axi-adrv9009-rx-hpc\") # RX/ADC Core in HDL for DMA\n \n return phy_a, phy_b, txdac, rxadc, ctx\n\ndef connect_generator():\n\n global COMgen, ser\n\n COMgen = str('COM' + gen_COM.get())\n\n # configure the serial connections (the parameters differs on the device you are connecting to)\n ser = serial.Serial(\n port=COMgen,\n baudrate=115200,\n parity=serial.PARITY_NONE,\n stopbits=serial.STOPBITS_ONE,\n bytesize=serial.EIGHTBITS\n )\n\n try:\n port = ser.isOpen()\n print (str(port))\n except serial.SerialException:\n ser.close()\n print (\"port is closed\")\n ser.isOpen()\n print (\"port is open\")\n\n #ser.write(('*IDN?' + '\\r\\n').encode('utf-8'))\n ser.write(('FREQ 70e6' + '\\r\\n').encode('utf-8'))\n ser.write(('POW ' + str(int(tx_pow.get())) + '\\r\\n').encode('utf-8'))\n ser.write(('OUTP OFF' + '\\r\\n').encode('utf-8'))\n\ndef disconnect_generator():\n # configure the serial connections (the parameters differs on the device you are connecting to)\n ser.close()\n\n#Compute frequencies for each band\ndef comp_freq():\n center_freq = np.array([]) #array that holds the center frequencies\n \n #Convert input start/stop frequency values to integers\n try:\n start_f.get()\n stop_f.get()\n except:\n center_freq = np.append(center_freq, ERROR)\n return center_freq\n \n #Get start/stop frequency values\n start_freq = float(start_f.get()) * float(1e6) #MHz\n stop_freq = float(stop_f.get()) * float(1e6) #MHz\n \n #Check if start frequency is larger that input frequency\n if (start_freq > stop_freq or start_freq < 70e6 or stop_freq > 6e9):\n center_freq = np.append(center_freq, ERROR)\n else:\n nr_center_freq = int((stop_freq - start_freq)/FREQ_BAND) + 1 \n center_freq = np.append(center_freq, start_freq)\n \n #Compute center frequencies for each band\n for i in range(1, nr_center_freq):\n center_freq = np.append(center_freq, center_freq[i-1] + FREQ_BAND)\n return center_freq, start_freq, stop_freq\n\ndef configure_device():\n\n with open('Tx_BW200_IR245p76_Rx_BW100_OR122p88_ORx_BW200_OR245p76_DC245p76.txt', 'r') as myfile:\n filterfile = myfile.read()\n\n iio.Context.set_timeout(ctx, 30000);\n time.sleep(0.1)\n\n phy_a.attrs[\"profile_config\"].value = filterfile\n phy_b.attrs[\"profile_config\"].value = filterfile\n\n iio.Context.set_timeout(ctx, 3000);\n\ndef RXA1():\n\n rx_channel = phy_a.find_channel(\"voltage0\")\n return rx_channel\n\ndef RXA2():\n\n rx_channel = phy_a.find_channel(\"voltage1\")\n return rx_channel\n\ndef RXB1():\n\n rx_channel = phy_b.find_channel(\"voltage0\")\n return rx_channel\n\ndef RXB2():\n\n rx_channel = phy_b.find_channel(\"voltage1\")\n return rx_channel\n\n#Transciever settings \ndef setup_device():\n \n global tx, rx, TX1_I_F1, TX1_Q_F1, TX2_I_F1, TX2_Q_F1, TX2_Q_F1, TX3_I_F1, TX3_Q_F1, TX4_I_F1, TX4_Q_F1\n global TRX_LO_A, TRX_LO_B\n\n # Global configuration\n TRX_LO_A = phy_a.find_channel(\"altvoltage0\", True)\n TRX_LO_A.attrs[\"frequency\"].value = str(int(TRXLO))\n TRX_LO_A.attrs[\"frequency_hopping_mode_enable\"].value = str(0)\n\n TRX_LO_B = phy_b.find_channel(\"altvoltage0\", True)\n TRX_LO_B.attrs[\"frequency\"].value = str(int(TRXLO))\n TRX_LO_B.attrs[\"frequency_hopping_mode_enable\"].value = str(0)\n\n # Default RX Configuration\n\n #configure just the RX channel under test\n rx_chann = {\"RX1\": RXA1, \"RX2\": RXA2, \"RX3\": RXB1, \"RX4\": RXB2}\n func = rx_chann.get(rx_channel.get(), \"nothing\")\n rx = func()\n\n rx.attrs['gain_control_mode'].value = \"manual\"\n rx.attrs['hardwaregain'].value = rx_gain.get()\n #rx.attrs[\"rf_bandwidth\"].value = (str(int(RX0BW)))\n #rx.attrs[\"sampling_frequency\"].value = str(int(RX0FS))\n #rx.attrs[\"powerdown\"].value = str(0)\n\n #rx.attrs[\"gain_control_pin_mode_en\"].value = str(1)\n if(track_en.get() == True):\n rx.attrs['quadrature_tracking_en'].value = str(1)\n else:\n rx.attrs['quadrature_tracking_en'].value = str(0)\n\n # axi-adrv9009-tx-hpc (buffer capable) channels\n TX1_I_F1 = txdac.find_channel('altvoltage0',True)\n TX1_I_F2 = txdac.find_channel('altvoltage1',True)\n TX1_Q_F1 = txdac.find_channel('altvoltage2',True)\n TX1_Q_F2 = txdac.find_channel('altvoltage3',True)\n TX2_I_F1 = txdac.find_channel('altvoltage4',True)\n TX2_I_F2 = txdac.find_channel('altvoltage5',True)\n TX2_Q_F1 = txdac.find_channel('altvoltage6',True)\n TX2_Q_F2 = txdac.find_channel('altvoltage7',True)\n TX3_I_F1 = txdac.find_channel('altvoltage8',True)\n TX3_I_F2 = txdac.find_channel('altvoltage9',True)\n TX3_Q_F1 = txdac.find_channel('altvoltage10',True)\n TX3_Q_F2 = txdac.find_channel('altvoltage11',True)\n TX4_I_F1 = txdac.find_channel('altvoltage12',True)\n TX4_I_F2 = txdac.find_channel('altvoltage13',True)\n TX4_Q_F1 = txdac.find_channel('altvoltage14',True)\n TX4_Q_F2 = txdac.find_channel('altvoltage15',True)\n\n # Turn TX tone off\n TX1_I_F1.attrs[\"frequency\"].value = \"10000000\"\n TX1_I_F1.attrs[\"scale\"].value = \"0.0\"#\"0.031616\"#\"0.1\" = -20dBFS, \"0.031616 = -30dBFS = -20dBm\"\n TX1_Q_F1.attrs[\"frequency\"].value = \"10000000\"\n TX1_Q_F1.attrs[\"scale\"].value = \"0.0\"\n TX1_I_F2.attrs[\"frequency\"].value = \"10000000\"\n TX1_I_F2.attrs[\"scale\"].value = \"0.0\"#\"0.031616\"#\"0.1\" = -20dBFS, \"0.031616 = -30dBFS = -20dBm\"\n TX1_Q_F2.attrs[\"frequency\"].value = \"10000000\"\n TX1_Q_F2.attrs[\"scale\"].value = \"0.0\"\n TX2_I_F1.attrs[\"frequency\"].value = \"10000000\"\n TX2_I_F1.attrs[\"scale\"].value = \"0.0\"\n TX2_Q_F1.attrs[\"frequency\"].value = \"10000000\"\n TX2_Q_F1.attrs[\"scale\"].value = \"0.0\"\n TX2_I_F2.attrs[\"frequency\"].value = \"10000000\"\n TX2_I_F2.attrs[\"scale\"].value = \"0.0\"\n TX2_Q_F2.attrs[\"frequency\"].value = \"10000000\"\n TX2_Q_F2.attrs[\"scale\"].value = \"0.0\"\n TX3_I_F1.attrs[\"frequency\"].value = \"10000000\"\n TX3_I_F1.attrs[\"scale\"].value = \"0.0\"\n TX3_Q_F1.attrs[\"frequency\"].value = \"10000000\"\n TX3_Q_F1.attrs[\"scale\"].value = \"0.0\"\n TX3_I_F2.attrs[\"frequency\"].value = \"10000000\"\n TX3_I_F2.attrs[\"scale\"].value = \"0.0\"\n TX3_Q_F2.attrs[\"frequency\"].value = \"10000000\"\n TX3_Q_F2.attrs[\"scale\"].value = \"0.0\"\n TX4_I_F1.attrs[\"frequency\"].value = \"10000000\"\n TX4_I_F1.attrs[\"scale\"].value = \"0.0\"\n TX4_Q_F1.attrs[\"frequency\"].value = \"10000000\"\n TX4_Q_F1.attrs[\"scale\"].value = \"0.0\"\n TX4_I_F2.attrs[\"frequency\"].value = \"10000000\"\n TX4_I_F2.attrs[\"scale\"].value = \"0.0\"\n TX4_Q_F2.attrs[\"frequency\"].value = \"10000000\"\n TX4_Q_F2.attrs[\"scale\"].value = \"0.0\"\n\n v0_i = rxadc.find_channel(\"voltage0_i\")\n v0_q = rxadc.find_channel(\"voltage0_q\")\n v1_i = rxadc.find_channel(\"voltage1_i\")\n v1_q = rxadc.find_channel(\"voltage1_q\")\n v2_i = rxadc.find_channel(\"voltage2_i\")\n v2_q = rxadc.find_channel(\"voltage2_q\")\n v3_i = rxadc.find_channel(\"voltage3_i\")\n v3_q = rxadc.find_channel(\"voltage3_q\")\n v0_i.enabled = False\n v0_q.enabled = False\n v1_i.enabled = False\n v1_q.enabled = False\n v2_i.enabled = False\n v2_q.enabled = False\n v3_i.enabled = False\n v3_q.enabled = False\n\n # Enable I/Q channels to be associated with RX buffer\n if(rx_channel.get() == \"RX1\"):\n v0_i.enabled = True\n v0_q.enabled = True\n elif(rx_channel.get() == \"RX2\"):\n v1_i.enabled = True\n v1_q.enabled = True\n elif(rx_channel.get() == \"RX3\"):\n v2_i.enabled = True\n v2_q.enabled = True\n elif(rx_channel.get() == \"RX4\"):\n v3_i.enabled = True\n v3_q.enabled = True\n else:\n txt1.insert(tk.END, 'Ghinion. Nu-i bine canalu de RX!\\n\\n')\n\n #turn radio on\n phy_a.attrs[\"ensm_mode\"]. value = \"radio_on\"\n phy_b.attrs[\"ensm_mode\"]. value = \"radio_on\"\n\n\n#Die temperature\ndef die_temp():\n \n temp_a = int(phy_a.channels[TMP].attrs[\"input\"].value) / 1000.0\n txt1.insert(tk.END, 'Die Temperature A: ' + str(temp_a) + '\\n\\n')\n temp_b = int(phy_b.channels[TMP].attrs[\"input\"].value) / 1000.0\n txt1.insert(tk.END, 'Die Temperature B: ' + str(temp_b) + '\\n\\n')\n root.update_idletasks()\n root.update()\n\n#Get and plot data\ndef get_plot_data(dev, center_freq):\n \n global save_freq, save_data, save_noise, save_spur_number, save_max_spur\n global save_spur_freq, save_spur_data\n\n TX_offset = float(tone_offset.get())*1e6\n ylim = [0,0]\n # Create IIO RX Buffer\n rxbuf = iio.Buffer(dev[3], BUFLEN, False) \n \n # Window function, max value = unity\n window = np.hanning(BUFLEN)\n #window = np.blackman(BUFLEN)\n \n avg_step = 0\n avgband = np.array([])\n\n save_data = []\n save_freq = []\n save_noise = []\n save_spur_freq = []\n save_spur_data = []\n save_spur_number = []\n save_max_spur = []\n\n\n if(gen_en.get() == True):\n ser.write(('POW ' + str(int(tx_pow.get())) + '\\r\\n').encode('utf-8'))\n ser.write(('OUTP ON' + '\\r\\n').encode('utf-8'))\n\n ss = 0\n\n while(avg_step == 0):\n\n #acquire data\n for i in range(0, len(center_freq)):\n \n RXLO = center_freq[i]\n if(rx_channel.get() == 'RX1' or rx_channel.get() == 'RX2'):\n TRX_LO_A.attrs[\"frequency\"].value = str(int(RXLO))\n elif(rx_channel.get() == 'RX3' or rx_channel.get() == 'RX4'):\n TRX_LO_B.attrs[\"frequency\"].value = str(int(RXLO))\n else:\n print(\"Nu-i bine!\")\n\n time.sleep(0.2)\n root.update_idletasks()\n root.update()\n \n #generate test tone\n if(gen_en.get() == True):\n ser.write(('FREQ ' + str(RXLO + TX_offset) + '\\r\\n').encode('utf-8'))\n #delay before data acquisition\n time.sleep(0.5)\n \n btn_aq.config(bg = \"red\")\n root.update()\n for k in range(0, int(avg_nr.get())+1):\n #flush operations\n for j in range(5):\n rxbuf.refill()\n x = rxbuf.read()\n \n buff = np.frombuffer(x, dtype=np.int16)\n \n #apply window\n rxvals_i = buff[0::2] * window\n rxvals_q = buff[1::2] * window\n \n #construct complex IQ data\n rxvals_iq = rxvals_i + (1j * rxvals_q)\n\n # apply FFT and get amplitude of the IQ data \n newband = np.abs(np.fft.fft(rxvals_iq)) \n \n #apply averaging\n if(k != 0):\n avgband = (newband) * 1/k + avgband * (k-1) / k;#(newband)/int(avg_nr.get())\n else:\n avgband = newband\n\n btn_aq.config(bg = \"grey\")\n root.update()\n\n #compute cutoff thresholds \n low_th = int(((RX0FS - FREQ_BAND)/(RX0FS * 2)) * BUFLEN)\n high_th = int(BUFLEN - (((RX0FS - FREQ_BAND)/(RX0FS * 2)) * BUFLEN))\n\n #compute frequency bins\n # 0, 1, 2, ..., n/2-1, -n/2,..., -1\n freq_bins = (np.fft.fftfreq(BUFLEN, 1/RX0FS) + (center_freq[0] + FREQ_BAND * i)) /1e6\n\n # Create tuple such that frequencies and corresponding amplitudes can be manipulated together\n tuple1 = zip(freq_bins, avgband)\n \n # Rearrange such that the center frequency is in the middle.\n tuple1 = sorted(tuple1, key=lambda x: x[0])\n #print(tuple1)\n # Extract the passband of the FIR response\n tuple1 = tuple1[low_th : high_th]\n \n #iq = np.array([nr[1] for nr in tuple1]) / (10 ** (gain_calib/10))\n iq = np.array([nr[1] for nr in tuple1])\n fbin = np.array([nr[0] for nr in tuple1])\n\n fft_rxvals_iq_dbFS = 10 * np.log10(iq**2) + 20 * np.log10(2/2**(N_BITS-1))- 20 * np.log10(BUFLEN) + 20 * np.log10(1/(1.5**0.5))# IIO\n # Compute in dB, subtract hardware gain to normalize to absolute analog signal level at input\n\n fft_rxvals_iq_dbm = fft_rxvals_iq_dbFS - 6.7\n\n noise_f = compute_noise_floor(fft_rxvals_iq_dbFS)\n spurs = scipy.signal.find_peaks(fft_rxvals_iq_dbFS, ((noise_f + 6), 0), None, 5, 3, None, None, 0.5, None)\n\n n_bins = fft_rxvals_iq_dbm.size\n\n freqbin = FREQ_BAND/n_bins\n spurs_fund_th_low = int((FREQ_BAND/2 + TX_offset - 3e6)/freqbin)\n spurs_fund_th_high = int((FREQ_BAND/2 + TX_offset + 3e6)/freqbin)\n\n RX_crosstalk_ampl = np.max(fft_rxvals_iq_dbm[spurs_fund_th_low : spurs_fund_th_high])\n\n txt1.insert(tk.END, \"Center Frequency set to: \" + str(RXLO/1e6) + ' MHz\\n')\n txt1.insert(tk.END, \"RX crosstalk : \" + str('%04.3f'%(RX_crosstalk_ampl)+ \" dBm\\n\"))\n txt1.insert(tk.END, \"Noise floor: \" + str('%04.3f'%noise_f)+ \" dBFS\\n\")\n\n spurs_number_band = len(spurs[0])\n spurs_number_save = 0\n for i in range(0, spurs_number_band):\n if spurs[0][i] <= spurs_fund_th_low or spurs_fund_th_high <= spurs[0][i]:\n save_spur_freq.append((RXLO - (FREQ_BAND/2) + ((spurs[0][i])*freqbin))/1e6)#1875\n save_spur_data.append(spurs[1]['peak_heights'][i])\n txt1.insert(tk.END, \"Spurs freq: \" + str('%04.3f'%save_spur_freq[ss+spurs_number_save]) + \" MHz\\n\" +\" Spurs amplitude: \" + str('%04.3f'%save_spur_data[ss+spurs_number_save])+ \" dBm\\n\")\n spurs_number_save += 1\n ss += spurs_number_save\n\n txt1.see(\"end\")\n\n save_freq.append(RXLO/1e6)\n save_data.append(int(tx_pow.get()) - RX_crosstalk_ampl)\n save_noise.append(noise_f)\n save_spur_number.append(spurs_number_save)\n save_max_spur.append(np.max(spurs[1]['peak_heights']))\n\n # Plot data\n a.clear()\n a.grid(True)\n a.set_title('Frequency Spectrum')\n a.set_xlabel('Fequency (MHz)')\n a.set_ylabel('Magnitude')\n\n\n a.plot(fbin, fft_rxvals_iq_dbFS)\n\n canvas.draw()\n root.update_idletasks()\n root.update()\n\n #txt1.insert(tk.END, \"time: \" + str(time.time()) + \"\\n\")\n #txt1.see(\"end\")\n\n if(stop.get() == True):\n break\n \n avg_step += 1\n\n if(gen_en.get() == True):\n #disable TX\n ser.write(('OUTP OFF' + '\\r\\n').encode('utf-8'))\n\n trace0 = go.Scatter(\n x = save_freq,\n y = save_data,\n mode = 'lines+markers',\n name = 'RX Crosstalk'\n )\n\n x_title = 'Frequency (MHz)'\n\n layout = go.Layout(\n # width=1500, height=750,\n title='RX channel separation', titlefont=dict(family='Arial', size=28),\n xaxis=dict(title=x_title, titlefont=dict(family='Arial', size=28),\n tickangle=0, tickfont=dict(family='Arial', size=14), dtick=1000, range = [0, 6000]),\n yaxis=dict(title='Magnitude (dB)', titlefont=dict(family='Arial', size=28),\n tickfont=dict(family='Arial', size=14), dtick=10, range = [50, 120]),\n barmode='group',\n legend=dict(\n #orientation=\"h\", x=0.0, y=-0.25,\n font=dict(family='sans-serif', size=18)),\n showlegend = True)\n\n data = [trace0]\n plotly.offline.plot({\"data\": data, \"layout\": layout}, auto_open=False,\n filename = os.path.join(dirname, 'Crosstalk/RX_to_RX/ADRV9009_FullBW_crosstalk_' + rx_channel.get() + '_n11dBm_rx_gain_' + rx_gain.get() + '.html'))\n\n data_saving()\n\ndef compute_noise_floor(fft_data):\n #global noise_floor\n\n avg_size = fft_data.size/2\n noise_floor = fft_data[0] / avg_size\n\n for i in range(1, int(avg_size/2)):\n if(fft_data[i] < (noise_floor + 2)):\n noise_floor += fft_data[i] / avg_size\n else:\n noise_floor += noise_floor / avg_size\n\n for i in range(int(3*avg_size/2), fft_data.size):\n if(fft_data[i] < (noise_floor + 2)):\n noise_floor += fft_data[i] / avg_size\n else:\n noise_floor += noise_floor / avg_size\n\n return noise_floor\n\ndef data_saving():\n data = {'Frequency(MHz):': save_freq, 'Magnitude(dB):': save_data, 'Noise Floor (dBFS):': save_noise, 'Number of Spurs:': save_spur_number, 'Max Spur (dBFS):': save_max_spur}\n\n df = pd.DataFrame(data)\n df.to_csv(os.path.join(dirname, 'Crosstalk/RX_to_RX/ADRV9009_FullBW_crosstalk_' + rx_channel.get() + '_n11dBm_rx_gain_' + rx_gain.get() + '.csv'), index = False, sep = ',')\n\n data1 = {'Spur Freq (MHz):': save_spur_freq, 'Spur Data (dBFS):':save_spur_data}\n df = pd.DataFrame(data1)\n df.to_csv(os.path.join(dirname, 'Crosstalk/RX_to_RX/ADRV9009_FullBW_spurs_' + rx_channel.get() + '_n11dBm_rx_gain_' + rx_gain.get() + '.csv'), index = False, sep = ',')\n\ndef check_connection(dev):\n if(dev == ERROR):\n txt1.config(fg = \"red\")\n txt1.insert('1.0', \"No Device Detected.\\n\\n\")\n return ERROR\n else:\n txt1.config(fg = 'black')\n txt1.insert('1.0', \"Device Connected.\\n\\n\")\n return SUCCESS\n\ndef check_freq(freq):\n if(freq[0][0] == ERROR):\n txt1.config(fg = 'red')\n txt1.delete('1.0', tk.END)\n txt1.insert('1.0', \"Please insert valid start/stop frequencies.\")\n return ERROR\n else:\n txt1.config(fg = \"black\")\n txt1.insert(tk.END, \"Start frequency set to: \" + str(freq[START_FREQ]/1e6) + \" MHz\\n\\n\")\n txt1.insert(tk.END, \"Stop frequency set to: \" + str(freq[STOP_FREQ]/1e6) + \" MHz\\n\\n\")\n return SUCCESS\n\ndef check_avg_nr():\n try:\n int(avg_nr.get())\n return SUCCESS\n except:\n txt1.config(fg = \"red\")\n txt1.insert(tk.END, \"Please insert valid average number.\")\n btn_text.set(\"Start\")\n btn_start.config(bg = \"lime green\")\n return ERROR\n\n#Sweep Button\ndef sweep():\n \n sweep_en.set(True)\n \n #Clear GUI Content\n clr_content()\n\n #Check connection\n if(check_connection(dev) == ERROR):\n return\n\n # Read and print Die Temperature\n die_temp() \n \n #compute center frequencies\n freq = comp_freq()\n\n #Check for valid input frequencies\n if(check_freq(freq) == ERROR):\n return\n \n #Check for valid average number \n if(check_avg_nr() == ERROR):\n return\n \n if(load_profile.get() == str(1)):\n configure_device()\n time.sleep(0.1)\n\n setup_device()\n\n if(gen_en.get() == True):\n connect_generator()\n time.sleep(0.1)\n\n get_plot_data(dev, freq[CENTER_FREQ])\n\n if(gen_en.get() == True):\n disconnect_generator()\n\n sweep_en.set(False)\n\ndef stop():\n stop.set(true)\n\n#Create GUI\ndef gui():\n \n global root, txt1, start_f, stop_f, btn_stop, btn_aq, gen_COM, tx_pow, rx_channel, load_profile, tone_offset, rx_gain, track_en\n global a, canvas, sweep_en, avg_nr, gen_en, stop\n \n root = tk.Tk()\n root.iconbitmap(\"favicon.ico\")\n root.title(\"ADRV9009_RX_testing (Analog Devices, Inc.)\")\n\n start_f = tk.StringVar()\n stop_f = tk.StringVar()\n avg_nr = tk.StringVar()\n sweep_en = tk.BooleanVar()\n gen_en = tk.BooleanVar()\n gen_COM = tk.StringVar()\n tx_pow = tk.StringVar()\n rx_channel = tk.StringVar()\n load_profile = tk.StringVar()\n tone_offset = tk.StringVar()\n rx_gain = tk.StringVar()\n stop = tk.BooleanVar()\n track_en = tk.BooleanVar()\n\n #default values\n rx_channel.set(\"RX1\")\n gen_COM.set(\"13\")\n tx_pow.set(\"-11\")\n start_f.set(\"101\")\n stop_f.set(\"6000\")\n avg_nr.set(\"64\")\n sweep_en.set(False)\n gen_en.set(False)\n load_profile.set(False)\n tone_offset.set(\"10\")\n rx_gain.set(\"30\")\n stop.set(False)\n track_en.set(False)\n\n fr1 = tk.Frame(root)\n fr1.pack(side = tk.LEFT, anchor = 'n', padx = 10, pady = 10)\n\n fr2 = tk.Frame(fr1)\n fr2.grid(row = 0, column = 0, pady = 10)\n\n label1 = tk.Label(fr2, text = \"Start frequency (MHz): \")\n label1.grid(row = 0, column = 0)\n\n\n entry1 = tk.Entry(fr2, textvariable=start_f)\n entry1.grid(row = 0, column = 1)\n\n label2 = tk.Label(fr2, text = \"Stop frequency (MHz): \")\n label2.grid(row = 1, column = 0, pady = (0,5))\n\n entry2 = tk.Entry(fr2, textvariable=stop_f)\n entry2.grid(row = 1, column = 1)\n \n label3 = tk.Label(fr2, text = \"Load Profile: \")\n label3.grid(row = 2, column = 0)\n\n check1 = tk.Checkbutton(fr2, variable=load_profile)\n check1.grid(row = 2, column = 1)\n \n label4 = tk.Label(fr2, text = \"Average: \")\n label4.grid(row = 3, column = 0)\n\n entry3 = tk.Entry(fr2, textvariable=avg_nr)\n entry3.grid(row = 3, column = 1)\n \n label5 = tk.Label(fr2, text = \"Enable Generator: \")\n label5.grid(row = 4, column = 0)\n\n check2 = tk.Checkbutton(fr2, variable=gen_en)\n check2.grid(row = 4, column = 1)\n\n label7 = tk.Label(fr2, text = \"Generator COM: \")\n label7.grid(row = 6, column = 0)\n\n entry4 = tk.Entry(fr2, textvariable=gen_COM)\n entry4.grid(row = 6, column = 1)\n\n label8 = tk.Label(fr2, text = \"TX Power [dBm]: \")\n label8.grid(row = 7, column = 0)\n\n entry5 = tk.Entry(fr2, textvariable=tx_pow)\n entry5.grid(row = 7, column = 1)\n\n label6 = tk.Label(fr2, text = \"Tone Offset [MHz]: \")\n label6.grid(row = 8, column = 0)\n\n entry7 = tk.Entry(fr2, textvariable=tone_offset)\n entry7.grid(row = 8, column = 1)\n\n label9 = tk.Label(fr2, text = \"RX Channel: \")\n label9.grid(row = 9, column = 0)\n\n entry6 = tk.Entry(fr2, textvariable=rx_channel)\n entry6.grid(row = 9, column = 1)\n\n label10 = tk.Label(fr2, text = \"RX Gain [dB]: \")\n label10.grid(row = 10, column = 0)\n\n entry8 = tk.Entry(fr2, textvariable=rx_gain)\n entry8.grid(row = 10, column = 1)\n\n label11 = tk.Label(fr2, text = \"Tracking Enable: \")\n label11.grid(row = 11, column = 0)\n\n check3 = tk.Checkbutton(fr2, variable=track_en)\n check3.grid(row = 11, column = 1)\n\n fr3 = tk.Frame(fr1)\n fr3.grid(row = 1, column = 0)\n\n btn_sweep = tk.Button(fr3, text=\"Single Sweep\", command=sweep)\n btn_sweep.config(width = 13, height = 1, bg = \"orange\")\n btn_sweep.grid(row = 0, column = 0, pady = (10,0))\n\n btn_stop = tk.Button(fr3, text=\"Stop\", command=stop)\n btn_stop.config(width = 13, height = 1, bg = \"lime green\")\n btn_stop.grid(row = 0, column = 1, pady = (10,0))\n\n btn_aq = tk.Button(fr3, text=\"Acq&Proc\")\n btn_aq.config(width = 13, height = 1, bg = \"grey\")\n btn_aq.grid(row = 1, column = 0, pady = (10,0))\n\n fr4 = tk.Frame(fr1)\n fr4.grid(row = 2, column = 0)\n \n label9 = tk.Label(fr4, text = \"Message Log: \")\n label9.grid(row = 0, column = 0)\n \n txt1 = tkscrolled.ScrolledText(fr4, width = 40, height = 20)\n txt1.grid(row = 1, column = 0)\n \n fig = plt.figure()\n DPI = fig.get_dpi()\n fig.set_size_inches(1024.0/float(DPI), 640.0/float(DPI)) \n a = fig.add_subplot(111)\n a.grid(True)\n a.set_title('Frequency Spectrum')\n a.set_xlabel('Fequency (MHz)')\n a.set_ylabel('Magnitude')\n plt.tight_layout()\n plotFrame = tk.Frame(master=root)\n plotFrame.pack(side = tk.LEFT, pady = 10, padx = 10, anchor = 'n')\n\n toolbarFrame = tk.Frame(master=plotFrame)\n toolbarFrame.pack(anchor = 'w', pady = (0,10))\n \n canvas = FigureCanvasTkAgg(fig, master=plotFrame)\n canvas.get_tk_widget().pack(fill = tk.BOTH)\n canvas.draw()\n root.update_idletasks()\n\n toolbar = NavigationToolbar2TkAgg(canvas, toolbarFrame)\n toolbar.update()\n \n root.mainloop()\n\n#main function\ndef main():\n\n global dev\n\n #connect device\n dev = connect_device()\n\n configure_device()\n gui()\n\nmain()","sub_path":"ADRV9009_test_scripts/ADRV9009_crosstalk_RX.py","file_name":"ADRV9009_crosstalk_RX.py","file_ext":"py","file_size_in_byte":28358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"101217663","text":"#!/usr/bin/env python \n# -*- coding: utf-8 -*-\n# @Time : 2020-07-04 19:47\n# @Author : NingAnMe \nimport argparse\nfrom dateutil.relativedelta import relativedelta\n\nfrom lib.config import *\nfrom lib.dbkucun import *\nfrom lib.dbyingxiao import *\nfrom lib.path import *\n\n\ndef order_add(order_file, dt_s, dt_e):\n \"\"\"\n 将订单文件导入数据库\n :param order_file: csv文件\n :param dt_s: 发货时间-开始时间\n :param dt_e: 发货时间-结束时间\n :return:\n \"\"\"\n orders = PddOrder.csv2order(order_file)\n if len(orders) <= 0:\n print('没有有效的订单')\n return -1\n orders_filter_by_datetime = list()\n for order in orders:\n if dt_s <= order['fahuoshijian'] <= dt_e:\n orders_filter_by_datetime.append(order)\n\n if len(orders_filter_by_datetime) <= 0:\n print(f'没有有效的订单:{dt_s} to {dt_e}')\n return -1\n\n # 剔除已经录入的订单\n # 找到数据库里面这个时间范围的订单\n with session_scope() as session:\n orders_db = PddOrder.query_fahuoshijian(session, dt_s, dt_e)\n\n # 剔除已经录入的订单\n dingdanhao_db = set()\n if orders_db is not None:\n for order in orders_db:\n dingdanhao_db.add(order.dingdanhao)\n\n orders_filter = list()\n for order in orders_filter_by_datetime:\n if order[\"dingdanhao\"] not in dingdanhao_db:\n orders_filter.append(order)\n\n print(f\"有效订单数量:{len(orders_filter)}\")\n\n # 将过滤以后的订单入库\n with session_scope() as session:\n PddOrder.add(session, orders_filter)\n print(\"success\")\n\n\ndef goods_qukucun(dingdanhao):\n with session_scope() as session:\n order = PddOrder.query_dingdanhao(session, dingdanhao)\n if order is None or order.shifouqukucun == '是':\n return\n\n skubianma = order.skubianma\n sku = PddSku.query_bianma(session, skubianma)\n if sku is None:\n print(f\"没有对应的sku:{skubianma}\")\n return\n\n # 获取商品和商品需要减少的数量\n jianshu = order.shangpinshuliang\n for goods in sku.goods:\n goods.goods.shuliang -= goods.shuliang * jianshu\n order.shifouqukucun = '是'\n return True\n\n\ndef goods_detail_add(json_data, dt):\n datas = PddGoodsDetail.json2data(json_data)\n with session_scope() as session:\n result = PddGoodsDetail.query_datetime(session, dt)\n ids = set()\n for row in result:\n ids.add(row.goodsId)\n datas_filter = list()\n for i in datas:\n if str(i['goodsId']) not in ids:\n datas_filter.append(i)\n PddGoodsDetail.add(session, datas_filter)\n print(f\"goods_detail_add Success: {len(datas_filter)}\")\n\n\ndef ad_unit_add(json_data, dt, ad_type):\n datas = PddAdUnit.json2data(json_data, dt, ad_type)\n with session_scope() as session:\n result = PddAdUnit.query_datetime(session, dt)\n ids = set()\n for row in result:\n if row.adType == ad_type:\n ids.add(row.adId)\n datas_filter = list()\n for i in datas:\n if str(i['adId']) not in ids:\n datas_filter.append(i)\n PddAdUnit.add(session, datas_filter)\n print(f\"ad_unit_add Success: {ad_type} 处理数据量:{len(datas_filter)}\")\n\n\ndef deal_paid_free_order(dt):\n PddGoodsDetail.paid_free_order(dt)\n\n\n# def goods_detail_add(dt_s, dt_e):\n# if dt_s == dt_e:\n# dt_e = dt_e + relativedelta(days=1) - relativedelta(minutes=1)\n#\n# count = 0\n# with session_scope() as session:\n# orders = PddOrder.query_fahuoshijian(session, datetime_start=dt_s, datetime_end=dt_e)\n# print(f'本次有效订单数量:{len(orders)}')\n#\n# goods_xiaoliang = defaultdict(int)\n# for order in orders:\n# skubianma = order.skubianma\n# sku = PddSku.query_bianma(session, skubianma)\n# if sku is None:\n# print(f\"没有对应的sku:{skubianma}\")\n# continue\n#\n# # 获取商品和商品需要减少的数量\n# jianshu = order.shangpinshuliang\n# for goods in sku.goods:\n# goods_xiaoliang[goods.goods.bianma] += goods.shuliang * jianshu\n# count += 1\n# print(f'本次处理订单数量: {count}')\n# goods_details = list()\n# for k, v in goods_xiaoliang.items():\n# goods_details.append({\n# 'statDate': dt_s,\n# 'bianma': k,\n# 'xiaoliang': v,\n# })\n# GoodsDetail.add(session, goods_details)\n\n\ndef goods_qukucun_datetime(dt_s, dt_e):\n if dt_s == dt_e:\n dt_e = dt_e + relativedelta(days=1) - relativedelta(minutes=1)\n dingdanhaos = list()\n with session_scope() as session:\n orders = PddOrder.query_fahuoshijian(session, datetime_start=dt_s, datetime_end=dt_e)\n print(f'总订单数量:{len(orders)}')\n for order in orders:\n if order.shifouqukucun != '是':\n dingdanhaos.append(order.dingdanhao)\n print(f'本次有效订单数量:{len(dingdanhaos)}')\n count = 0\n for dingdanhao in dingdanhaos:\n r = goods_qukucun(dingdanhao)\n if r:\n count += 1\n print(f'本次处理订单数量: {count}')\n\n\ndef order_file_ruku_datetime(dt_s, dt_e):\n print(dt_s, dt_e)\n order_files = os.listdir(order_file_path)\n order_files.sort()\n while dt_s <= dt_e:\n dt_tmp_s = dt_s\n dt_tmp_e = dt_tmp_s + relativedelta(days=1) - relativedelta(seconds=1)\n dt_str = dt_tmp_s.strftime('%Y-%m-%d')\n # 处理订单并入库\n order_file = None\n for filename in order_files:\n if (\"orders_export\" + dt_str) in filename:\n order_file = os.path.join(order_file_path, filename)\n if order_file is not None:\n print(f'订单文件:{order_file}')\n order_add(order_file, dt_tmp_s, dt_tmp_e)\n dt_s += relativedelta(days=1)\n\n\ndef detail_file_ruku_datetime(dt_s, dt_e):\n json_data_files = os.listdir(json_file_path)\n json_data_files.sort()\n\n while dt_s <= dt_e:\n dt_tmp = dt_s\n dt_str = dt_tmp.strftime('%Y-%m-%d')\n dt = datetime.strptime(dt_str, \"%Y-%m-%d\")\n\n # 添加营销数据\n for filename in json_data_files:\n if dt_str in filename:\n json_data_file = os.path.join(json_file_path, filename)\n # 添加商品销售数据\n if 'detail' in filename:\n goods_detail_add(json_data_file, dt)\n\n # 添加搜索推广数据\n if 'search' in filename:\n ad_unit_add(json_data_file, dt, 'search')\n\n # 添加场景推广数据\n if 'scene' in filename:\n ad_unit_add(json_data_file, dt, 'scene')\n\n # 处理付费订单和免费数量\n deal_paid_free_order(dt)\n dt_s += relativedelta(days=1)\n\n\ndef set_all_order_qu_ku_cun_yes(dt_s, dt_e):\n # 将所有订单的状态设置为去库存\n with session_scope() as session:\n orders = session.query(PddOrder).filter(PddOrder.fahuoshijian >= dt_s,\n PddOrder.fahuoshijian <= dt_e,\n PddOrder.shifouqukucun != '是').all()\n for order in orders:\n order.shifouqukucun = '是'\n print(f\"set_all_order_qu_ku_cun Success: 处理数据量:{len(orders)}\")\n\n\ndef set_all_order_qu_ku_cun_no(dt_s, dt_e):\n # 将所有订单的状态设置为去库存\n with session_scope() as session:\n orders = session.query(PddOrder).filter(PddOrder.fahuoshijian >= dt_s,\n PddOrder.fahuoshijian <= dt_e,\n PddOrder.shifouqukucun != '否').all()\n for order in orders:\n order.shifouqukucun = '否'\n print(f\"set_all_order_qu_ku_cun Success: 处理数据量:{len(orders)}\")\n\n\nif __name__ == '__main__':\n # ######################### 业务运行 ###################################\n parser = argparse.ArgumentParser(description='地外太阳能数据生产工具')\n parser.add_argument('--addOrder', help='处理订单文件,数据入库')\n parser.add_argument('--quKuCun', help='销库存')\n parser.add_argument('--addGoodsDetail', help='处理营销Json文件,数据入库')\n parser.add_argument('--date', help='开始时间(北京时),YYYY-mm-dd(2019-01-01)')\n parser.add_argument('--dateStart', '-s', help='开始时间(北京时),YYYY-mm-dd(2019-01-01)')\n parser.add_argument('--dateEnd', '-e', help='结束时间(北京时),YYYY-mm-dd(2019-01-01)')\n parser.add_argument('--setAllOrderQuKuCunYes', help='将所有的订单状态设置为去库存', default=False)\n parser.add_argument('--setAllOrderQuKuCunNo', help='将所有的订单状态设置为去库存', default=False)\n parser.add_argument('--debug', help='是否DEBUG', default=False)\n parser.add_argument('--test', help='是否TEST', default=False)\n args = parser.parse_args()\n\n datetime_ = None\n if args.date is not None:\n datetime_ = datetime.strptime(args.date, '%Y-%m-%d')\n\n if args.date is not None and args.dateStart is None:\n args.dateStart = args.date\n\n datetime_s = datetime_e = None\n if args.dateStart is not None:\n datetime_s = datetime.strptime(args.dateStart, '%Y-%m-%d')\n if args.dateEnd is not None:\n datetime_e = datetime.strptime(args.dateEnd, '%Y-%m-%d')\n else:\n datetime_e = datetime_s\n\n # 处理订单文件\n if args.addOrder:\n print(f'addOrder: {args.addOrder}')\n order_file_ruku_datetime(datetime_s, datetime_e)\n\n # 销库存\n if args.quKuCun:\n goods_qukucun_datetime(datetime_s, datetime_e)\n\n # 营销数据入库且处理\n if args.addGoodsDetail:\n detail_file_ruku_datetime(datetime_s, datetime_e)\n\n # 将所有订单的状态设置为已经去库存的状态'是'\n if args.setAllOrderQuKuCunYes:\n set_all_order_qu_ku_cun_yes(datetime_s, datetime_e)\n\n # 将所有订单的状态设置为已经去库存的状态’否‘\n if args.setAllOrderQuKuCunNo:\n set_all_order_qu_ku_cun_no(datetime_s, datetime_e)\n\n # 销量统计\n goods_xiaoliang_tongji(datetime_s, datetime_e)\n","sub_path":"business.py","file_name":"business.py","file_ext":"py","file_size_in_byte":10571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"189171903","text":"# 1290. Convert Binary Number in a Linked List to Integer\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n def getDecimalValue(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: int\n \"\"\"\n n = 0\n cur = head\n while cur != None:\n cur = cur.next\n n += 1\n \n number = 0\n while head != None:\n number += head.val * 2**(n-1)\n n = n - 1\n head = head.next\n return number\n","sub_path":"easy/1290.py","file_name":"1290.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"71661290","text":"from lxml import etree as ET\nfrom copy import deepcopy\n\n\ndef create_body():\n return ET.Element(\"body\")\n\n\nxml_body = ET.Element(\"body\")\nprint(xml_body)\n\n\ndef create_div(body, act):\n div = ET.SubElement(body, \"div\")\n div.set(\"act\", act)\n sp = ET.SubElement(div, \"sp\")\n sp.text = \"stuff\"\n\n\ncreate_div(xml_body, \"1\")\n\nxml_sp = ET.Element(\"sp\")\nspeaker = ET.SubElement(xml_sp, \"speaker\")\nspeaker.text = \"Jean\"\np = ET.SubElement(xml_sp, 'p')\np.text = \"Ta mère en slip\"\np = ET.SubElement(xml_sp, 'p')\np.text = \"ta mere a poil\"\nprint(ET.tostring(xml_sp))\n\n\ndef combine_xmltree_element(element_1, element_2):\n \"\"\"\n Recursively combines the given two xmltree elements. Common properties will be overridden by values of those\n properties in element_2.\n\n :param element_1: A xml Element\n :type element_1: L{Element}\n\n :param element_2: A xml Element\n :type element_2: L{Element}\n\n :return: A xml element with properties combined.\n \"\"\"\n\n if element_1 is None:\n return element_2.copy()\n\n if element_2 is None:\n return element_1.copy()\n\n if element_1.tag != element_2.tag:\n raise TypeError(\n \"The two XMLtree elements of type {t1} and {t2} cannot be combined\".format(\n t1=element_1.tag,\n t2=element_2.tag\n )\n )\n\n combined_element = ET.Element(tag=element_1.tag, attrib=element_1.attrib)\n combined_element.attrib.update(element_2.attrib)\n\n # Create a mapping from tag name to child element\n element_1_child_mapping = {child.tag: child for child in element_1}\n element_2_child_mapping = {child.tag: child for child in element_2}\n\n for child in element_1:\n if child.tag not in element_2_child_mapping:\n combined_element.append(child.copy())\n\n for child in element_2:\n if child.tag not in element_1_child_mapping:\n combined_element.append(child.copy())\n\n else:\n if len(child) == 0: # Leaf element\n combined_child = element_1_child_mapping[child.tag].copy()\n combined_child.text = child.text\n combined_child.attrib.update(child.attrib)\n\n else:\n # Recursively process the element, and update it in the same way\n combined_child = combine_xmltree_element(\n element_1_child_mapping[child.tag], child)\n\n combined_element.append(combined_child)\n\n return combined_element\n\n\nprint(xml_sp.tag)\n","sub_path":"test_tree.py","file_name":"test_tree.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"232210832","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef gaussian(mu,sig,val):\n coef = 1.0/(sig*np.sqrt(2*np.pi))\n main = np.exp(-1*((val-mu)/(2*sig))**2)\n return coef*main\n\n\ndef quad(x,a,b,c):\n return a*x**2+b*x+c\n\n# Get \"observed\" quadratic\n# parameters for \"observed\" quadratic function\na = 0.3\nb = -1.8\nc = 1.8\nstp = 0.5\nx = np.arange(start=0,stop=10+stp,step=stp)\nvquad = np.vectorize(lambda x: quad(x,a,b,c))\ny = vquad(x)\n\ndef obsquad(ax=plt.gca()):\n spread = 1.5\n for _ in range(4):\n ax.plot(x,y+spread*np.random.randn(len(x)),linestyle='None',marker='o',c='blue',mfc='None')\n ax.set_xlabel('\"Input\" Variable')\n ax.set_ylabel('\"Response\" Variable')\n\ndef vobsquad(ax=plt.gca()):\n obsquad(ax)\n ax.plot(x,vquad(x),color='green')\n","sub_path":"whitty_meeting/quad.py","file_name":"quad.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"549152300","text":"import scrapy\r\nimport re\r\n\r\n\r\nclass FinnSpider(scrapy.Spider):\r\n \"\"\"Run 'scrapy crawl properties' in virtualenv\"\"\"\r\n allowed_domains = ['finn.no']\r\n name = \"FinnSpider\"\r\n\r\n # V70\r\n # start_urls = [\"https://www.finn.no/car/used/search.html?filters=&make=0.818&model=1.818.3077\"] \r\n\r\n # XC70\r\n # start_urls = [\"https://www.finn.no/car/used/search.html?filters=&make=0.818&model=1.818.7781\"]\r\n # start_urls = []\r\n\r\n def parse(self, response):\r\n ''' \r\n This method, as well as any other Request callback, must return an\r\n iterable of Request and/or dicts or Item objects.\r\n '''\r\n\r\n for ad_data, ad_title in zip(response.css('div.ads__unit__content__keys'), response.css('h2.ads__unit__content__title')):\r\n keys = ad_data.css('*::text').getall()\r\n title = ad_title.css('*::text').getall()\r\n\r\n if len(keys) > 1:\r\n item = dict()\r\n # parse year, remove non-numbers\r\n item['year'] = re.sub('[^0-9]', \"\", keys[0])\r\n # parse mileage, remove non-numbers\r\n item['mileage'] = re.sub('[^0-9]', \"\", keys[1])\r\n # parse price, remove non-numbers\r\n item['price'] = re.sub('[^0-9]', \"\", keys[2])\r\n\r\n try:\r\n # convert to integers\r\n item['year'] = int(item['year'])\r\n item['mileage'] = int(item['mileage'])\r\n item['price'] = int(item['price'])\r\n\r\n except ValueError:\r\n continue\r\n\r\n item['title'] = title[0]\r\n\r\n yield item\r\n\r\n for a in response.css('a.button--icon-right'):\r\n print('RESPONSE: ', a)\r\n yield response.follow(a, callback=self.parse)\r\n","sub_path":"properties/spiders/finn_spider.py","file_name":"finn_spider.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"458950856","text":"#!/usr/bin/env python3\n\nimport pandas as pd\nimport plotly.graph_objects as go\nfrom scipy.io import loadmat\n\ndef load_panda():\n d=pd.read_csv('excel/hfos_clean.csv')\n labels=[i for i in d]\n return d[labels[1:]]\n\ndef needles_list(patient=None, all=False):\n d=load_panda()\n if patient!=None:\n d=d.loc[d['Patient']==patient]\n res=[]\n if all:\n res.append('All')\n for e in d['Channel']:\n ee=''.join(filter(str.isalpha, e))\n if ee not in res:\n res.append(ee)\n return res\n\ndef pand():\n out,noOut= 0,0\n d=load_panda()\n #print(data[data.columns[0]])\n #print(data)\n for e in d['Zone']:\n if 'Outside' in e:\n out +=1\n else:\n noOut +=1\n total=out+noOut\n print(out, noOut, total)\n\ndef patients():\n d=load_panda()\n patients_list=[]\n for patient in d['Patient']:\n if patient not in patients_list:\n patients_list.append(patient)\n return patients_list\n\ndef pand_sensores(selected_patient):\n dic={}\n d=load_panda()\n for amplitude, patient, channel in zip(d['Amplitude'],d['Patient'],d['Channel']):\n if selected_patient in patient:\n if channel in dic:\n dic[channel].append(amplitude)\n else:\n dic[channel] = [amplitude]\n #print(dic, len(dic))\n return dic\n\ndef dic_to_data(d):\n x=[]\n y=[]\n for sensor in d:\n x.append(sensor)\n median=sum([float(e) for e in d[sensor]])/len(d[sensor])\n y.append(median)\n return x,y\n\ndef multiplot_soz1(selected_patient, *args):\n d=load_panda()\n filtered_d=d.loc[d['Patient']==selected_patient]\n dic={'Zone':[]}\n for zone in filtered_d['Zone']:\n if 'Outside' in zone:\n dic['Zone'].append(0)\n else:\n dic['Zone'].append(1) \n for e in args:\n dic[e]=[]\n for row_zone, row_e in zip(filtered_d['Zone'], filtered_d[e]):\n if 'Propagation' in row_zone:\n pass\n else:\n dic[e].append(row_e)\n return dic\n\n\ndef multiplot_soz(selected_patient, selector, args):\n d=load_panda()\n filtered_d=d.loc[d['Patient']==selected_patient]\n needles=needles_list(selected_patient)\n a=[]\n res=[]\n if selector != 'needles':\n for e in d[selector]:\n if e not in a:\n d={0:e}\n for h in args:\n d[h]=[]\n res.append(d)\n a.append(e)\n else:\n for e in needles:\n d={0:e}\n for h in args:\n d[h]=[]\n res.append(d)\n for y in args:\n for e in res:\n if selector != 'needles':\n for row_selector, row_e in zip(filtered_d[selector], filtered_d[y]):\n if row_selector == e[0]:\n e[y].append(row_e)\n else:\n for row_selector, row_e in zip(filtered_d['Channel'], filtered_d[y]):\n if e[0]==''.join(filter(str.isalpha, row_selector)):\n e[y].append(row_e)\n return res\n\ndef mp(selected_patient, selector, values):\n x=multiplot_soz(selected_patient, selector, values)\n data=[]\n for e in x:\n d=go.Splom(\n dimensions=[dict(label=k,values=e[k]) for k in e if k != 0],\n name=e[0],\n marker=dict(size=4),\n diagonal=dict(visible=False))\n data.append(d)\n layout=go.Layout(title=\"Multiplot prove\", dragmode='select', hovermode='closest', showlegend=True)\n fig=go.Figure(data=data,layout=layout)\n return fig\n\ndef scatter_soz(selected_patient, selector, args): #args=[x,y]\n d=load_panda()\n filtered_d=d.loc[d['Patient']==selected_patient]\n needles=needles_list(selected_patient)\n a=[]\n res=[]\n if selector != 'needles':\n for e in d[selector]:\n if e not in a:\n res.append({0:e, 'x':[], 'y':[]})\n a.append(e)\n else:\n for e in needles:\n res.append({0:e, 'x':[], 'y':[]})\n for e in res:\n if selector != 'needles':\n for row_selector, row_x, row_y in zip(filtered_d[selector], filtered_d[args[0]], filtered_d[args[1]]):\n if row_selector == e[0]:\n e['x'].append(row_x)\n e['y'].append(row_y)\n else:\n for row_selector, row_x, row_y in zip(filtered_d['Channel'], filtered_d[args[0]], filtered_d[args[1]]):\n if e[0]==''.join(filter(str.isalpha, row_selector)):\n e['x'].append(row_x)\n e['y'].append(row_y)\n return res\n\ndef scatter(selected_patient, selector, values):\n x=scatter_soz(selected_patient, selector, values)\n data=[]\n for e in x:\n d=go.Scatter(\n x=e['x'],\n y=e['y'],\n name=e[0],\n mode='markers',\n marker=dict(size=4))\n data.append(d)\n layout=go.Layout(title=\"Scatterplot prove\", hovermode='closest', showlegend=True, xaxis_title=values[0], yaxis_title=values[1])\n fig=go.Figure(data=data, layout=layout)\n return fig\n\ndef histogram_soz(selected_patient, selector, args): #args=[x,y]\n d=load_panda()\n filtered_d=d.loc[d['Patient']==selected_patient]\n needles=needles_list(selected_patient)\n a=[]\n res=[]\n if selector != 'needles':\n for e in d[selector]:\n if e not in a:\n res.append({0:e, 'd':[], 'len':0})\n a.append(e)\n else:\n for e in needles:\n res.append({0:e, 'd':[], 'len':0})\n for e in res:\n if selector != 'needles':\n for row_selector, row_e in zip(filtered_d[selector], filtered_d[args]):\n if row_selector == e[0]:\n e['d'].append(row_e)\n else:\n for row_selector, row_e in zip(filtered_d['Channel'], filtered_d[args]):\n if e[0]==''.join(filter(str.isalpha, row_selector)):\n e['d'].append(row_e)\n for e in res:\n e['len']=len(e['d'])\n res.sort(key= lambda i: i['len'], reverse=True)\n return res\n\ndef histogram(selected_patient, selector, value):\n x=histogram_soz(selected_patient, selector, value)\n data=[]\n for e in x:\n d=go.Histogram(\n x=e['d'],\n name=e[0],\n opacity=0.75,\n bingroup=1)\n data.append(d)\n layout=go.Layout(title_text=\"Histogram prove\", showlegend=True, xaxis_title_text=value, yaxis_title_text='Count', barmode='overlay')\n fig=go.Figure(data=data, layout=layout)\n return fig\n\ndef heatmap():\n mat = loadmat('excel/data.mat')\n mat_data = mat['stockwell']\n data=go.Heatmap(\n z=mat_data\n )\n layout=go.Layout(title_text=\"Heatmap prove\", showlegend=True, xaxis_title_text='X-axis', yaxis_title_text='Y-axis')\n fig=go.Figure(data=data, layout=layout)\n return fig\n\ndef scatter3d_soz(selected_patient, selector, args): #args=[x,y,z]\n d=load_panda()\n filtered_d=d.loc[d['Patient']==selected_patient]\n needles=needles_list(selected_patient)\n a=[]\n res=[]\n if selector != 'needles':\n for e in d[selector]:\n if e not in a:\n res.append({0:e, 'x':[], 'y':[], 'z':[]})\n a.append(e)\n else:\n for e in needles:\n res.append({0:e, 'x':[], 'y':[], 'z':[]})\n for e in res:\n if selector != 'needles':\n for row_selector, row_x, row_y, row_z in zip(filtered_d[selector], filtered_d[args[0]], filtered_d[args[1]], filtered_d[args[2]]):\n if row_selector == e[0]:\n e['x'].append(row_x)\n e['y'].append(row_y)\n e['z'].append(row_z)\n else:\n for row_selector, row_x, row_y, row_z in zip(filtered_d['Channel'], filtered_d[args[0]], filtered_d[args[1]], filtered_d[args[2]]):\n if e[0]==''.join(filter(str.isalpha, row_selector)):\n e['x'].append(row_x)\n e['y'].append(row_y)\n e['z'].append(row_z)\n return res\n\ndef scatter3d(selected_patient, selector, values):\n x=scatter3d_soz(selected_patient, selector, values)\n data=[]\n for e in x:\n d=go.Scatter3d(\n x=e['x'],\n y=e['y'],\n z=e['z'],\n name=e[0],\n mode='markers',\n marker=dict(size=4))\n data.append(d)\n layout=go.Layout(title=\"3D Scatterplot prove\", hovermode='closest', showlegend=True, scene=dict(xaxis_title=values[0], yaxis_title=values[1], zaxis_title=values[2]))\n fig=go.Figure(data=data, layout=layout)\n return fig\n\ndef list_needles_3dscatter(filtered_d, needles):\n res=[]\n for e in needles:\n dic={0:e, 'data':[]}\n a=[]\n for y, row_x, row_y, row_z in zip(filtered_d['Channel'], filtered_d['x'], filtered_d['y'], filtered_d['z']):\n if (e==''.join(filter(str.isalpha, y))) and (y not in a):\n dic['data'].append({0:y, 'xyz':[row_x, row_y, row_z], 'd':[], 'd_scale':[]})\n a.append(y)\n res.append(dic)\n return res\n\ndef scatter3d_soz_v1(selected_patient, args):\n d=load_panda()\n filtered_d=d.loc[d['Patient']==selected_patient]\n needles=needles_list()\n res=list_needles_3dscatter(filtered_d, needles_list(selected_patient))\n for e in res:\n for y in e['data']:\n for row_selector, value in zip(filtered_d['Channel'], filtered_d[args]):\n if y[0]==row_selector:\n y['d'].append(value)\n mini=0\n maxi=0\n for e in res:\n for y in e['data']:\n calc=sum(y['d'])/len(y['d'])\n y['d']=calc\n if calc>maxi:\n maxi=calc\n if calc%{text}
\" +\n \"%{customdata[1]} = %{customdata[0]:.02f}
\" +\n \" \",\n marker = dict(\n sizemode='diameter',\n sizeref=1,\n size=[k['d_scale'] for k in e['data']],\n ),\n )\n data.append(d)\n layout=go.Layout(title=\"3D Scatterplot needles prove\", hovermode='closest', showlegend=True, scene=dict(xaxis_title='X-axis', yaxis_title='Y-axis', zaxis_title='Z-axis'))\n fig=go.Figure(data=data, layout=layout)\n return fig\n\nif __name__=='__main__':\n pand_sensores()\n","sub_path":"ppanda.py","file_name":"ppanda.py","file_ext":"py","file_size_in_byte":9794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"28535862","text":"import random\r\nimport json\r\nfrom pico2d import *\r\n\r\nhp_heart_data = open('Data\\\\Hp_Heart.txt', 'r')\r\nhp_heart = json.load(hp_heart_data)\r\nhp_heart_data.close()\r\n\r\nclass Spring_Map_SPEED:\r\n\r\n PIXEL_PER_METER = (10.0 / 0.3)\r\n RUN_SPEED_KMPH = 30.0\r\n RUN_SPEED_MPM = (RUN_SPEED_KMPH * 1000.0 / 60.0)\r\n RUN_SPEED_MPS = (RUN_SPEED_MPM / 60.0)\r\n RUN_SPEED_PPS = (RUN_SPEED_MPS * PIXEL_PER_METER)\r\n\r\nclass Sky_Map_SPEED:\r\n PIXEL_PER_METER = (10.0 / 0.3)\r\n RUN_SPEED_KMPH = 40.0\r\n RUN_SPEED_MPM = (RUN_SPEED_KMPH * 1000.0 / 60.0)\r\n RUN_SPEED_MPS = (RUN_SPEED_MPM / 60.0)\r\n RUN_SPEED_PPS = (RUN_SPEED_MPS * PIXEL_PER_METER)\r\n\r\nclass Hp_Heart:\r\n\r\n image = None\r\n\r\n def __init__(self):\r\n self.x = 0\r\n self.y = 0\r\n self.state = \"None\"\r\n self.collision_time = 0\r\n\r\n if Hp_Heart.image == None:\r\n self.Hp_Heart = load_image('Resource\\\\Item\\\\hp_heart.png')\r\n\r\n def create(self):\r\n hp_state_table = {\r\n \"Hp\" : self.Hp_Heart\r\n }\r\n\r\n hp = []\r\n\r\n for name in hp_heart:\r\n item = Hp_Heart()\r\n item.name = name\r\n item.x = hp_heart[name]['x']\r\n item.y = hp_heart[name]['y']\r\n item.state = hp_state_table[hp_heart[name]['state']]\r\n hp.append(item)\r\n\r\n return hp\r\n\r\n def update(self, frame_time):\r\n if Spring_Map_SPEED.RUN_SPEED_PPS * frame_time < 12:\r\n self.distance = frame_time * Spring_Map_SPEED.RUN_SPEED_PPS\r\n self.x -= self.distance\r\n self.collision_time = 0\r\n\r\n elif self.state == \"Smashing\":\r\n if self.collision_time < 30:\r\n self.collision_time += 10\r\n for i in range(2):\r\n if self.x > 150:\r\n self.x += 20\r\n else:\r\n self.x -= 20\r\n\r\n elif self.state != \"Smashing\":\r\n self.distance = frame_time * Spring_Map_SPEED.RUN_SPEED_PPS\r\n self.x -= self.distance\r\n self.collision_time = 0\r\n\r\n def draw(self):\r\n self.Hp_Heart.draw(self.x, self.y)\r\n\r\n def draw_bb(self):\r\n draw_rectangle(*self.get_bb())\r\n\r\n def get_bb(self):\r\n return self.x - 20, self.y - 20, self.x + 20, self.y + 20\r\n\r\n","sub_path":"item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"619043095","text":"def Floyd(dist, M):\r\n #print(*dist, sep = '\\n')\r\n for k in range(1, N + 1):\r\n for i in range(1, N + 1):\r\n for j in range(1, N + 1):\r\n dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])\r\n\r\nINF = 10**9\r\nt = 1\r\nN = 20\r\nwhile True:\r\n try:\r\n dist = [[ INF for j in range(N + 1)] for i in range( N + 1)]\r\n for i in range(1, N):\r\n arr = list(map(int, input().split()))\r\n for j in range(1, arr[0] + 1):\r\n #print(\"canh la: \", i, arr[j])\r\n dist[i][arr[j]] = 1\r\n dist[arr[j]][i] = 1\r\n \r\n Floyd(dist, N)\r\n\r\n print(\"Test Set #{}\".format(t))\r\n t += 1\r\n test = int(input())\r\n for i in range(test):\r\n u, v = map(int, input().split())\r\n print(\"{:2d} to {:2d}: {}\".format(u, v, dist[u][v]))\r\n print()\r\n except EOFError:\r\n break","sub_path":"Lecture12/Risk_poj.py","file_name":"Risk_poj.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"543298072","text":"import unittest\nfrom django.test import TestCase\nfrom django.test import Client\nfrom django.urls import reverse\nfrom aliss.tests.fixtures import Fixtures\nfrom aliss.models import *\nfrom aliss.search import *\n\n\nclass SearchTestCase(TestCase):\n fixtures = ['service_areas.json', 'g2_postcodes.json']\n\n def setUp(self):\n t, u, c, _ = Fixtures.create_users()\n self.org = Fixtures.create_organisation(t, u, c)\n self.org2 = Organisation.objects.create(name=\"Test0rg\", description=\"A test description\",\n created_by=self.org.created_by, updated_by=self.org.updated_by)\n self.org3 = Organisation.objects.create(name=\"Another org\", description=\"A Test0rg description\",\n created_by=self.org.created_by, updated_by=self.org.updated_by)\n location1 = Fixtures.create_location(self.org)\n location2 = Fixtures.create_another_location(self.org)\n\n self.s1 = Service.objects.create(name=\"Food For All\", description=\"A handy food activity\", organisation=self.org, created_by=t, updated_by=u)\n self.s2 = Service.objects.create(name=\"Physical Fun\", description=\"Physical activity classes\", organisation=self.org, created_by=t, updated_by=u)\n self.s3 = Service.objects.create(name=\"Step Fit 1\", description=\"Physical activity classes\", organisation=self.org, created_by=t, updated_by=u)\n self.s4 = Service.objects.create(name=\"Step Fit 2\", description=\"Phyzical activiti classes\", organisation=self.org, created_by=t, updated_by=u)\n\n self.s1.locations.add(location1); self.s1.save()\n self.s2.locations.add(location1); self.s2.save()\n self.s3.locations.add(location1); self.s3.save()\n self.s4.locations.add(location2); self.s4.save()\n\n pks = [self.s1.pk, self.s2.pk, self.s3.pk, self.s4.pk]\n self.queryset = get_services(Fixtures.es_connection(), pks)\n\n\n def test_filter_by_postcode(self):\n p = Postcode.objects.get(pk=\"G2 4AA\")\n result = filter_by_postcode(self.queryset, p, 100)\n self.assertNotEqual(result.count(), self.queryset.count())\n\n\n def test_postcode_order(self):\n p = Postcode.objects.get(pk=\"G2 4AA\")\n result = filter_by_postcode(self.queryset, p, 100000)\n order = postcode_order(result, p)\n services = Service.objects.filter(id__in=order[\"ids\"]).order_by(order[\"order\"])\n self.assertTrue(services[0] in [self.s1, self.s2, self.s3])\n self.assertEqual(services[3], self.s4)\n self.assertEqual(result.count(), self.queryset.count())\n\n\n def test_combined_order(self):\n p = Postcode.objects.get(pk=\"G2 9ZZ\")\n result = filter_by_postcode(self.queryset, p, 100000)\n result = filter_by_query(result, \"Physical Activity\")\n order = combined_order(result, p)\n services = Service.objects.filter(id__in=order[\"ids\"]).order_by(order[\"order\"])\n self.assertNotEqual(services[2], self.s4)\n self.assertEqual(result.count(), 3)\n\n\n def test_organisation_query(self):\n org_queryset = get_organisations(Fixtures.es_organisation_connection(), [self.org3.pk, self.org2.pk, self.org.pk])\n result = filter_organisations_by_query(org_queryset, \"TestOrg\")\n x = result.execute()\n order = keyword_order(result)\n orgs = Organisation.objects.filter(id__in=order[\"ids\"]).order_by(order[\"order\"])\n self.assertTrue(self.org2 in orgs) #basic test for travis\n self.assertTrue(self.org in orgs)\n #self.assertEqual(self.org.id, orgs[0].id)\n #self.assertEqual(self.org2.id, orgs[1].id)\n\n\n @unittest.skipIf(settings.TESTING_ENV=='travis', \"Does not work accurately on Travis\")\n def test_keyword_order(self):\n success_counter = 0\n failure_counter = 0\n loop_counter = 0\n while loop_counter < 10:\n result = filter_by_query(self.queryset, \"Physical Activity\")\n order = keyword_order(result)\n services = Service.objects.filter(id__in=order[\"ids\"]).order_by(order[\"order\"])\n if ((services[0] == self.s2) and (services[2] == self.s4)):\n success_counter += 1\n else:\n failure_counter += 1\n loop_counter += 1\n self.assertEqual(result.count(), 3)\n self.assertTrue(success_counter > 8)\n\n\n #Require boundary_data to work, please see PR.\n def test_boundary_match_single_data_set(self):\n data_set_path = './aliss/data/boundaries/scottish_local_authority.geojson'\n data_set_keys = {\n 'data_set_name': 'local_authority',\n 'code':'lad18cd',\n 'name':'lad18nm',\n }\n p = Postcode.objects.get(postcode='G2 1DY')\n long_lat = (p.longitude, p.latitude)\n boundary = {'data_file_path': data_set_path, 'data_set_keys': data_set_keys}\n result = find_boundary_matches(boundary, long_lat)\n expected = [{'code-type':'local_authority', 'code':'S12000046', 'name': 'Glasgow City' }]\n self.assertEqual(expected, result)\n\n\n def test_boundary_matches_multiple_data_sets(self):\n p = Postcode.objects.get(postcode='G2 1DY')\n long_lat = (p.longitude, p.latitude)\n result = check_boundaries(long_lat)\n expected = [{'code-type':'local_authority', 'code':'S12000046', 'name': 'Glasgow City' }, {'code-type':'health_board', 'code':'S08000031', 'name': 'Greater Glasgow and Clyde' }, {'code-type': 'health_integration_authority', 'code': 'S37000034', 'name': 'Glasgow City'}]\n self.assertEqual(result, expected)\n\n def tearDown(self):\n Fixtures.organisation_teardown()\n for organisation in Organisation.objects.filter(name=\"Test0rg\"):\n organisation.delete()\n for organisation in Organisation.objects.filter(name=\"Another org\"):\n organisation.delete()\n","sub_path":"aliss/tests/search/test_search.py","file_name":"test_search.py","file_ext":"py","file_size_in_byte":5825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"462571207","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/phaneron/steps.py\n# Compiled at: 2019-09-03 05:18:33\n# Size of source mod 2**32: 2592 bytes\n\n\nclass Steps(object):\n __doc__ = ' Steps '\n\n def __init__(self, client):\n \"\"\"\n Create a new Steps instance\n \"\"\"\n self._client = client\n\n def __str__(self):\n \"\"\"Return a pretty-print of the class\"\"\"\n return 'Steps for Brayns'\n\n def set_steps_geometry(self, mesh_filename, ca_count_filename):\n \"\"\"\n Loads a mesh generated by STEPS, together with the Calcium concentration, and sends it to\n Brayns\n :param mesh_filename: Full path of the file containing the mesh\n :param ca_count_filename: Full path of the file containing the CA concentrations\n :return: Result of the request submission\n \"\"\"\n import steps.utilities.meshio as meshio\n mesh = meshio.loadMesh(mesh_filename)[0]\n data = open(ca_count_filename, 'r').readlines()\n tets = data[0].split()\n ca_count = data[(-2)].split()\n ntets = min(len(tets), len(ca_count))\n vertices = list()\n for i in range(mesh.countVertices()):\n vertex = mesh.getVertex(i)\n vertices.append(float(vertex[0]))\n vertices.append(float(vertex[1]))\n vertices.append(float(vertex[2]))\n\n indices = list()\n for i in range(ntets):\n for j in mesh.getTet(int(tets[i])):\n indices.append(int(j))\n\n ca = list()\n for i in range(ntets):\n ca.append(int(ca_count[i]))\n\n params = dict()\n params['vertices'] = vertices\n params['indices'] = indices\n params['caCount'] = ca\n params['scale'] = 100\n return self._client.request('addStepsGeometry', params=params)","sub_path":"pycfiles/phaneron-0.1.12-py3.7/steps.cpython-37.py","file_name":"steps.cpython-37.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"247489938","text":"import argparse, json, os, psycopg2, sys\n\n# A comment?\nhelpText = \"This program is designed to register (or deregister) a bot to help with the game.\"\n\nparser = argparse.ArgumentParser(description = helpText)\n\nparser.add_argument(\"--botname\",\"-b\", help=\"a valid bot name (required)\")\nparser.add_argument(\"--desc\",\"-d\", help=\"description of the bot (optional)\")\nparser.add_argument(\"--disable\",\"-x\", help=\"'True' to deactivate\")\nparser.add_argument(\"--verbose\",\"-v\",help=\"'True' to turn on verbose logging\")\n\nargs = parser.parse_args()\n\n# Setting some defaults\nisVerbose=False\nbotName=\"Null\"\nbotDesc=args.desc\nenableBot=True\nbotStatus=\"active\"\nbotStatusID=0\n\nif args.verbose:\n isVerbose=args.verbose\n print(\"Verbose logging enabled\")\n\n# decide whether to stop now or continue.\nif not args.botname:\n if isVerbose: print(\"No bot name provided. Exiting...\")\n sys.exit()\n\nbotName=args.botname\n\nif not args.desc:\n botDesc=args.botname\n\nif args.disable:\n enableBot=False\n botStatus=\"disabled\"\n\nif isVerbose: \n print(\"botName = \" + botName)\n print(\"botDesc = '\" + botDesc + \"'\")\n print(\"enableBot = \" + str(enableBot))\n\n\nscript_dir = os.path.dirname(__file__)\nfile_path = os.path.join(script_dir, \"database_credentials.json\")\nwith open(file_path, \"r\") as f:\n dbcred = json.load(f)\n\n# #print (dbcred[\"hostname\"])\n\nhostname = dbcred[\"hostname\"]\nusername = dbcred[\"username\"]\npassword = dbcred[\"password\"]\ndatabase = dbcred[\"database\"]\nport = dbcred[\"port\"]\n\nstatusQuery=\"select a.entity_status_id bot_status_id from game.entity_status a where a.status_name = '\"+botStatus+\"'\"\nif isVerbose: print (\"statusQuery = \\n\" + statusQuery)\n\n# execute query\nconn = psycopg2.connect(user=username, password=password, host=hostname, port=port, database=database)\ncur = conn.cursor()\ncur.execute( statusQuery )\nbot_status_id = cur.fetchone()\nbotStatusID = int(bot_status_id[-1])\nif isVerbose: print (\"botStatusID = \" + str(botStatusID))\n\nif(conn):\n cur.close()\n conn.close()\n if isVerbose: print(\"Connection to DB is closed...\")\n\n\n# write query\nregisterQuery = \"\"\nregisterQuery += \"insert into game.bot_registration \\n\"\nregisterQuery += \" (created_date \\n\"\nregisterQuery += \" ,modified_date \\n\"\nregisterQuery += \" ,bot_status_id \\n\"\nregisterQuery += \" ,bot_name\\n\"\nregisterQuery += \" ,bot_description\\n\"\nregisterQuery += \" )\\n\"\nregisterQuery += \"values\\n\"\nregisterQuery += \" (current_timestamp\\n\"\nregisterQuery += \" ,current_timestamp\\n\"\nregisterQuery += \" ,\" + str(botStatusID) + \"\\n\"\nregisterQuery += \" ,'\" + botName + \"'\\n\"\nregisterQuery += \" ,'\" + botDesc + \"'\\n\"\nregisterQuery += \" )\\n\"\nregisterQuery += \"on conflict on constraint AK_bot_registraton\\n\"\nregisterQuery += \"do update set \\n\"\nregisterQuery += \" modified_date = current_timestamp\\n\"\nregisterQuery += \" ,bot_status_id = \" + str(botStatusID) + \"\\n\"\nregisterQuery += \" ,bot_name = '\" + botName + \"'\\n\"\nregisterQuery += \" ,bot_description = '\" + botDesc + \"'\\n\"\nregisterQuery += \"returning bot_status_id\\n\"\n# registerQuery += \"; commit\\n\"\n\nif isVerbose: print (\"registerQuery = \\n\" + registerQuery)\n\nconn2 = psycopg2.connect(user=username, password=password, host=hostname, port=port, database=database)\nregCur = conn2.cursor()\nregCur.execute( registerQuery )\nregisterResult = regCur.fetchone()\nbotRegistrationID=int(registerResult[-1])\nif isVerbose: print(\"botRegistrationID = \" + str(botRegistrationID))\nprint(botRegistrationID)\n\n\n","sub_path":"public/deprecated/python/register_bot.py","file_name":"register_bot.py","file_ext":"py","file_size_in_byte":3446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"630110577","text":"''' Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.\n\nEach number in C may only be used once in the combination.\n\nNote:\nAll numbers (including target) will be positive integers.\nElements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).\nThe solution set must not contain duplicate combinations.\nFor example, given candidate set 10,1,2,7,6,1,5 and target 8, \nA solution set is: \n[1, 7] \n[1, 2, 5] \n[2, 6] \n[1, 1, 6]\n'''\nclass Solution:\n\t# @param {integer[]} candidates\n\t# @param {integer} target\n\t# @return {integer[][]}\n\tdef combinationSum(self,candidates, target):\n\t\tif(candidates == [] or candidates[0] > target):\n\t\t\treturn []\n\t\telse:\n\t\t\tmax_index = len(candidates) - 1\n\t\t\twhile(candidates[max_index] > target):\n\t\t\t\tmax_index -= 1\n\t\t\tmax_num = candidates[max_index]\n\t\t\tans = []\n\t\t\ttmp_ans1 = self.combinationSum2(candidates[0:max_index], target)\n\t\t\t# print('1, candidates =', candidates, 'target =', target)\n\t\t\ttmp_ans2 = self.combinationSum2(candidates[0:max_index], target - max_num)\n\t\t\t# print('2, candidates =', candidates, 'target =', target - max_num)\n\t\t\tfor ele in tmp_ans2:\n\t\t\t\tele.append(max_num)\n\t\t\tans = tmp_ans1 + tmp_ans2\n\t\t\tif(max_num == target):\n\t\t\t\tans.append([max_num,])\n\t\t\t# print('Max num =', max_num)\n\t\t\t# print('ans =', ans)\n\t\t\tres = []\n\t\t\tfor ele in ans:\n\t\t\t\tif(not ele in res):\n\t\t\t\t\tres.append(ele)\n\t\t\treturn res\n\tdef combinationSum2(self, candidates, target):\n\t\tcandidates.sort()\n\t\treturn self.combinationSum(candidates, target)\n\ns = Solution()\ncandidates = [4,4,2,1,4,2,2,1,3]\ntarget = 6\nprint(s.combinationSum2(candidates, target))\n","sub_path":"LeetCode/040M_Combination_Sum_II.py","file_name":"040M_Combination_Sum_II.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"453578975","text":"\"\"\"This is a doc string\r\n This program calculating the number of stops required to re-fuel before reaching destination\r\n\"\"\"\r\ndef get_odo_input():\r\n start=float(input(\"Enter the start reading of odometer\\n\"))\r\n end=float(input(\"Enter the end reading of odometer\\n\")) #the following k and l will take the inputs from the user\r\n liters=float(input(\"Enter the amount of gas in liters\\n\"))\r\n return float(start), float(end), float(liters)\r\n\r\ndef mileage(user):\r\n print(\"The mileage of your vehicle is=%f\"%mil)\r\n \r\n# main starts from here\r\n\"\"\"This is a doc string\r\n The complete calculation of the mileage is done in main\r\n\"\"\"\r\nstart,end,liters=get_odo_input()\r\ndiff=end-start\r\nmil=diff/liters\r\nmileage(mil)\r\n \r\n","sub_path":"mileage.py","file_name":"mileage.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"50381150","text":"while 1:\n n = int(input())\n if n == -1:\n break\n cp = res = 0\n for _ in range(n):\n s, t = map(int, input().split())\n res += s*(t-cp)\n cp = t\n print(f\"{res} miles\")\n","sub_path":"src/BaekJoon/Simple_Implementation/4635.py","file_name":"4635.py","file_ext":"py","file_size_in_byte":206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"271569508","text":"#!/usr/bin/env python\n\nimport os.path\nimport urllib2\n\nfrom WMCore.Configuration import Configuration\n\n# ---\n# Some parameter steering\nPROCESS = 'MSSMHbb'\nUNITS_PER_JOB = 1\nTYPE = 'MC'\nPSET = 'ntuplizer_mc.py'\nCAMPAIGN = 'Fall15.SomeVersion'\nBASEOUTDIR = '/store/user/MyUserName/Analysis/Ntuples/' + PROCESS\nURL = 'http://www.desy.de/~MyUserName/cms/analysis/samples/miniaod'\n\n# ---\ndataset_list = URL + '/' + PROCESS + '.txt'\ndatasets = urllib2.urlopen(dataset_list)\n\n# _________________________________________________________________________\n\nif __name__ == '__main__':\n\n from CRABAPI.RawCommand import crabCommand\n from CRABClient.ClientExceptions import ClientException\n from httplib import HTTPException\n \n from Analysis.Tools.crabConfig import crabConfig\n config = crabConfig()\n \n if TYPE == 'MC':\n config.Data.splitting = 'FileBased'\n config.JobType.psetName = 'ntuplizer_mc.py'\n if TYPE == 'DATA':\n config.Data.splitting = 'LumiBased'\n config.JobType.psetName = 'ntuplizer_data.py'\n \n config.General.workArea += '_' + PROCESS\n config.Data.unitsPerJob = UNITS_PER_JOB\n \n for dataset in datasets:\n dataset = dataset.split('\\n')[0]\n dataset_name = dataset.split('/')[1]\n dataset_cond = dataset.split('/')[2]\n dataset_tier = dataset.split('/')[3]\n config.Data.inputDataset = dataset\n config.Data.outputDatasetTag = dataset_cond\n config.General.requestName = dataset_name\n config.Data.outLFNDirBase = BASEOUTDIR + '/' + dataset_tier + '/' + CAMPAIGN + '/'\n config.JobType.psetName = PSET\n crabCommand('submit', config = config)\n\n# _________________________________________________________________________\n","sub_path":"test/submitCrab3.py","file_name":"submitCrab3.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"593586840","text":"\"\"\"\nTest that accuracy of FitBenchmarking is consistent with previous versions\n\"\"\"\n\ntry:\n from itertools import zip_longest\nexcept ImportError:\n from itertools import izip_longest as zip_longest\nimport os\nimport tempfile\nfrom unittest import TestCase\n\nfrom fitbenchmarking.cli.main import run\nfrom fitbenchmarking.utils.options import Options\n\n\nclass TestRegression(TestCase):\n \"\"\"\n Regression tests for the Fitbenchmarking software\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n \"\"\"\n Create an options file, run it, and get the results.\n \"\"\"\n\n # Get defaults which should have minimizers for every software\n opts = Options()\n # Use only the first minimizer for each software\n opts.minimizers = {k: [v[0]] for k, v in opts.minimizers.items()}\n # Get a list of all softwares\n # (sorted to ensure it is the same order as expected)\n opts.software = sorted(opts.minimizers.keys())\n opts.results_dir = os.path.join(os.path.dirname(__file__), 'results')\n\n opt_file = tempfile.NamedTemporaryFile(suffix='.ini')\n opts.write(opt_file.name)\n\n problem = os.path.abspath(os.path.join(os.path.dirname(__file__),\n os.pardir,\n 'mock_problems',\n 'all_parsers_set'))\n run([problem], options_file=opt_file.name)\n\n def test_results_consistent(self):\n \"\"\"\n Regression testing that the results of fitting a set of problems\n containing all problem types against a single minimiser from each of\n the supported softwares\n \"\"\"\n\n expected_file = os.path.join(os.path.dirname(__file__),\n 'expected_results',\n 'results_regression.txt')\n\n actual_file = os.path.join(os.path.dirname(__file__),\n 'results',\n 'all_parsers_set',\n 'all_parsers_set_acc_weighted_table.txt')\n\n with open(expected_file, 'r') as f:\n expected = f.readlines()\n\n with open(actual_file, 'r') as f:\n actual = f.readlines()\n\n diff = []\n for exp_line, act_line in zip_longest(expected, actual):\n exp_line = exp_line.strip('\\n')\n act_line = act_line.strip('\\n')\n if exp_line != act_line:\n diff.append([exp_line, act_line])\n\n num_diff = min(6, len(diff))\n msg = 'Accuracy has changed in at least 1 minimizer-' \\\n + 'problem pair. \\n' \\\n + 'First {} of {} differences: \\n'.format(num_diff, len(diff)) \\\n + '\\n'.join(['{} \\n{}'.format(*diff[i])\n for i in range(num_diff)])\n self.assertListEqual([], diff, msg)\n","sub_path":"fitbenchmarking/systests/test_regression.py","file_name":"test_regression.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"584335081","text":"import logging\nimport analyse.reader\nimport os\nimport pandas as pd\nimport analyse.plot\nimport json\nimport time\nimport numpy as np\nimport analyse.skims\nfrom analyse.skims import set_simba_binnenverkehr_fq_attributes, get_station_to_station_skims\nfrom variable import *\nimport analyse.compare\nimport gc\n\n_cache = {}\n\n\ndef clear_cache():\n _cache.clear()\n\n\ndef cache(func):\n \" Used on methods to convert them to methods that replace themselves\\\n with their return value once they are called. \"\n\n def f(*args, **kwargs):\n self = args[0] # Reference to the class who owns the method\n funcname = func.__name__\n key = (self, funcname, args) + tuple(json.dumps(kwargs, sort_keys=True))\n if key not in _cache:\n _cache[key] = func(*args, **kwargs)\n else:\n logging.info(\"Loading from cache :). Use clear_cache\")\n return _cache[key]\n\n return f\n\n\nkeys = {\"acts\":\n {\"path\": \"matsim_activities.txt\", \"sep\": \"\\t\"},\n \"journeys\":\n {\"path\": \"matsim_journeys.txt\", \"sep\": \"\\t\"},\n \"legs\":\n {\"path\": \"matsim_trips.txt\", \"sep\": \"\\t\"},\n \"vehjourneys\":\n {\"path\": \"matsim_vehjourneys.csv\", \"sep\": \";\"},\n \"stops\":\n {\"path\": \"matsim_stops.csv\", \"sep\": \";\"},\n \"linkvolumes\":\n {\"path\": \"matsim_linkvolumes.csv\", \"sep\": \";\"},\n \"planelements\":\n {\"path\": \"plan_elements.csv\", \"sep\": \";\"},\n \"persons\":\n {\"path\": \"agents.csv\", \"sep\": \";\"}}\n\n\ndef _start_logging():\n logger = logging.getLogger()\n\n for handler in logger.handlers:\n logger.removeHandler(handler)\n\n logger.setLevel(logging.DEBUG)\n ch = logging.StreamHandler()\n ch.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s')\n ch.setFormatter(formatter)\n logger.addHandler(ch)\n\n\n_start_logging()\nanalyse.plot.set_matplotlib_params()\n\ndtypes = {u'activity_id': int,\n u'person_id': str,\n trip_id: int,\n leg_id: int,\n u'boarding_stop': float,\n u'alighting_stop': float,\n u'alighting': str,\n u'link_id': str,\n u'work': str,\n u'season_ticket': str,\n u'subpopulation': str,\n u'employed': str,\n u'carAvail': str,\n u\"gender\": str,\n u\"work: employment status\": str,\n u\"sex\": str,\n u\"hasLicense\": str}\n\n\nclass Run:\n def __init__(self, path=None, name=None, runId=None, scale_factor=1.0, perimeter_attribute=\"08_SIMBA_CH_Perimeter\",\n datenherkunft_attribute=\"SBB_Simba.CH_2016\"):\n self.path = path\n self.name = name\n self.scale_factor = scale_factor\n\n self.runId = runId\n self.data = {}\n\n self.trip_persons_merged = False\n self.legs_persons_merged = False\n self.route_merged = False\n self.link_merged = False\n self.name_perimeter_attribute = perimeter_attribute\n self.name_datenherkunft_attribute = datenherkunft_attribute\n self.sample = None\n\n def get_persons(self):\n return self._get(\"persons\")\n\n def get_acts(self):\n return self._get(\"acts\")\n\n def get_trips(self):\n return self._get(\"journeys\")\n\n def get_legs(self):\n df = self._get(\"legs\")\n assert np.any(df.duplicated(leg_id)) == False\n return df\n\n def get_pt_legs(self):\n df = self.get_legs()\n\n if \"pt_legs\" not in self.data:\n\n cols = list(df.columns)\n\n df = pd.DataFrame(df[df[BOARDING_STOP].notnull() & df[ALIGHTING_STOP].notnull()])\n\n n = len(df)\n\n df[START_TIME] = df[START_TIME].apply(int)\n df[END_TIME] = df[END_TIME].apply(int)\n df[BOARDING_STOP] = df[BOARDING_STOP].apply(float)\n df[ALIGHTING_STOP] = df[ALIGHTING_STOP].apply(float)\n\n stop_attributes = self.get_stop_attributes()\n stops_in_perimeter = stop_attributes[stop_attributes[self.name_perimeter_attribute] == \"1\"][STOP_FACILITY].map(\n float).unique()\n stops_in_fq = stop_attributes[stop_attributes[FQ_RELEVANT] == \"1\"][STOP_FACILITY].map(float).unique()\n\n if IS_SIMBA not in df.columns:\n df = self.merge_route(df)\n\n df[IS_SIMBA_ROUTE] = False\n df.loc[df[\"01_Datenherkunft\"] == self.name_datenherkunft_attribute, IS_SIMBA_ROUTE] = True\n\n df = set_simba_binnenverkehr_fq_attributes(df, stops_in_perimeter, stops_in_fq)\n cols_ = cols + [\"is_binnenverkehr_simba\", \"journey_has_fq_leg\",\n \"start_time_first_stop\", \"end_time_last_stop\", \"first_stop\", \"last_stop\"]\n if IS_SIMBA not in cols_:\n cols_.append(IS_SIMBA)\n assert n == len(df)\n assert np.any(df.duplicated(leg_id)) == False\n self.data[\"pt_legs\"] = df\n\n return pd.DataFrame(self.data[\"pt_legs\"])\n\n def filter_to_simba_binnenverkehr_fq_legs(self):\n df = self.get_pt_legs()\n return df[df[IS_SIMBA] & df.is_binnenverkehr_simba & df.journey_has_fq_leg]\n\n def get_skims_simba(self, **kwargs):\n if \"skims\" not in self.data:\n df = self.filter_to_simba_binnenverkehr_fq_legs()\n skims = get_station_to_station_skims(df, self.get_stop_attributes())\n skims.set_index([\"first_stop_code\", \"last_stop_code\"], inplace=True)\n self.data[\"skims\"] = skims\n return self.data[\"skims\"]\n\n def get_skim_simba(self, name, **kwargs):\n return self.get_skims_simba()[[name]]\n\n def get_vehjourneys(self):\n return self._get(\"vehjourneys\")\n\n def get_boarding_alighting(self):\n return self._get(\"stops\")\n\n def get_stops(self):\n return self.get_boarding_alighting()\n\n def get_ea(self):\n return self.get_boarding_alighting()\n\n def get_linkvolumes(self):\n df = self._get(\"linkvolumes\")\n id = LINK_ID\n if NAME in df.columns:\n id = NAME\n df = pd.DataFrame(df.groupby([id, \"mode\"])[VOLUME].sum()).reset_index()\n self.data[\"linkvolumes\"] = df\n return df\n\n def get_planelements(self):\n return self._get(\"planelements\")\n\n def get_stop_points(self):\n return self._get(\"stop_points\")\n\n def get_stop_attributes(self):\n return self._get(\"stop_attributes\")\n\n def get_route_attributes(self):\n return self._get(\"route_attributes\")\n\n def _get(self, name, reload_data=False):\n self._load_data(name, reload_data=reload_data)\n df = self.data[name]\n if self.sample is not None:\n df = df.sample(self.sample, axis=0, replace=True)\n return df\n\n def load_stop_attributes(self, path):\n df = analyse.reader.get_attributes(path, STOP_FACILITY)\n df[STOP_FACILITY] = df[STOP_FACILITY].map(float)\n self.data[\"stop_attributes\"] = df\n\n def load_route_attributes(self, path):\n self.data[\"route_attributes\"] = analyse.reader.get_attributes(path, TRANSIT_ROUTE)\n\n def load_stop_points(self):\n self.data[\"stop_points\"] = analyse.reader.get_stops(self.path)\n\n def _load_data(self, name, reload_data=True):\n if not reload_data and name in self.data:\n logging.debug(\"Data %s already loaded\" % name)\n return\n\n try:\n time1 = time.time()\n sep = keys[name][\"sep\"]\n filename = keys[name][\"path\"]\n if self.runId is not None:\n filename = self.runId + \".\" + filename\n path = os.path.join(self.path, filename)\n logging.info(\"Starting loading data %s: %s \" % (name, path))\n df = pd.read_csv(path, sep=sep, encoding=\"utf-8\", dtype=dtypes).reset_index(drop=True)\n self.data[name] = df\n logging.info(\"%s loaded in %i seconds\" % (name, time.time() - time1))\n except Exception as e:\n logging.error(e.message)\n\n def unload_data(self):\n self.data.clear()\n self.trip_persons_merged = False\n self.legs_persons_merged = False\n self.link_merged = False\n\n def load_data(self, with_stop_points=False):\n logging.info(\"Loading Data for %s\" % self.name)\n for name in keys:\n self._load_data(name)\n if with_stop_points:\n self.load_stop_points()\n\n def _set_dummy_pf(self):\n df = self.get_legs()\n df[PF] = self.scale_factor\n df[PKM] = df[DISTANCE] * df[PF]\n\n df = self.get_trips()\n df[PF] = self.scale_factor\n df[PKM] = df[DISTANCE] * df[PF]\n\n def prepare(self, ref=None, persons=None, transit_schedule=None,\n shapefile_attributes=None, zone_attributes=[\"N_Gem\"], zone_merge_attribute=\"ID_ALL\"):\n # self.unload_data()\n\n if transit_schedule is not None:\n self.load_stop_attributes(transit_schedule)\n self.load_route_attributes(transit_schedule)\n\n if persons is not None:\n logging.info(\"Using a special dataframe for persons\")\n self.data[\"persons\"] = persons\n\n df = self.get_trips()\n df.loc[df.main_mode == TRANSIT_WALK, MAIN_MODE] = WALK_AGGR\n df.loc[df.main_mode == WALK, MAIN_MODE] = WALK_AGGR\n df.loc[df.main_mode == \"detPt\", \"main_mode\"] = \"pt\"\n\n df = self.get_legs()\n df.loc[df[\"mode\"] == \"detPt\", \"mode\"] = \"pt\"\n\n self._set_dummy_pf()\n\n df = self.merge_trips_persons()\n df = self.merge_legs_persons()\n\n self.create_starttime_class_for_legs()\n\n if ref is not None:\n stations = ref.get_count_stations()\n self.merge_link_id_to_name(stations)\n\n if shapefile_attributes is not None and zone_attributes is not None:\n self.merge_trips_zone(shapefile_attributes, zone_attributes, zone_merge_attribute)\n\n def merge_activities_to_zone(self, attirbutes_path, zone_attributes=[\"N_Gem\"], merge_attribute=\"ID_ALL\"):\n zones = pd.read_csv(attirbutes_path, sep=\",\", encoding=\"utf-8\")\n df = self.get_acts()\n df.activity_id = df.activity_id.apply(int)\n\n acts = df.merge(zones[[merge_attribute] + zone_attributes], left_on=\"zone\", right_on=merge_attribute)\n self.data[\"acts\"] = acts\n return self.get_acts()\n\n def merge_trips_zone(self, attirbutes_path, zone_attributes=[\"N_Gem\"], merge_attribute=\"ID_ALL\"):\n acts = self.merge_activities_to_zone(attirbutes_path, zone_attributes, merge_attribute)\n acts = acts.set_index(\"activity_id\")\n\n trips = self.get_trips()\n trips.from_act = trips.from_act.apply(int)\n trips.to_act = trips.to_act.apply(int)\n\n df = trips.merge(acts[zone_attributes], left_on=\"from_act\", right_index=True, how=\"left\")\n\n zone_attributes_dict = dict(zip(zone_attributes, [\"from_\" + a for a in zone_attributes]))\n df.rename(columns=zone_attributes_dict, inplace=True)\n df = df.merge(acts[zone_attributes], left_on=\"to_act\", right_index=True, how=\"left\")\n zone_attributes_dict = dict(zip(zone_attributes, [\"to_\" + a for a in zone_attributes]))\n df.rename(columns=zone_attributes_dict, inplace=True)\n\n self.data[\"journeys\"] = df\n return self.get_trips()\n\n def merge_trips_persons(self):\n if not self.trip_persons_merged:\n trips = self.get_trips().merge(self.get_persons(), on=person_id, how=\"left\", suffixes=(\"\", \"_p\"))\n self.trip_persons_merged = True\n self.data[\"journeys\"] = trips\n return self.get_trips()\n\n def merge_legs_persons(self):\n if not self.legs_persons_merged:\n legs = self.get_legs().merge(self.merge_trips_persons(), on=trip_id, how=\"left\", suffixes=(\"\", \"_trips\"))\n self.legs_persons_merged = True\n self.data[\"legs\"] = legs\n return self.get_legs()\n\n def merge_link_id_to_name(self, stations):\n logging.info(\"merging links\")\n if not self.link_merged:\n df = self.get_linkvolumes()\n # fix because of error in matsim-sbb\n df = df[df[\"mode\"] == \"car\"]\n df = df.merge(stations, how=\"right\", left_on=LINK_ID, right_index=True)\n self.data[\"linkvolumes\"] = df\n self.link_merged = True\n logging.info(\"done merging links\")\n return self.get_linkvolumes()\n\n def _do(self, df, by, value, foreach=None, aggfunc=\"count\", percent=None, inverse_percent_axis=False,\n percent_level=None, **kwargs):\n def check_variable(values):\n if not isinstance(values, list):\n values = [values]\n for _value in values:\n if _value not in df.columns:\n df[_value] = \"Undefined\"\n\n def make_percent(df):\n if inverse_percent_axis:\n do = False\n if df.columns.nlevels > 1:\n do = True\n df = df.stack(percent_level)\n _df = df.sum(axis=1)\n df = df.divide(_df, axis=0)\n if do:\n df = df.unstack(percent_level)\n df = df.swaplevel(0, 1, axis=1)\n else:\n df = df.divide(df.sum(level=percent_level))\n return df\n\n check_variable(by)\n check_variable(foreach)\n\n if foreach is not None:\n df = df.pivot_table(index=by, columns=foreach, values=value, aggfunc=aggfunc)\n else:\n df = df.groupby(by).agg({value: aggfunc})\n\n if percent:\n df = make_percent(df)\n\n df = df.fillna(0)\n return df\n\n @cache\n def calc_nb_trips(self, by=mode_trip, **kwargs):\n return self._do(self.get_trips(), by=by, value=PF, aggfunc=\"sum\", **kwargs)\n\n @cache\n def calc_nb_legs(self, **kwargs):\n return self._do(self.get_legs(), value=PF, aggfunc=\"sum\", **kwargs)\n\n @cache\n def calc_dist_trips(self, **kwargs):\n return self._do(self.get_trips(), value=PKM, aggfunc=\"sum\", **kwargs)\n\n @cache\n def calc_dist_legs(self, **kwargs):\n return self._do(self.get_legs(), value=PKM, aggfunc=\"sum\", **kwargs)\n\n @cache\n def calc_dist_distr_trips(self, inverse_percent_axis=False, rotate=True, **kwargs):\n self.create_distance_class_for_trips()\n df = self._do(self.get_trips(), by=CAT_DIST, value=PF, aggfunc=\"sum\", rotate=rotate,\n inverse_percent_axis=inverse_percent_axis, **kwargs)\n if inverse_percent_axis:\n return df\n else:\n return df.cumsum()\n\n @cache\n def calc_dist_distr_legs(self, inverse_percent_axis=False, rotate=True, **kwargs):\n self.create_distance_class_for_legs()\n df = self._do(self.get_legs(), by=CAT_DIST, value=PF, aggfunc=\"sum\", rotate=rotate,\n inverse_percent_axis=inverse_percent_axis, **kwargs)\n if inverse_percent_axis:\n return df\n else:\n return df.cumsum()\n\n def plot_timing(self):\n analyse.plot.plot_timing(self.path)\n\n def plot_score(self):\n analyse.plot.plot_score([self.path])\n\n @cache\n def calc_einsteiger(self, simba_only=False, codes=None, **kwargs):\n if simba_only:\n df = self.filter_to_simba_binnenverkehr_fq_legs()\n else:\n df = self.get_pt_legs()\n\n try:\n df = df.merge(right=self.get_stop_attributes(), how=\"left\", left_on=\"boarding_stop\", right_on=STOP_FACILITY)\n df.rename(columns={\"03_Stop_Code\": \"03_Stop_Code_boarding\"}, inplace=True)\n except KeyError as e:\n logging.warn(e)\n\n df = self._do(df, value=PF, aggfunc=\"sum\", **kwargs)\n\n if codes is not None:\n df = df.loc[codes]\n\n gc.collect()\n return df\n\n @cache\n def calc_pt_pkm(self, simba_only=False, **kwargs):\n if simba_only:\n df = self.filter_to_simba_binnenverkehr_fq_legs()\n else:\n df = self.get_pt_legs()\n\n df = self.merge_route(df)\n\n df = self._do(df, value=PKM, aggfunc=\"sum\", **kwargs)\n\n gc.collect()\n return df\n\n @cache\n def calc_pt_pf(self, simba_only=False, **kwargs):\n if simba_only:\n df = self.filter_to_simba_binnenverkehr_fq_legs()\n else:\n df = self.get_pt_legs()\n\n df = self.merge_route(df)\n df = self._do(df, value=PF, aggfunc=\"sum\", **kwargs)\n\n gc.collect()\n return df\n\n def merge_route(self, df):\n if self.route_merged:\n return df\n try:\n n = len(df)\n df = df.merge(right=self.get_route_attributes(), how=\"left\", left_on=\"route\", right_on=TRANSIT_ROUTE)\n assert n == len(df), \"Size of DF changed\"\n self.route_merged = True\n except KeyError as e:\n logging.warn(e)\n return df\n\n @cache\n def calc_dist_distr_pt_legs(self, inverse_percent_axis=False, rotate=True, **kwargs):\n df = self.get_pt_legs()\n self._create_distance_class(df)\n\n df = self.merge_route(df)\n\n df = self._do(df, by=CAT_DIST, value=PF, aggfunc=\"sum\", rotate=rotate,\n inverse_percent_axis=inverse_percent_axis, **kwargs)\n return df\n\n @cache\n def calc_pt_dist_distr_trips(self, simba_only=False, **kwargs):\n if simba_only:\n df = self.filter_to_simba_binnenverkehr_fq_legs()\n else:\n df = self.get_pt_legs()\n\n agg_dict = {PF: \"first\", DISTANCE: \"sum\"}\n if \"foreach\" in kwargs:\n foreach = kwargs[\"foreach\"]\n if foreach is not None:\n for a in foreach:\n agg_dict[a] = \"first\"\n\n df = df.groupby(\"journey_id\").agg(agg_dict)\n\n self._create_distance_class(df)\n\n return self._do(df, by=CAT_DIST, value=PF, aggfunc=\"sum\", **kwargs)\n\n @cache\n def calc_duration_trips(self, **kwargs):\n df = self.get_trips()\n df[\"duration\"] = (df.end_time - df.start_time) // (60 * 10)\n df = self._do(df, value=PF, aggfunc=\"sum\", by=DURATION, **kwargs)\n return df\n\n @cache\n def calc_vehicles(self, **kwargs):\n df = self.get_linkvolumes()\n df = self._do(df, value=VOLUME, aggfunc=\"sum\", by=NAME, **kwargs) * self.scale_factor\n return df\n\n def get_umstiege(self, only_train=False, var=UMSTIEG):\n def get_count(data):\n def get_umstieg(_data, name):\n if len(_data) <= 1:\n return \"%s_direkt\" % name\n elif len(_data) == 2:\n return \"%i_Umstieg_%s\" % (len(_data) - 1, name)\n elif len(_data) < 6:\n return \"%i_Umstiege_%s\" % (len(_data) - 1, name)\n else:\n return \">4_Umstiege_%s\" % name\n\n _data = data.values\n # Only Bahn\n if \"Bahn\" in _data and \"OPNV\" not in _data:\n return get_umstieg(_data, \"Bahn\")\n # Only OPNV\n elif \"Bahn\" not in _data and \"OPNV\" in _data:\n return get_umstieg(_data, \"OPNV\")\n # OeV\n else:\n return get_umstieg(_data, \"OeV\")\n\n def get_count_train(data):\n _data = data.values\n # Only Bahn\n name = \"Bahn\"\n if \"Bahn\" in _data:\n n = list(_data).count(\"Bahn\")\n if n <= 1:\n return \"%s_direkt\" % name\n elif n == 2:\n return \"%i_Umstieg_%s\" % (n - 1, name)\n elif n < 6:\n return \"%i_Umstiege_%s\" % (n - 1, name)\n else:\n return \">4_Umstiege_%s\" % name\n else:\n return \"keine_Bahnetappe\"\n\n df = self.get_pt_legs()\n filtered_df = df[df[\"08_TSysName\"].notnull()]\n filtered_df[var] = filtered_df[\"08_TSysName\"].apply(lambda x: tsys2pt[x])\n\n if only_train:\n return self._do(filtered_df, by=trip_id, value=var, aggfunc=get_count_train)\n else:\n return self._do(filtered_df, by=trip_id, value=var, aggfunc=get_count)\n\n @cache\n def calc_pt_umstiege(self, only_train=False, **kwargs):\n df = self.get_trips()\n df = df[df[MAIN_MODE] == \"pt\"]\n var = UMSTIEG\n if not only_train and UMSTIEG not in df.columns:\n df_trips = self.get_umstiege(only_train=False, var=UMSTIEG)\n df = df.merge(df_trips, left_on=trip_id, right_index=True, how=\"right\")\n\n if only_train and UMSTIEG_BAHN not in df.columns:\n df_trips = self.get_umstiege(only_train=True, var=UMSTIEG_BAHN)\n df = df.merge(df_trips, left_on=trip_id, right_index=True, how=\"right\")\n\n if only_train:\n var = UMSTIEG_BAHN\n df = df[np.logical_not(df[UMSTIEG_BAHN].str.contains(\"keine\"))]\n\n return self._do(df, by=var, aggfunc=\"sum\", **kwargs)\n\n @cache\n def calc_pt_uh(self, simba_only=False, **kwargs):\n if simba_only:\n df = self.filter_to_simba_binnenverkehr_fq_legs()\n else:\n df = self.get_pt_legs()\n df = df.groupby(trip_id).agg({leg_id: \"count\", PF: \"first\"})\n df[\"nb_transfer\"] = df[leg_id] - 1\n return self._do(df, by=\"nb_transfer\", value=PF, aggfunc=\"sum\", percent=True, **kwargs)\n\n @cache\n def calc_pt_nb_trips(self, simba_only=False, by=\"mode\", **kwargs):\n if simba_only:\n df = self.filter_to_simba_binnenverkehr_fq_legs()\n else:\n df = self.get_pt_legs()\n columns = [PF, by]\n if \"foreach\" in kwargs:\n foreach = kwargs[\"foreach\"]\n if foreach is not None:\n columns += foreach\n df = df.groupby(trip_id)[columns].min()\n\n return self._do(df, by=by, value=PF, aggfunc=\"sum\", **kwargs)\n\n @staticmethod\n def _create_distance_class(df, column=DISTANCE, category_column=CAT_DIST):\n classes = distance_classes\n labels = distance_labels\n\n df[category_column] = pd.cut(df[column], classes, labels=labels)\n\n def create_distance_class_for_legs(self, **kwargs):\n self._create_distance_class(self.get_legs(), **kwargs)\n\n def create_distance_class_for_trips(self, **kwargs):\n self._create_distance_class(self.get_trips(), **kwargs)\n\n @staticmethod\n def _create_starttime_class(df):\n logging.info(\"creating start_time category\")\n df[CAT_START_TIME] = df[START_TIME] // (60 * 60)\n\n def create_starttime_class_for_legs(self):\n self._create_starttime_class(self.get_legs())\n\n def create_starttime_class_for_trips(self):\n self._create_starttime_class(self.get_trips())\n\n\ndistance_classes = np.array([-1, 0, 2, 4, 6, 8, 10, 15, 20, 25, 30, 40, 50, 100, 150, 200, 250, 300, np.inf]) * 1000.0\ndistance_labels = [\"0\", \"0-2\", \"2-4\", \"4-6\", \"6-8\", \"8-10\", \"10-15\", \"15-20\", \"20-25\", \"25-30\", \"30-40\", \"40-50\",\n \"50-100\", \"100-150\", \"150-200\", \"200-250\", \"250-300\", \"300+\"]\n\ntsys2pt = {'BUS': 'OPNV',\n 'FUN': 'OPNV',\n 'FV - ProduktA': 'Bahn',\n 'RV - ProduktD': 'Bahn',\n 'FV - ProduktB': 'Bahn',\n 'FV-RV - ProduktC': 'Bahn',\n 'IPV - HGV': 'Bahn',\n 'IPV - Konventionell': 'Bahn',\n 'IPV - Regionalverkehr': 'Bahn',\n 'KB': 'OPNV',\n 'M': 'OPNV',\n \"BAT\": \"OPNV\",\n \"FAE\": \"OPNV\",\n 'NFB': 'OPNV',\n 'NFO': 'OPNV',\n 'LB': 'OPNV',\n 'GB': 'OPNV',\n 'NFT': 'OPNV',\n 'T': 'OPNV'}\n","sub_path":"analyse/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":23666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"223300134","text":"import os\r\n\r\nimport pytest\r\nimport numpy as np\r\n\r\nfrom arcticpy import add_cti\r\n\r\nimport autocti as ac\r\n\r\npath = \"{}/\".format(os.path.dirname(os.path.realpath(__file__)))\r\n\r\n\r\ndef test__data_mapped_to_2d_and_then_1d():\r\n arr_1d = ac.Array1D.no_mask(\r\n values=[1.0, 2.0, 3.0, 4.0],\r\n pixel_scales=1.0,\r\n header=ac.Header(\r\n header_sci_obj=None, header_hdu_obj=None, readout_offsets=(3,)\r\n ),\r\n ).native\r\n\r\n arr_2d = ac.Array2D.no_mask(\r\n values=[[1.0], [2.0], [3.0], [4.0]],\r\n pixel_scales=1.0,\r\n header=ac.Header(\r\n header_sci_obj=None, header_hdu_obj=None, readout_offsets=(3,)\r\n ),\r\n ).native\r\n\r\n roe = ac.ROE(\r\n dwell_times=[1.0],\r\n empty_traps_between_columns=True,\r\n empty_traps_for_first_transfers=False,\r\n force_release_away_from_readout=True,\r\n use_integer_express_matrix=False,\r\n )\r\n ccd_phase = ac.CCDPhase(\r\n full_well_depth=1e3, well_notch_depth=0.0, well_fill_power=1.0\r\n )\r\n ccd = ac.CCD(phases=[ccd_phase], fraction_of_traps_per_phase=[1.0])\r\n traps = [ac.TrapInstantCapture(10.0, -1.0 / np.log(0.5))]\r\n\r\n image_via_arctic = add_cti(\r\n image=arr_2d,\r\n parallel_traps=traps,\r\n parallel_ccd=ccd,\r\n parallel_roe=roe,\r\n parallel_express=3,\r\n )\r\n\r\n cti = ac.CTI1D(trap_list=traps, ccd=ccd_phase)\r\n\r\n clocker_1d = ac.Clocker1D(express=3, roe=roe)\r\n\r\n image_via_clocker = clocker_1d.add_cti(data=arr_1d, cti=cti)\r\n\r\n assert image_via_arctic.flatten() == pytest.approx(image_via_clocker, 1.0e-4)\r\n\r\n image_corrected = clocker_1d.remove_cti(data=image_via_clocker, cti=cti)\r\n\r\n assert (image_corrected[:] > image_via_clocker[:]).all()\r\n","sub_path":"test_autocti/clocker/test_one_d.py","file_name":"test_one_d.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"144265752","text":"summ = 0\r\n\r\nwhile True:\r\n a = input('Введите число или Стоп для выхода: ')\r\n if a.lower() == 'стоп':\r\n break\r\n if a.isdigit():\r\n summ += int(a)\r\n else: print('Ошибка ввода')\r\nprint('Сумма:', summ)\r\n","sub_path":"lesson_7/end_count_sum.py","file_name":"end_count_sum.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"625242330","text":"# -*- coding:utf-8 -*-\n\nimport random\nfrom Kit.Figure import *\nfrom UIL.View.Operation import *\nfrom Setting.Config import *\nfrom DAL.Loader import *\nfrom Setting.Config import *\nfrom LIB.ClusterLIB.Metric.Measure import *\nimport numpy as np\nimport pandas as pd\nimport random\nimport time\nfrom Setting.Config import *\nimport sys\nmodules = ['pymssql','pymysql']\nfor each in modules:\n try:\n __import__(each)\n except:\n pass\n\n\n\n\nconf = getConfig()\n\n# 0.21 10\n# def synt():\n# leng = 12\n# ddd = []\n# for i in range(1, 200):\n# dd = []\n# v = float(i)\n# dd.append(60*v * v+10*v)\n# dd.append(v+float(random.randint(0,5)))\n# dd.append(math.pow(v,-2.6)+float(random.randint(0,5))/20)\n# dd.append(math.pow(v,-2.1)+float(random.randint(0,5))/20)\n# dd.append(math.exp(v))\n# dd.append(math.log(2*v))\n# dd.append(math.log(v) * 4)\n# dd.append(math.log(v) * 2)\n# dd.append(math.pow(v, -2))\n# dd.append(math.pow(v, 7))\n# dd.append(math.pow(v, -4.2))\n# dd.append(math.pow(v, 0.5))\n# ddd.append(dd)\n# ground_truth.append(0)\n#\n# for i in range(1, 200):\n# dd = []\n# v = float(i)\n# dd.append(120 * v * v - 190 * v + 450)\n# dd.append(v + float(random.randint(0, 5))+ 200)\n# dd.append(math.pow(v, -2.6) + float(random.randint(0, 5)) / 20)\n# dd.append(math.pow(v, -2.1) + float(random.randint(0, 5)) / 20)\n# dd.append(math.exp(v))\n# dd.append(math.log(2 * v))\n# dd.append(math.log(v) * 4)\n# dd.append(math.log(v) * 2)\n# dd.append(math.pow(v, -2))\n# dd.append(math.pow(v, 7))\n# dd.append(math.pow(v, 4.2))\n# dd.append(math.pow(v, 0.5))\n# ddd.append(dd)\n# ground_truth.append(1)\n#\n# for i in range(1, 200):\n# dd = []\n# v = float(i)\n# dd.append(-600 * v * v + 90 * v)\n# dd.append(v + float(random.randint(0, 5)) + 350)\n# dd.append(math.pow(v, -2.6) + float(random.randint(0, 5)) / 20)\n# dd.append(math.pow(v, -2.1) + float(random.randint(0, 5)) / 20)\n# dd.append(math.exp(v)+ 150)\n# dd.append(math.log(2 * v))\n# dd.append(math.log(v) * 4)\n# dd.append(math.log(v) * 2)\n# dd.append(math.pow(v, -2))\n# dd.append(math.pow(v, 7))\n# dd.append(math.pow(v, -4.2))\n# dd.append(math.pow(v, 0.5))\n# ddd.append(dd)\n# ground_truth.append(2)\n#\n# ddd = pd.DataFrame(ddd)\n# ddd = (ddd - ddd.min())/(ddd.max() - ddd.min())\n# leng = len(list(ddd.columns))\n# # for i in range(leng-1):\n# # for j in range(i+1,leng):\n# # print(pearson(ddd[i].as_matrix(),ddd[j].as_matrix()))\n# return ddd\n\n# def synt():\n# leng = 12\n# ddd = []\n# for i in range(1, 100):\n# dd = []\n# v = float(i)\n# dd.append(v * v)\n# dd.append(v)\n# dd.append(math.pow(v,0.6))\n# dd.append(math.pow(v,0.1))\n# dd.append(math.exp(v))\n# dd.append(math.log(v))\n# dd.append(math.pow(v,2.4))\n# dd.append(math.pow(v, 1.4))\n# dd.append(math.pow(v, 5))\n# dd.append(math.pow(v, 3))\n# dd.append(math.pow(v, 4.2))\n# dd.append(math.pow(v, -2.5))\n# ddd.append(dd)\n# ground_truth.append(0)\n# for i in range(100, 200):\n# dd = []\n# v = float(i)\n# for j in range(12):\n# dd.append(random.randint(-45, 0))\n# ddd.append(dd)\n# ground_truth.append(1)\n# for i in range(200, 300):\n# dd = []\n# v = float(i)\n# for j in range(12):\n# dd.append(random.randint(5,45))\n# ddd.append(dd)\n# ground_truth.append(2)\n# ddd = pd.DataFrame(ddd)\n# ddd = (ddd - ddd.min())/(ddd.max() - ddd.min())\n# leng = len(list(ddd.columns))\n# # for i in range(leng-1):\n# # for j in range(i+1,leng):\n# # print(pearson(ddd[i].as_matrix(),ddd[j].as_matrix()))\n# return ddd\n\ndef synt():\n ddd = []\n t = datasets.make_moons(n_samples=300)\n\n\n for ii in range(len(t[0])):\n v = t[0][ii]\n dd = []\n for _ in range(6):\n dd.append(v[0]+float(random.randint(0,6))/10.0)\n for _ in range(6):\n dd.append(v[1]+float(random.randint(0,6))/10.0)\n ddd.append(dd)\n ground_truth.append(t[1][ii])\n\n ddd = pd.DataFrame(ddd)\n ddd = (ddd - ddd.min())/(ddd.max() - ddd.min())\n leng = len(list(ddd.columns))\n # for i in range(leng-1):\n # for j in range(i+1,leng):\n # print(pearson(ddd[i].as_matrix(),ddd[j].as_matrix()))\n return ddd\n\ndef predict():\n\n operation = Operation()\n eval = 'log_loss'\n cs = {\n 'type':'single',\n 'classifier':NaiveXGBoostClassifier(),\n 'param':{\n 'silent':'1',\n 'objective':'multi:softmax',\n 'num_class':3,\n 'max_depth':20,\n 'eta':'0.05',\n #'colsample_bytree':0.65,\n #'subsample':0.95,\n 'min_child_weight':60,\n 'num_round':10\n },\n 'extraction':{\n 'type':None\n },\n 'eval':eval\n }\n\n operation.predictImmediate(predict_strategy = cs)\n\nshow_label = {'single':None,'ensemble':None}\n\n\n\ndef group(single=True,ensemble=True,show_label={}):\n shrink = 5\n cluster_num = 2\n filter_num = 'auto'\n instance = conf['instance']['experiment']\n opeartion = Operation()\n\n 啊 = True\n if True:\n cluster = SpectralCluster(params={'degree':5,'affinity':'nearest_neighbors','num_cluster':cluster_num,'n_neighbors':40,'filter_num':filter_num,\n 'shrink': shrink})\n cluster_e = SpectralCluster(\n params={'degree': 5, 'affinity': 'nearest_neighbors', 'num_cluster': cluster_num, 'n_neighbors': 40, 'filter_num': filter_num,\n 'shrink': shrink})\n\n if False:\n print('DBSCAN')\n cluster = DBSCANCluster(params={'eps':0.20,'mpts':10,'filter_num':filter_num,\n 'shrink': shrink,'num_cluster':cluster_num,'algorithm':'ball_tree'})\n cluster_e = DBSCANCluster(params={'eps': 0.19, 'mpts': 10,'filter_num':filter_num,\n 'shrink': shrink,'num_cluster':cluster_num,'algorithm':'ball_tree'})\n\n if False:\n print('AgglomerativeCluster'\n '')\n cluster = AgglomerativeCluster(params={'num_cluster':cluster_num,\n 'linkage':'ward',\n 'affinity':'euclidean',\n 'n_neighbours': None,\n 'connectivity':False,\n 'filter_num':filter_num,\n 'shrink': shrink})\n\n cluster_e = AgglomerativeCluster(params={'num_cluster': cluster_num,\n 'linkage': 'ward',\n 'affinity': 'euclidean',\n 'n_neighbours': None,\n 'connectivity': False,\n 'filter_num': filter_num,\n 'shrink': shrink})\n if False:\n print('KMEANS')\n cluster = KMeansCluster(params={'num_cluster':cluster_num,'n_init':10,'init':'k-means++','filter_num':filter_num,'shrink':shrink})\n cluster_e = KMeansCluster(params={'num_cluster':cluster_num,'n_init':10,'init':'k-means++','filter_num':filter_num,'shrink':shrink})\n if single:\n css = {\n 'type':'single',\n 'cluster':cluster,\n 'param':None,\n\n # 'cluster':BirchCluster(),\n # 'param':{\n # 'filter_num':filter_num,\n # 'num_cluster':cluster_num\n # },\n\n 'cluster_eval':[{\n 'name':'DBI',\n 'param':None\n },{\n 'name':'SDBW',\n 'param':None\n }],\n 'feature_eval':{\n 'name':'RANGE',\n 'param':None\n },\n 'num_cluster':cluster_num\n }\n print('------------------------Cluster From Single Mode------------------------')\n\n dsynt = synt()\n opeartion.groupImmediate(direct=dsynt,cluster_strategy=css,top_feature_num=3,instance=instance)\n show_label['single'] = opeartion.structure_group.getLabel()\n labelMatch(ground_truth,show_label['single'])\n if 啊:\n corr = 0\n for i in range(len(ground_truth)):\n if show_label['single'][i] == ground_truth[i]:\n corr += 1\n sa = float(corr)/float(len(ground_truth))\n print('single accuracy:'+str(sa))\n opeartion.show(feature_show=False,name='Single Cluster')\n if ensemble:\n cse = {\n 'type':'ensemble',\n #'cluster':KMeansCluster(params={'num_cluster':cluster_num,'n_init':10,'init':'k-means++','filter_num':filter_num}),\n #'cluster': DBSCANCluster(params={'eps': 0.2, 'mpts':2}),\n 'cluster':cluster_e,\n #'cluster':BirchCluster(params={'num_cluster':cluster_num,'filter_num':filter_num}),\n 'param':{\n 'type':'ENSEMBLE_PROJ',\n 'sample_strategy':'SUBSIM',\n 'round':20,\n 'feature_sample_ratio':0.8,\n 'filter_num':filter_num,\n 'shrink': shrink,\n 'thres':0.01,\n 'sim_limit':2,\n 'weight_eval':{\n 'name':'RELIEF',\n 'param':{'SEGMENT':4}\n },\n 'num_cluster':cluster_num\n },\n 'cluster_eval':[{\n 'name':'DBI',\n 'param':None\n },{\n 'name':'SDBW',\n 'param':None\n }],\n 'feature_eval':{\n 'name':'RELIEF',\n 'param':None\n },\n 'num_cluster':cluster_num\n }\n print('------------------------Cluster From Ensemble Mode------------------------')\n opeartion.groupImmediate(direct=dsynt, cluster_strategy=cse, top_feature_num=3,instance=instance,lf=True)\n show_label['ensemble'] = opeartion.structure_group.getLabel()\n labelMatch(ground_truth, show_label['ensemble'])\n if 啊:\n corr = 0\n for i in range(len(ground_truth)):\n if show_label['ensemble'][i] == ground_truth[i]:\n corr += 1\n ea = float(corr) / float(len(ground_truth))\n print('ensemble accuracy:' + str(ea))\n\n print('草拟粑粑:'+str(ea-sa))\n\n opeartion.show(feature_show=False,name='Vote Cluster')\n print(conf['instance']['experiment']['io_definition']['business_group']['train']['destination_entrance']+'/KM/'+cse['param']['sample_strategy']+'/W-'+cse['param']['weight_eval']['name']+'/'+str(cluster_num))\n\n\n\n\ndef __prepareForShowData(data, label, limit=2000, ratio=0.2):\n if len(data) > limit:\n show_data, ps = customSample(data, ratio)\n else:\n show_data = data\n ps = [i for i in range(len(data))]\n if len(data[0]) > 3:\n show_data = np.array(doPCA(show_data, 2))\n show_label = label\n tmp = []\n for v in ps:\n tmp.append(show_label[v])\n show_label = tmp\n return show_data, show_label\n\nif True:\n group(True,True,show_label)\n #predict()\n plt.show()\n\n\n\n\n\n\n\n\nfeature_a = ['ID',\n 'LEVEL',\n 'GENDER',\n 'AGE',\n 'INTEGRAL',\n 'MEMBER_LIFE', #*\n 'RECENT_CONSUME_SPAN', #*\n 'CONSUME_LIFE', #*\n 'MEMBER_UNIT_SOURCE',\n 'MEMBER_SOURCE',\n 'CARD_LIFE', #*\n 'RECHARGE_AMOUNT_SUM', #*\n 'CONSUME_AMOUNT_SUM', #*\n 'RECHARGE_AMOUNT_REAL_SUM', #*\n 'CONSUME_WITH_RECHARGE_SUM', #*\n 'CURRENT_BALANCE_SUM',\n 'INRETURN_IN_AMOUNT_SUM',\n 'INRETURN_OUT_AMOUNT_SUM',\n 'RETURN_AMOUNT_SUM',\n 'VALID_INRETURN_AMOUNT_SUM',\n 'ALL_INRETURN_AMOUNT_SUM',\n 'INVALID_INRETURN_AMOUNT_SUM',\n 'SOON_INVALID_INRETURN_AMOUNT_SUM',\n 'CONSUME_AMOUNT_BY_UNIT_MEAN',\n 'CONSUME_AMOUNT_BY_UNIT_VAR',\n 'CONSUME_AMOUNT_BY_UNIT_TOP',\n 'IF_WITHDRAW_SUM',\n 'AMOUNT_FREQ_TOP_UNIT',\n 'AMOUNT_TOP_UNIT',\n 'AMOUNT_UNIQUE_TOP_QUANTITY',\n 'ALL_INTEGRAL_IN_SUM',\n 'ALL_INTEGRAL_OUT_SUM',\n 'ALL_INTEGRAL_OUT_V_IN',\n 'CURRENT_INTEGRAL_SUM',\n 'SOON_INVALID_INTEGRAL',\n 'INVALID_INTEGRAL_SUM',\n 'VALID_INTEGRAL_SUM',\n 'INTEGRAL_SOONINVALID_V_CRTVALID',\n 'INTEGRAL_SUM',\n 'INTEGRAL_PRODUCT_BY_UNIT_MEAN',\n 'INTEGRAL_PRODUCT_BY_UNIT_VAR',\n 'INTEGRAL_PRODUCT_BY_UNIT_TOP',\n 'INTEGRAL_CONSUME_BY_UNIT_MEAN',\n 'INTEGRAL_CONSUME_BY_UNIT_VAR',\n 'INTEGRAL_CONSUME_BY_UNIT_TOP',\n 'INTEGRAL_FREQ_TOP_UNIT',\n 'INTEGRAL_PRODUCT_AMOUNT_TOP_UNIT',\n 'INTEGRAL_CONSUME_AMOUNT_TOP_UNIT',\n 'INTEGRAL_UNIQUE_UNIT_QUANTITY',\n 'ITEM_QUANTITY_BY_CATEGORY_MEAN',\n 'ITEM_QUANTITY_BY_CATEGORY_VAR',\n 'ITEM_QUANTITY_BY_CATEGORY_MAX',\n 'ITEM_QUANTITY_BY_CATEGORY_TOP_CATEGORY',\n 'ITEM_UNIQUE_CATEGORY_QUANTITY',\n 'ITEM_IF_OFTEN_SUM',\n 'ITEM_IF_SERVICE_SUM',\n 'COUPONVALUE_V_ORDERREALPAYMENT_MEAN',\n 'COUPONVALUE_V_ORDERREALPAYMENT_VAR',\n 'COUPONVALUE_V_ORDERREALPAYMENT_TOP',\n 'COUPON_QUANTITY_MEAN',\n 'COUPON_QUANTITY_SUM',\n 'COUPON_QUANTITY_VAR',\n 'COUPON_QUANTITY_TOP',\n 'COUPON_PERIOD_MEAN',\n 'COUPON_AMOUNT_MEAN',\n 'COUPON_AMOUNT_SUM',\n 'COUPON_AMOUNT_VAR',\n 'COUPON_AMOUNT_TOP',\n 'COUPON_CAN_REPEAT_MEAN',\n 'COUPON_CAN_REPEAT_SUM',\n 'ORDER_QUANTITY_SUM_BY_VIP', #*\n 'ORDER_ALL_AMOUNT_MEAN_BY_VIP', #*\n 'ORDER_ALL_AMOUNT_SUM_BY_VIP', #*\n 'ORDER_ALL_AMOUNT_VAR_BY_VIP',\n 'ORDER_ALL_AMOUNT_TOP_BY_VIP',\n 'ORDER_REAL_PAYMENT_MEAN_BY_VIP',\n 'ORDER_REAL_PAYMENT_SUM_BY_VIP',\n 'ORDER_REAL_PAYMENT_VAR_BY_VIP',\n 'ORDER_REAL_PAYMENT_TOP_BY_VIP',\n 'ORDER_SUB_BY_AMOUNT_AND_PAYMENT_MEAN',\n 'ORDER_SUB_BY_AMOUNT_AND_PAYMENT_SUM',\n 'ORDER_SUB_BY_AMOUNT_AND_PAYMENT_VAR',\n 'ORDER_PAYMENT_INTEGRAL_V_CASH_MEAN',\n 'ORDER_PAYMENT_INTEGRAL_V_CASH_VAR',\n 'ORDER_PAYMENT_INTEGRAL_V_CASH_TOP',\n 'ORDER_DISCOUNT_MEAN',\n 'ORDER_DISCOUNT_VAR',\n 'ORDER_DISCOUNTVALUE_V_REALPAYMENT_MEAN',\n 'ORDER_DISCOUNTVALUE_V_REALPAYMENT_VAR',\n 'ORDER_INTEGRAL_RECEIVE_V_CONSUME_MEAN',\n 'ORDER_INTEGRAL_RECEIVE_V_CONSUME_VAR',\n 'ORDER_INTEGRAL_RECEIVE_V_CONSUME_TOP',\n 'ORDER_CANCLE_SUM_V_COMPLETE',\n 'ORDER_COMPLETE_QUANTITY',\n 'ORDER_IF_COMMENT_SUM',\n 'ORDER_IF_GROUP_SUM',\n 'ORDER_DELIVERY_A_V_B',\n 'ORDER_COMPLETE_SPAN_MEAN',\n 'ORDER_COMPLETE_SPAN_VAR',\n 'ORDER_COMPLETE_SPAN_TOP',\n 'ITEM_QUANTITY_BY_PRICERANGE_MEAN',\n 'ITEM_QUANTITY_BY_PRICERANGE_VAR',\n 'ITEM_QUANTITY_BY_PRICERANGE_TOP_PRICERANGE',\n 'ITEM_UNIQUE_PRICERANGE_QUANTITY',\n 'ORDER_FREQ_TOP_UNIT',\n 'ORDER_ACTUAL_AMOUNT_TOP_UNIT',\n 'ORDER_UNIQUE_UNIT_QUANTITY',\n 'ORDER_FREQ_TOP_ORDERTYPE',\n 'ORDER_ACTUAL_AMOUNT_TOP_ORDERTYPE',\n 'ORDER_UNIQUE_ORDERTYPE_QUANTITY',\n 'ORDER_FREQ_TOP_PAYTYPE',\n 'ORDER_ACTUAL_AMOUNT_TOP_PAYTYPE',\n 'ORDER_UNIQUE_PAYTYPE_QUANTITY',\n 'ORDER_RETURN_QUANTITY',\n 'ORDER_RETURN_AMOUNT',\n 'ORDER_SUB_BY_REAL_AND_REQUIRE_RETURN_AMOUNT',\n 'ORDER_REAL_RETURN_QUANTITY',\n 'ORDER_SUB_BY_REQUIRE_AND_ACTUAL_QUANTITY',\n 'ORDER_AMOUNT_IN_PAYTYPE_A',\n 'ORDER_AMOUNT_IN_PAYTYPE_B',\n 'ORDER_AMOUNT_IN_PAYTYPE_C',\n 'ORDER_AMOUNT_IN_PAYTYPE_D',\n 'ORDER_INTERVAL_MEAN',\n 'ORDER_INTERVAL_VAR',\n 'ORDER_INTERVAL_TOP',\n 'ORDER_HISTORY',\n 'UNIT_CONSUME_INTERVAL_MEAN',\n 'UNIT_CONSUME_INTERVAL_VAR',\n 'UNIT_CONSUME_INTERVAL_TOP',\n 'UNIT_CONSUME_HISTORY']\nfeature_b = ['ID',\n 'RECHARGE_AMOUNT_SUM',\n 'CONSUME_AMOUNT_SUM',\n 'AMOUNT_OUT_V_IN',\n 'AMOUNT_END_MINUS_IN',\n 'CURRENT_BALANCE_SUM',\n 'RETURN_AMOUNT_SUM',\n 'CONSUME_AMOUNT_BY_VIP_MEAN',\n 'CONSUME_AMOUNT_BY_VIP_VAR',\n 'CONSUME_AMOUNT_BY_VIP_TOP',\n 'IF_WITHDRAW_SUM'\n ]\n\n\n\n","sub_path":"TEST/PUnit.py","file_name":"PUnit.py","file_ext":"py","file_size_in_byte":17523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"279329886","text":"import numpy as np\nfrom skimage.graph import MCP\nfrom scipy.spatial.distance import cityblock\nimport traitlets\n\nDUNGEON = [] # will eventually store the dungeon as numpy array\n\n\nclass Unit(traitlets.HasTraits):\n \"\"\"\n A generic class to represent units in the dungeon.\n\n Eeally the only difference is what side the units take, so (just about)\n everything can be defined here.\n \"\"\"\n\n attack_power = traitlets.Integer(default_value=3)\n hit_points = traitlets.Integer(default_value=200)\n\n location = traitlets.Tuple(traitlets.Integer(), traitlets.Integer()) # y, x\n\n dead = traitlets.Bool(default_value=False)\n\n members = [] # here to store class instances\n opponents = traitlets.Type('__main__.Unit')\n\n def __new__(cls, *args, **kwargs):\n instance = super().__new__(cls, *args, **kwargs)\n cls.members.append(instance)\n return instance\n\n def attack(self, other):\n other.hit_points -= self.attack_power\n if other.hit_points <= 0:\n other.dead = True\n self.opponents.members.remove(other)\n\n def distance(self, other):\n return cityblock(self.location, other.location)\n\n @property\n def target(self):\n \"\"\"\n Find the nearest target for attack assuming one is available.\n\n :rtype: Unit\n \"\"\"\n opponent_distances = [\n self.distance(foe)\n for foe in self.opponents.members\n ]\n potential_targets = [\n foe\n for foe, distance\n in zip(self.opponents.members, opponent_distances)\n if distance == 1\n ]\n if not potential_targets:\n return None\n elif len(potential_targets) == 1:\n return potential_targets[0]\n else:\n return sorted(\n potential_targets,\n key = lambda u: (u.hit_points, *u.location)\n )[0]\n\n def move(self):\n \"\"\"\n Move the current unit to the closest valid target\n\n Use a minimum cost path through the grid, after removing path through\n allies spaces (you can ignore blocking out enemies because if a path\n would go through an enemy it's going to end up closer).\n\n :rtype: None\n \"\"\"\n # first, block out your buddies\n current_dungeon = DUNGEON.copy()\n\n allies = np.array([\n friend.location for friend in self.members\n if friend is not self\n ])\n\n if allies.size: # assuming there are any allies left\n # locations are stored as y, x, so:\n current_dungeon[allies[:, 0], allies[:, 1]] = -1\n\n foe_locations = np.array([\n foe.location\n for foe in self.opponents.members\n ])\n\n # and now find the costs\n mcp = MCP(current_dungeon, fully_connected=False)\n cum_costs, traceback = mcp.find_costs(\n starts=[self.location],\n find_all_ends=True\n )\n\n foe_distances = cum_costs[\n foe_locations[:, 0], foe_locations[:, 1]\n ]\n if np.isinf(foe_distances.min()):\n return # no route available to any foe\n closest_foes = np.arange(len(foe_distances))[foe_distances == foe_distances.min()]\n closest_foe = sorted(\n self.opponents.members[i] for i in\n closest_foes\n )[0]\n\n # now you have one closest foe, reverse the distance calc\n # and move one step closer\n\n mcp = MCP(current_dungeon, fully_connected=False)\n cum_costs, traceback = mcp.find_costs(\n ends=[self.location],\n starts=[closest_foe.location],\n find_all_ends=False\n )\n\n # the minimum foe distance will be the location of self, so decrease\n # by one\n target_locations = np.argwhere(cum_costs == foe_distances.min() - 1)\n\n # the MCP algorithm will expand out in many directions, so make sure\n # to filter out only those points around self.\n valid_locations = target_locations[(\n (target_locations >= np.array(self.location) - 1) &\n (target_locations <= np.array(self.location) + 1)\n ).all(axis=1)]\n\n # this is _ugly_, but I couldn't quickly think of a better way to sort\n # the locations\n y, x = (sorted(tuple(coords) for coords in valid_locations))[0]\n self.location = (int(y), int(x))\n\n # define comparison methods for sorting:\n def __eq__(self, other):\n return self.location == other.location\n\n def __lt__(self, other):\n return self.location < other.location\n\n def __gt__(self, other):\n return self.location == other.location\n\n def __repr__(self):\n \"\"\"Nice string representation\"\"\"\n return f'<{self.__class__.__name__} ap{self.attack_power} hp{self.hit_points} loc{self.location}>'\n\n # define add and radd so you can easily sum the list of units\n def __add__(self, other):\n return self.hit_points + other.hit_points\n\n def __radd__(self, other):\n return self.hit_points + other\n\n\nclass Goblin(Unit):\n \"\"\"A Goblin, sworn enemy of the Christmas Elf\"\"\"\n\n members = []\n # note that using the traitlets type we can defer the dependency on the\n # Elf class until the opponents attribute is accessed\n opponents = traitlets.Type('__main__.Elf')\n\nclass Elf(Unit):\n \"\"\"A Christmas Elf\"\"\"\n\n members = []\n # likewise access to the Goblins is deferred until required.\n opponents = traitlets.Type('__main__.Goblin')\n\nap = 3 # Elves start with 3 attack points, like goblins\nwhile True:\n\n # yes, I could change this so that I only created the dungeon object once\n # but really, I figured it would be easier this way\n DUNGEON = []\n Goblin.members.clear() # make sure the victors are still removed\n Elf.members.clear()\n\n # create the dungeon from the input file\n for y, line in enumerate(open('input.txt')):\n\n row = []\n for x, square in enumerate(line.rstrip('\\n')):\n if square == '#':\n row.append(-1)\n else:\n row.append(1)\n if square == 'G':\n Goblin(location=(y, x)) # creating a goblins adds it to the Goblin members\n elif square == 'E':\n # likewise the elves\n Elf(location=(y, x), attack_power=ap)\n DUNGEON.append(row)\n\n DUNGEON = np.array(DUNGEON)\n\n num_elves = len(Elf.members) # ensure that no elf dies\n counter = 0\n while Elf.members and Goblin.members:\n for unit in sorted(Goblin.members + Elf.members):\n if not unit.opponents.members or not unit.members:\n break\n if unit.dead:\n continue\n target = unit.target\n\n if not target:\n unit.move()\n target = unit.target\n\n if target:\n unit.attack(target)\n\n if not unit.opponents.members:\n break\n else:\n counter += 1\n\n if num_elves == len(Elf.members):\n # victory for the elves!\n break\n elif ap == 3:\n print(counter, 'turns')\n print('Solution 1', (counter) * sum(Elf.members + Goblin.members))\n ap += 1\n\nprint(ap, 'AP')\nprint(counter, 'turns')\nprint('Solution 2', (counter) * sum(Elf.members + Goblin.members))","sub_path":"2018/day15/solution_combined.py","file_name":"solution_combined.py","file_ext":"py","file_size_in_byte":7392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"509327475","text":"##\n## Imprima una tabla en formato CSV que contenga por registro,\n## la cantidad de elementos de las columnas 4 y 5\n## (filas en el archivo)\n##\n## E,3,5\n## A,3,4\n## B,4,4\n## ...\n## C,4,3\n## E,2,3\n## E,3,3\n##\na=open('data.csv').readlines()\nb =[row[0:-1] for row in a]\naa=[row[0] for row in a]\n\n\nii=0\nfor i in b:\n bb=i.split('\\t')\n ii=0\n for j in bb:\n if ii==0:\n pri=j\n if ii==3:\n se=len(j)\n bbb=j.replace(',','')\n se=(len(bbb))\n if ii==4:\n bbb=j.split(',')\n tr=(len(bbb))\n\n ii=ii+1\n print(pri+','+str(se)+','+str(tr))\n","sub_path":"q11.py","file_name":"q11.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"617142028","text":"from django import forms\nfrom campaign.models import Category, Campaign, CampaignProposals, CampaignPost, CampaignComments\nfrom datetime import datetime\nfrom django.core.validators import RegexValidator\nfrom tinymce.widgets import TinyMCE\nfrom django.utils.translation import ugettext_lazy as _\nfrom taggit.forms import *\nfrom register.commons import WydlWrapper\nfrom django.core.validators import ValidationError\nimport re\n\nclass CategoryForm(forms.ModelForm):\n class Meta:\n model = Category\n fields = ['name',]\n\nclass CampaignForm(forms.ModelForm):\n\n T_CHOICES = (\n ('Timed', 'Timed'),\n ('Ongoing', 'Ongoing')\n )\n LIVE_CHOICES = (\n ('Live', 'Live'),\n ('Draft', 'Draft')\n )\n\n title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}), max_length=255, error_messages={'required': 'Please enter title'})\n description = forms.CharField(required=True, widget=TinyMCE, error_messages={'required': 'Description is required.'})\n timebased_type = forms.ChoiceField(choices=T_CHOICES)\n goal_of_campaign = forms.IntegerField(required=False)\n live = forms.ChoiceField(choices=LIVE_CHOICES)\n category_filed = forms.ChoiceField(choices=[])\n city = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}), max_length=255, error_messages={'required': 'Please enter city name'})\n state = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}), max_length=255, error_messages={'required': 'Please enter state name'})\n zip = forms.CharField(validators=[RegexValidator(\n regex=r'^(^[0-9]{5}(?:-[0-9]{4})?$|^$)',\n message=_(u'Must be valid zipcode in formats 12345 or 12345-1234'),\n )], error_messages={'required': 'Please enter zip code'})\n\n m_tags = TagField(help_text='A comma-separated list of tags')\n\n def __init__(self, *args, **kwargs):\n super(CampaignForm, self).__init__(*args, **kwargs)\n choices = [(c.pk, c.name) for c in Category.objects.all()]\n self.fields['category_filed'].choices = choices\n\n\n\n # def __init__(self, *args, **kwargs):\n # super(CampaignForm, self).__init__(*args, **kwargs)\n # choices = [(c.pk, c.name) for c in Category.objects.all()]\n # self.fields['category_filed'].choices = choices\n\n def clean_title(self):\n cleaned_data = super(CampaignForm, self).clean()\n title = cleaned_data.get(\"title\")\n\n reg = re.compile('^[a-zA-Z0-9 ]+$')\n if not reg.match(title):\n raise ValidationError(\"Enter title without special character\")\n\n wdyl = WydlWrapper()\n if wdyl.get({'q':self.cleaned_data['title']})['response'] == 'true':\n raise ValidationError(wdyl.get_error_message())\n return title\n\n class Meta:\n model = Campaign\n fields = ['title', 'description', 'timebased_type', 'live', 'category_filed', 'start_date', 'end_date', ]\n\nclass ProposalForm(forms.ModelForm):\n\n title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}), required=True, max_length=50, error_messages={'required': 'Title is required.'})\n description = forms.CharField(required=True, widget=TinyMCE, error_messages={'required': 'Description is required.'})\n amount = forms.IntegerField(required=True, error_messages={'required': 'Amount is required.'})\n\n def clean_title(self):\n cleaned_data = super(ProposalForm, self).clean()\n title = cleaned_data.get(\"title\")\n\n reg = re.compile('^[a-zA-Z0-9 ]+$')\n if not reg.match(title):\n raise ValidationError(\"Enter proposla title without special character\")\n\n wdyl = WydlWrapper()\n if wdyl.get({'q':self.cleaned_data['title']})['response'] == 'true':\n raise ValidationError(wdyl.get_error_message())\n return title\n\n class Meta:\n model = CampaignProposals\n fields = ['title', 'description', 'amount', ]\n\nclass CampaignPostForm(forms.ModelForm):\n\n # message = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control'}), required=True, max_length=255, error_messages={'required': 'Please enter message.'})\n\n class Meta:\n model = CampaignPost\n fields = ['message', ]\n\nclass PaymentForm(forms.Form):\n\n name = forms.CharField(label=\"Name:\", widget=forms.TextInput(attrs={'class': 'form-control'}), required=True,\n validators=[\n RegexValidator(\n regex='^[a-zA-Z0-9 ]+$',\n message='Enter name without special character',\n code='invalid_name'\n ),])\n amount = forms.CharField(label=\"Amount:\", widget=forms.TextInput(attrs={'class': 'form-control', 'readonly': 'readonly'}), required=False)\n today = datetime.now().date()\n MONTH_CHOICES = [\n ('1', '01 - January'),\n ('2', '02 - February'),\n ('3', '03 - March'),\n ('4', '04 - April'),\n ('5', '05 - May'),\n ('6', '06 - June'),\n ('7', '07 - July'),\n ('8', '08 - August'),\n ('9', '09 - September'),\n ('10', '10 - October'),\n ('11', '11 - November'),\n ('12', '12 - December'),\n ]\n YEAR_CHOICES = [(y, y) for y in range(today.year, today.year + 21)]\n number = forms.CharField(max_length=255, label='Number:', widget=forms.TextInput(attrs={'class': 'form-control',}), error_messages={'required': 'Please Provide Proper Number without any dash/\"-\"', 'invalid': 'Please Enter Card Number without Spaces and Dashes'},\n validators=[\n RegexValidator(\n regex='^[0-9]',\n message='Only number are allowed',\n code='invalid_number'\n ),])\n expiry = forms.CharField(max_length=255,error_messages={'required': 'Enter verification Code','invalid': \"Please Enter verification Number Only\"},widget=forms.TextInput(attrs={'class':'form-control',}) , required=True)\n\n cvc = forms.IntegerField(error_messages={'required': 'Enter verification Code','invalid': \"Please Enter verification Number Only\"},widget=forms.TextInput(attrs={'class':'form-control','type':'number'}) , required=True)\n\n\n\n\nclass CommentForm(forms.ModelForm):\n message = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control'}), required=True, max_length=255, error_messages={'required': 'Please enter message.'})\n class Meta:\n model = CampaignComments\n fields = ['message', ]","sub_path":"campaign/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":6671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"296698745","text":"from rest_framework import serializers\nfrom apps.warehouse.models.biscuit import WareHouseBiscuit\nfrom api.biscuit.serializers.biscuit import BiscuitModelSerializer\n\n\nclass WareHouseBiscuitCreateModelSerializer(serializers.ModelSerializer):\n class Meta:\n model = WareHouseBiscuit\n fields = [\n 'biscuit'\n ]\n\n def run_validators(self, value):\n for validator in self.validators:\n if isinstance(validator, validators.UniqueTogetherValidator):\n self.validators.remove(validator)\n super(WareHouseBiscuitCreateModelSerializer, self).run_validators(value)\n\n def create(self, validated_data):\n biscuit = validated_data.pop('biscuit')\n biscuit, _ = WareHouseBiscuit.objects.get_or_create(\n biscuit=biscuit, **validated_data)\n return biscuit\n\n\nclass WareHouseBiscuitDetailModelSerializer(serializers.ModelSerializer):\n biscuit = BiscuitModelSerializer(read_only=True, many=False)\n\n class Meta:\n model = WareHouseBiscuit\n fields = [\n 'biscuit',\n 'quantity',\n 'total_price',\n 'average_price',\n 'unit_of_measurement',\n 'currency',\n 'created_date'\n ]","sub_path":"api/warehouse/serializers/biscuit.py","file_name":"biscuit.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"554659672","text":"from oeda.rtxlib.analysischannels.AnalysisStrategy import AnalysisStrategy\n\n\nclass AnalysisStrategySnapshot(AnalysisStrategy):\n\n def _parse_intermediate_result(self, wf, data):\n self.parse_final_result(wf, data)\n\n def parse_final_result(self, wf, data):\n algorithm_name = data['name']\n results = data['results']\n media_type = results['media_type']\n\n file_name = algorithm_name + \"_\" + wf.id + \".png\"\n contour_plot = results.pop(\"contour_plot\", None)\n\n self.store_image(experiment_id=wf.id, image_name=file_name, image_format=media_type, contour_plot=contour_plot)\n results[\"local_image\"] = file_name\n\n self.store_database(experiment_id=wf.id, algorithm_name=algorithm_name, results=results)\n\n","sub_path":"Backend/oeda/rtxlib/analysischannels/AnalyisStrategySnapshot.py","file_name":"AnalyisStrategySnapshot.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"567493900","text":"import random\nimport typing\nimport json\n\nimport httpcore\nimport httpx\nfrom httpx import Timeout\n\nfrom googleparser import urls, utils\nfrom googleparser.gtoken import TokenAcquirer\nfrom googleparser.constants import (\n DEFAULT_CLIENT_SERVICE_URLS,\n DEFAULT_FALLBACK_SERVICE_URLS,\n DEFAULT_USER_AGENT, LANGCODES, LANGUAGES, SPECIAL_CASES,\n DEFAULT_RAISE_EXCEPTION, DUMMY_DATA\n)\nfrom googleparser.models import Translated, Detected, TranslatedPart\n\nEXCLUDES = ('en', 'ca', 'fr')\n\nRPC_ID = 'MkEWBc'\n\n\nclass Translator:\n \"\"\"\n General class to represent translations\n Attributes\n ----------\n client : httpx.Client\n client to communicate with Google Translate\n service_urls : List[str]\n list of urls to make requests to\n raise_exception : bool\n raise exception flag\n client_type : str\n determines the way of parsing\n token_acquirer : TokenAcquirer\n generates token for parsing\n \"\"\"\n\n def __init__(self, service_urls=DEFAULT_CLIENT_SERVICE_URLS, user_agent=DEFAULT_USER_AGENT,\n raise_exception=DEFAULT_RAISE_EXCEPTION,\n proxies: typing.Dict[str, httpcore.SyncHTTPTransport] = None,\n timeout: Timeout = None,\n http2=True,\n use_fallback=False):\n\n self.client = httpx.Client(http2=http2)\n if proxies is not None: # pragma: nocover\n self.client.proxies = proxies\n\n self.client.headers.update({\n 'User-Agent': user_agent,\n #'Referer': 'https://translate.google.com',\n })\n\n if timeout is not None:\n self.client.timeout = timeout\n\n if use_fallback:\n self.service_urls = DEFAULT_FALLBACK_SERVICE_URLS\n self.client_type = 'gtx'\n pass\n else:\n #default way of working: use the defined values from user app\n self.service_urls = service_urls\n self.client_type = 'tw-ob'\n self.token_acquirer = TokenAcquirer(\n client=self.client, host=self.service_urls[0])\n\n self.raise_exception = raise_exception\n\n def _build_rpc_request(self, text: str, dest: str, src: str):\n return json.dumps([[\n [\n RPC_ID,\n json.dumps([[text, src, dest, True], [None]], separators=(',', ':')),\n None,\n 'generic',\n ],\n ]], separators=(',', ':'))\n\n def _pick_service_url(self):\n if len(self.service_urls) == 1:\n return self.service_urls[0]\n return random.choice(self.service_urls)\n\n def _translate(self, text: str, dest: str, src: str):\n url = urls.TRANSLATE_RPC.format(host=self._pick_service_url())\n data = {\n 'f.req': self._build_rpc_request(text, dest, src),\n }\n params = {\n 'rpcids': RPC_ID,\n 'bl': 'boq_translate-webserver_20201207.13_p0',\n 'soc-app': 1,\n 'soc-platform': 1,\n 'soc-device': 1,\n 'rt': 'c',\n }\n r = self.client.post(url, params=params, data=data)\n if r.status_code != 200 and self.raise_exception:\n raise Exception('Unexpected status code \"{}\" from {}'.format(\n r.status_code, self.service_urls))\n\n return r.text, r\n\n def _translate_legacy(self, text, dest, src, override):\n token = '' #dummy default value here as it is not used by api client\n if self.client_type == 'webapp':\n token = self.token_acquirer.do(text)\n\n params = utils.build_params(client=self.client_type, query=text, src=src, dest=dest,\n token=token, override=override)\n\n url = urls.TRANSLATE.format(host=self._pick_service_url())\n r = self.client.get(url, params=params)\n\n if r.status_code == 200:\n data = utils.format_json(r.text)\n return data, r\n\n if self.raise_exception:\n raise Exception('Unexpected status code \"{}\" from {}'.format(\n r.status_code, self.service_urls))\n\n DUMMY_DATA[0][0][0] = text\n return DUMMY_DATA, r\n\n def _parse_extra_data(self, data):\n response_parts_name_mapping = {\n 0: 'translation',\n 1: 'all-translations',\n 2: 'original-language',\n 5: 'possible-translations',\n 6: 'confidence',\n 7: 'possible-mistakes',\n 8: 'language',\n 11: 'synonyms',\n 12: 'definitions',\n 13: 'examples',\n 14: 'see-also',\n }\n\n extra = {}\n\n for index, category in response_parts_name_mapping.items():\n extra[category] = data[index] if (\n index < len(data) and data[index]) else None\n\n return extra\n\n def translate(self, text: str, dest='en', src='auto'):\n \"\"\"Translate text from source language to destination language\n Parameters\n ----------\n text : str, str sequence\n The source text(s) to be translated. Batch translation is supported via sequence input.\n dest : str\n The language to translate the source text into.\n The value should be one of the language codes listed in `googleparser.LANGUAGES`\n or in `googleparser.LANGCODES`.\n src: str\n The language of the source text.\n The value should be one of the language codes listed in `googleparser.LANGUAGES`\n or in `googleparser.LANGCODES`.\n If a language is not specified,\n the system will attempt to identify the source language automatically.\n Returns\n -------\n Translated\n Translated object with translation info\n \"\"\"\n\n dest = dest.lower().split('_', 1)[0]\n src = src.lower().split('_', 1)[0]\n\n if src != 'auto' and src not in LANGUAGES:\n if src in SPECIAL_CASES:\n src = SPECIAL_CASES[src]\n elif src in LANGCODES:\n src = LANGCODES[src]\n else:\n raise ValueError('invalid source language')\n\n if dest not in LANGUAGES:\n if dest in SPECIAL_CASES:\n dest = SPECIAL_CASES[dest]\n elif dest in LANGCODES:\n dest = LANGCODES[dest]\n else:\n raise ValueError('invalid destination language')\n\n origin = text\n data, response = self._translate(text, dest, src)\n\n token_found = False\n square_bracket_counts = [0, 0]\n resp = ''\n\n for line in data.split('\\n'):\n token_found = token_found or f'\"{RPC_ID}\"' in line[:30]\n if not token_found:\n continue\n\n is_in_string = False\n for index, char in enumerate(line):\n if char == '\\\"' and line[max(0, index - 1)] != '\\\\':\n is_in_string = not is_in_string\n if not is_in_string:\n if char == '[':\n square_bracket_counts[0] += 1\n elif char == ']':\n square_bracket_counts[1] += 1\n\n resp += line\n if square_bracket_counts[0] == square_bracket_counts[1]:\n break\n data = json.loads(resp)\n parsed = json.loads(data[0][2])\n # not sure\n\n try:\n translated_parts = list(\n map(lambda part: TranslatedPart(part[0], part[1] if len(part) >= 2 else []), parsed[1][0][0][5]))\n except IndexError as e:\n translated_parts = list(map(lambda part: TranslatedPart(part[0], part[1] if len(part) >= 2 else []),\n [[parsed[1][0][0][0], [parsed[1][0][0][0]]]]))\n\n translated = ''.join(\n map(lambda part: part.text if part.text[-1] == ' ' else part.text + ' ', translated_parts))[:-1]\n\n if src == 'auto':\n try:\n src = parsed[2]\n except:\n pass\n if src == 'auto':\n try:\n src = parsed[0][2]\n except:\n pass\n\n # currently not available\n confidence = None\n\n origin_pronunciation = None\n try:\n origin_pronunciation = parsed[0][0]\n except:\n pass\n\n pronunciation = None\n try:\n pronunciation = parsed[1][0][0][1]\n except:\n pass\n\n extra_data = {\n 'confidence': confidence,\n 'parts': translated_parts,\n 'origin_pronunciation': origin_pronunciation,\n 'parsed': parsed,\n }\n result = Translated(src=src, dest=dest, origin=origin,\n text=translated, pronunciation=pronunciation,\n parts=translated_parts,\n extra_data=extra_data,\n response=response)\n return result\n\n def translate_legacy(self, text, dest='en', src='auto', **kwargs):\n dest = dest.lower().split('_', 1)[0]\n src = src.lower().split('_', 1)[0]\n\n if src != 'auto' and src not in LANGUAGES:\n if src in SPECIAL_CASES:\n src = SPECIAL_CASES[src]\n elif src in LANGCODES:\n src = LANGCODES[src]\n else:\n raise ValueError('invalid source language')\n\n if dest not in LANGUAGES:\n if dest in SPECIAL_CASES:\n dest = SPECIAL_CASES[dest]\n elif dest in LANGCODES:\n dest = LANGCODES[dest]\n else:\n raise ValueError('invalid destination language')\n\n if isinstance(text, list):\n result = []\n for item in text:\n translated = self.translate_legacy(item, dest=dest, src=src, **kwargs)\n result.append(translated)\n return result\n\n origin = text\n data, response = self.translate_legacy(text, dest, src)\n\n # this code will be updated when the format is changed.\n translated = ''.join([d[0] if d[0] else '' for d in data[0]])\n\n extra_data = self._parse_extra_data(data)\n\n # actual source language that will be recognized by Google Translator when the\n # src passed is equal to auto.\n try:\n src = data[2]\n except Exception: # pragma: nocover\n pass\n\n pron = origin\n try:\n pron = data[0][1][-2]\n except Exception: # pragma: nocover\n pass\n\n if pron is None:\n try:\n pron = data[0][1][2]\n except: # pragma: nocover\n pass\n\n if dest in EXCLUDES and pron == origin:\n pron = translated\n\n # put final values into a new Translated object\n result = Translated(src=src, dest=dest, origin=origin,\n text=translated, pronunciation=pron,\n extra_data=extra_data,\n response=response)\n\n return result\n\n def detect(self, text: str):\n \"\"\"Detect language of the input text\n Parameters\n ----------\n text : str, str sequence\n The source text(s) whose language you want to identify.\n Returns\n -------\n Detected\n Detected object with detection info\n \"\"\"\n\n translated = self.translate(text, src='auto', dest='en')\n result = Detected(lang=translated.src, confidence=translated.extra_data.get('confidence', None), response=translated._response)\n return result\n\n def detect_legacy(self, text, **kwargs):\n\n if isinstance(text, list):\n result = []\n for item in text:\n lang = self.detect(item)\n result.append(lang)\n return result\n\n data, response = self._translate_legacy(text, 'en', 'auto', kwargs)\n\n # actual source language that will be recognized by Google Translator when the\n # src passed is equal to auto.\n src = ''\n confidence = 0.0\n try:\n if len(data[8][0]) > 1:\n src = data[8][0]\n confidence = data[8][-2]\n else:\n src = ''.join(data[8][0])\n confidence = data[8][-2][0]\n except Exception: # pragma: nocover\n pass\n result = Detected(lang=src, confidence=confidence, response=response)\n\n return result\n\n def translate_secure(self, text, retries=3):\n \"\"\" Securely translate text from source language to destination language\n Parameters\n ----------\n text : str, str sequence\n The source text(s) to be translated. Batch translation is supported via sequence input.\n retries : int\n number of retries to make request again\n Returns\n -------\n dict\n dictionary with 'text' - translated text and 'src' - source language\n \"\"\"\n\n if not text:\n return {'text': '', 'src': ''}\n title_trans = ''\n for _ in range(retries):\n try:\n title_trans = self.translate(text[:5000], dest='en')\n break\n except Exception as error:\n # empty responses restart session\n self._reset()\n else:\n title_trans = Translated(src='', dest='', origin='',\n text='', pronunciation='',\n extra_data='',\n response='', parts=[])\n\n title_trans, title_lang = title_trans.text, title_trans.src\n\n for chunk in range(1, len(text) // 5000 + 1):\n for _ in range(retries):\n try:\n title_trans += self.translate(text[chunk * 5000:5000 * (chunk + 1)], dest='en')['text']\n break\n except Exception as error:\n # empty responses restart session\n self._reset() # TODO REINIT\n else:\n return {'text': '', 'src': ''}\n return {'text': title_trans, 'src': title_lang}\n\n def _reset(self):\n self.client = httpx.Client(http2=True)\n\n self.token_acquirer = TokenAcquirer(client=self.client, host=self.service_urls[0])\n","sub_path":"googleparser/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":14412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"629047569","text":"# -*- coding: utf-8 -*-\nimport sys, os\nsys.path.append(\"/home/zhangweibin/api_auto\")\nprint(sys.path)\n\nimport json\nimport unittest\nfrom public.Log_method import Logger\nfrom public.operation_Excel import OperExcel\nfrom public.reque import RunMethod\nfrom ddt import ddt, data, unpack\n\n\nloger = Logger(\"RunCase\", file_dir=\"/home/zhangweibin/api_auto/data/test.log\")\ntestdatas = OperExcel(filename=\"/home/zhangweibin/api_auto/data/testcase1.xlsx\").read()\n\n\n@ddt\nclass TestMethod(unittest.TestCase):\n \"\"\"异常用例\"\"\"\n\n def setUp(self):\n # 设置全局变量,供其他用例使用,字典储存\n self.g = globals()\n print(\"start\")\n\n def tearDown(self):\n print(\"end\")\n\n @data(*testdatas)\n @unpack\n def test_01(self, method, url, data, headers, expect_result, case_name):\n run = RunMethod()\n run_res = run.run_test(method=method, url=url,\n data=eval(data), headers=json.loads(headers))\n \n run_res = json.loads(run_res)\n print(run_res)\n\n expec = expect_result.split(\"=\", 1)[1]\n if run_res[\"msg\"] in(\"pika登录认证服务器不可用\", \"业务流79不存在\"):\n loger.debug(\"其他异常%s,算通过\" % run_res)\n return\n else:\n self.assertEqual(str(run_res[\"code\"]), expec, \"reality return%s\" % run_res)\n\nif __name__ == '__main__':\n unittest.main()\n\n\n\n\n\n","sub_path":"api_pika/test_case/testcase1.py","file_name":"testcase1.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"613565712","text":"import psycopg2,csv\nfrom numpy import *\nimport pandas as pd\n\n\n#Establishing the connection\nconn = psycopg2.connect(\n database=\"Sose2020-mobi-mobility\", user='student', password='mobi-project2020', host='141.13.162.166', port= '5432'\n)\n\nconn.autocommit = True\ncursor = conn.cursor()\n\nwith open('indoor_data_groundtruth.csv', newline='') as myFile:\n readerp = csv.reader(myFile)\n csv_data = list(readerp)[1:]\nfor row in csv_data:\n \n aa=int(row[0])\n bb=pd.to_datetime(row[1] + ' ' + row[2])\n cc=pd.to_datetime(row[1] + ' ' + row[3])\n dd=row[4]\n ee=double(row[5])\n ff = double(row[6])\n \n cursor.execute(\"INSERT INTO public.indoor_groundtruth(userid,starttime,endtime,label,posx,posy) VALUES (%s,%s,%s,%s,%s,%s)\", (aa,bb,cc,dd,ee,ff))\n\nconn.commit()\n \n\n\n\n\n# Commit your changes in the database\n\nprint(\"Records inserted groundt truth........\")\n\n# Closing the connect\n\n\n\n\n\n\n\n","sub_path":"Trajectory data analysis project/implementation/Insert_Indoor_Groundtruth_code_task4.py","file_name":"Insert_Indoor_Groundtruth_code_task4.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"10634463","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\n\n\nPATH = os.path.dirname(os.path.abspath(__file__))\nIDXS = [5, 10, 15, 20, 25, 30]\n\n\ndef run(jar, mode):\n for idx in IDXS:\n path = '{}/{}/{}_neighbors'.format(PATH, mode, idx)\n for ff in os.listdir(path):\n command = 'java -Xmx25000m -jar {} --run {}'.format(\n jar,\n path + '/' + ff\n )\n os.system(command)\n #print(command)\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n raise Exception('Missing {jar file} as parameter')\n\n jar = str(sys.argv[1])\n\n run(jar, 'original')\n run(jar, 'prediction')\n","sub_path":"app/generators/execute_eval.py","file_name":"execute_eval.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"532569426","text":"\"\"\"\r\nKrishna Bhattarai\r\nCSE 4391\r\nThe university of texas at Arlington\r\nJanuary 31, 2016\r\n\"\"\"\r\nimport itertools\r\n\r\n\r\n\"\"\"\r\nThis method assumes that the file has vertices and faces only nothing else\r\n\"\"\"\r\ndef load_txt(file_name):\r\n mode = \"r\"\r\n file_pointer = open(file_name, mode)\r\n data = file_pointer.readlines()\r\n file_pointer.close()\r\n\r\n vertices = []\r\n faces = []\r\n for each_line in data:\r\n if each_line[0] == \"v\":\r\n # print(each_line)\r\n vertex_tokens =each_line.strip().split()\r\n\r\n x, y, z = float(vertex_tokens[1]), float(vertex_tokens[2]), float(vertex_tokens[3])\r\n vertices.append([x, y, z])\r\n if each_line[0] == \"f\":\r\n face_tokens = each_line.strip().split()\r\n k, l, m = int(face_tokens[1])-1, int(face_tokens[2])-1, int(face_tokens[3])-1\r\n faces.append([k, l, m])\r\n\r\n VERTICES = list(itertools.chain(*vertices))\r\n FACES = list(itertools.chain(*faces))\r\n print(\"var vertices =\", VERTICES, \";\")\r\n # print(len(VERTICES))\r\n print(\"var faces = \",FACES, \";\")\r\n # print(len(FACES))\r\n\r\n\"\"\"\r\nThis method assumes that ply only has vertices and faces\r\nnormals or colors are not accounted for\r\n\"\"\"\r\ndef load_ply(file_name):\r\n with open(file_name) as fp:\r\n data = fp.readlines()[10:]\r\n\r\n vertices = []\r\n faces = []\r\n for each_line in data:\r\n tokens = each_line.strip().split()\r\n # print(tokens)\r\n\r\n # assume that faces start with '3' meaning that there are 3 faces in each line\r\n\r\n if tokens[0] == \"3\" and len(tokens) == 4:\r\n k, l, m = int(tokens[1]), int(tokens[2]), int(tokens[3])\r\n faces.append([k, l, m])\r\n else:\r\n\r\n x, y, z = float(tokens[0]), float(tokens[1]), float(tokens[2])\r\n vertices.append([x, y, z])\r\n\r\n VERTICES = list(itertools.chain(*vertices))\r\n FACES = list(itertools.chain(*faces))\r\n\r\n\r\n\r\n print(VERTICES, \";\")\r\n print(len(VERTICES))\r\n print(FACES, \";\")\r\n print(len(FACES))\r\n\r\n# Name of the txt files\r\n# file_name = \"pyramid.txt\"\r\n# file_name = \"cow.txt\"\r\n# file_name = \"bunny.txt\"\r\n# file_name = \"teapot.txt\"\r\n# load_txt(file_name)\r\n\r\n# Name of the ply files\r\n\r\n# file_name = \"weathervane.ply\"\r\n# file_name = \"ant.ply\"\r\n# file_name = \"apple.ply\"\r\n# file_name = \"beethoven.txt\"\r\n# file_name = \"dragon.ply\"\r\n# file_name = \"big_dodge.ply\"\r\n# file_name = \"big_porsche.ply\"\r\n# file_name = \"big_spider.ply\"\r\n# file_name = \"canstick.ply\"\r\n# file_name = \"chopper.ply\"\r\n# file_name = \"dolphins.ply\"\r\n# file_name = \"pickup_big.ply\"\r\n# file_name = \"head1.ply\"\r\n# load_ply(file_name)\r\n","sub_path":"resources/WebGL/scripts/data_parser.py","file_name":"data_parser.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"188615989","text":"import psycopg2\nimport json\nimport datetime\n\ndef get_connection():\n try:\n cnx = psycopg2.connect(host=\"localhost\", database=\"c4f00g03\", user=\"c4f00g03\", password=\"j4g6x7b3\")\n return cnx\n except psycopg2.OperationalError as err:\n print(json.dumps(\"check DB connection\"))\n if cnx is not None:\n cnx.close()\n quit() \n\n# execute query, format response into an array of dictionaries\ndef exec_and_parse(cursor, cnx, query):\n\tout = []\n\ttry:\n\t\tcursor.execute(query)\n\t\tcnx.commit()\n\texcept psycopg2.Error as err:\n\t\tprint(err)\n\t\treturn(False, out)\n\tif not cursor.description:\n\t\tif cursor.rowcount > 0:\n\t\t\treturn(True, out)\n\t\telse:\n\t\t\treturn(False, out)\n\twhile True:\n\t\trow = cursor.fetchone()\n\t\tif not row:\n\t\t\tbreak\n\t\ttmp = {}\n\t\tfor (desc, val) in zip(cursor.description, row):\n\t\t\tif isinstance(val, datetime.datetime):\n\t\t\t\tval = str(val)\n\t\t\ttmp[desc[0]] = val\n\t\tout.append(tmp)\n\treturn(True, out)\n\n","sub_path":"webportal/React UI bb/MySQL/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"572996169","text":"#!/usr/bin/env python3\nimport time\nfrom testflows.core import *\n\npool = Pool(3)\n\n\n@TestScenario\ndef subtest(self):\n with Step(\"step\"):\n time.sleep(1)\n\n\n@TestScenario\ndef test1(self):\n with Step(\"step\"):\n note(f\"{self.name} note1\")\n pool.submit(Scenario(test=subtest)).result()\n\n # if self.name.endswith(\"test1\"):\n # fail(f\"{self.name} failed\")\n\n\n@TestScenario\n@Parallel(True)\n@Executor(pool)\ndef ptest(self):\n note(\"parallel test\")\n time.sleep(1)\n note(\"parallel test done\")\n fail(f\"{self.name} failed\")\n\n\n@TestScenario\ndef ptest2(self):\n note(\"parallel test\")\n try:\n try:\n for i in range(10):\n with Step(\"step\"):\n time.sleep(0.1)\n finally:\n note(\"tryin to cleanup\")\n with Given(\"I try to do some setup\"):\n pass\n finally:\n with Finally(\"clean up\"):\n note(f\"{self.name} clean up\")\n note(\"parallel test done\")\n\n\n@TestScenario\ndef ptest3(self):\n fail(\"failed\")\n\n\n@TestSuite\ndef suite(self):\n self.executor = Pool(3)\n\n tasks = []\n with pool:\n\n for i in range(3):\n tasks.append(Scenario(name=f\"ptest2-{i}\", run=ptest2, parallel=True))\n tasks.append(Scenario(run=ptest3, parallel=True))\n\n join(*tasks)\n\n\nif main():\n suite()\n","sub_path":"tests/parallel.py","file_name":"parallel.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"156373104","text":"\nfrom LinkedStack import LinkedStack\n\n\n#/* *** ODSATag: TOH *** */\n# Compute the moves to solve a Tower of Hanoi puzzle.\n# Function move does (or prints) the actual move of a disk\n# from one pole to another.\n# - n: The number of disks\n# - start: The start pole\n# - goal: The goal pole\n# - temp: The other pole\n#/* *** ODSATag: TOHshort *** */\ndef TOH_recursive(n, start, goal, temp):\n if n == 0: # Base case\n return\n TOH_recursive(n-1, start, temp, goal) # Recursive call: n-1 rings\n move(start, goal) # Move bottom disk to goal\n TOH_recursive(n-1, temp, goal, start) # Recursive call: n-1 rings\n#/* *** ODSAendTag: TOHshort *** */\n#/* *** ODSAendTag: TOH *** */\n\n\nMOVE = 13\nTOH = 15\n\n#/* *** ODSATag: TOHstack *** */\ndef TOH_stack(n, start, goal, temp):\n S = LinkedStack()\n S.push(TOH_object(TOH, n, start, goal, temp))\n while S.size() > 0:\n it = S.pop() # Get next task\n if it.op == MOVE: # Do a move\n move(it.start, it.goal)\n elif it.num > 0: # Imitate TOH recursive solution (in reverse)\n S.push(TOH_object(TOH, it.num-1, it.temp, it.goal, it.start));\n S.push(TOH_object(MOVE, 0, it.start, it.goal)); # A move to do\n S.push(TOH_object(TOH, it.num-1, it.start, it.temp, it.goal));\n\nclass TOH_object:\n def __init__(self, o, n, s, g, t=None):\n self.op = o\n self.num = n\n self.start = s\n self.goal = g\n self.temp = t\n#/* *** ODSAendTag: TOHstack *** */\n\ncounter = None\n\ndef move(start, goal):\n global counter\n print(f\"{counter}: Move {start} to {goal}\")\n counter += 1\n\n\nif __name__ == '__main__':\n import sys\n n = 4\n if len(sys.argv) == 2:\n n = int(sys.argv[1])\n start, goal, temp = 1, 2, 3\n\n print(\"Recursive solution\")\n counter = 1\n TOH_recursive(n, start, goal, temp)\n print()\n print(\"Stack solution\")\n counter = 1\n TOH_stack(n, start, goal, temp)\n","sub_path":"SourceCode/Python/ChalmersGU/DemoTowersOfHanoi.py","file_name":"DemoTowersOfHanoi.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"141954211","text":"# -*- coding: utf-8 -*-\n\nwith open('B-small-attempt0.in') as f:\n\twith open('output.txt', 'w') as fout:\n\t\tn = int(f.readline())\n\t\tfor i in range(n):\n\t\t\t\tans = 0\n\t\t\t\tt,s,p, *mas = map(int, f.readline().split())\n\t\t\t\tfor x in mas:\n\t\t\t\t\tif x < p:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif x >= 3 * p:\n\t\t\t\t\t\tans += 1\n\t\t\t\t\telse:\n\t\t\t\t\t\tx = x - p\n\t\t\t\t\t\tif x % 2 == 0:\n\t\t\t\t\t\t\tif x / 2 == p-1:\n\t\t\t\t\t\t\t\tans +=1\n\t\t\t\t\t\t\telif x / 2 == p-2 and s> 0 :\n\t\t\t\t\t\t\t\tans +=1\n\t\t\t\t\t\t\t\ts -= 1\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif x == (p-1)+(p-2) and s > 0:\n\t\t\t\t\t\t\t\tans +=1\n\t\t\t\t\t\t\t\ts -=1\n\t\t\t\t\t\t\telif x == p+(p-1):\n\t\t\t\t\t\t\t\tans += 1\n\t\t\t\tfout.write('Case #{0}: {1} \\n'.format(i+1, ans))\n\n","sub_path":"solutions_python/Problem_96/1841.py","file_name":"1841.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"599926344","text":"#!/usr/bin/env python3\n\n# Sopeq: service_instance.py\n# License: GPLv2\n# Author: Brad Cable\n\nfrom collections import OrderedDict\n\nfrom iptables_helpers import *\nfrom ipv4 import IPv4\nfrom pool import pool\nfrom rule_generator import rule_generator\n\n# structured for incoming/traffic classes, outgoing generally will swap\n# \"in\" variables for \"out\" variables\n\nclass service_instance(rule_generator):\n\t_controller = None\n\t_target = None\n\tservice_name = None\n\t_log_prefix = None\n\t_rule_comment = None\n\t_in_addrs = None\n\t_out_addrs = None\n\t_in_if = None\n\t_out_if = None\n\n\tdef __init__(self,\n\t\tcontroller, target, service_name, log_prefix, rule_comment,\n\t\tin_addrs, out_addrs, in_if=None, out_if=None\n\t):\n\t\tsuper().__init__()\n\n\t\tself._target = target.upper()\n\n\t\tself._controller = controller\n\t\tself.service_name = service_name\n\t\tself._log_prefix = log_prefix\n\t\tself._rule_comment = rule_comment\n\t\tself._in_addrs = in_addrs\n\t\tself._out_addrs = out_addrs\n\t\tself._in_if = in_if\n\t\tself._out_if = out_if\n\n\tdef rules(self):\n\t\tin_pool = self._controller.get_pool(self._in_addrs)\n\t\tout_pool = self._controller.get_pool(self._out_addrs)\n\n\t\tif in_pool is not None:\n\t\t\tin_addrs = in_pool.get_all_ips()\n\t\telse:\n\t\t\tin_addrs = [self._in_addrs]\n\n\t\tif out_pool is not None:\n\t\t\tout_addrs = out_pool.get_all_ips()\n\t\telse:\n\t\t\tout_addrs = [self._out_addrs]\n\n\t\tret_rules = []\n\t\tfor in_addr in in_addrs:\n\t\t\tif not IPv4(in_addr).valid():\n\t\t\t\traise Exception # TODO\n\n\t\t\tfor out_addr in out_addrs:\n\t\t\t\tif not IPv4(out_addr).valid():\n\t\t\t\t\traise Exception # TODO\n\n\t\t\t\trules = self.rule(in_addr, out_addr)\n\t\t\t\tfor rule in rules:\n\t\t\t\t\tif rule[1] != \"out\" or self._egress:\n\t\t\t\t\t\tret_rules.append((rule[0], rule[2]))\n\n\t\treturn ret_rules\n\n\tdef rule(self, in_addr, out_addr):\n\t\tinput_rule = \"-A {}_IN\".format(self.service_name)\n\t\toutput_rule = \"-A {}_OUT\".format(self.service_name)\n\n\t\tif self._log_prefix is not None:\n\t\t\tinput_rule_log = input_rule\n\t\t\toutput_rule_log = output_rule\n\n\t\tinput_flags = OrderedDict()\n\t\toutput_flags = OrderedDict()\n\n\t\tif self._in_addrs is not None:\n\t\t\tinput_flags[\"d\"] = in_addr\n\t\t\toutput_flags[\"s\"] = in_addr\n\n\t\tif self._out_addrs is not None:\n\t\t\tinput_flags[\"s\"] = out_addr\n\t\t\toutput_flags[\"d\"] = out_addr\n\n\t\tif self._in_if is not None:\n\t\t\tinput_flags[\"i\"] = self._in_if\n\t\t\toutput_flags[\"o\"] = self._in_if\n\n\t\tif self._out_if is not None:\n\t\t\tinput_flags[\"o\"] = self._out_if\n\t\t\toutput_flags[\"i\"] = self._out_if\n\n\t\t# not necessary anymore since I\"m changing how validate works\n\t\t### these are in order of what iptables outputs\n\t\t### (the first isn\"t necessary since the others will move past it)\n\t\t###if \"s\" in input_flags:\n\t\t###\tinput_flags.move_to_end(\"s\")\n\t\t###if \"s\" in output_flags:\n\t\t###\toutput_flags.move_to_end(\"s\")\n\t\t##if \"d\" in input_flags:\n\t\t##\tinput_flags.move_to_end(\"d\")\n\t\t##if \"d\" in output_flags:\n\t\t##\toutput_flags.move_to_end(\"d\")\n\t\t##if \"i\" in output_flags:\n\t\t##\tinput_flags.move_to_end(\"i\")\n\t\t##if \"i\" in output_flags:\n\t\t##\toutput_flags.move_to_end(\"i\")\n\t\t##if \"o\" in input_flags:\n\t\t##\tinput_flags.move_to_end(\"o\")\n\t\t##if \"o\" in output_flags:\n\t\t##\toutput_flags.move_to_end(\"o\")\n\n\t\tinput_flags[\"j\"] = self._target\n\t\toutput_flags[\"j\"] = self._target\n\n\t\tfor flag in input_flags:\n\t\t\tcur_append = \" -{} {}\".format(\n\t\t\t\tflag, input_flags[flag]\n\t\t\t)\n\t\t\tinput_rule += cur_append\n\t\t\tif self._log_prefix is not None and flag != \"j\":\n\t\t\t\tinput_rule_log += cur_append\n\n\t\tfor flag in output_flags:\n\t\t\tcur_append = \" -{} {}\".format(\n\t\t\t\tflag, output_flags[flag]\n\t\t\t)\n\t\t\toutput_rule += cur_append\n\t\t\tif self._log_prefix is not None and flag != \"j\":\n\t\t\t\toutput_rule_log += cur_append\n\n\t\tif self._log_prefix is not None:\n\t\t\tlog_append = ipt_construct_log(\n\t\t\t\tself._controller.log_level, self._log_prefix\n\t\t\t)\n\t\t\tinput_rule_log += log_append\n\t\t\toutput_rule_log += log_append\n\n\t\tif self._rule_comment is not None:\n\t\t\tcomment_append = ipt_construct_comment(self._rule_comment)\n\t\t\tinput_rule += comment_append\n\t\t\toutput_rule += comment_append\n\t\t\tif self._log_prefix is not None:\n\t\t\t\tinput_rule_log += comment_append\n\t\t\t\toutput_rule_log += comment_append\n\n\t\trule_list = [\n\t\t\t(\"filter\", \"in\", input_rule), (\"filter\", \"out\", output_rule)\n\t\t]\n\t\tif self._log_prefix is not None:\n\t\t\trule_list.extend([\n\t\t\t\t(\"filter\", \"in\", input_rule_log),\n\t\t\t\t(\"filter\", \"out\", output_rule_log)\n\t\t\t])\n\n\t\treturn rule_list\n","sub_path":"service_instance.py","file_name":"service_instance.py","file_ext":"py","file_size_in_byte":4286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"640472908","text":"\nclass Day6:\n\n @staticmethod\n def steps_to_infinite_loop(array: list) -> int:\n \"\"\"\n Redistribute the largest element in the list evenly across the list, starting at the element after the largest\n element. Continue until a configuration of the list is seen twice. Return the number of steps. This will be\n the number of steps before an infinite loop is detected.\n\n :param array: Input array of integers\n :return: Steps till an infinite loop is detected\n \"\"\"\n tuples = set()\n steps = 0\n\n while True:\n\n # Check if current configuration already exists, return if it does, add it if it doesn't\n tup = tuple(array)\n if tup in tuples:\n return steps\n else:\n tuples.add(tup)\n\n steps += 1\n\n # Get the value and index of the maximum value in the list\n max_i, max_value = max(enumerate(array), key=lambda e: e[1])\n\n # Reset the value of the maximum element\n array[max_i] = 0\n\n # Redistribute the maximum value across the list, starting at the next element\n for i in range(1, max_value + 1):\n update_i = (i + max_i) % len(array)\n array[update_i] += 1\n","sub_path":"2017/Graeme/python/advent/day/day_6.py","file_name":"day_6.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"152534132","text":"import datetime\nfrom GitTask.RequestMaker import RequestMaker\n\n\nclass PullRequestRequestMaker(RequestMaker):\n def __init__(self, query):\n super().__init__()\n self.url = \"https://api.github.com/search/issues\"\n self.params = {\n 'q': query,\n }\n\n\nclass PullRequestQueryMaker:\n @staticmethod\n def opened_pr(**kwargs):\n return f\"is:pr \" \\\n f\"repo:{kwargs['owner']}/{kwargs['repo']} \" \\\n f\"state:open \" \\\n f\"base:{kwargs['branch']} \" \\\n f\"created:<{kwargs['date_to']} \" \\\n f\"created:>={kwargs['date_from']} \"\n\n @staticmethod\n def closed_pr(**kwargs):\n return f\"is:pr \" \\\n f\"repo:{kwargs['owner']}/{kwargs['repo']} \" \\\n f\"state:closed \" \\\n f\"base:{kwargs['branch']} \" \\\n f\"created:<{kwargs['date_to']} \" \\\n f\"created:>={kwargs['date_from']} \"\n\n @staticmethod\n def old_pr(**kwargs):\n old_max_date = datetime.date.today() - datetime.timedelta(days=30)\n date_to = min(old_max_date, kwargs['date_to'])\n return f\"is:pr \" \\\n f\"repo:{kwargs['owner']}/{kwargs['repo']} \" \\\n f\"state:open \" \\\n f\"base:{kwargs['branch']} \" \\\n f\"created:<{date_to.strftime('%Y-%m-%d')} \" \\\n f\"created:>={kwargs['date_from']}\"\n","sub_path":"GitTask/payloads/PullRequest.py","file_name":"PullRequest.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"628843222","text":"import networkx as nx\nfrom networkx.readwrite import json_graph\nfrom itertools import islice\n\n\ndef window(seq, n=2):\n it = iter(seq)\n result = tuple(islice(it, n))\n if len(result) == n:\n yield result\n for elem in it:\n result = result[1:] + (elem,)\n yield result\n\n\ndef get(df):\n\n gdf = df.sort_values([\"Student Number\", \"Term\"]) \\\n .loc[:, [\"Student Number\", \"Term\", \"Node Column\"]] \\\n .groupby(\"Student Number\")\n\n a = list(gdf[\"Node Column\"])\n\n flow = [[el for el in x[1]] for x in a]\n \n sankey = [list(window([str(i) + x for i, x in enumerate(sub)])) for sub in flow]\n sankey = [item for sublist in sankey for item in sublist]\n\n s = nx.DiGraph()\n for edge in sankey:\n if s.has_edge(*edge):\n s[edge[0]][edge[1]]['weight'] += 1\n else:\n s.add_edge(*edge, weight=1)\n\n jdat = json_graph.node_link_data(s)\n \n #testdict = {\"flow\":flow, \"sankey\":sankey, \"s\":s, \"a\":a}\n\n return jdat #, testdict\n","sub_path":"Chemistry/Scripts/get_json.py","file_name":"get_json.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"103456574","text":"import requests\nimport pprint\nimport config\n\nBASE_URL = 'https://api.telegram.org/bot722151765:AAHAHusl-PEL4wMPRvt5U-rZ56ct4dCwj8Y/'\n\n\n# Главное иметь url самого bot api и токен который тебе дал Господь бог\n\n###############################################\n# #\n# для определеного метода создаеться масив #\n# с параметрами такие как chat_id и #\n# text (смотреть код ниже), дальше #\n# передаеться через запрос requests по url #\n# бота и в конце этому запросу присвается #\n# Метод с масивом параметров #\n# #\n###############################################\n\n###############################################\n# #\n# Подсказки для пользование API telegram Бота #\n# #\n###############################################\n\n# декоратор для определение данных в консоле\ndef Decorators(func):\n def decors_wrapper():\n print(\"#############################\")\n func()\n print(\"#############################\")\n\n return decors_wrapper\n\n\n# Запрос на информацию о боте\n@Decorators\ndef bot_info():\n r = requests.get(f'{BASE_URL}getMe')\n print(r)\n print(\"Bots information: \")\n pprint.pprint(r.json())\n\n\n# Запрос на обновление информации от сервера\n@Decorators\ndef getUpdates():\n # load = ['id, first_name', 'user_name', 'language_code']\n u = requests.get(f'{BASE_URL}getUpdates') # allowed_updates=load\n print(u)\n print(\"Update data information on server: \")\n # pprint.pprint(u.json()) # Показ данных в удобном формате json\n pprint.pprint(u.json()['result'][-1]) # Вывод последних данных\n\n\n# Отправка данных по id #\n# Можно юзать для администрирования бота\n@Decorators\ndef send_message_to_id_user():\n payload = {}\n payload['chat_id'] = 535364051\n payload['text'] = 'Habib win'\n print(\"Last message information: \")\n print(payload)\n p = requests.post(f'{BASE_URL}sendMessage', data=payload)\n return p\n\n\n# Отправка локации #\n# Можно юзать вместе с выводом постов для геолокации хат\n@Decorators\ndef send_location():\n payload = {}\n payload['chat_id'] = 535364051\n payload['latitude'] = 47.830284\n payload['longitude'] = 35.165504\n r = requests.post(f'{BASE_URL}sendLocation', data=payload)\n print('Location has been send')\n return r\n\n\n@Decorators\ndef edit_button():\n pass\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"179914516","text":"'''\nЗадание 1\nПользователь вводит с клавиатуры строку. Проверьте\nявляется ли введенная строка палиндромом. Палиндром — слово или текст, которое читается одинаково\nслева направо и справа налево. Например, кок; А роза\nупала на лапу Азора; доход; А буду я у дуба.\n'''\n\nmessag_e = input(\"Введіть строку: \")\nmessage_1 = messag_e.replace(\" \" , \"\").lower() \nif message_1 == message_1[::-1]:\n print(messag_e, ' - палиндром')\nelse:\n print(messag_e, ' - не палиндром')\n","sub_path":"Lesson_7_DZ_Nichipurenko_A.V/Lesson_7_DZ_1_Nichipurenko_A.V.py","file_name":"Lesson_7_DZ_1_Nichipurenko_A.V.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"580521747","text":"from django.conf import settings\nfrom home.models import User_Info, Variables, Documents_Info, Comment\nfrom home.forms import PostForm\nfrom django.shortcuts import render, redirect\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom home.custom import *\nfrom django.http import HttpResponseForbidden\n\n\ncontext_default = {\n 'version': settings.SITE_VER,\n 'css_version': settings.CSS_VER,\n 'superuser_id': settings.SUPERUSER_ID,\n 'user_info_condition': settings.USER_INFO_CONDITION,\n 'process_rate': settings.PROCESS_RATE,\n}\n\ndocument_context = {\n 'document_info' : Documents_Info.objects.all(),\n}\n\n\ndef update_context():\n global document_context, context_default\n document_context = {\n 'document_info': Documents_Info.objects.all(),\n }\n datas = Variables.objects.all()\n if len(datas) == 0:\n obj = Variables(\n visits= 0,\n doc_index_recent= 0,\n visits_free=0,\n visits_rout=0,\n visits_lol=0,\n visits_dl=0,\n visits_web=0,\n visits_java=0,\n visits_window=0,\n visits_indiv=0\n )\n obj.save()\n context_default = {\n 'version' : settings.SITE_VER,\n 'css_version' : settings.CSS_VER,\n 'superuser_id' : settings.SUPERUSER_ID,\n 'user_info_condition': settings.USER_INFO_CONDITION,\n 'variables' : Variables.objects.all().first(),\n 'process_rate' : settings.PROCESS_RATE,\n }\n\n\ndef index(request):\n save_count = 0\n for visit_counter in Variables.objects.filter().all():\n save_count = visit_counter.visits+1\n break\n\n Variables.objects.filter().all().update(visits=save_count)\n\n context2 = {\n 'superuser_id': settings.SUPERUSER_ID,\n }\n update_context()\n return render(request, 'major/homepage.html', merge_dicts(context_default, context2))\n\n\ndef get_develop_log(request):\n update_context()\n\n return render(request, 'major/development_log.html', context_default)\n\n\ndef get_login_page(request):\n update_context()\n User_Infos = User_Info.objects.all()\n\n prev = request.GET.get('call')\n login_context = {\n 'user_information': User_Infos,\n 'previous_call' : prev,\n }\n return render(request, 'major/login_page.html', merge_dicts(context_default, login_context))\n\n\ndef get_signup_page(request):\n update_context()\n User_Infos = User_Info.objects.all()\n login_context = {\n 'user_information': User_Infos,\n }\n return render(request, 'major/signup.html', merge_dicts(context_default, login_context))\n\n\ndef post_user_info(request):\n obj = User_Info(\n user_id=request.POST.get('user-id'),\n user_nickname=request.POST.get('user-nickname'),\n user_pw=request.POST.get('user-pw')\n )\n obj.save()\n return redirect('/login')\n\n\ndef post_user_login(request):\n for user in User_Info.objects.filter().all():\n if user.user_id == request.POST.get('user-id'):\n request.session['username'] = user.user_nickname\n request.session['userid'] = user.user_id\n break\n\n previous = request.GET.get('call')\n\n if previous == None:\n return redirect('/homepage')\n return redirect('/board?name=' + previous)\n\n\ndef user_logout(request):\n try:\n del request.session['username']\n del request.session['userid']\n except:\n pass\n return redirect('/homepage')\n\n\ndef get_board_list(request):\n update_context()\n\n classification = request.GET.get('name')\n\n visit_num = update_visits(classification)\n\n board_name = switch_urlname_to_board_name(classification)\n\n post_all_list = Documents_Info.objects.filter(classify=classification).order_by('doc_index').reverse()\n paginator = Paginator(post_all_list, settings.PAGE_MAX_DETAILS)\n\n page = request.GET.get('page')\n\n try:\n posts = paginator.page(page)\n except PageNotAnInteger:\n posts = paginator.page(1)\n except EmptyPage:\n posts = paginator.page(paginator.num_pages)\n\n ranger = range(1,settings.PAGE_MAX_CHAPTER+1)\n\n if page != None :\n pagei = int(page)\n page_page = (int)((pagei-1)/settings.PAGE_MAX_CHAPTER)\n ranger = range(\n page_page * settings.PAGE_MAX_CHAPTER + 1,\n (page_page+1) * settings.PAGE_MAX_CHAPTER + 1,\n )\n\n page_viewed_total = 0\n posts_num = len(post_all_list)\n\n\n for post_data in post_all_list:\n page_viewed_total += post_data.doc_view_cnt\n\n addition = {\n 'posts' : posts,\n 'max_page': settings.PAGE_MAX_CHAPTER,\n 'page_range': ranger,\n 'board_name' : board_name,\n 'classification' : classification,\n 'visits': visit_num,\n 'post_num': posts_num,\n 'page_viewed_total': page_viewed_total,\n }\n merged = merge_dicts(context_default, document_context)\n return render(request, 'major/post_list.html', merge_dicts(merged, addition))\n\n\n\n# WRITE PAGES\n\n\ndef get_write_post(request):\n update_context()\n pform = PostForm()\n\n if 'userid' not in request.session:\n return render(request, 'major/forbidden.html', context_default)\n\n classification = request.GET.get('board')\n board_rename = switch_urlname_to_board_name_trick(classification)\n addition = {\n 'form' : pform,\n 'board_name' : board_rename,\n 'classification' : classification\n }\n merged = merge_dicts(context_default, document_context)\n return render(request, 'major/new_post.html', merge_dicts(merged, addition))\n\n\n\n# Posting PAGES\n\n\ndef post_document(request):\n recent_index = Variables.objects.all().first().doc_index_recent + 1\n Variables.objects.all().update(doc_index_recent=recent_index)\n\n classification = request.GET.get('board')\n\n new_doc = Documents_Info(\n classify= classification,\n doc_index='{:05d}'.format(recent_index),\n doc_title=request.POST.get('doc-title'),\n doc_writer=request.session['username'],\n doc_content=request.POST.get('fields'),\n doc_view_cnt=0\n )\n\n new_doc.save()\n\n url_trick = request.GET.get('board')\n\n return redirect('/board?name='+url_trick)\n\n\n# Post View\n\n\ndef postview(request):\n update_context()\n\n classification = request.GET.get('classify')\n board_name = switch_urlname_to_board_name_trick(classification)\n\n post_index = request.GET.get('pindex')\n datas = Documents_Info.objects.filter(doc_index=post_index)\n Documents_Info.objects.filter(doc_index=post_index).update(doc_view_cnt= datas.first().doc_view_cnt+1)\n\n post = Documents_Info.objects.filter(doc_index=post_index).first()\n\n\n addition = {\n 'doc_data' : datas.first(),\n 'board_name' : board_name,\n 'post': post,\n }\n\n merged = merge_dicts(context_default, document_context)\n return render(request, 'major/show_post.html', merge_dicts(merged, addition))\n\n\ndef save_new_comment(request):\n if request.method == 'POST':\n\n recent_index = Variables.objects.all().first().comment_index_recent + 1\n Variables.objects.all().update(comment_index_recent=recent_index)\n\n post = Documents_Info.objects.filter(doc_index=request.POST['post_id']).first()\n user = User_Info.objects.filter(user_id=request.session['userid']).first()\n Comment.objects.create(\n comment_content=request.POST['comment_contents'],\n comment_writer=user,\n comment_post=post,\n comment_id='{:06d}'.format(recent_index),\n )\n return redirect('/postview?pindex='+post.doc_index+'&classify='+post.classify)\n\n\ndef delete_comment(request):\n comment_id = request.GET.get('comment_id')\n comment_obj = Comment.objects.filter(comment_id=comment_id).first()\n post = comment_obj.comment_post\n comment_obj.delete()\n\n return redirect('/postview?pindex='+post.doc_index+'&classify='+post.classify)","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"64257874","text":"from pylab import *\nimport postgkyl\n\nd = postgkyl.GData(\"c-m1-2d-adv-dg_distf_0.bp\")\nq0 = d.q\n\nd = postgkyl.GData(\"c-m1-2d-adv-dg_distf_1.bp\")\nq1 = d.q\n\ndx = (d.upperBounds[0]-d.lowerBounds[0])/d.numCells[0]\ndy = (d.upperBounds[1]-d.lowerBounds[1])/d.numCells[1]\nvol = dx*dy\n\ndq = q1-q0\nerr = dx*dy/4.0*(dq[0]**2 + dq[1]**2 + dq[2]**2 + dq[3]**2)\n\ntotalErr = sqrt(sum(err))\nprint(\"dx = %g; err = %g\" % (dx, totalErr))\n\n","sub_path":"source/sims-g2/pos-adv/c-m1/calcErr.py","file_name":"calcErr.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"39756735","text":"# Import libraries\nfrom bs4 import BeautifulSoup\nimport requests\nimport time\nfrom win10toast import ToastNotifier\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}\n\n\ndef weather(city):\n city = city.replace(\" \", \"+\")\n res = requests.get(\n f'https://www.google.com/search?q={city}&oq={city}&aqs=chrome.0.35i39l2j0l4j46j69i60.6128j1j7&sourceid=chrome&ie=UTF-8',\n headers=headers)\n\n soup = BeautifulSoup(res.text, 'html.parser')\n\n location = soup.select('#wob_loc')[0].getText().strip()\n current_time = soup.select('#wob_dts')[0].getText().strip()\n info = soup.select('#wob_dc')[0].getText().strip()\n weather = soup.select('#wob_tm')[0].getText().strip()\n\n information = f\"{location}\\n{current_time}\\n{info}\\n{weather} °F \"\n \n toaster = ToastNotifier()\n toaster.show_toast(\"Weather Information\",\n f\"{information}\",\n duration=10,\n threaded=True)\n while toaster.notification_active(): time.sleep(0.005)\n \n\n\ncity = \"Grand Rapids\"\ncity = city + \" weather\"\nweather(city)\n","sub_path":"Weather.py","file_name":"Weather.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"45946791","text":"from maid.netmaid import netmaid\nfrom django.core.management.base import NoArgsCommand\n\nclass Command(NoArgsCommand):\n help = \"Netmaid latest crawler\"\n\n def handle_noargs(self, **options):\n a = netmaid()\n a.url = 'http://netmaid.com.sg/Last-24hr-Maid.html'\n a.start_crawl()\n","sub_path":"maid/management/commands/getlatestmaid.py","file_name":"getlatestmaid.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"440366981","text":"'''\r\nCreated on Oct 12, 2016\r\n\r\n@author: mwittie\r\n'''\r\nimport queue\r\nimport threading\r\n\r\n\r\n## wrapper class for a queue of packets\r\nclass Interface:\r\n ## @param maxsize - the maximum size of the queue storing packets\r\n def __init__(self, maxsize=0):\r\n self.queue = queue.Queue(maxsize);\r\n self.mtu = None\r\n\r\n ##get packet from the queue interface\r\n def get(self):\r\n try:\r\n return self.queue.get(False)\r\n except queue.Empty:\r\n return None\r\n\r\n ##put the packet into the interface queue\r\n # @param pkt - Packet to be inserted into the queue\r\n # @param block - if True, block until room in queue, if False may throw queue.Full exception\r\n def put(self, pkt, block=False):\r\n self.queue.put(pkt, block)\r\n\r\n\r\n## Implements a network layer packet (different from the RDT packet\r\n# from programming assignment 2).\r\n# NOTE: This class will need to be extended to for the packet to include\r\n# the fields necessary for the completion of this assignment.\r\nclass NetworkPacket:\r\n ## packet encoding lengths\r\n dst_addr_S_length = 5\r\n snd_addr_S_length = 5\r\n pack_length_length = 4\r\n frag_flag_length = 1\r\n pack_id_length = 1\r\n pack_off_length = 3\r\n ack_length = 1\r\n\r\n # head size for initial send\r\n head_size = ack_length + dst_addr_S_length + snd_addr_S_length + pack_length_length + frag_flag_length + pack_id_length + pack_off_length\r\n\r\n ##@param dst_addr: address of the destination host\r\n # @param data_S: packet payload\r\n def __init__(self, ack, snd_addr, dst_addr, data_S):\r\n self.snd_addr = snd_addr\r\n self.dst_addr = dst_addr\r\n self.data_S = data_S\r\n\r\n # frag capabilities\r\n self.pack_length = self.head_size + len(data_S)\r\n self.pack_id = 0\r\n self.frag_flag = 0\r\n self.pack_off = 3\r\n\r\n # ACK\r\n self.ack = ack\r\n\r\n\r\n ## called when printing the object\r\n def __str__(self):\r\n return self.to_byte_S()\r\n\r\n # set frag_val\r\n def frag_val(self, length, id, frag, off):\r\n self.frag_flag = frag\r\n self.pack_length = length + len(self.data_S)\r\n self.pack_id = id\r\n self.pack_off = off\r\n\r\n ## convert packet to a byte string for transmission over links\r\n def to_byte_S(self):\r\n byte_S = str(self.pack_length).zfill(self.pack_length_length)\r\n byte_S += str(self.pack_id).zfill(self.pack_id_length)\r\n byte_S += str(self.frag_flag).zfill(self.frag_flag_length)\r\n byte_S += str(self.pack_off).zfill(self.pack_off_length)\r\n byte_S += str(self.ack).zfill(self.ack_length)\r\n byte_S += str(self.snd_addr).zfill(self.snd_addr_S_length)\r\n byte_S += str(self.dst_addr).zfill(self.dst_addr_S_length)\r\n byte_S += self.data_S\r\n return byte_S\r\n\r\n ## extract a packet object from a byte string\r\n # @param byte_S: byte string representation of the packet\r\n @classmethod\r\n def from_byte_S(self, byte_S):\r\n pointer = 0\r\n pack_length = int(byte_S[pointer : pointer + NetworkPacket.pack_length_length])\r\n\r\n pointer += NetworkPacket.pack_length_length\r\n p_id = int(byte_S[pointer : pointer + NetworkPacket.pack_id_length])\r\n\r\n pointer += NetworkPacket.pack_id_length\r\n frag_flag = int(byte_S[pointer : pointer + NetworkPacket.frag_flag_length])\r\n\r\n pointer += NetworkPacket.frag_flag_length\r\n off = int(byte_S[pointer : pointer + NetworkPacket.pack_off_length])\r\n\r\n pointer += NetworkPacket.pack_off_length\r\n ack = int(byte_S[pointer : pointer + NetworkPacket.ack_length])\r\n\r\n pointer += NetworkPacket.ack_length\r\n snd_addr = int(byte_S[pointer : pointer + NetworkPacket.snd_addr_S_length])\r\n\r\n pointer += NetworkPacket.snd_addr_S_length\r\n dst_addr = int(byte_S[pointer : pointer + NetworkPacket.dst_addr_S_length])\r\n\r\n pointer += NetworkPacket.dst_addr_S_length\r\n data_S = byte_S[pointer : ]\r\n\r\n # create packet from data\r\n p = self(ack, snd_addr, dst_addr, data_S)\r\n\r\n p.frag_val(pack_length, p_id, frag_flag, off)\r\n\r\n return p\r\n\r\n\r\n\r\n\r\n## Implements a network host for receiving and transmitting data\r\nclass Host:\r\n\r\n ##@param addr: address of this node represented as an integer\r\n def __init__(self, addr):\r\n self.addr = addr\r\n self.in_intf_L = [Interface()]\r\n self.out_intf_L = [Interface()]\r\n self.stop = False #for thread termination\r\n self.received_buf = [] #for tracking all packets received\r\n\r\n ## called when printing the object\r\n def __str__(self):\r\n return 'Host_%s' % (self.addr)\r\n\r\n ## create a packet and enqueue for transmission\r\n # @param dst_addr: destination address for the packet\r\n # @param data_S: data being transmitted to the network layer\r\n def udt_send(self, dst_addr, data_S, ack=0):\r\n count = 0\r\n while len(data_S) + NetworkPacket.head_size > self.out_intf_L[0].mtu:\r\n p = NetworkPacket(ack, self.addr, dst_addr, data_S[0:self.out_intf_L[0].mtu - NetworkPacket.head_size])\r\n p.pack_id = count\r\n count += 1\r\n self.out_intf_L[0].put(p.to_byte_S()) #send packets always enqueued successfully\r\n print('%s: sending packet \"%s\" on the out interface with mtu=%d' % (self, p, self.out_intf_L[0].mtu))\r\n data_S = data_S[self.out_intf_L[0].mtu - NetworkPacket.head_size:]\r\n # self.udt_send(dst_addr,data_S[self.out_intf_L[0].mtu - NetworkPacket.head_size:])\r\n if len(data_S) > 0:\r\n p = NetworkPacket(ack, self.addr, dst_addr, data_S)\r\n p.pack_id = count\r\n self.out_intf_L[0].put(p.to_byte_S()) # send packets always enqueued successfully\r\n print('%s: sending packet \"%s\" on the out interface with mtu=%d' % (self, p, self.out_intf_L[0].mtu))\r\n\r\n ## receive packet from the network layer\r\n def udt_receive(self):\r\n pkt_S = self.in_intf_L[0].get()\r\n if pkt_S is not None:\r\n p = NetworkPacket.from_byte_S(pkt_S)\r\n\r\n self.received_buf.append(p)\r\n # if the packet was fragmented\r\n if p.frag_flag:\r\n done = False\r\n while not done:\r\n # get more information\r\n pkt_S_next = self.in_intf_L[0].get()\r\n # keep trying until more information is received\r\n if pkt_S_next is None:\r\n continue\r\n\r\n # at this point there is information so make a packet\r\n p_next = NetworkPacket.from_byte_S(pkt_S_next)\r\n\r\n # if the id's match use the data\r\n if p_next.pack_id == p.pack_id:\r\n pkt_S += p_next.data_S\r\n # if there are more fragments keep looking\r\n if p_next.frag_flag:\r\n continue\r\n # otherwise use the data and exit\r\n else:\r\n print('%s: received packet \"%s\" on the in interface' % (self, pkt_S))\r\n if p_next.ack is not 1:\r\n self.sendACK(p_next)\r\n done = True\r\n # otherwise use the data\r\n else:\r\n print('%s: received packet \"%s\" on the in interface' % (self, pkt_S))\r\n if p.ack is not 1:\r\n self.sendACK(p)\r\n\r\n def sendACK(self, packet):\r\n snd_addr = packet.snd_addr\r\n id = packet.pack_id\r\n self.udt_send(snd_addr, \"ACK for packet with id=%s\" % id, 1)\r\n\r\n\r\n ## thread target for the host to keep receiving data\r\n def run(self):\r\n print (threading.currentThread().getName() + ': Starting')\r\n while True:\r\n #receive data arriving to the in interface\r\n self.udt_receive()\r\n #terminate\r\n if(self.stop):\r\n msgs = \"\"\r\n for packet in self.received_buf:\r\n if packet.pack_id == 0:\r\n msgs += \"\\n\"\r\n msgs += packet.data_S\r\n if len(msgs) > 0:\r\n print (threading.currentThread().getName() + ': Ending, received the following message(s):%s' % msgs + '\\n')\r\n else:\r\n print (threading.currentThread().getName() + ': Ending, received no messages.\\n')\r\n return\r\n\r\n\r\n\r\n## Implements a multi-interface router described in class\r\nclass Router:\r\n id_options = [1, 2, 3, 4, 5, 6, 7, 8, 9]\r\n id_pointer = 0\r\n\r\n ##@param name: friendly router name for debugging\r\n # @param intf_count: the number of input and output interfaces\r\n # @param max_queue_size: max queue length (passed to Interface)\r\n def __init__(self, name, intf_count, table, max_queue_size):\r\n self.stop = False #for thread termination\r\n self.name = name\r\n self.table = table\r\n #create a list of interfaces\r\n self.in_intf_L = [Interface(max_queue_size) for _ in range(intf_count)]\r\n self.out_intf_L = [Interface(max_queue_size) for _ in range(intf_count)]\r\n\r\n\r\n ## called when printing the object\r\n def __str__(self):\r\n return 'Router_%s' % (self.name)\r\n\r\n ## look through the content of incoming interfaces and forward to\r\n # appropriate outgoing interfaces\r\n def forward(self):\r\n for i in range(len(self.in_intf_L)):\r\n pkt_S = None\r\n try:\r\n #get packet from interface i\r\n pkt_S = self.in_intf_L[i].get()\r\n #if packet exists make a forwarding decision\r\n if pkt_S is not None:\r\n p = NetworkPacket.from_byte_S(pkt_S) #parse a packet out\r\n\r\n # if there is to much data\r\n if len(pkt_S) > self.out_intf_L[i].mtu:\r\n # available send space\r\n space = self.out_intf_L[i].mtu - NetworkPacket.head_size\r\n\r\n # while there is data left\r\n while len(pkt_S) > 0:\r\n # make a sub packet to the send address with all info from old packet\r\n # this includes the old packets header as raw data\r\n p_next = NetworkPacket(p.ack, p.snd_addr, p.dst_addr, pkt_S[0:space])\r\n pkt_S = pkt_S[space:]\r\n if len(pkt_S) > 0:\r\n frag = 1\r\n else:\r\n frag = 0\r\n p_next.frag_val(space, self.id_options[self.id_pointer], frag, int(space/8))\r\n self.forwardPacket(p_next)\r\n if self.id_pointer >= len(self.id_options)-1:\r\n self.id_pointer = 0\r\n else:\r\n self.id_pointer += 1\r\n\r\n else:\r\n self.forwardPacket(p)\r\n except queue.Full:\r\n print('%s: packet \"%s\" lost on interface %d' % (self, p, i))\r\n pass\r\n\r\n # forwards packet to correct out interface using the routing table (self.table)\r\n def forwardPacket(self, packet):\r\n interfaceNum = self.table[packet.dst_addr]\r\n self.out_intf_L[interfaceNum].put(packet.to_byte_S(), True)\r\n print('%s: forwarding packet \"%s\" from interface %d to %d with mtu %d' \\\r\n % (self, packet, interfaceNum, interfaceNum, self.out_intf_L[interfaceNum].mtu))\r\n\r\n ## thread target for the host to keep forwarding data\r\n def run(self):\r\n print (threading.currentThread().getName() + ': Starting')\r\n while True:\r\n self.forward()\r\n if self.stop:\r\n print (threading.currentThread().getName() + ': Ending')\r\n return\r\n","sub_path":"csci-466-networks/packet-segmentation-and-routing-lab/part4/network_4.py","file_name":"network_4.py","file_ext":"py","file_size_in_byte":11999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"302742256","text":"# -*- coding:utf-8 -*-\n#--\n# Copyright (c) 2012-2014 Net-ng.\n# All rights reserved.\n#\n# This software is licensed under the BSD License, as described in\n# the file LICENSE.txt, which you should have received as part of\n# this distribution.\n#--\n\nfrom elixir import using_options\nfrom elixir import Entity, ManyToMany, ManyToOne, OneToMany, OneToOne\nfrom elixir import Field, Unicode, Integer, DateTime, Date, UnicodeText\nfrom sqlalchemy.orm import subqueryload\nfrom nagare.database import session\nimport datetime\n\n\nclass DataCard(Entity):\n\n \"\"\"Card mapper\n \"\"\"\n using_options(tablename='card')\n title = Field(UnicodeText)\n description = Field(UnicodeText, default=u'')\n votes = OneToMany('DataVote')\n index = Field(Integer)\n column = ManyToOne('DataColumn')\n labels = ManyToMany('DataLabel')\n comments = OneToMany('DataComment', order_by=\"-creation_date\")\n assets = OneToMany('DataAsset', order_by=\"-creation_date\")\n checklists = OneToMany('DataChecklist', order_by=\"index\")\n members = ManyToMany('DataUser')\n cover = OneToOne('DataAsset', inverse=\"cover\")\n author = ManyToOne('DataUser', inverse=\"my_cards\")\n creation_date = Field(DateTime)\n due_date = Field(Date)\n history = OneToMany('DataHistory')\n weight = Field(Unicode(255), default=u'')\n\n def delete_history(self):\n for event in self.history:\n session.delete(event)\n session.flush()\n\n @classmethod\n def create_card(cls, column, title, user):\n \"\"\"Create new column\n\n In:\n - ``column`` -- DataColumn, father of the column\n - ``title`` -- title of the card\n - ``user`` -- DataUser, author of the card\n Return:\n - created DataCard instance\n \"\"\"\n new_card = cls(title=title, author=user,\n creation_date=datetime.datetime.utcnow())\n column.cards.append(new_card)\n return new_card\n\n @classmethod\n def delete_card(cls, card):\n \"\"\"Delete card\n\n Delete a given card and re-index other cards\n\n In:\n - ``card`` -- DataCard instance to delete\n \"\"\"\n index = card.index\n column = card.column\n card.delete()\n session.flush()\n # legacy databases may be broken…\n if index is None:\n return\n q = cls.query\n q = q.filter(cls.index >= index)\n q = q.filter(cls.column == column)\n q.update({'index': cls.index - 1})\n\n @classmethod\n def get_all(cls):\n query = cls.query.options(subqueryload('labels'), subqueryload('comments'))\n return query\n\n def make_cover(self, asset):\n \"\"\"\n \"\"\"\n DataCard.get(self.id).cover = asset.data\n\n def remove_cover(self):\n \"\"\"\n \"\"\"\n DataCard.get(self.id).cover = None\n\n def remove_board_member(self, member):\n \"\"\"Remove member from board\"\"\"\n if member.get_user_data() in self.members:\n self.members.remove(member.get_user_data())\n session.flush()\n","sub_path":"kansha/card/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"313894566","text":"from tkinter import *\r\nroot = Tk()\r\n\r\nlabel1 = Label(root, text = \"Enter your expression\")\r\nlabel1.grid(row = 0)\r\n\r\nlabelHelp = Label(root,text = \" \")\r\nlabelHelp.grid(row = 0, column = 1)\r\n\r\nlabel2 = Label(root, text = \"Your result is:\")\r\nlabel2.grid(row=2, column=0)\r\n\r\ndef evaluate(event):\r\n data = e.get()\r\n ans.configure(text = \"Answer.\" + str(eval(data)))\r\n \r\ne = Entry(root)\r\n\r\ne.bind(\"\", evaluate)\r\ne.grid(row=1)\r\n\r\nans = Label(root)\r\nans.grid(row=2,column=1)\r\n\r\nroot.mainloop()\r\n\r\n\r\n","sub_path":"Mini_calculator.py","file_name":"Mini_calculator.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"479021645","text":"import os\n\nfrom .settings import *\n\n# Google App Engine Settings\nimport sys\nsys.path.append('/usr/local/google_appengine')\nsys.path.append('/usr/local/google_appengine/lib/yaml/lib')\nsys.path.append('/usr/local/google_appengine/lib/fancy_urllib')\n\n\nDEBUG = False\n\nUSE_CACHEMANAGER = False\nENABLE_DB_LOGGER = True\n\n\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',\n 'LOCATION': 'horizon_api',\n 'TIMEOUT': 60,\n }\n}\n\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\n\n\nINSTALLED_APPS = ('django_nose',) + INSTALLED_APPS\nTEST_RUNNER = 'django_nose.NoseTestSuiteRunner'\nNOSE_ARGS = [\n '--with-gae',\n '-s',\n '--logging-level=WARNING',\n '--exclude-dir=gaenv_lib',\n '--with-coverage',\n '--cover-erase',\n ]\nAPPS_TO_COVER = [x for x in INSTALLED_APPS if not x.startswith('django') and x != 'jlib']\nNOSE_ARGS += ['--cover-package=%s'%x for x in APPS_TO_COVER]\n","sub_path":"food_trucks/test_settings.py","file_name":"test_settings.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"173903914","text":"from django.forms import ModelForm\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, Submit, Button, ButtonHolder\nfrom crispy_forms.bootstrap import FormActions\n\n# Models\nfrom blog.models import Article\n\nclass ArticleForm(ModelForm):\n \n class Meta:\n model = Article\n fields = '__all__'\n exclude = ('slug',)\n\n def __init__(self, *args, **kwargs):\n super(ArticleForm, self).__init__(*args, **kwargs)\n self.helper = FormHelper(self)\n self.helper.layout = Layout(\n 'title',\n 'content',\n 'tags',\n ButtonHolder(\n Button('cancel', 'Cancelar'), \n Submit('save', 'Salvar'),\n css_class='float-right'\n )\n )","sub_path":"blog/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"415460297","text":"import os\nimport sys\nimport time\nimport subprocess\n\n# Use subprocess to Manage Child Processes\n\n# result = subprocess.run(\n# [\"echo\", \"Hello from the child!\"], capture_output=True, encoding=\"utf-8\"\n# )\n# result.check_returncode() # No exception means clean exit\n# print(result.stdout)\n\n## Decoupling the child process from the parent frees up the parent process to\n## run many child processes in parallel. Here I do this by starting all the child\n## processes together with Popen upfront\n# start = time.time()\n# sleep_procs = []\n# for _ in range(10):\n# proc = subprocess.Popen([\"sleep\", \"1\"])\n# sleep_procs.append(proc)\n\n##\n# for proc in sleep_procs:\n# proc.communicate()\n\n# end = time.time()\n# delta = end - start\n## Takes about 1.05 seconds to perform all the 10 tasks concurrently\n# print(f\"Process took: {delta:.3} seconds\")\n\n## If these processes ran in a sequential manner then the total delay would be\n## 10+ seconds rather than ~1 second\n\n## You can also pipe data from a Python program into a subprocess and retrieve\n## its output.\n\n\ndef run_encrypt(data):\n \"\"\"\n Use the openssl command-line tool to encrypt some data.\n This function starts the child process with CLI arguments and I/O pipes\n \"\"\"\n env = os.environ.copy()\n\n env[\"password\"] = \"zhsklsdfjw4e2888jsda/sfshnssd/m/KJ)2329#\"\n proc = subprocess.Popen(\n [\"openssl\", \"enc\", \"-des3\", \"-pass\", \"env:password\"],\n env=env,\n stdin=subprocess.PIPE, # Allow sending of data to process's stdin\n stdout=subprocess.PIPE, # To retrieve the result instead of None\n )\n proc.stdin.write(data)\n proc.stdin.flush() # Ensure that the child gets the input\n return proc\n\n\n# procs = []\n# for _ in range(3):\n# data = os.urandom(10)\n# proc = run_encrypt(data)\n# procs.append(proc)\n\n# for proc in procs:\n# out, _ = proc.communicate()\n# print(\"Out: \", out)\n\n\ndef run_hash(input_stdin):\n \"\"\"\n Start the openssl CLI tool as a subprocess to generate a Whirpool hash of\n the input stream\n\n Args:\n input_stdin -> Earlier subprocess that passes input to this process\n \"\"\"\n return subprocess.Popen(\n [\"openssl\", \"dgst\", \"-whirlpool\", \"-binary\"],\n stdin=input_stdin,\n stdout=subprocess.PIPE,\n )\n\n\ndef sleep_pipe(input_stdin):\n return subprocess.Popen([\"sleep\", \"1\"], stdin=input_stdin, stdout=subprocess.PIPE)\n\n\n# Now, one set of processes is used to encrypt some data and another set of\n# processes is used to hash their encrypted output.\n\nencrypt_procs = []\nhash_procs = []\nsleep_procs = []\n\nstart = time.time()\nfor _ in range(3):\n data = os.urandom(100)\n # Encrypt the data first\n encrypt_proc = run_encrypt(data)\n encrypt_procs.append(encrypt_proc)\n\n sleep_proc = sleep_pipe(encrypt_proc.stdout)\n sleep_procs.append(sleep_proc)\n\n # Pass the encrypted data stream to run_hash()\n hash_proc = run_hash(encrypt_proc.stdout)\n hash_procs.append(hash_proc)\n\n # Ensures that the child consumes the input stream and the communicate()\n # method doesn't inadvertently steal input from the child\n encrypt_proc.stdout.close()\n encrypt_proc.stdout = None\n\n sleep_proc.stdout.close()\n sleep_proc.stdout = None\n\n\nfor proc in encrypt_procs:\n try:\n proc.communicate(timeout=0.1)\n assert proc.returncode == 0\n except subprocess.TimeoutExpired:\n print(\"Exit status\", proc.poll())\n proc.terminate()\n proc.wait()\n sys.exit(1)\n\nfor proc in sleep_procs:\n try:\n # timeout of 0.1 should cause the entire process to end if the sleep is\n # longer than 0.1\n proc.communicate(timeout=2)\n assert proc.returncode == 0\n except subprocess.TimeoutExpired:\n print(\"Exit status\", proc.poll())\n proc.terminate()\n proc.wait()\n sys.exit(1)\n\nfor proc in hash_procs:\n try:\n out, _ = proc.communicate(timeout=0.1)\n print(out[-10:])\n assert proc.returncode == 0\n except subprocess.TimeoutExpired:\n print(\"Exit status\", proc.poll())\n proc.terminate()\n proc.wait()\n sys.exit(1)\n\nend = time.time()\ndelta = end - start\nprint(f\"Took {delta:.3} seconds\")\n","sub_path":"ConcurrencyAndParellelism/conc.py","file_name":"conc.py","file_ext":"py","file_size_in_byte":4197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"69396906","text":"from pyspark.sql import SparkSession\nfrom operator import add\nfrom itertools import combinations\nimport csv\nimport sys\nimport time\n\n\ndef candidateCount(partitionBasket, candidateItems):\n itemCount = {}\n\n for candidate in candidateItems:\n if type(candidate) is int:\n candidate = [candidate]\n item = tuple(sorted(candidate))\n candidate = set(candidate)\n for basket in partitionBasket:\n if candidate.issubset(basket):\n itemCount[item] = itemCount.get(item, 0) + 1\n\n return itemCount\n\n\ndef getFrequentItems(partitionBasket, candidateItems, basketSupport):\n itemCount = candidateCount(partitionBasket, candidateItems)\n filteredFrequentItems = [item for item in itemCount if itemCount[item] >= basketSupport]\n return filteredFrequentItems\n\n\ndef getCandidateItems(frequentItems, k):\n\n if k == 2:\n return list(combinations(frequentItems, 2))\n\n candidateItems = []\n\n for item in combinations(frequentItems, 2):\n new_item = set(item[0] + item[1])\n new_item_tuple = tuple(sorted(new_item))\n if len(new_item) == k and new_item_tuple not in candidateItems:\n flag = True\n for sub_item in combinations(new_item, k - 1):\n if tuple(sorted(sub_item)) not in frequentItems:\n flag = False\n break\n if flag:\n candidateItems.append(new_item_tuple)\n\n return candidateItems\n\n\ndef aprioriAlgorithm(partitionBasket, support, totalCount):\n\n partitionBasket = list(partitionBasket)\n basketSupport = support * (float(len(partitionBasket)) / float(totalCount))\n finalResult = list()\n\n candidateItems = []\n for basket in partitionBasket:\n candidateItems += list(basket)\n\n frequentItems = []\n for item in set(candidateItems):\n if candidateItems.count(item) >= basketSupport:\n frequentItems.append(item)\n\n frequentItems = sorted(frequentItems)\n\n finalResult.extend(frequentItems)\n\n k = 2\n while len(frequentItems) > 0:\n\n candidateItems = getCandidateItems(frequentItems, k)\n\n if len(candidateItems) > 0:\n frequentItems = getFrequentItems(partitionBasket, candidateItems, basketSupport)\n frequentItems = sorted(frequentItems)\n finalResult.extend(frequentItems)\n else:\n frequentItems = []\n\n k = k + 1\n\n return finalResult\n\n\ndef writeItemsToFile(outputItems, outFilePtr):\n\n length = 1\n output = {}\n\n nextList = list(filter(lambda l: len(l) == length, outputItems))\n\n while nextList:\n output[length] = nextList\n length += 1\n nextList = list(filter(lambda l: len(l) == length, outputItems))\n\n for key in sorted(output.keys()):\n\n outputList = output[key]\n outputItems = []\n for item in outputList:\n outputItems.append(tuple(sorted(str(i) for i in item)))\n\n outputItems = sorted(outputItems)\n\n if key == 1:\n outFilePtr.write(str(outputItems[0]).replace(\",\", \"\"))\n for i in outputItems[1:]:\n outFilePtr.write(\",\")\n outFilePtr.write(str(i).replace(\",\", \"\"))\n else:\n outFilePtr.write(\"\\n\\n\")\n outFilePtr.write(str(outputItems[0]))\n for i in outputItems[1:]:\n outFilePtr.write(\",\")\n outFilePtr.write(str(i))\n\n\ndef removeLeadingZeros(num):\n while num[0] == \"0\":\n num = num[1:]\n return int(num)\n\n\ndef update_year(date_string):\n date_list = date_string.split(\"/\")\n if len(date_list[2]) == 4:\n date_string = \"/\".join(date_list[:2]) + \"/\" + date_list[2][-2:]\n return date_string\n\n\nif __name__ == \"__main__\":\n\n start = time.time()\n\n filterThreshold = int(sys.argv[1])\n support = int(sys.argv[2])\n inputFile = sys.argv[3]\n outputFile = sys.argv[4]\n\n outFile = open(outputFile, \"w\")\n\n spark = SparkSession.builder.appName('inf-553-2b').getOrCreate()\n sc = spark.sparkContext\n\n dataset = sc.textFile(inputFile).mapPartitions(lambda x : csv.reader(x))\n\n # Data PreProcessing\n header = dataset.first()\n transactionIndex = header.index(\"TRANSACTION_DT\")\n customerIndex = header.index(\"CUSTOMER_ID\")\n productIndex = header.index(\"PRODUCT_ID\")\n dataset = dataset.filter(lambda x: x != header)\n\n dataset = dataset.map(lambda x: (update_year(x[transactionIndex]) + \"-\" + x[customerIndex], removeLeadingZeros(x[productIndex])))\n with open('divya_ramesha_preprocessed.csv', 'w') as csvFile:\n writer = csv.writer(csvFile)\n writer.writerows([['DATE-CUSTOMER_ID', 'PRODUCT_ID']] + dataset.collect())\n\n # Filter Baskets\n marketBaskets = dataset.groupByKey().mapValues(set).filter(lambda x: len(x[1]) > filterThreshold)\n marketBaskets = marketBaskets.map(lambda x: x[1])\n basketsCount = marketBaskets.count()\n\n # First Map\n firstMap = marketBaskets.mapPartitions(lambda partitionBasket: aprioriAlgorithm(partitionBasket, support, basketsCount)).map(lambda x: (x, 1))\n\n # First Reduce\n firstReduce = firstMap.reduceByKey(add).keys()\n\n outFile.write(\"Candidates:\\n\")\n singleItems = firstReduce.filter(lambda x: type(x) == int).collect()\n it = iter(singleItems)\n singleItems = list(zip(it))\n otherItems = firstReduce.filter(lambda x: type(x) != int).collect()\n writeItemsToFile(singleItems + otherItems, outFile)\n\n candidateKeys = firstReduce.collect()\n # Second Map\n secondMap = marketBaskets.mapPartitions(lambda partitionBasket: candidateCount(list(partitionBasket), candidateKeys).items())\n # Second Reduce\n secondReduce = secondMap.reduceByKey(add).filter(lambda x: x[1] >= support)\n\n outFile.write(\"\\n\\nFrequent Itemsets:\\n\")\n writeItemsToFile(secondReduce.keys().collect(), outFile)\n\n outFile.close()\n end = time.time()\n print(\"Duration: \", end - start)","sub_path":"project2/divya_ramesha_task2.py","file_name":"divya_ramesha_task2.py","file_ext":"py","file_size_in_byte":5916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"631445396","text":"# Given bottom left and top right points of two rectangles,\n# check if the rectangles intersect\n\ndef rect_intrs(rect1, rect2):\n if (rect2[0] in range(rect1[0], rect1[2]) \\\n or rect2[2] in range(rect1[0] + 1, rect1[2]) ) \\\n and (rect2[1] in range(rect1[1] + 1, rect1[3]) \\\n or rect2[3] in range(rect1[1] + 1, rect1[3]) ):\n return True\n else:\n return False\n\nprint (rect_intrs([5,15,8,18], [0,3,7,9]))\nprint(rect_intrs([0, 0, 1, 1], [2, 2, 3, 3]))\nprint (rect_intrs([0,0,1,1], [1,0,2,1]))\nprint (rect_intrs([0,0,2,2], [1,1,3,3]))\n","sub_path":"Problem Set One/rect_int.py","file_name":"rect_int.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"490427686","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.utils\n\nfrom utils import assert_expected_size\n\nclass Highway(nn.Module):\n def __init__(self, word_embed_size):\n '''Initializing Highway Model\n @param embed_size: word embed length\n '''\n super(Highway, self).__init__()\n self.word_embed_size = word_embed_size\n self.w_projection = nn.Linear(word_embed_size, word_embed_size, bias=True)\n self.w_gate = nn.Linear(word_embed_size, word_embed_size, bias=True)\n\n def forward(self, x_conv_out: torch.Tensor) -> torch.Tensor:\n '''\n @param x_conv_out (Tensor): Tensor of padded source sentences with shape (b, e_word), where\n b = batch_size, e_word = word embedding length. These are the outputs\n from convolutional neural network\n @returns x_highway (Tensor) : Tensor of padded source sentences with shape (b, e_word)\n '''\n batch_size, e_word = len(x_conv_out), self.word_embed_size\n assert_expected_size(x_conv_out, 'x_conv_out', [batch_size, e_word])\n\n relu = nn.ReLU()\n x_proj = relu(self.w_projection(x_conv_out)) # shape = (b, e_word)\n assert_expected_size(x_proj, 'x_proj', [batch_size, e_word])\n\n x_gate = torch.sigmoid(self.w_gate(x_conv_out)) # shape = (b, e_word)\n assert_expected_size(x_gate, 'x_gate', [batch_size, e_word])\n\n x_highway = x_gate*x_proj + (1-x_gate)*x_conv_out\n assert_expected_size(x_highway, 'x_highway', [batch_size, e_word])\n return x_highway\n\n","sub_path":"highway.py","file_name":"highway.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"308954210","text":"import sys\nimport dal\n\nfrom PyQt5.Qt import *\nfrom tableModel import *\nfrom frm_main import *\nfrom br_main import *\n\n# 全局变量\ndata_list = []\ndata_dic = {}\nphone_list = []\nphone_dic = {}\nphone_edit = PhEdit()\ngu_ke = Guke()\n\n\nclass MyWin(QMainWindow, Ui_MainWindow):\n # 窗口初始化\n def __init__(self, parent=None):\n super().__init__()\n self.setupUi(self)\n self.Cal.setVisible(False)\n self.br_listview()\n self.list_guzhang_view()\n self.lbl_danhao.setText(test.dan_hao())\n\n # 信号绑定\n self.list_br.clicked.connect(self.list_br_clicked)\n self.list_phone.clicked.connect(self.list_phone_clicked)\n self.btnAdd.clicked.connect(self.select_guzhang_clicked)\n self.btn_print.clicked.connect(self.prSave)\n self.btnDate.clicked.connect(self.E_clicked)\n self.Cal.clicked.connect(self.Cal_select)\n self.rd_gkSex1.toggled.connect(self.sex_select)\n self.rd_gkSex0.toggled.connect(self.sex_select)\n self.menu.triggered[QAction].connect(self.br_add)\n # 菜单点击\n def br_add(self,QAction):\n # print(QAction.text())\n if QAction.text()=='品牌维护':\n self.frm_br=DL_br()\n self.frm_br.my_Signal.connect(self.br_listview)\n self.frm_br.show()\n\n\n\n if QAction.text()=='机型维护':\n print('点击机型维护')\n if QAction.text()=='故障现象维护':\n print('点击故障现象维护')\n\n # 列表框填充数据\n def ref_listview(self, listName, listDate):\n slm = slm = QStringListModel()\n slm.setStringList(listDate)\n listName.setModel(slm)\n\n # 填充品牌列表\n def br_listview(self):\n global data_dic\n global data_list\n data_dic, data_list = dal.date_all(Br, 'brID', 'brName')\n self.ref_listview(self.list_br, data_list)\n\n # 填充故障选择列表\n def list_guzhang_view(self):\n global str_guzhang\n str_guzhang = \"\"\n # temp_list=[]\n #\n # for i in temp_list:\n # box = QCheckBox(i)\n # item = QListWidgetItem()\n # self.list_guzhang.addItem(item)\n # self.list_guzhang.setItemWidget(item, box)\n\n _, temp_list = dal.date_all(EditPs, 'id', 'Name')\n for i in temp_list:\n box = QCheckBox(i)\n item = QListWidgetItem()\n self.list_guzhang.addItem(item)\n self.list_guzhang.setItemWidget(item, box)\n\n # 品牌列表左键单击\n def list_br_clicked(self, index):\n\n global data_dic\n global data_list\n global phone_dic\n global phone_list\n global phone_edit\n\n phone_edit.phID = None\n\n temp_dic = {}\n for k, v in data_dic.items():\n temp_dic[v] = k\n\n str_br = data_list[index.row()]\n str_id = str(temp_dic[str_br])\n str_filter = \"Phone.brID==\" + str_id\n\n phone_dic, phone_list = dal.date_select(Phone, 'id', 'phName', str_filter)\n self.ref_listview(self.list_phone, phone_list)\n\n # 手机列表左键单击\n def list_phone_clicked(self, index):\n global phone_dic\n global phone_list\n global phone_edit\n\n temp_dic = {}\n for k, v in phone_dic.items():\n temp_dic[v] = k\n str_ph = phone_list[index.row()]\n # str_id=temp_dic[str_ph]\n phone_edit.phID = temp_dic[str_ph]\n\n # 选择故障后按钮事件\n def select_guzhang_clicked(self):\n \"\"\"\n 得到备选统计项的字段\n :return: list[str]\n \"\"\"\n global phone_edit\n\n count = self.list_guzhang.count() # 得到QListWidget的总个数\n cb_list = [self.list_guzhang.itemWidget(self.list_guzhang.item(i))\n for i in range(count)] # 得到QListWidget里面所有QListWidgetItem中的QCheckBox\n chooses = [] # 存放被选择的数据\n for cb in cb_list:\n if cb.isChecked():\n chooses.append(cb.text())\n choose = \",\".join(chooses)\n str_t = self.txtGz.toPlainText()\n self.txtGz.setText(str_t + choose)\n # phone_edit.guzhang = choose\n\n # 显示日期选择窗口\n def E_clicked(self):\n self.Cal.setVisible(True)\n\n # 日期窗口点击\n def Cal_select(self):\n self.txt_date.setText(self.Cal.selectedDate().toString(\"yyyy-MM-dd\"))\n self.Cal.setVisible(False)\n\n # 顾客性别选择\n def sex_select(self):\n\n if self.rd_gkSex0.isChecked() == True:\n gu_ke.sex = '女士'\n if self.rd_gkSex1.isChecked() == True:\n gu_ke.sex = '先生'\n return gu_ke.sex\n\n # 控件初始化\n def view_init(self):\n self.br_listview()\n self.list_guzhang.clear()\n self.list_guzhang_view()\n self.ref_listview(self.list_phone, [])\n self.txtGz.setText(\"\")\n self.textEdit.setText(\"\")\n self.txt_gkName.setText(\"\")\n self.txt_date.setText(\"\")\n self.txt_cost.setText(\"\")\n self.txt_gkphone.setText(\"\")\n self.lbl_danhao.setText(test.dan_hao())\n\n # 检查所有控件的值\n def check_up(self):\n if self.list_br.currentIndex().row() == -1:\n QMessageBox.critical(self, \"请检查\", \"请选择品牌\", QMessageBox.Yes)\n return False\n if self.list_phone.currentIndex().row() == -1:\n QMessageBox.critical(self, \"请检查\", \"请选择机型\", QMessageBox.Yes)\n return False\n if len(self.txtGz.toPlainText()) == 0:\n QMessageBox.critical(self, \"请检查\", \"请生成故障现象\", QMessageBox.Yes)\n return False\n if len(self.textEdit.toPlainText()) == 0:\n QMessageBox.critical(self, \"请检查\", \"维修项目未录入\", QMessageBox.Yes)\n return False\n if len(self.txt_cost.text()) == 0:\n QMessageBox.critical(self, \"请检查\", \"请输入收费\", QMessageBox.Yes)\n return False\n if len(self.txt_date.text()) == 0:\n QMessageBox.critical(self, \"请检查\", \"请输入日期\", QMessageBox.Yes)\n return False\n if len(self.txt_gkName.text()) == 0:\n QMessageBox.critical(self, \"请检查\", \"请输入顾客姓名\", QMessageBox.Yes)\n return False\n if len(self.txt_gkphone.text()) == 0:\n QMessageBox.critical(self, \"请检查\", \"请输入顾客电话\", QMessageBox.Yes)\n return False\n if self.rd_gkSex1.isChecked() or self.rd_gkSex0.isChecked():\n return True\n else:\n QMessageBox.critical(self, \"请检查\", \"请选择顾客性别\", QMessageBox.Yes)\n return False\n\n # print(self.rd_gkSex0.isChecked())\n return True\n\n # 打印按钮单击\n def prSave(self):\n global phone_edit\n global gu_ke\n\n if self.check_up():\n gu_ke.Name = self.txt_gkName.text()\n gu_ke.dianhua = self.txt_gkphone.text()\n phone_edit.phedit = self.textEdit.toPlainText()\n phone_edit.jiage = self.txt_cost.text()\n phone_edit.rq = self.txt_date.text()\n phone_edit.id = self.lbl_danhao.text()\n phone_edit.guzhang = self.txtGz.toPlainText()\n gu_ke.sex = self.sex_select()\n # Sess = sessionmaker(bind=engine)\n # ss = Sess()\n # ss.add(phone_edit)\n # ss.add(gu_ke)\n # ss.commit()\n\n print(phone_edit.id,\n phone_edit.phID,\n phone_edit.guzhang,\n phone_edit.phedit,\n phone_edit.jiage,\n phone_edit.rq,\n gu_ke.Name,\n gu_ke.sex,\n gu_ke.dianhua\n )\n\n phone_edit = PhEdit()\n gu_ke = Guke()\n self.view_init()\n\n\nif __name__ == '__main__':\n QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)\n app = QApplication(sys.argv)\n win = MyWin()\n win.show()\n sys.exit(app.exec_())\n","sub_path":"logMain.py","file_name":"logMain.py","file_ext":"py","file_size_in_byte":8098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"574241387","text":"\"\"\" Cosc264 Socket Assignment\n Author: Isaac Murtagh\n itm20, 78178123\n Date: 17/8/2019\n\"\"\"\n\nimport sys\nimport socket\nimport datetime\nimport os.path\n\nBUFF_SIZE = 4096\nSERVER_ADDRESS = \"127.0.0.1\"\n\n\nclass Server:\n \"\"\"A command line application that will act as a TCP Server to send and \n recieve data.\n \"\"\"\n\n def __init__(self, port_number):\n \"\"\"Accepts a port number which must be in the range 1,025 - 64,000,\n then begins calling functions to set up the socket.\n \"\"\"\n self.s = socket.socket()\n try:\n if port_number.isdigit() and 1024 < int(port_number) <= 64000:\n self.port_number = int(port_number)\n else:\n print(\"ERROR: Port number not in range 1,025 - 64,000\")\n raise Exception\n self.bind_address()\n self.start_listen()\n self.start_loop()\n except Exception:\n pass\n finally:\n self.s.close()\n sys.exit()\n\n\n def bind_address(self):\n \"\"\"Attempts to bind to an address with given port number, otherwise \n prints an error message and raises an error, closing the socket \n and exiting.\n \"\"\"\n try:\n self.s.bind((SERVER_ADDRESS, self.port_number))\n except Exception:\n print(f\"ERROR: Could not bind to port {self.port_number}\")\n raise Exception\n\n def start_listen(self):\n \"\"\"Attempts to execute the listen() call of the socket, if this does \n not work, then an error is printed and the socket is closed.\n \"\"\"\n try:\n self.s.listen()\n except Exception:\n print(\"ERROR: Server could not listen for connections\")\n raise Exception\n\n\n def start_loop(self):\n \"\"\"Starts an infinite loop where connections are accepted by clients. \n Once a connection is complete or fails some how, the client_socket \n is closed and the loops resumes.\n \"\"\"\n while True:\n client_socket, address = self.s.accept()\n self.s.settimeout(1)\n\n try:\n self.log(f\"Connection from {address}\")\n\n file_request = self.recieve_data(client_socket)\n filename = self.decode_request(file_request)\n\n self.send_file(filename, client_socket)\n except Exception:\n pass\n finally:\n self.s.settimeout(None)\n client_socket.close()\n print()\n\n\n def decode_request(self, arr):\n \"\"\"Decodes a byte array to determine if it is correct, returning the \n filename that has been recieved by the client.\n \"\"\"\n magic_number = (arr[0] << 8) + arr[1]\n if magic_number != 0x497E:\n print(\"ERROR: File request MAGIC NUMBER incorrect\")\n raise Exception\n\n file_type = arr[2]\n if file_type != 1:\n print(\"ERROR: File request FILE TYPE incorrect\")\n raise Exception\n\n file_len = (arr[3] << 8) + arr[4]\n\n filename = \"\"\n start = 5\n for ele in arr[start:start + file_len]:\n filename += chr(ele)\n\n return filename\n\n\n def send_file(self, filename, client):\n \"\"\"Attempts to send the requested file to the client, if it does not \n exist then an appropriate response is sent to the client informing\n them of this outcome. If the file exists, but was unable to be \n opened or read, an error occurs and the client is dropped.\n \"\"\"\n code = 1\n contents = \"\"\n\n if (os.path.exists(filename)):\n try:\n file = open(filename)\n contents = file.read()\n except Exception:\n print(\"ERROR: File is unable to be opened or read\")\n code = 0\n finally:\n file.close()\n else:\n code = 0\n print(f\"'{filename}' does not exist within the server.\")\n\n response = self.create_response(code, contents)\n\n try:\n client.send(response)\n except Exception:\n print(\"ERROR: Was unable to send response back to client\")\n raise Exception\n\n if code == 0:\n print(\"A response has been sent to client that the file \" +\n \"could not be found\")\n\n print(f\"File transfer complete, {len(response)} bytes \" +\n \"transferred to client.\")\n\n\n def create_response(self, code, contents):\n \"\"\"Returns a byte array payload for the file request\"\"\"\n file_len = len(contents)\n magic_num = 0x497E\n file_type = 2\n\n b = bytearray(bytes(8))\n b[0] = (magic_num >> 8)\n b[1] = magic_num - (b[0] << 8)\n b[2] = file_type\n b[3] = code\n b[4] = (file_len >> 24)\n b[5] = (file_len - (b[4] * 2**24)) >> 16\n b[6] = (file_len - (b[4] * 2**24 + b[5] * 2**16)) >> 8\n b[7] = (file_len - (b[4] * 2**24 + b[5] * 2**16 + b[6] * 2**8))\n\n return b + bytearray(contents.encode())\n\n\n def recieve_data(self, client):\n \"\"\"Attempts to recieve a file request and checks if it is correct. \n If it takes longer than 1 second to recieve data, a timeout\n error occurs.\n \"\"\"\n data = b''\n while True:\n try:\n part = client.recv(BUFF_SIZE)\n except:\n print(\"ERROR: Time out error has occured\")\n data += part\n if len(part) < BUFF_SIZE:\n break\n return bytearray(data)\n\n\n def log(self, message):\n \"\"\"logs the current time\"\"\"\n time = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n print(f\"[{time}] {message}\")\n\n\nServer(input())","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":5860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"321023695","text":"#!/usr/bin/python3\n\n# discord-py requirements\nimport discord\nfrom discord.ext import commands\nimport asyncio\n\n# For DB Functionality\nimport sqlite3\nimport datetime\n\n# Other utilities\nimport random\nfrom .utils.paginator import Pages\n\n# For remindme functionality\nimport re\n\n\nclass Reminder:\n def __init__(self, bot):\n self.bot = bot\n self.frequencies = {\"daily\": 1, \"weekly\": 7, \"monthly\": 30}\n\n async def check_reminders(self):\n \"\"\"\n Co-routine that periodically checks if the bot must issue reminders to users.\n :return: None\n \"\"\"\n\n await self.bot.wait_until_ready()\n while not self.bot.is_closed():\n conn = sqlite3.connect(self.bot.config.db_path)\n c = conn.cursor()\n g = (guild for guild in self.bot.guilds\n if guild.name == 'McGill University')\n try:\n guild = next(g)\n except StopIteration:\n return\n reminders = c.execute('SELECT * FROM Reminders').fetchall()\n for i in range(len(reminders)):\n member = discord.utils.get(guild.members, id=reminders[i][0])\n\n # If non-repeating reminder is found\n if reminders[i][3] == 'once':\n # Check date to remind user\n reminder_activation_date = datetime.datetime.strptime(\n reminders[i][4], \"%Y-%m-%d %H:%M:%S.%f\")\n # Compute future_date-current_date and if <= 0:00:00, means time is due to remind user\n if reminder_activation_date - datetime.datetime.now(\n ) <= datetime.timedelta(0):\n await member.send(\"Reminding you to {}!\".format(\n reminders[i][2]))\n # Remove from from DB non-repeating reminder\n c.execute(\n 'DELETE FROM Reminders WHERE Reminder=? AND ID=? AND DATE=?',\n (reminders[i][2], reminders[i][0],\n reminder_activation_date))\n conn.commit()\n await asyncio.sleep(1)\n else:\n last_date = datetime.datetime.strptime(\n reminders[i][5], \"%Y-%m-%d %H:%M:%S.%f\")\n if datetime.datetime.now() - last_date > datetime.timedelta(\n days=self.frequencies[reminders[i][3]]):\n await member.send(\"Reminding you to {}! [{:d}]\".format(\n reminders[i][2], i + 1))\n\n c.execute(\n \"UPDATE 'Reminders' SET LastReminder = ? WHERE Reminder = ?\",\n (datetime.datetime.now(), reminders[i][2]))\n conn.commit()\n await asyncio.sleep(1)\n conn.close()\n await asyncio.sleep(60 * 1)\n\n @commands.command(aliases=['rm', 'rem'])\n async def remindme(self, ctx, *, quote: str = \"\"):\n \"\"\"\n Parses the reminder and adds a one-time reminder to the reminder database or\n calls remindme_repeating to deal with repetitive reminders when keyword\n \"daily\", \"weekly\" or \"monthly\" is found.\n \"\"\"\n\n if quote == \"\":\n await ctx.send(\n '**Usage:** \\n `?remindme in 1 hour and 20 minutes and 20 seconds to eat` **or** \\n '\n '`?remindme at 2020-04-30 11:30 to graduate` **or** \\n `?remindme daily to sleep`'\n )\n\n # Copies original reminder message and sets lowercase for regex.\n original_input_copy = quote.lower()\n\n # Letter numbers to number numbers\n replacements = [\n (r\"twenty[-\\s]one\", \"21\"), (r\"twenty[-\\s]two\",\n \"22\"), (r\"twenty[-\\s]three\", \"23\"),\n (r\"twenty[-\\s]four\",\n \"24\"), (r\"twenty[-\\s]five\",\n \"25\"), (r\"twenty[-\\s]six\",\n \"26\"), (r\"twenty[-\\s]seven\",\n \"27\"), (r\"twenty[-\\s]eight\",\n \"28\"), (r\"twenty[-\\s]nine\", \"29\"),\n (r\"thirty[-\\s]one\",\n \"31\"), (r\"thirty[-\\s]two\",\n \"32\"), (r\"thirty[-\\s]three\",\n \"33\"), (r\"thirty[-\\s]-four\",\n \"34\"), (r\"thirty[-\\s]four\",\n \"34\"), (r\"thirty[-\\s]five\", \"35\"),\n (r\"thirty[-\\s]six\",\n \"36\"), (r\"thirty[-\\s]seven\",\n \"37\"), (r\"thirty[-\\s]eight\",\n \"38\"), (r\"thirty[-\\s]nine\",\n \"39\"), (r\"forty[-\\s]one\",\n \"41\"), (r\"forty[-\\s]two\", \"42\"),\n (r\"forty[-\\s]three\",\n \"43\"), (r\"forty[-\\s]four\",\n \"44\"), (r\"forty[-\\s]five\",\n \"45\"), (r\"forty[-\\s]six\",\n \"46\"), (r\"forty[-\\s]seven\",\n \"47\"), (r\"forty[-\\s]eight\", \"48\"),\n (r\"forty[-\\s]nine\",\n \"49\"), (\"tomorrow\", \"1 day\"), (\"next week\",\n \"1 week\"), (\"later\",\n \"6 hours\"), (\"a\", \"1\"),\n (\"an\", \"1\"), (\"zero\",\n \"0\"), (\"no\", \"0\"), (\"none\",\n \"0\"), (\"one\", \"1\"), (\"two\", \"2\"),\n (\"three\", \"3\"), (\"four\", \"4\"), (\"five\",\n \"5\"), (\"six\", \"6\"), (\"seven\", \"7\"),\n (\"eight\",\n \"8\"), (\"nine\",\n \"9\"), (\"ten\",\n \"10\"), (\"eleven\",\n \"11\"), (\"twelve\",\n \"12\"), (\"thirteen\",\n \"13\"), (\"fourteen\",\n \"14\"), (\"fifteen\",\n \"15\"),\n (\"sixteen\",\n \"16\"), (\"seventeen\",\n \"17\"), (\"eighteen\",\n \"18\"), (\"nineteen\",\n \"19\"), (\"twenty\",\n \"20\"), (\"thirty\",\n \"30\"), (\"forty\",\n \"40\"), (\"fifty\",\n \"50\")\n ]\n\n # Regex for misspellings of time units\n units = {\n \"years\": \"ye?a?r?s?\",\n \"days\": \"da?y?s?\",\n \"hours\": \"ho?u?r?s?\",\n \"seconds\": \"se?c?o?n?d?s?\",\n \"minutes\": \"mi?n?u?t?e?s?\",\n \"weeks\": \"we?e?k?s?\"\n }\n\n # Stores units + number for calculating timedelta\n time_offset = {\n \"years\": 0,\n \"days\": 0,\n \"hours\": 0,\n \"seconds\": 0,\n \"minutes\": 0,\n \"weeks\": 0\n }\n\n punctuation_chars = \".,+&/ \"\n string_word_separator_regex = r\"(\\s|[\" + punctuation_chars + \"])+\"\n time_separator_regex = r\"(,|\\+|&|and|plus|in)\"\n # Regex to match units below (Which accounts for spelling mistakes!)\n unit_regex = r\"(\" + \"|\".join(list(units.values())) + \")\"\n # Matches a natural number\n number_regex = r\"[1-9]+[0-9]*(|\\.[0-9]+)\"\n # Regex for format YYYY-MM-DD\n ymd_regex = r\"(2[0-1][0-9][0-9])[\\s./-]((1[0-2]|0?[1-9]))[\\s./-](([1-2][0-9]|3[0-1]|0?[1-9]))\"\n # Regex for time HH:MM\n hm_regex = r\"\\b([0-1]?[0-9]|2[0-4]):([0-5][0-9])\"\n\n # Replaces word representation of numbers into numerical representation\n for k, v in replacements:\n original_input_copy = re.sub(r\"\\b\" + k + r\"\\b\", v,\n original_input_copy)\n\n # Split on spaces and other relevant punctuation\n input_segments = re.split(string_word_separator_regex,\n original_input_copy)\n input_segments = [x.strip(punctuation_chars) for x in input_segments]\n\n # Remove empty strings from list\n input_segments = [x for x in input_segments if x != \"\"]\n\n time_segments = []\n last_number = \"0\"\n first_reminder_segment = \"\"\n \"\"\" Checks the following logic:\n 1. If daily, weekly or monthly is specified, go to old reminder function for repetitive reminders\n for all input segments:\n 2. If one of the keywords commonly used for listing times is there, continue\n 3. If a number is found, save the number, mark that a number has been found for next iteration\n 4. Elif: A \"unit\" (years, days ... etc.) has been found, append the last number + its unit\n 5. Lastly: save beginning of \"reminder quote\" and end loop\n \"\"\"\n\n if len(input_segments) > 0 and (input_segments[0] == \"daily\"\n or input_segments[0] == \"weekly\"\n or input_segments[0] == \"monthly\"):\n await self.__remindme_repeating(\n ctx,\n input_segments[0],\n quote=quote[len(input_segments[0]) + 1:])\n return\n for segment in input_segments:\n if re.match(\"^\" + time_separator_regex + \"$\", segment):\n continue\n if re.match(\"^\" + number_regex + \"$\", segment):\n last_number = segment\n elif re.match(\"^\" + unit_regex + \"$\", segment):\n time_segments.append(last_number + \" \" + segment)\n else:\n first_reminder_segment = segment\n break\n\n # They probably dont want their reminder nuked of punctuation, spaces\n # and formatting, so extract from original string.\n reminder = quote[quote.index(first_reminder_segment):]\n\n # Date-based reminder triggered by \"at\" and \"on\" keywords\n if input_segments[0] == 'at' or input_segments[0] == 'on':\n date_result = re.search(ymd_regex,\n original_input_copy) # Gets YYYY-mm-dd\n time_result = re.search(hm_regex,\n original_input_copy) # Gets HH:MM\n\n # If both a date and a time is found, continue\n if date_result and time_result:\n # Compute datetime.Object\n absolute_duedate = datetime.datetime.strptime(\n date_result.group(1) + \"-\" + date_result.group(2) + \"-\" +\n date_result.group(4) + \"-\" + time_result.group(1) + \"-\" +\n time_result.group(2) + \"-\" + str(0.1),\n \"%Y-%m-%d-%H-%M-%S.%f\")\n\n # Strips \"to\" and dates from the reminder message\n time_input_end = time_result.span()[1]\n if re.match(\n \"to\",\n reminder[time_input_end:time_input_end + 4].strip(),\n re.IGNORECASE):\n reminder = reminder[time_input_end + 3:].strip()\n else:\n reminder = reminder[time_input_end + 1:].strip()\n\n # Add message to database\n conn = sqlite3.connect(self.bot.config.db_path)\n c = conn.cursor()\n t = (ctx.message.author.id, ctx.message.author.name, reminder,\n \"once\", absolute_duedate, datetime.datetime.now())\n try:\n c.execute(\n 'INSERT INTO Reminders VALUES (?, ?, ?, ?, ?, ?)', t)\n except sqlite3.OperationalError:\n c.execute(\n \"CREATE TABLE 'Reminders' ('ID'INTEGER,'Name'TEXT,'Reminder'TEXT,'Frequency'TEXT,'Date'\\\n TEXT,'LastReminder'TEXT)\")\n c.execute(\n 'INSERT INTO Reminders VALUES (?, ?, ?, ?, ?. ?)', t)\n\n # Send user information and close database\n reminders = c.execute('SELECT * FROM Reminders WHERE ID =?',\n (ctx.message.author.id, )).fetchall()\n await ctx.author.send(\n 'Hi {}! \\nI will remind you to {} on {} at {} unless you send me a message to stop '\n 'reminding you about it! [{:d}]'.format(\n ctx.author.name, reminder, date_result.group(0),\n time_result.group(0),\n len(reminders) + 1))\n\n await ctx.send('Reminder added.')\n\n conn.commit()\n conn.close()\n\n return\n\n # Wrong input feedback depending on what is missing.\n await ctx.send(\n \"Please check your private messages for information on correct syntax!\"\n )\n await ctx.author.send(\"Please double check the following: \")\n if not date_result:\n await ctx.author.send(\n \"Make sure you have specified a date in the format: `YYYY-mm-dd`\"\n )\n if not time_result:\n await ctx.author.send(\n \"Make sure you have specified a time in the 24H format: `HH:MM`\"\n )\n await ctx.author.send(\n \"E.g.: `?remindme on 2020-12-05 at 21:44 to feed Marty`\")\n return\n\n # Regex for the number and time units and store in \"match\"\n for segment in time_segments:\n match = re.match(\n \"^(\" + number_regex + \")\" + r\"\\s+\" + unit_regex + \"$\", segment)\n number = float(match.group(1))\n\n # Regex potentially misspelled time units and match to proper spelling\n for regex in units:\n if re.match(\"^\" + units[regex] + \"$\", match.group(3)):\n time_offset[regex] += number\n\n # Convert years to a unit that datetime will understand\n time_offset[\"days\"] = time_offset[\"days\"] + time_offset[\"years\"] * 365\n\n time_now = datetime.datetime.now() # Current time\n reminder_time = time_now + datetime.timedelta(\n days=time_offset[\"days\"],\n hours=time_offset[\"hours\"],\n seconds=time_offset[\"seconds\"],\n minutes=time_offset[\"minutes\"],\n weeks=time_offset[\"weeks\"]) # Time to be reminded on\n if time_now == reminder_time: # No time in argument, or it's zero.\n await ctx.send(\"Please specify a time! E.g.: `?remindme in 1 hour \"\n + reminder + \"`\")\n return\n # Strips the string \"to \" from reminder messages\n if reminder[:3].lower() == 'to ':\n reminder = reminder[3:]\n # DB: Date will hold TDELTA (When reminder is due), LastReminder will hold datetime.datetime.now()\n conn = sqlite3.connect(self.bot.config.db_path)\n c = conn.cursor()\n t = (ctx.message.author.id, ctx.message.author.name, reminder, \"once\",\n reminder_time, time_now)\n reminders = c.execute('SELECT * FROM Reminders WHERE ID =?',\n (ctx.message.author.id, )).fetchall()\n try:\n c.execute('INSERT INTO Reminders VALUES (?, ?, ?, ?, ?, ?)', t)\n except sqlite3.OperationalError:\n c.execute(\n \"CREATE TABLE 'Reminders' ('ID'INTEGER,'Name'TEXT,'Reminder'TEXT,'Frequency'TEXT,'Date'\\\n TEXT,'LastReminder'TEXT)\")\n c.execute('INSERT INTO Reminders VALUES (?, ?, ?, ?, ?. ?)', t)\n\n # Gets reminder date in YYYY-MM-DD format\n due_date = str(\n datetime.date(reminder_time.year, reminder_time.month,\n reminder_time.day))\n # Gets reminder time in HH:MM\n due_time = str(reminder_time).split()[1].split(\":\")[0] + \":\" + str(\n reminder_time).split()[1].split(\":\")[1]\n await ctx.author.send(\n 'Hi {}! \\nI will remind you to {} on {} at {} unless you send me a message to stop '\n 'reminding you about it! [{:d}]'.format(ctx.author.name, reminder,\n due_date, due_time,\n len(reminders) + 1))\n await ctx.send('Reminder added.')\n conn.commit()\n conn.close()\n\n @commands.command(aliases=['lr'])\n async def list_reminders(self, ctx):\n \"\"\"\n List reminders\n \"\"\"\n await ctx.trigger_typing()\n if not isinstance(ctx.message.channel, discord.DMChannel):\n await ctx.send(\n 'Slide into my DMs ;). \\n `List Reminder feature only available when DMing Marty.`'\n )\n return\n else:\n pass\n conn = sqlite3.connect(self.bot.config.db_path)\n c = conn.cursor()\n rem_author = ctx.message.author\n author_id = rem_author.id\n t = (author_id, )\n c.execute('SELECT * FROM Reminders WHERE ID = ?', t)\n rem_list = c.fetchall()\n if rem_list:\n quote_list_text = [\n ('[{}] (Frequency: {}' +\n (' at {}'.format(quote[4].split('.')[0])\n if quote[3] == 'once' else '') + ') - {}').format(\n i + 1, quote[3].capitalize(), quote[2])\n for i, quote in zip(range(len(rem_list)), rem_list)\n ]\n p = Pages(\n ctx,\n item_list=quote_list_text,\n title=\"{}'s reminders\".format(rem_author.display_name))\n await p.paginate()\n\n def msg_check(msg):\n try:\n return (0 <= int(msg.content) <= len(rem_list)\n and msg.author.id == author_id\n and msg.channel == ctx.message.channel)\n except ValueError:\n return False\n\n while p.delete:\n await ctx.send(\n 'Delete option selected. Enter a number to specify which '\n 'reminder you want to delete, or enter 0 to return.',\n delete_after=60)\n try:\n message = await self.bot.wait_for(\n 'message', check=msg_check, timeout=60)\n except asyncio.TimeoutError:\n await ctx.send(\n 'Command timeout. You may want to run the command again.',\n delete_after=60)\n break\n else:\n index = int(message.content) - 1\n if index == -1:\n await ctx.send('Exit delq.', delete_after=60)\n else:\n t = (rem_list[index][0], rem_list[index][2])\n del rem_list[\n index] # Remove deleted reminder from list.\n c.execute(\n 'DELETE FROM Reminders WHERE ID = ? AND '\n 'Reminder = ?', t)\n conn.commit()\n await ctx.send('Reminder deleted', delete_after=60)\n p.itemList = [('[{}] (Frequency: {}' + (\n ' at {}'.format(quote[4].split('.')[0])\n if quote[3] == 'once' else '') + ') - {}').format(\n i + 1, quote[3].capitalize(), quote[2])\n for i, quote in zip(\n range(len(rem_list)), rem_list)]\n await p.paginate()\n conn.commit()\n conn.close()\n else:\n await ctx.send('No reminder found.', delete_after=60)\n\n async def __remindme_repeating(self,\n ctx,\n freq: str = \"\",\n *,\n quote: str = \"\"):\n \"\"\"\n Called by remindme to add a repeating reminder to the reminder database.\n \"\"\"\n\n bad_input = False\n if freq not in self.frequencies.keys():\n await ctx.send(\n \"Please ensure you specify a frequency from the following list: `daily`, `weekly`, \"\n \"`monthly`, before your message!\")\n bad_input = True\n if quote == \"\":\n if bad_input and freq == \"\" or not bad_input:\n await ctx.send(\"Please specify a reminder message!\")\n else:\n pass\n bad_input = True\n if bad_input:\n return\n\n conn = sqlite3.connect(self.bot.config.db_path)\n c = conn.cursor()\n t = (ctx.message.author.id, ctx.message.author.name, quote, freq,\n datetime.datetime.now(), datetime.datetime.now())\n reminders = c.execute(\n 'SELECT * FROM Reminders WHERE Reminder =? AND ID = ?',\n (quote, ctx.message.author.id)).fetchall()\n if len(reminders) > 0:\n await ctx.send(\n \"The reminder `{}` already exists in your database. Please specify a unique reminder \"\n \"message!\".format(quote))\n return\n reminders = c.execute('SELECT * FROM Reminders WHERE ID =?',\n (ctx.message.author.id, )).fetchall()\n try:\n c.execute('INSERT INTO Reminders VALUES (?, ?, ?, ?, ?, ?)', t)\n except sqlite3.OperationalError:\n c.execute(\n \"CREATE TABLE 'Reminders' ('ID'INTEGER,'Name'TEXT,'Reminder'TEXT,'Frequency'TEXT,'Date'\\\n TEXT,'LastReminder'TEXT)\")\n c.execute('INSERT INTO Reminders VALUES (?, ?, ?, ?, ?. ?)', t)\n # Strips the string \"to \" from reminder messages\n if quote[:3].lower() == \"to \":\n quote = quote[3:]\n await ctx.author.send(\n 'Hi {}! \\nI will remind you to {} {} until you send me a message to stop '\n 'reminding you about it! [{:d}]'.format(ctx.author.name, quote,\n freq,\n len(reminders) + 1))\n await ctx.send('Reminder added.')\n conn.commit()\n conn.close()\n\n\ndef setup(bot):\n database = Reminder(bot)\n bot.add_cog(database)\n bot.loop.create_task(database.check_reminders())\n","sub_path":"cogs/reminder.py","file_name":"reminder.py","file_ext":"py","file_size_in_byte":22746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"336907034","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nimport sys\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nloaddatapath=os.getenv(\"PWD\")+'/../'\nsys.path.append(loaddatapath)\nimport loaddata as LD\nimport pdb \nplt.rc('font',family='Arial')\n\nif __name__==\"__main__\":\n columnsName_CPG=['RFO1','RFO2','RHO1','RHO2','LFO1','LFO2','LHO1','LKO2',\n 'RFSA','RHSA','LFSA','LHSA',\n 'RFACITerm0','RFACITerm1','RHACITerm0','RHACITerm1','LFACITerm0','LFACITerm1','LHACITerm0','LHACITerm1',\n 'RFSFTerm0','RFSFTerm1','RHSFTerm0','RHSFTerm1','LFSFTerm0','LFSFTerm1','LHSFTerm0','LHSFTerm1',\n 'RFFM','RHFM','LFFM','LHFM']\n fileName_CPG=\"controlfile_CPG\"\n columnsName_GRF=['RF','RH','LF','LH']\n fileName_GRF='sensorfile_GRF'\n fileName_joint='sensorfile_joint'\n columnsName_joint=['j1','j2','j3','j4','j5,''j6',\n 'j7','j8','j9','j10','j11','j12','s'\n ]*2\n fileName_POSE='sensorfile_POSE'\n columnsName_POSE=['roll','picth','yaw', 'x','y','z']\n freq=60.0 # 60Hz,\n joint_data=LD.loadData(fileName_joint,columnsName_joint,'1225222042')\n pose_data=LD.loadData(fileName_POSE,columnsName_POSE,'1225222042')\n grf_data=LD.loadData(fileName_GRF,columnsName_GRF,'1225222042')\n\n #2) postprecessing \n if len(sys.argv)>=2:\n run_id = int(sys.argv[1]) # The id of the experiments\n else:\n run_id = 0\n\n read_rows=min([40000,grf_data[run_id].shape[0], pose_data[run_id].shape[0]])\n start_point=1000\n end_point=read_rows\n time = np.linspace(int(start_point/freq),int(end_point/freq),end_point-start_point)\n\n #3) plot\n font_legend = {'family' : 'Arial',\n 'weight' : 'light',\n 'size' : 10,\n 'style' :'italic'\n }\n font_label = {'family' : 'Arial',\n 'weight' : 'light',\n 'size' : 12,\n 'style' :'normal'\n }\n\n font_title = {'family' : 'Arial',\n 'weight' : 'light',\n 'size' : 12,\n 'style' :'normal'\n }\n\n figsize=(10.5118,4.1244)\n fig,axs = plt.subplots(2,1,figsize=figsize,constrained_layout=False)\n fig.subplots_adjust(hspace=0.15)\n fig.subplots_adjust(left=0.14)\n fig.subplots_adjust(bottom=0.11)\n fig.subplots_adjust(right=0.98)\n fig.subplots_adjust(top=0.98)\n xticks=list(range(int(time[0]),int(time[-1])+1,1))\n\n idx=0\n axs[idx].plot(time,grf_data[run_id].iloc[start_point:end_point,0],'r')\n axs[idx].plot(time,grf_data[run_id].iloc[start_point:end_point,1],'g')\n axs[idx].plot(time,grf_data[run_id].iloc[start_point:end_point,2],'b')\n axs[idx].plot(time,grf_data[run_id].iloc[start_point:end_point,3],'k')\n #axs[idx].plot(time,joint_data[run_id].iloc[start_point:end_point,4],'b')\n axs[idx].legend([r'Pitch'], loc='upper left',prop=font_legend)\n axs[idx].grid(which='both',axis='x',color='k',linestyle=':')\n axs[idx].axis([time[0],time[-1],-3,3],'tight')\n axs[idx].set_xticks(xticks)\n axs[idx].set_xticklabels(labels=[])\n axs[idx].set_yticks([-1.0,0.0,1.0])\n #axs[idx].set_yticklabels(labels=['-1.0','0.0','1.0'],fontweight='light')\n axs[idx].set_ylabel('CPG',font_label)\n #axs[idx].set_title(\"CPG outputs of the right front leg\",font2)\n#\n# idx=1\n# axs[idx].plot(time,grf_data[run_id].iloc[start_point:end_point,1],'b')\n# axs[idx].legend([r'Pitch'], loc='upper left',prop=font_legend)\n# axs[idx].grid(which='both',axis='x',color='k',linestyle=':')\n# axs[idx].axis([time[0],time[-1],-1.0,1.0],'tight')\n# axs[idx].set_xticks(xticks)\n# axs[idx].set_xticklabels(labels=[])\n# axs[idx].set_yticks([-1.0,0.0,1.0])\n# axs[idx].set_yticklabels(labels=['-1.0','0.0','1.0'],fontweight='light')\n# axs[idx].set_ylabel('CPG',font_label)\n# #axs[idx].set_title(\"CPG outputs of the right front leg\",font2)\n# axs[idx].set_xlabel('Time [s]',font_label)\n# #axs[idx].set_title(\"Adaptive control input term of the right front leg\")\n#\n \n plt.savefig('/media/suntao/DATA/Research/P1_workspace/Figures/Fig13_source.svg')\n plt.show()\n\n","sub_path":"P1/Fig13.py","file_name":"Fig13.py","file_ext":"py","file_size_in_byte":4044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"287452285","text":"from lg_msg_defs.msg import WindowGeometry\nimport subprocess\nimport os\n\n\nclass WindowIdentityError(Exception):\n pass\n\n\ndef regex_escape(raw):\n \"\"\"Escape lua regex.\"\"\"\n escaped = raw\n escaped = escaped.replace(\"%\", \"%%\")\n escaped = escaped.replace(\"^\", \"%^\")\n escaped = escaped.replace(\"$\", \"%$\")\n escaped = escaped.replace(\"(\", \"%(\")\n escaped = escaped.replace(\")\", \"%)\")\n escaped = escaped.replace(\"[\", \"%[\")\n escaped = escaped.replace(\"]\", \"%]\")\n escaped = escaped.replace(\".\", \"%.\")\n escaped = escaped.replace(\"*\", \"%*\")\n escaped = escaped.replace(\"+\", \"%+\")\n escaped = escaped.replace(\"-\", \"%-\")\n escaped = escaped.replace(\"?\", \"%?\")\n escaped = escaped.replace(\"\\0\", \"%z\")\n return escaped\n\n\ndef get_rule_types(window):\n \"\"\"Get a dict of rule types and values for the window.\n\n Args:\n window (ManagedWindow)\n\n Returns:\n Dict[str,str]\n\n Raises:\n WindowIdentityError: If the window identity can not be determined.\n \"\"\"\n rules = {}\n if window.w_name is not None:\n rules['name'] = regex_escape(window.w_name)\n if window.w_instance is not None:\n rules['instance'] = regex_escape(window.w_instance)\n if window.w_class is not None:\n rules['class'] = regex_escape(window.w_class)\n if not rules:\n raise WindowIdentityError('Could not determine window identity')\n return rules\n\n\ndef get_rule_pattern(window):\n \"\"\"Get a rule to match the given window.\n\n Args:\n window (ManagedWindow)\n\n Returns:\n str: Comma-separated awesome rules to match the window.\n \"\"\"\n def pattern(r):\n return \"%s = '%s'\" % r\n patternized = list(map(pattern, iter(get_rule_types(window).items())))\n return ', '.join(patternized)\n\n\ndef get_properties(window, chrome_kiosk_workaround=False):\n \"\"\"Get a properties string to converge the window to its state.\n\n Args:\n window (ManagedWindow)\n\n Returns:\n str: Comma-separated awesome properties for the window.\n \"\"\"\n prop_list = [\n \"border_width = 0\",\n \"size_hints_honor = false\",\n \"floating = true\",\n # Chrome Kiosk Workaround:\n # Trick Chrome in kiosk mode by setting fullscreen to true here.\n # In the callback we will set it to false.\n \"fullscreen = {}\".format('true' if chrome_kiosk_workaround else 'false'),\n \"maximized = false\",\n \"hidden = {}\".format('false' if window.is_visible else 'true'),\n \"minimized = {}\".format('false' if window.is_visible else 'true'),\n \"opacity = {}\".format(1 if window.is_visible else 0),\n ]\n if window.geometry is not None:\n prop_list.extend([\n \"width = {}\".format(window.geometry.width),\n \"height = {}\".format(window.geometry.height),\n ])\n return ', '.join(prop_list)\n\n\ndef get_callback(window):\n \"\"\"Get an awesome callback to move the window to its proper spot.\n\n Args:\n window (ManagedWindow)\n\n Returns:\n str: awesome callback for window geometry.\n \"\"\"\n if window.geometry is not None:\n return \"function(c) awful.client.property.set(c, 'fullscreen', false) c.fullscreen = false c:geometry({x=%d, y=%d, width=%d, height=%d}) c:connect_signal('property::fullscreen', function() if c.fullscreen then c.fullscreen = false end end) end\" % (\n window.geometry.x,\n window.geometry.y,\n window.geometry.width,\n window.geometry.height,\n )\n else:\n return \"\"\n\n\ndef get_entry(window, chrome_kiosk_workaround=False):\n \"\"\"Get the full awesome (awful) rule that will converge the window.\n\n Args:\n window (ManagedWindow)\n\n Returns:\n str: awesome rule for the window.\n \"\"\"\n rule = get_rule_pattern(window)\n properties = get_properties(window, chrome_kiosk_workaround)\n callback = get_callback(window)\n return \"{ rule = { %s }, properties = { %s }, callback = %s }\" % (rule, properties, callback)\n\n\ndef get_subtractive_script(window):\n \"\"\"Get a script that will remove existing awesome (awful) rules for the\n window.\n\n Args:\n window (ManagedWindow)\n\n Returns:\n str: Lua code to remove existing rules for the window.\n \"\"\"\n rules = get_rule_types(window)\n\n def rule(r):\n return \"rule['rule']['%s'] == '%s'\" % r\n checks = ' and '.join(map(rule, iter(rules.items())))\n return \"for key,rule in pairs(awful.rules.rules) do if rule['rule'] ~= nil and {checks} then table.remove(awful.rules.rules, key) end end\".format(\n checks=checks\n )\n\n\ndef get_additive_script(window, chrome_kiosk_workaround=False):\n \"\"\"Get a script that will add an awesome (awful) rule for the window.\n\n Args:\n window (ManagedWindow)\n\n Returns:\n str: Lua code to add the window rule.\n \"\"\"\n entry = get_entry(window, chrome_kiosk_workaround)\n return \"table.insert(awful.rules.rules, 1, {entry})\".format(entry=entry)\n\n\ndef get_apply_script(window):\n \"\"\"Get a script that will apply rules to all awesome window clients that\n match the window's identity.\n\n Args:\n window (ManagedWindow)\n\n Returns:\n str: Lua code to apply rules to all matching windows.\n \"\"\"\n pattern = get_rule_pattern(window)\n return \"for k,c in pairs(client.get()) do if awful.rules.match(c, {%s}) then awful.rules.apply(c) end end\" % pattern\n\n\ndef get_script(window, chrome_kiosk_workaround=False):\n \"\"\"Combine scripts to form a mega-script that fixes everything.\n\n Args:\n window (ManagedWindow)\n\n Returns:\n str: Lua code to make awesome put the window in the right place.\n \"\"\"\n return ' '.join([\n \"local awful = require('awful') awful.rules = require('awful.rules')\",\n get_subtractive_script(window),\n get_additive_script(window, chrome_kiosk_workaround),\n get_apply_script(window)\n ])\n\n\ndef get_awesome_pid():\n awesome_pid = None\n\n try:\n awesome_pid = int(subprocess.check_output(['pidof', 'x-window-manager']))\n except Exception:\n pass\n try:\n awesome_pid = int(subprocess.check_output(['pidof', 'awesome']))\n except Exception:\n pass\n try:\n awesome_pid = int(subprocess.check_output(['pidof', '/usr/bin/awesome']))\n except Exception:\n pass\n\n return awesome_pid\n\n\ndef get_environ():\n \"\"\"Attempt to copy relevant environment of the window manager.\"\"\"\n awesome_pid = get_awesome_pid()\n if awesome_pid is None:\n raise Exception('Could not find awesome pid')\n\n with open('/proc/{}/environ'.format(awesome_pid), 'r') as f:\n awesome_environ_raw = f.read().strip('\\0')\n\n def split_environ(raw):\n pair = raw.split('=', 1)\n return pair[0], pair[1]\n pairs = list(map(split_environ, awesome_environ_raw.split('\\0')))\n awesome_environ = dict((p[0], p[1]) for p in pairs)\n\n env = os.environ.copy()\n\n def copy_environ(k):\n env[k] = awesome_environ[k]\n copy_environ('DISPLAY')\n copy_environ('DBUS_SESSION_BUS_ADDRESS')\n copy_environ('XAUTHORITY')\n\n return env\n\n# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n","sub_path":"lg_common/src/lg_common/awesome.py","file_name":"awesome.py","file_ext":"py","file_size_in_byte":7145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"443356208","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 5 13:58:31 2021\r\n\r\n@author: ustc\r\n\"\"\"\r\n# this is a programmon which searches restaurants in a city,and then rank them\r\n\r\nfrom flask import Flask, render_template\r\nimport requests\r\nimport json\r\nimport time\r\nimport random\r\nimport re\r\nfrom bs4 import BeautifulSoup\r\n\r\ndef getjson(location,page_num=0):#get data from the API of baidu map\r\n headers = {'User-Agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.16) Gecko/20201130 Firefox/3.5.16'}\r\n restaurant = {'q':'美食',\r\n #keyword is the yummy food\r\n \r\n 'region': location,\r\n 'scope': '2',\r\n 'page-size':20,\r\n 'page_num': page_num,\r\n 'output':'json',\r\n #'ak':'8Aoqw1l43V8GTCniw0coFWVPVBgPYRjO' #a backup for 'ak',which is an access to API\r\n 'ak':'DDtVK6HPruSSkqHRj5gTk0rc' \r\n }\r\n r = requests.get(\"http://api.map.baidu.com/place/v2/search\",params=restaurant,headers= headers)\r\n decodejson = json.loads(r.text)\r\n #print(decodejson)\r\n return decodejson\r\n\r\n\r\nclass resturants_of_city:\r\n def __init__ (self,city,region1,region2,region3,region4):\r\n self.city = city\r\n self.region1 = region1\r\n self.region2 = region2\r\n self.region3 = region3\r\n self.region4 = region4 \r\n \r\n def search_and_show(self):\r\n region_list = {self.region1,self.region2,self.region3,self.region4}\r\n \r\n #initial the list\r\n best1=most_popular1=most_expensive1={'rank':1,'name':'0','image':'0','address':'0','price':0,'overall_rating':0,'comment_num':0}\r\n best2=most_popular2=most_expensive2={'rank':2,'name':'0','image':'0','address':'0','price':0,'overall_rating':0,'comment_num':0}\r\n best3=most_popular3=most_expensive3={'rank':3,'name':'0','image':'0','address':'0','price':0,'overall_rating':0,'comment_num':0}\r\n \r\n for each_region in region_list:\r\n not_last_page = True\r\n page_num = 0\r\n while not_last_page:\r\n decodejson = getjson(self.city + each_region,page_num)\r\n print(each_region,page_num)\r\n time.sleep(random.random())#avoid the restriction from baidu API\r\n \r\n try:\r\n decodejson['total'] #something goes wrong when it turns the last page\r\n \r\n if decodejson['total']!=0:\r\n for each_place in decodejson['results']:#get information of a restaurant\r\n place = each_place['name']\r\n address = each_place['address']\r\n try:\r\n price = float(each_place['detail_info']['price'] ) \r\n except:\r\n price = 0\r\n try:\r\n rating = float(each_place['detail_info']['overall_rating'] ) \r\n except:\r\n rating = 0\r\n try:\r\n comment_num = int(each_place['detail_info']['comment_num'] ) \r\n except:\r\n comment_num = 0\r\n \r\n output = '\\t'.join([place,address,str(price),str(rating),str(comment_num)]) + '\\r\\n'\r\n #print(output)\r\n \r\n #store all the information in a file named \"restaurants.txt\"\r\n with open('restaurants.txt', 'a+', encoding='UTF-8') as f:\r\n f.write(output)\r\n f.close()\r\n \r\n new={'rank':0,'name':place,'image':'0','address':address,'price':price,'overall_rating':rating,'comment_num':comment_num}\r\n \r\n #rank by price/rating/comment number\r\n if price>=most_expensive1['price']:\r\n most_expensive3 = most_expensive2\r\n most_expensive2 = most_expensive1\r\n most_expensive1 = new\r\n elif price>=most_expensive2['price']:\r\n most_expensive3 = most_expensive2\r\n most_expensive2 = new \r\n elif price>=most_expensive3['price']:\r\n most_expensive3 = new \r\n \r\n if rating>=best1['overall_rating']:\r\n best3 = best2\r\n best2 = best1\r\n best1 = new\r\n elif rating>=best2['overall_rating']:\r\n best3 = best2\r\n best2 = new\r\n elif rating>=best3['overall_rating']:\r\n best3 =new\r\n \r\n if comment_num>=most_popular1['comment_num']:\r\n most_popular3 = most_popular2\r\n most_popular2 = most_popular1\r\n most_popular1 = new\r\n elif comment_num>=most_popular2['comment_num']:\r\n most_popular3 = most_popular2\r\n most_popular2 = new\r\n elif comment_num>=most_popular3['comment_num']:\r\n most_popular3 = new \r\n \r\n #after collecting all the information in a page ,turn to next page\r\n page_num=page_num+1\r\n \r\n else:\r\n not_last_page = False\r\n except:\r\n not_last_page = False\r\n \r\n #intial the rank\r\n best1['rank']=most_popular1['rank']=most_expensive1['rank']=1\r\n best2['rank']=most_popular2['rank']=most_expensive2['rank']=2\r\n best3['rank']=most_popular3['rank']=most_expensive3['rank']=3\r\n \r\n #collect all the names of the three top restaurants,and then go to \"www.dianping.com\" to find their images\r\n new = [most_expensive1['name'],most_expensive2['name'],most_expensive3['name'],most_popular1['name'],most_popular2['name'],most_popular3['name'],best1['name'],best2['name'],best3['name']]\r\n \r\n headers = {'User-Agent' : 'Mozilla/5.0 (Windows; U; Windows NT6.1; en-US; rv:1.9.1.6) Gecko/20201201 Firefox/3.5.6'}\r\n \r\n #the cookie may fail, need to be changed from time to time \r\n cookie=\"fspop=test; cye=hefei; _lxsdk_cuid=178970e9127c8-0a7e2614614ad4-4c3f237d-144000-178970e9127c8; _lxsdk=178970e9127c8-0a7e2614614ad4-4c3f237d-144000-178970e9127c8; Hm_lvt_602b80cf8079ae6591966cc70a3940e7=1617540449,1617603737,1617612171,1617712454; _hc.v=2d291f0f-f5e3-68c0-5121-15b43625688f.1617442019; s_ViewType=10; cy=110; _lx_utm=utm_source%3DBaidu%26utm_medium%3Dorganic; _lxsdk_s=178a72d1497-b7-792-6c3%7C%7C105; Hm_lpvt_602b80cf8079ae6591966cc70a3940e7=1617712942\"\r\n cookie_dict = {i.split(\"=\")[0]:i.split(\"=\")[-1] for i in cookie.split(\"; \")}\r\n \r\n i=0\r\n str2 = ['0']*10\r\n for name in new:\r\n link = 'https://www.dianping.com/search/keyword/110/0_' + name \r\n proxies ={'http':'http://49.70.17.135'}\r\n response =requests.get(link, proxies=proxies)\r\n r = requests.get(link, headers =headers, cookies =cookie_dict, timeout=1)\r\n soup = BeautifulSoup(r.text,\"lxml\")\r\n time.sleep(random.random())\r\n html =r.text\r\n #print(html)\r\n \r\n #search the sites of the photo,which exist in two ways below\r\n try:\r\n result = re.search('src=\"https://.*?/>',html)\r\n str1 = result.group()\r\n except:\r\n result = re.search('src=\"http://.*?/>',html)\r\n str1 = result.group()\r\n\r\n #absorb the surplus chars\r\n str1=str1.lstrip('src=\"')\r\n str1=str1.rstrip('\"/>')\r\n \r\n print(name)\r\n print(str1)\r\n \r\n#store the sites of photos of each restaurant in list str2[]\r\n str2[i]=str1\r\n i=i+1\r\n \r\n #create lists:most_popular,most_expensive,best\r\n most_popular = [most_popular1,most_popular2,most_popular3]\r\n most_expensive = [most_expensive1,most_expensive2,most_expensive3]\r\n best = [best1,best2,best3]\r\n \r\n i=0\r\n \r\n for a in most_expensive: \r\n a['image']=str2[i]\r\n i=i+1\r\n \r\n for a in most_popular: \r\n a['image']=str2[i]\r\n i=i+1 \r\n \r\n for a in best: \r\n a['image']=str2[i]\r\n i=i+1 \r\n \r\n print(most_popular)\r\n print(most_expensive)\r\n print(best)\r\n \r\n app = Flask(__name__)\r\n \r\n @app.route(\"/\")\r\n def index():\r\n return render_template('index.html')\r\n @app.route(\"/best\")\r\n def index1():\r\n return render_template('module1.html', restaurants=best)\r\n @app.route(\"/most_popular\")\r\n def index2():\r\n return render_template('module1.html', restaurants=most_popular)\r\n @app.route(\"/most_expensive\")\r\n def index3():\r\n return render_template('module1.html', restaurants=most_expensive) \r\n\r\n app.run()\r\n","sub_path":"another_test.py","file_name":"another_test.py","file_ext":"py","file_size_in_byte":9900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"179149799","text":"from tkinter import *\n\nroot = Tk()\nroot.title(\"Nado GUI\")\nroot.geometry(\"640x480\") # \"가로 x 세로 + x좌표 + y좌표\"\nroot.resizable(True, True)\n\nchkvar = IntVar() #chkvar 에 int 형으로 값을 저장\nchkbox = Checkbutton(root, text = \"오늘하루 보지 않기\", variable = chkvar)\n# chkbox.select()\n# chkbox.deselect()\nchkbox.pack()\n\nchkvar2 = IntVar()\nchkbox2 = Checkbutton(root, text = \"일주일동안 보지 않기\", variable = chkvar2)\nchkbox2.pack()\n\n\n\ndef btncmd():\n print(chkvar.get()) # 0 : 체크 해제, 1: 체크\n print(chkvar2.get())\n\n \nbtn = Button(root, text=\"click\", command=btncmd)\nbtn.pack()\n\nroot.mainloop()\n","sub_path":"GUI/6_checkbox.py","file_name":"6_checkbox.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"486057106","text":"import csv\nimport sys\nimport sklearn\nimport numpy\n\n\nfrom sklearn import svm\n\nfrom sklearn.neural_network import MLPClassifier\n\nfrom sklearn import tree\n\nfrom sklearn.ensemble import RandomForestClassifier\n\nfrom sklearn.model_selection import ShuffleSplit\nfrom sklearn import preprocessing as pp\nfrom sklearn.preprocessing import StandardScaler, RobustScaler\n\nfr = 0.95\n\n\n\n# read input\nreader = csv.reader(open(\"dataset1.csv\"), delimiter=\",\")\nx = list(reader)\n\ndata = numpy.array(x).astype(\"float\")\nlabel_idx = data.shape[1]-1\nlabels = data[:, label_idx].astype(int)\ndata = data[:, 0:label_idx]\n\n\n# create cross-validation sets\nsample_size = data.shape[0]-1\norder = numpy.arange(sample_size)\nrs = ShuffleSplit(n_splits = 5, test_size=0.20)\n\noverall = 0\nfor train_index, test_index in rs.split(order):\n\n lim = int(train_index.shape[0] * fr)\n\n train_main_idx = train_index[0:lim]\n train_seco_idx = train_index[lim:]\n\n train_main_data = data[train_main_idx][:]\n train_main_label = labels[train_main_idx]\n\n train_seco_data = data[train_seco_idx][:]\n train_seco_label = labels[train_seco_idx]\n\n robust_scaler = RobustScaler()\n fold_train = robust_scaler.fit_transform(train_main_data)\n train_seco_data = robust_scaler.transform(train_seco_data)\n fold_test = robust_scaler.transform(data[test_index, :])\n\n # train the basic classifier with fold train\n #linear svm\n classifier_svm = svm.LinearSVC()\n classifier_svm = classifier_svm.fit(fold_train, train_main_label)\n # mlp\n classifier_mlp = MLPClassifier( hidden_layer_sizes = (72,28) )\n classifier_mlp = classifier_mlp.fit(fold_train, train_main_label)\n # random forrest\n classifier_raf = RandomForestClassifier(n_estimators=13)\n classifier_raf = classifier_raf.fit(fold_train, train_main_label)\n\n\n\n\n # boosting classifier\n label_svm = classifier_svm.predict(train_seco_data)\n label_mlp = classifier_mlp.predict(train_seco_data)\n label_raf = classifier_raf.predict(train_seco_data)\n tmp = numpy.vstack((label_svm, label_mlp, label_raf))\n boosting_features = numpy.transpose(tmp)\n\n # boosting mlp\n #classifier = MLPClassifier( hidden_layer_sizes = (5,5) )\n classifier = RandomForestClassifier(n_estimators=14)\n classifier = classifier.fit(boosting_features, train_seco_label)\n\n label_svm = classifier_svm.predict(fold_test)\n label_mlp = classifier_mlp.predict(fold_test)\n label_raf = classifier_raf.predict(fold_test)\n tmp = numpy.vstack((label_svm, label_mlp, label_raf))\n boosting_test = numpy.transpose(tmp)\n\n z = classifier.score(boosting_test, labels[test_index])\n\n\n\n overall += z\n\n\n\nprint (overall/5*100)\n","sub_path":"combined.py","file_name":"combined.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"623644886","text":"# Copyright 2020-, Gavin E. Crooks and the QuantumFlow contributors\n#\n# This source code is licensed under the Apache License, Version 2.0 found in\n# the LICENSE.txt file in the root directory of this source tree.\n\n\"\"\"\nQuantumFlow: Gates peculiar to Rigetti's Forest\n\"\"\"\n\nfrom typing import List\n\nimport numpy as np\n\nfrom .. import tensors, var\nfrom ..config import CTRL, NCTRL\nfrom ..future import cached_property\nfrom ..paulialgebra import Pauli, sZ\nfrom ..qubits import Qubit\nfrom ..tensors import QubitTensor\nfrom ..var import Variable\nfrom .stdgates import StdGate\n\n__all__ = (\"CPhase\", \"CPhase00\", \"CPhase01\", \"CPhase10\", \"PSwap\")\n\n\nclass CPhase(StdGate):\n r\"\"\"A 2-qubit 11 phase-shift gate\n\n .. math::\n \\text{CPhase}(\\theta) \\equiv \\text{diag}(1, 1, 1, e^{i \\theta})\n \"\"\"\n cv_interchangeable = True\n cv_tensor_structure = \"diagonal\"\n\n def __init__(self, theta: Variable, q0: Qubit = 0, q1: Qubit = 1) -> None:\n super().__init__(params=[theta], qubits=[q0, q1])\n\n @property\n def hamiltonian(self) -> Pauli:\n q0, q1 = self.qubits\n theta = self.param(\"theta\")\n return -theta * (1 + sZ(q0) * sZ(q1) - sZ(q0) - sZ(q1)) / 4\n\n @cached_property\n def tensor(self) -> QubitTensor:\n theta = var.asfloat(self.param(\"theta\"))\n unitary = [\n [1.0, 0, 0, 0],\n [0, 1.0, 0, 0],\n [0, 0, 1.0, 0],\n [0, 0, 0, np.exp(1j * theta)],\n ]\n return tensors.asqutensor(unitary)\n\n @property\n def H(self) -> \"CPhase\":\n return self**-1\n\n def __pow__(self, t: Variable) -> \"CPhase\":\n theta = self.param(\"theta\") * t\n return CPhase(theta, *self.qubits)\n\n def _diagram_labels_(self) -> List[str]:\n return [CTRL, \"P({theta})\"]\n\n\n# end class CPhase\n\n\nclass CPhase00(StdGate):\n r\"\"\"A 2-qubit 00 phase-shift gate\n\n .. math::\n \\text{CPhase00}(\\theta) \\equiv \\text{diag}(e^{i \\theta}, 1, 1, 1)\n \"\"\"\n cv_interchangeable = True\n cv_tensor_structure = \"diagonal\"\n\n def __init__(self, theta: Variable, q0: Qubit = 0, q1: Qubit = 1) -> None:\n super().__init__(params=[theta], qubits=[q0, q1])\n\n @property\n def hamiltonian(self) -> Pauli:\n q0, q1 = self.qubits\n theta = self.param(\"theta\")\n return -theta * (1 + sZ(q0) * sZ(q1) + sZ(q0) + sZ(q1)) / (4)\n\n @cached_property\n def tensor(self) -> QubitTensor:\n theta = var.asfloat(self.param(\"theta\"))\n unitary = [\n [np.exp(1j * theta), 0, 0, 0],\n [0, 1.0, 0, 0],\n [0, 0, 1.0, 0],\n [0, 0, 0, 1.0],\n ]\n return tensors.asqutensor(unitary)\n\n @property\n def H(self) -> \"CPhase00\":\n return self**-1\n\n def __pow__(self, t: Variable) -> \"CPhase00\":\n theta = self.param(\"theta\")\n return CPhase00(theta * t, *self.qubits)\n\n def _diagram_labels_(self) -> List[str]:\n return [NCTRL + \"({theta})\", NCTRL + \"({theta})\"]\n\n\n# end class CPhase00\n\n\nclass CPhase01(StdGate):\n r\"\"\"A 2-qubit 01 phase-shift gate\n\n .. math::\n \\text{CPhase01}(\\theta) \\equiv \\text{diag}(1, e^{i \\theta}, 1, 1)\n \"\"\"\n cv_tensor_structure = \"diagonal\"\n\n def __init__(self, theta: Variable, q0: Qubit = 0, q1: Qubit = 1) -> None:\n super().__init__(params=[theta], qubits=[q0, q1])\n\n @property\n def hamiltonian(self) -> Pauli:\n q0, q1 = self.qubits\n return -self.param(\"theta\") * (1 - sZ(q0) * sZ(q1) + sZ(q0) - sZ(q1)) / (4)\n\n @cached_property\n def tensor(self) -> QubitTensor:\n unitary = [\n [1.0, 0, 0, 0],\n [0, np.exp(1j * var.asfloat(self.param(\"theta\"))), 0, 0],\n [0, 0, 1.0, 0],\n [0, 0, 0, 1.0],\n ]\n return tensors.asqutensor(unitary)\n\n @property\n def H(self) -> \"CPhase01\":\n return self**-1\n\n def __pow__(self, t: Variable) -> \"CPhase01\":\n theta = self.param(\"theta\")\n return CPhase01(theta * t, *self.qubits)\n\n def _diagram_labels_(self) -> List[str]:\n return [NCTRL + \"({theta})\", CTRL + \"({theta})\"]\n\n\n# end class CPhase01\n\n\nclass CPhase10(StdGate):\n r\"\"\"A 2-qubit 10 phase-shift gate\n\n .. math::\n \\text{CPhase10}(\\theta) \\equiv \\text{diag}(1, 1, e^{i \\theta}, 1)\n \"\"\"\n cv_tensor_structure = \"diagonal\"\n\n def __init__(self, theta: Variable, q0: Qubit = 0, q1: Qubit = 1) -> None:\n super().__init__(params=[theta], qubits=[q0, q1])\n\n @property\n def hamiltonian(self) -> Pauli:\n q0, q1 = self.qubits\n theta = self.param(\"theta\")\n return -theta * (1 - sZ(q0) * sZ(q1) - sZ(q0) + sZ(q1)) / (4)\n\n @cached_property\n def tensor(self) -> QubitTensor:\n unitary = [\n [1.0, 0, 0, 0],\n [0, 1.0, 0, 0],\n [0, 0, np.exp(1j * var.asfloat(self.param(\"theta\"))), 0],\n [0, 0, 0, 1.0],\n ]\n return tensors.asqutensor(unitary)\n\n @property\n def H(self) -> \"CPhase10\":\n return self**-1\n\n def __pow__(self, t: Variable) -> \"CPhase10\":\n theta = self.param(\"theta\")\n return CPhase10(theta * t, *self.qubits)\n\n def _diagram_labels_(self) -> List[str]:\n return [CTRL + \"({theta})\", NCTRL + \"({theta})\"]\n\n\n# end class CPhase10\n\n\nclass PSwap(StdGate):\n r\"\"\"A 2-qubit parametric-swap gate, as defined by Quil.\n Interpolates between SWAP (theta=0) and iSWAP (theta=pi/2).\n\n Locally equivalent to ``CAN(1/2, 1/2, 1/2 - theta/pi)``\n\n .. math::\n \\text{PSwap}(\\theta) \\equiv \\begin{pmatrix} 1&0&0&0 \\\\\n 0&0&e^{i\\theta}&0 \\\\ 0&e^{i\\theta}&0&0 \\\\ 0&0&0&1 \\end{pmatrix}\n \"\"\"\n cv_interchangeable = True\n cv_tensor_structure = \"monomial\"\n\n def __init__(self, theta: Variable, q0: Qubit = 0, q1: Qubit = 1) -> None:\n super().__init__(params=[theta], qubits=[q0, q1])\n\n @cached_property\n def tensor(self) -> QubitTensor:\n theta = var.asfloat(self.param(\"theta\"))\n unitary = [\n [[[1, 0], [0, 0]], [[0, 0], [np.exp(theta * 1.0j), 0]]],\n [[[0, np.exp(theta * 1.0j)], [0, 0]], [[0, 0], [0, 1]]],\n ]\n return tensors.asqutensor(unitary)\n\n @property\n def H(self) -> \"PSwap\":\n theta = self.param(\"theta\")\n theta = 2.0 * np.pi - theta % (2.0 * np.pi)\n return PSwap(theta, *self.qubits)\n\n\n# end class PSwap\n\n\n# fin\n","sub_path":"quantumflow/stdgates/stdgates_forest.py","file_name":"stdgates_forest.py","file_ext":"py","file_size_in_byte":6341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"219684982","text":"import RPi.GPIO as GPIO\nimport os\n\npowerLed = 4\nled1 = 2\nled2 = 3\n\npowerSwitch = 17\nswitchMode1 = 27\nswitchMode2 = 22\n\n# Quick gpio setup method.\nledList = [powerLed, led1, led2]\nswitchList = [powerSwitch, switchMode1, switchMode2]\n\nGPIO.setmode(GPIO.BCM)\n\nfor i in range(len(switchList)):\n GPIO.setup(switchList[i], GPIO.IN, pull_up_down=GPIO.PUD_UP)\n print('Switch:', switchList[i], 'has been setup as an input')\n\nfor i in range(len(ledList)):\n GPIO.setup(ledList[i], GPIO.OUT)\n print('LED:', ledList[i], 'Has been setup as an output')\n\ntry:\n while True:\n for i in range(len(switchList)):\n inputState = GPIO.input(switchList[i])\n if not inputState and int(switchList[i]) == switchMode1:\n GPIO.output(led2, GPIO.LOW)\n GPIO.output(led1, GPIO.HIGH)\n os.system(\"omxplayer -o local Audio1.mp3\")\n elif not inputState and int(switchList[i]) == switchMode2:\n GPIO.output(led1, GPIO.LOW)\n GPIO.output(led2, GPIO.HIGH)\n os.system(\"omxplayer -o local Audio2.mp3\")\nexcept KeyboardInterrupt:\n for i in range(len(ledList)):\n GPIO.output(ledList[i], GPIO.LOW)\nfinally:\n print('Now exiting')\n GPIO.cleanup()\n\n","sub_path":"TESTING/audio_test.py","file_name":"audio_test.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"375136528","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 21 10:35:39 2018\n\n@author: user\n\"\"\"\nfrom tensorflow.python.framework import ops\nops.reset_default_graph()\nimport tensorflow as tf\nimport numpy as np\nimport os\n\nx1 = np.random.randn(5,5).astype('float32')\ny1 = np.random.randn(5,5).astype('float32')\nu1 = np.random.randn(5,5).astype('float32')\nv1 = np.random.randn(5,5).astype('float32')\n\n#print(x1,y1,u1,v1)\n\n#with tf.name_scope('sum') as scope:\nu = tf.placeholder(tf.float32,shape = [None,5])\nv = tf.placeholder(tf.float32,shape = [None,5])\nw = tf.reduce_sum(u + v)\nt = tf.reduce_sum(u - v)\n\nwriter = tf.summary.FileWriter('tb2',tf.get_default_graph())\ntf.summary.scalar('w',w)\ntf.summary.scalar('t',t)\ntf.summary.histogram('u',u)\ntf.summary.histogram('v',v)\nsumm = tf.summary.merge_all()\n\ninit = tf.global_variables_initializer()\nwith tf.Session() as sess:\n sess.run(init)\n for i in range(5): \n b,c,s = sess.run([w,t,summ],feed_dict = {u:u1+i , v:v1+2*i })\n print(b,c)\n writer.add_summary(s, int(i))\n\nwriter.close()\nos.system('tensorboard --logdir=/home/user/atulmlpython/TF_assign/tb2/ --port=6006') \n","sub_path":"TestAddSummary.py","file_name":"TestAddSummary.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"209230737","text":"from random import randint \n\nclass Player(object):\n def __init__(self, lifes):\n self.lifes = lifes\n self.scores = 0\n self.did_hit = False\n self.is_hitted = False\n\n def fire(self):\n sikta = randint(1, 5) \n if sikta in {1,2,3}: \n self.did_hit=True\n undvika = randint(1, 10)\n if undvika in {1,2,3}:\n self.is_hitted = True\n \n def inc_scores(self):\n self.scores= self.scores + 1\n self.did_hit= False\n\n def reduce_lifes(self):\n self.lifes = self.lifes - 1\n self.is_hitted = False\n\na_player = Player(3) \n\nwhile True:\n input('Tryck Enter för att skjuta')\n a_player.fire()\n if a_player.did_hit:\n print('Träff!')\n a_player.inc_scores() \n else:\n print('Miss, sikta bättre')\n if a_player.is_hitted:\n print('Aaaaaah, du blev träffad')\n a_player.reduce_lifes() \n else:\n print('Du klarade dig denna gång!')\n print(f\"{a_player.scores} poäng\")\n print(f\"{a_player.lifes} liv\")\n if a_player.lifes <= 0:\n print(\"du dog\")\n break\n","sub_path":"pang-pang.py","file_name":"pang-pang.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"595385887","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass 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 data = []\n q = [root]\n \n while q:\n node = q.pop(0)\n if node is None:\n data.append(None)\n else:\n data.append(node.val)\n q.append(node.left)\n q.append(node.right)\n return data\n\n def deserialize(self, data):\n \"\"\"Decodes your encoded data to tree.\n \n :type data: str\n :rtype: TreeNode\n \"\"\"\n if not data:\n return None\n n = len(data)\n nums = [0 for i in range(n)]\n nodes = [None for i in range(n)]\n \n for i in range(n):\n if i > 0:\n nums[i] = nums[i - 1]\n if data[i] is None:\n nums[i] += 1\n else:\n nodes[i] = TreeNode(data[i])\n \n for i in range(n):\n if nodes[i] is None:\n continue\n else:\n l = 2 * (i - nums[i]) + 1\n r = 2 * (i - nums[i]) + 2\n nodes[i].left = nodes[l]\n nodes[i].right = nodes[r]\n return nodes[0]\n \n","sub_path":"Tree Recur backtracking/297-Serialize and Deserialize Binary Tree/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"619110421","text":"'''\nFunctions for creating and connecting PyLGN networks.\n'''\n\nimport quantities as pq\nfrom matplotlib import pyplot as plt\n\nimport pylgn\nimport pylgn.kernels.spatial as spl\nimport pylgn.kernels.temporal as tpl\n\nfrom . import util \n\n\ndef create_staticnetwork(params=None):\n \"\"\"\n Create a PyLGN network where all temporal kernels are delta functions.\n \n Parameters\n ----------\n params : None, dict, str\n passed to util._parse_parameters\n \"\"\"\n \n params = util.parse_parameters(params)\n \n # network\n network = pylgn.Network()\n integrator = network.create_integrator(\n nt=0, \n nr=params['nr'], \n dt=params['dt'], \n dr=params['dr']\n )\n \n # neurons\n ganglion = network.create_ganglion_cell()\n relay = network.create_relay_cell()\n cortical = network.create_cortical_cell()\n \n # RGC impulse-response function\n delta_t = tpl.create_delta_ft()\n Wg_r = spl.create_dog_ft(\n A=params['A_g'], \n a=params['a_g'], \n B=params['B_g'], \n b=params['b_g']\n )\n ganglion.set_kernel((Wg_r, delta_t))\n \n # excitatory FF connection\n Krg_r = spl.create_gauss_ft(A=params['A_rg_ex'], a=params['a_rg_ex'])\n network.connect(ganglion, relay, (Krg_r, delta_t), weight=params['w_rg_ex'])\n \n # inhibitory FF\n Krig_r = spl.create_gauss_ft(A=params['A_rg_in'], a=params['a_rg_in'])\n network.connect(ganglion, relay, (Krig_r, delta_t), weight=params['w_rg_in'])\n\n # excitatory FB\n Krc_ex_r = spl.create_gauss_ft(A=params['A_rc_ex'], a=params['a_rc_ex'])\n network.connect(cortical, relay, (Krc_ex_r, delta_t), weight=params['w_rc_ex'])\n \n # inhibitory FB\n Krc_in_r = spl.create_gauss_ft(A=params['A_rc_in'], a=params['a_rc_in'])\n network.connect(cortical, relay, (Krc_in_r, delta_t), weight=params['w_rc_in'])\n \n # TC feed-forward\n Kcr_r = spl.create_delta_ft()\n network.connect(relay, cortical, (Kcr_r, delta_t), weight=1)\n \n return network\n\n\ndef create_dynamicnetwork(params=None):\n \"\"\"\n Create PyLGN network with temporal kernels.\n \n Parameters\n ----------\n params : None, dict, str\n passed to util._parse_parameters\n \"\"\"\n \n params = util.parse_parameters(params)\n\n # network\n network = pylgn.Network()\n integrator = network.create_integrator(\n nt=params['nt'], \n nr=params['nr'], \n dt=params['dt'], \n dr=params['dr']\n )\n \n # neurons\n ganglion = network.create_ganglion_cell()\n relay = network.create_relay_cell()\n cortical = network.create_cortical_cell()\n \n # RGC impulse-response function\n Wg_r = spl.create_dog_ft(\n A=params['A_g'], \n a=params['a_g'], \n B=params['B_g'], \n b=params['b_g']\n )\n Wg_t = tpl.create_biphasic_ft(\n phase=params['phase_g'], \n damping=params['damping_g']\n )\n ganglion.set_kernel((Wg_r, Wg_t))\n \n # excitatory FF connection\n Krg_r = spl.create_gauss_ft(A=params['A_rg_ex'], a=params['a_rg_ex'])\n Krg_t = tpl.create_exp_decay_ft(\n tau=params['tau_rg_ex'], \n delay=params['delay_rg_ex']\n )\n network.connect(ganglion, relay, (Krg_r, Krg_t), weight=params['w_rg_ex'])\n \n # inhibitory FF\n Krig_r = spl.create_gauss_ft(A=params['A_rg_in'], a=params['a_rg_in'])\n Krig_t = tpl.create_exp_decay_ft(\n tau=params['tau_rg_in'], \n delay=params['delay_rg_in']\n )\n network.connect(ganglion, relay, (Krig_r, Krig_t), weight=params['w_rg_in'])\n \n # excitatory FB\n Krc_ex_r = spl.create_gauss_ft(A=params['A_rc_ex'], a=params['a_rc_ex'])\n Krc_ex_t = tpl.create_exp_decay_ft(\n tau=params['tau_rc_ex'], \n delay=params['delay_rc_ex'])\n network.connect(cortical, relay, (Krc_ex_r, Krc_ex_t), weight=params['w_rc_ex'])\n \n # inhibitory FB\n Krc_in_r = spl.create_gauss_ft(A=params['A_rc_in'], a=params['a_rc_in'])\n Krc_in_t = tpl.create_exp_decay_ft(\n tau=params['tau_rc_in'], \n delay=params['delay_rc_in'])\n network.connect(cortical, relay, (Krc_in_r, Krc_in_t), weight=params['w_rc_in'])\n \n # TC feed-forward\n Kcr_r = spl.create_delta_ft()\n Kcr_t = tpl.create_delta_ft()\n network.connect(relay, cortical, (Kcr_r, Kcr_t), weight=params['w_cr'])\n\n return network\n\n\ndef get_neuron(name, network):\n \"\"\"\n Returns requested pylgn.Neuron object. Taken from \n https://github.com/miladh/edog-simulations.\n\n Parameters\n ----------\n name : string\n name of the neuron\n\n network : pylgn.Network\n\n Returns\n -------\n out : pylgn.Neuron\n \"\"\"\n neuron = [neuron for neuron in network.neurons if type(neuron).__name__ == name]\n \n if not neuron:\n raise NameError(\"neuron not found in network\", name)\n \n elif len(neuron) > 1 and name == \"Relay\":\n raise ValueError(\"more than one Relay cell found in network\")\n \n return neuron\n\n","sub_path":"dlgnsim/networks.py","file_name":"networks.py","file_ext":"py","file_size_in_byte":4979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"362235790","text":"from tables.common import parse_file, grid_search_eval\n\nPRETRAIN_EVAL_RESULTS_TEMPLATE = \"\"\"global_step = {global_step:d}\nloss = {loss:f}\nmasked_lm_accuracy = {masked_lm_accuracy:f}\nmasked_lm_loss = {masked_lm_loss:f}\nnext_sentence_accuracy = {next_sentence_accuracy:f}\nnext_sentence_loss = {next_sentence_loss:f}\n\"\"\"\n\ntable_rows = []\nfor sparsity in [0, .1, .2, .3, .4, .5, .6, .7, .8, .9]:\n\n eval_entries, train_losses = grid_search_eval(lambda task, lr: f'models/{task}/gradual_prune_{int(sparsity*100)}_less_embed_lr_{lr}/eval_results.txt')\n\n pretrain_results = parse_file(f'models/pretrain/gradual_prune_0_head_pruned_{int(sparsity*100)}/eval_results.txt', PRETRAIN_EVAL_RESULTS_TEMPLATE)\n pretrain_loss = pretrain_results['loss'] if pretrain_results else float('inf')\n\n avg_eval = sum(eval_entries) / len(eval_entries)\n avg_loss = sum(train_losses) / len(train_losses)\n table_rows.append(\n f\"{sparsity} & {pretrain_loss:.2f} & \" #+ \" & \".join([f\"{acc:.2f}|{loss:.2f}\" for acc, loss in zip(eval_entries, train_losses)]) + f\" & {avg_eval:.2f}|{avg_loss:.2f}\"\n )\n\nrows = \"\\\\\\\\\\n\".join(table_rows)\nprint(f\"\"\"\n\\\\begin{{tabular}}{{ccccccccccc}}\nPruned & Pre-train Loss & MNLI & QQP & QNLI & SST-2 & CoLA & STS-B & MRPC & RTE & AVG\\\\\\\\\n\\hline\n{rows}\\\\\\\\\n\\\\end{{tabular}}\n\"\"\")\n","sub_path":"tables/head_pruned.py","file_name":"head_pruned.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"635699395","text":"\"\"\"Support for Ezviz binary sensors.\"\"\"\nimport logging\n\nfrom pyezviz.constants import BinarySensorType\n\nfrom homeassistant.components.binary_sensor import BinarySensorEntity\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.core import HomeAssistant\nfrom homeassistant.helpers.entity import DeviceInfo\nfrom homeassistant.helpers.entity_platform import AddEntitiesCallback\nfrom homeassistant.helpers.update_coordinator import CoordinatorEntity\n\nfrom .const import DATA_COORDINATOR, DOMAIN, MANUFACTURER\nfrom .coordinator import EzvizDataUpdateCoordinator\n\n_LOGGER = logging.getLogger(__name__)\n\n\nasync def async_setup_entry(\n hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback\n) -> None:\n \"\"\"Set up Ezviz sensors based on a config entry.\"\"\"\n coordinator: EzvizDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][\n DATA_COORDINATOR\n ]\n sensors = []\n\n for idx, camera in enumerate(coordinator.data):\n for name in camera:\n # Only add sensor with value.\n if camera.get(name) is None:\n continue\n\n if name in BinarySensorType.__members__:\n sensor_type_name = getattr(BinarySensorType, name).value\n sensors.append(\n EzvizBinarySensor(coordinator, idx, name, sensor_type_name)\n )\n\n async_add_entities(sensors)\n\n\nclass EzvizBinarySensor(CoordinatorEntity, BinarySensorEntity):\n \"\"\"Representation of a Ezviz sensor.\"\"\"\n\n coordinator: EzvizDataUpdateCoordinator\n\n def __init__(\n self,\n coordinator: EzvizDataUpdateCoordinator,\n idx: int,\n name: str,\n sensor_type_name: str,\n ) -> None:\n \"\"\"Initialize the sensor.\"\"\"\n super().__init__(coordinator)\n self._idx = idx\n self._camera_name = self.coordinator.data[self._idx][\"name\"]\n self._name = name\n self._sensor_name = f\"{self._camera_name}.{self._name}\"\n self.sensor_type_name = sensor_type_name\n self._serial = self.coordinator.data[self._idx][\"serial\"]\n\n @property\n def name(self) -> str:\n \"\"\"Return the name of the Ezviz sensor.\"\"\"\n return self._name\n\n @property\n def is_on(self) -> bool:\n \"\"\"Return the state of the sensor.\"\"\"\n return self.coordinator.data[self._idx][self._name]\n\n @property\n def unique_id(self) -> str:\n \"\"\"Return the unique ID of this sensor.\"\"\"\n return f\"{self._serial}_{self._sensor_name}\"\n\n @property\n def device_info(self) -> DeviceInfo:\n \"\"\"Return the device_info of the device.\"\"\"\n return {\n \"identifiers\": {(DOMAIN, self._serial)},\n \"name\": self.coordinator.data[self._idx][\"name\"],\n \"model\": self.coordinator.data[self._idx][\"device_sub_category\"],\n \"manufacturer\": MANUFACTURER,\n \"sw_version\": self.coordinator.data[self._idx][\"version\"],\n }\n\n @property\n def device_class(self) -> str:\n \"\"\"Device class for the sensor.\"\"\"\n return self.sensor_type_name\n","sub_path":"homeassistant/components/ezviz/binary_sensor.py","file_name":"binary_sensor.py","file_ext":"py","file_size_in_byte":3090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"150075485","text":"from tkinter import *\r\n#导入tkinter模块所有内容\r\n\r\n#创建一个toplevel的根窗口,并把它作为参数实例化下列的textLabel、imgLabel对象\r\nroot = Tk()\r\nroot.title(\"温馨提示\")\r\n#穿件一个文本label对象\r\ntextLabel = Label(root,\\\r\ntext = \"您所下载的影片含有未成年人限制的内容,请满18周岁后再点击观看!\")\r\ntextLabel.pack(side=LEFT)\r\n#创建一个图像Label对象\r\n#用PhotosImage实例化一个图片对象(支持gif格式的图片)\r\nphoto = PhotoImage(file = \"18.gif\")\r\nimgLabel = Label(root,image = photo)\r\nimgLabel.pack(side=RIGHT)\r\n\r\nmainloop()","sub_path":"p15_3.py","file_name":"p15_3.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"565827513","text":"import os\r\nimport re\r\n\r\npath = 'C:/ShareSSD/scop/maxcluster_filtered/'\r\npath_to_summaries = 'C:/ShareSSD/scop/maxcluster_summaries/'\r\n\r\ndef startSummaries():\r\n\r\n #start with gdt_2 files\r\n\r\n for filename in os.listdir(path):\r\n print(filename)\r\n if 'gdt_2' in filename:\r\n\r\n with open(path+filename,'r') as fp:\r\n\r\n line = fp.readline()\r\n while line:\r\n if 'RMSD' in line:\r\n parsed = re.findall(r\"[-+]?\\d*\\.\\d+|\\d+\", line)\r\n rmsd = parsed[5]\r\n maxsub = parsed[3]\r\n tmscore = parsed[6]\r\n\r\n #gdt-ha\r\n if 'GDT' in line:\r\n for n in line.split():\r\n try: \r\n gdt = float(n)\r\n except ValueError:\r\n pass\r\n\r\n line = fp.readline()\r\n\r\n new_name = str(filename).replace('gdt_2','summary')\r\n\r\n with open(path_to_summaries+new_name,'w') as nf:\r\n nf.write('RMSD= '+rmsd+'\\n')\r\n nf.write('MaxSub= '+maxsub+'\\n')\r\n nf.write('TM-score= '+tmscore+'\\n')\r\n nf.write('GDT-HA= '+str(gdt)+'\\n')\r\n\r\n appendGDTTS()\r\n\r\ndef appendGDTTS():\r\n\r\n for filename in os.listdir(path):\r\n print(filename)\r\n if 'gdt_4' in filename:\r\n\r\n parsed = str(filename).split('_')\r\n\r\n structure1 = parsed[0]\r\n if '.ent' not in structure1:\r\n structure1 = structure1+'_.ent'\r\n structure2 = parsed[2]\r\n if '.ent' not in structure2:\r\n structure2 = structure2+'_.ent'\r\n\r\n print(structure1)\r\n print(structure2)\r\n\r\n with open(path+filename) as fp:\r\n line = fp.readline()\r\n while line:\r\n if 'GDT' in line:\r\n for n in line.split():\r\n try: \r\n gdt = float(n)\r\n except ValueError:\r\n pass\r\n\r\n line = fp.readline()\r\n\r\n summary_name = structure1+'_'+structure2+'_summary'\r\n\r\n with open(path_to_summaries+summary_name,'a') as nf:\r\n nf.write('GDT-TS= '+str(gdt)+'\\n')\r\n\r\nstartSummaries() \r\n\r\n","sub_path":"Alignments/ParseMaxCluster.py","file_name":"ParseMaxCluster.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"182918977","text":"from itertools import chain\nfrom typing import Optional\nimport logging\nimport pathlib\nimport os\nimport json\nimport shutil\n\nimport click\n\nfrom libs import google_sheet_helpers, wide_dates_df\nfrom libs.datasets import statistical_areas\nfrom libs.datasets.combined_datasets import (\n ALL_TIMESERIES_FEATURE_DEFINITION,\n US_STATES_FILTER,\n ALL_FIELDS_FEATURE_DEFINITION,\n)\nfrom libs.datasets.latest_values_dataset import LatestValuesDataset\nfrom libs.datasets.timeseries import MultiRegionTimeseriesDataset\nfrom libs.datasets.timeseries import add_new_cases\nfrom libs.qa import dataset_summary\nfrom libs.qa import data_availability\nfrom libs.datasets.timeseries import TimeseriesDataset\nfrom libs.datasets import dataset_utils\nfrom libs.datasets import combined_dataset_utils\nfrom libs.datasets import combined_datasets\nfrom libs.datasets.sources import forecast_hub\nfrom pyseir import DATA_DIR\nimport pyseir.icu.utils\nfrom pyseir.icu import infer_icu\n\n\nPROD_BUCKET = \"data.covidactnow.org\"\n\n_logger = logging.getLogger(__name__)\n\n\n@click.group(\"data\")\ndef main():\n pass\n\n\ndef _save_field_summary(\n timeseries_dataset: MultiRegionTimeseriesDataset, output_path: pathlib.Path\n):\n\n _logger.info(\"Starting dataset summary generation\")\n summary = dataset_summary.summarize_timeseries_fields(timeseries_dataset.data)\n summary.to_csv(output_path)\n _logger.info(f\"Saved dataset summary to {output_path}\")\n\n\n@main.command()\n@click.option(\"--filename\", default=\"external_forecasts.csv\")\ndef update_forecasts(filename):\n \"\"\"Updates external forecasts to the current checked out covid data public commit\"\"\"\n path_prefix = dataset_utils.DATA_DIRECTORY.relative_to(dataset_utils.REPO_ROOT)\n data_root = dataset_utils.LOCAL_PUBLIC_DATA_PATH\n data_path = forecast_hub.ForecastHubDataset.DATA_PATH\n shutil.copy(data_root / data_path, path_prefix / filename)\n _logger.info(f\"Updating External Forecasts at {path_prefix / filename}\")\n\n\n@main.command()\n@click.option(\"--summary-filename\", default=\"timeseries_summary.csv\")\n@click.option(\"--wide-dates-filename\", default=\"multiregion-wide-dates.csv\")\n@click.option(\"--aggregate-to-msas\", is_flag=True, help=\"Aggregate counties to MSAs\")\ndef update(summary_filename, wide_dates_filename, aggregate_to_msas: bool):\n \"\"\"Updates latest and timeseries datasets to the current checked out covid data public commit\"\"\"\n path_prefix = dataset_utils.DATA_DIRECTORY.relative_to(dataset_utils.REPO_ROOT)\n\n data_source_classes = set(\n chain(\n chain.from_iterable(ALL_FIELDS_FEATURE_DEFINITION.values()),\n chain.from_iterable(ALL_TIMESERIES_FEATURE_DEFINITION.values()),\n )\n )\n data_sources = {\n data_source_cls.SOURCE_NAME: data_source_cls.local()\n for data_source_cls in data_source_classes\n }\n timeseries_dataset: TimeseriesDataset = combined_datasets.build_from_sources(\n TimeseriesDataset, data_sources, ALL_TIMESERIES_FEATURE_DEFINITION, filter=US_STATES_FILTER\n )\n latest_dataset: LatestValuesDataset = combined_datasets.build_from_sources(\n LatestValuesDataset, data_sources, ALL_FIELDS_FEATURE_DEFINITION, filter=US_STATES_FILTER,\n )\n multiregion_dataset = MultiRegionTimeseriesDataset.from_timeseries_and_latest(\n timeseries_dataset, latest_dataset\n )\n multiregion_dataset = add_new_cases(multiregion_dataset)\n if aggregate_to_msas:\n aggregator = statistical_areas.CountyToCBSAAggregator.from_local_public_data()\n multiregion_dataset = multiregion_dataset.append_regions(\n aggregator.aggregate(multiregion_dataset)\n )\n\n _, multiregion_pointer = combined_dataset_utils.update_data_public_head(\n path_prefix, latest_dataset, multiregion_dataset,\n )\n\n # Write DataSource objects that have provenance information, which is only set when significant\n # processing of the source data is done in this repo before it is combined. The output is not\n # used downstream, it is for debugging only.\n for data_source in data_sources.values():\n if data_source.provenance is not None:\n wide_dates_df.write_csv(\n data_source.timeseries().get_date_columns(),\n path_prefix / f\"{data_source.SOURCE_NAME}-wide-dates.csv\",\n )\n\n if wide_dates_filename:\n wide_dates_df.write_csv(\n timeseries_dataset.get_date_columns(),\n multiregion_pointer.path.with_name(wide_dates_filename),\n )\n\n if summary_filename:\n _save_field_summary(multiregion_dataset, path_prefix / summary_filename)\n\n\n@main.command()\n@click.option(\"--output-dir\", type=pathlib.Path, required=True)\n@click.option(\"--filename\", type=pathlib.Path, default=\"timeseries_field_summary.csv\")\ndef save_summary(output_dir: pathlib.Path, filename: str):\n \"\"\"Saves summary of timeseries dataset indexed by fips and variable name.\"\"\"\n us_timeseries = combined_datasets.load_us_timeseries_dataset()\n _save_field_summary(us_timeseries, output_dir / filename)\n\n\n@main.command()\n@click.option(\"--name\", envvar=\"DATA_AVAILABILITY_SHEET_NAME\", default=\"Data Availability - Dev\")\n@click.option(\"--share-email\")\ndef update_availability_report(name: str, share_email: Optional[str]):\n sheet = google_sheet_helpers.open_or_create_spreadsheet(name, share_email=share_email)\n info_worksheet = google_sheet_helpers.update_info_sheet(sheet)\n data_sources_by_source_name = data_availability.load_all_latest_sources()\n\n for name, dataset in data_sources_by_source_name.items():\n _logger.info(f\"Updating {name}\")\n report = data_availability.build_data_availability_report(dataset)\n data_availability.update_multi_field_availability_report(\n sheet, report, name, columns_to_drop=[\"source\", \"fips\"]\n )\n\n # Reorder sheets with combined data first and metadata last\n COLUMN_ORDER_OVERRIDE = {data_availability.COMBINED_DATA_KEY: -5, info_worksheet.title: 5}\n worksheets = sheet.worksheets()\n worksheets = sorted(worksheets, key=lambda x: (COLUMN_ORDER_OVERRIDE.get(x.title, 0), x.title))\n sheet.reorder_worksheets(worksheets)\n\n _logger.info(\"Finished updating data availability report\")\n\n\n@main.command()\ndef update_case_based_icu_utilization_weights():\n \"\"\"\n Calculate the updated States to Counties disaggregation weights and save to disk. These\n weights are used to estimate county level ICU heads-in-beds as an input for the ICU Utilization\n metric.\n\n The output is callable with county aggregation-level fips keys and returns a normalized [0,1]\n value such that the weights for all counties in a given state sum to unity.\n \"\"\"\n output_path = os.path.join(DATA_DIR, infer_icu.ICUWeightsPath.ONE_MONTH_TRAILING_CASES.value)\n output = pyseir.icu.utils.calculate_case_based_weights()\n _logger.info(f\"Saved case-based ICU Utilization weights to {output_path}\")\n with open(output_path, \"w\") as f:\n json.dump(output, f)\n","sub_path":"cli/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":6986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"321603653","text":"#scraping code modified from Mark Needham's Python NLTK/Neo4j: Analysing the transcripts of How I Met Your Mother\nimport requests\nfrom bs4 import BeautifulSoup\nfrom soupsieve import select\n\nepisodes = {}\n\nfor i in range(5,7):\n \n page = open(\"data/html/page-\" + str(i) + \".html\", 'r')\n soup = BeautifulSoup(page.read(), features=\"lxml\")\n doc = soup.select(\".topic-titles.row2 h3 a\")\n for row in doc:\n if row != doc[0] and row != doc[1]: \n parts = row.text.split(\" - \")\n episodes[parts[0]] = {\"title\": parts[1], \"link\": row.get(\"href\")}\n\nwebsite = \"http://transcripts.foreverdreaming.org\"\nfor key, value in episodes.items():\n\n parts = key.split(\"x\")\n season = int(parts[0])\n episode = int(parts[1])\n\n filename = \"data/transcripts/S%d-Ep%d.txt\" %(season, episode)\n link = value[\"link\"] #for pages 3-14\n link = website+ link[1:] #for pages 3-14\n \n with open(filename, 'wb') as handle:\n headers = {'User-Agent': 'Chrome/78.0.3904.106'}\n response = requests.get(link,headers = headers) #use value[\"link\"] instead of link for pages 1 and 2 #use link for other pages\n if response.ok:\n for block in response.iter_content(1024):\n if not block:\n break\n\n handle.write(block)\n","sub_path":"code/scraping.py","file_name":"scraping.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"557225462","text":"'''\n2017/04/20\nWritten By Eunjin Cho\nDetermining the importance of proteins using PageRank\n'''\nimport sys\nimport numpy as np\nimport scipy\nimport matplotlib.pyplot as plt\n\n\nclass PR:\n\tdef __init__(self, filename, beta, iters):\n\t\tself.filename = filename\n\t\tself.beta = float(beta)\n\t\tself.iters = int(iters)\n\n\n\tdef parse_matrix(self):\n\t\t'''\n\t\tRead protein data and convert it to dictionaries to later create a matrix\n\t\t'''\n\n\t\tidx = -1\n\t\t# key: idx, value: a real protein values\n\t\tself.idx_protein_dict = dict()\n\t\t# key: source, value: set of destinations\n\t\tself.protein_link_dict = dict()\n\t\tfor line in self.filename.readlines():\n\t\t\tif (idx == -1):\n\t\t\t\tidx += 1\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tline = line.strip()\n\t\t\t\tline_split = line.split('\\t')\n\t\t\t\tsrc_protein = line_split[0]\n\t\t\t\tdest_protein = line_split[1]\n\t\t\t\tif (src_protein not in self.idx_protein_dict.values()):\n\t\t\t\t\tself.idx_protein_dict[idx] = src_protein\n\t\t\t\t\tidx += 1\n\t\t\t\tif (dest_protein not in self.idx_protein_dict.values()):\n\t\t\t\t\tself.idx_protein_dict[idx] = dest_protein\n\t\t\t\t\tidx += 1\n\t\t\t\tif src_protein in self.protein_link_dict:\n\t\t\t\t\tself.protein_link_dict[src_protein].add(dest_protein)\n\t\t\t\tif src_protein not in self.protein_link_dict:\n\t\t\t\t\tself.protein_link_dict[src_protein] = set()\n\t\t\t\t\tself.protein_link_dict[src_protein].add(dest_protein)\n\n\t\t# key: protein, value: idx\n\t\tself.protein_idx_dict = dict()\n\t\tfor k, v in self.idx_protein_dict.items():\n\t\t\tself.protein_idx_dict[v] = k\n\n\t\tself.protein_idx_dict_new = self.protein_idx_dict.copy()\n\t\tself.idx_protein_dict_new = self.idx_protein_dict.copy()\n\n\n\tdef create_matrix(self):\n\t\t'''\n\t\tCreate a numpy matrix for faster matrix multiplication\n\t\t'''\n\n\t\t# initialize the matrix\n\t\t# rows are destinations and columns are sources\n\t\tlist_matrix = []\n\t\tfor i in range(len(self.idx_protein_dict)):\n\t\t\tlist_inside = [0]*len(self.idx_protein_dict)\n\t\t\tlist_matrix.append(list_inside)\n\n\t\tfor src, dest_set in self.protein_link_dict.items():\n\t\t\tsrc_idx = self.protein_idx_dict[src]\n\t\t\tfor dest in dest_set:\n\t\t\t\tdest_idx = self.protein_idx_dict[dest]\n\t\t\t\tlist_matrix[dest_idx][src_idx] = 1/len(dest_set)\n\t\t\n\t\t# Create a numpy array\n\t\tself.np_protein_mat_orig = np.array(list_matrix)\n\t\tself.np_protein_mat = np.array(list_matrix)\t\n\n\n\tdef remove_dead_ends(self):\n\t\t'''\n\t\tIteratively remove all the dead ends (vertices with no links coming out)\n\t\t'''\n\t\tself.removed_vertices = set()\n\t\tcanStop = False # stop when all of the dead ends are removed\n\t\twhile (not canStop):\n\t\t\tcols_to_remove = []\n\t\t\tfor col in range(len(self.np_protein_mat)):\n\t\t\t\tcolumn = self.np_protein_mat[:, col]\n\t\t\t\t# if there's no out links, remove\n\t\t\t\tif (not np.any(column)):\n\t\t\t\t\tcols_to_remove.append(col)\n\t\t\t\t\tself.mat_remove(col)\n\t\t\t\t\tbreak\n\t\t\t\t\t\n\t\t\t# if there's no dead ends\n\t\t\tif (len(cols_to_remove) == 0):\n\t\t\t\tcanStop = True\n\n\t\tprint (\"Number of unique proteins after removing dead ends: \", len(self.np_protein_mat))\n\n\n\tdef mat_remove(self, col):\n\t\tself.removed_vertices.add(self.idx_protein_dict_new[col])\n\t\tself.update_bidict(col) \n\t\tself.np_protein_mat = scipy.delete(self.np_protein_mat, col, 1)\n\t\tself.np_protein_mat = scipy.delete(self.np_protein_mat, col, 0)\n\t\tself.recreate_matrix()\n\t\tprint (\"removed the dead end: \", col)\n\n\n\tdef update_bidict(self, i):\n\t\t'''\n\t\tUpdate two dictionaries after removing dead ends\n\t\t@ param\n\t\t\t- i : the column number that is removed\n\t\t'''\n\t\tnew_idx_protein_dict = dict()\n\t\tfor k, v in self.idx_protein_dict_new.items():\n\t\t\tif k > i:\n\t\t\t\tk -= 1\n\t\t\t\tnew_idx_protein_dict[k] = v\n\t\t\tif k < i:\n\t\t\t\tnew_idx_protein_dict[k] = v\n\n\t\tself.idx_protein_dict_new = new_idx_protein_dict\n\n\t\tnew_protein_idx_dict = dict()\n\t\tfor k, v in self.protein_idx_dict_new.items():\n\t\t\tif v > i:\n\t\t\t\tv -= 1\n\t\t\t\tnew_protein_idx_dict[k] = v\n\t\t\tif v < i:\n\t\t\t\tnew_protein_idx_dict[k] = v\n\t\tself.protein_idx_dict_new = new_protein_idx_dict\n\n\n\tdef recreate_matrix(self):\n\t\t'''\n\t\tRe-create a numpy matrix after dead ends are removed\n\t\t'''\n\n\t\t# initialize the matrix\n\t\t# rows are destinations and columns are sources\n\t\tlist_matrix = []\n\t\tfor i in range(len(self.np_protein_mat)):\n\t\t\tlist_inside = [0]*len(self.np_protein_mat)\n\t\t\tlist_matrix.append(list_inside)\n\t\t\n\t\tfor src, dest_set in self.protein_link_dict.items():\n\t\t\t# print (\"src: \", src, \" dest: \", dest_set)\n\t\t\tif (src not in self.removed_vertices):\n\t\t\t\tsrc_idx = self.protein_idx_dict_new[src]\n\t\t\t\tlen_dest_set_minus_removed = dest_set.difference(self.removed_vertices)\n\t\t\t\tfor dest in dest_set:\n\t\t\t\t\tif (dest not in self.removed_vertices):\n\t\t\t\t\t\tdest_idx = self.protein_idx_dict_new[dest]\n\t\t\t\t\t\tlist_matrix[dest_idx][src_idx] = 1/len(len_dest_set_minus_removed)\n\t\t\n\t\t# Create a numpy array\n\t\tself.np_protein_mat = np.array(list_matrix)\n\n\n\tdef iterate_mat(self, beta_param):\n\t\t'''\n\t\tUsing iterative method using the equation during the class\n\t\tdo this iteration for self.iters time\n\n\t\t'''\n\t\tinit_vec = [1/len(self.np_protein_mat)]*(len(self.np_protein_mat))\n\t\tinit_vec = np.array(init_vec)\n\t\te = [1/len(self.np_protein_mat)]*(len(self.np_protein_mat))\n\t\te = np.array(e)\n\n\t\tmy_vec = np.array(init_vec)\n\t\tfor i in range(self.iters):\n\t\t\tfirst = beta_param*(self.np_protein_mat.dot(my_vec))\n\t\t\tsecond = (1-(beta_param))*e\n\t\t\tmy_vec = first + second\n\t\t\n\t\t# my_vec is the rank for each protein\n\t\tself.my_protein_rank = my_vec\n\t\tprint (\"final rank: \")\n\t\tprint (self.my_protein_rank)\n\t\tprint (len(self.my_protein_rank))\n \n\n\tdef num_highest(self, number):\n\t\t'''\n\t\tFind the top 5 ranks\n\t\t'''\n\t\tnum_high = -number\n\t\ttop_ind = np.argpartition(self.my_protein_rank, num_high)[num_high:]\n\t\treal_value = self.my_protein_rank[top_ind]\n\t\tprint (\"real_value: \", real_value)\n\t\tprint ()\n\t\tprint (\" ---------------------------------------------- \")\n\t\ti = 0\n\t\tfor ind in top_ind:\n\t\t\tprint (\"Protein: \", self.idx_protein_dict_new[ind], \" pageRank: \", real_value[i])\n\t\t\ti += 1\n\t\tprint (\" ---------------------------------------------- \")\n\n\n\tdef draw_histogram(self):\n\t\t''' \n\t\tDraw histogram of the distribution\n\t\t''' \n\t\tx_axis = []\n\t\tfor i in range(len(self.my_protein_rank)):\n\t\t\t# x_axis.append(self.idx_protein_dict_new[i])\n\t\t\tx_axis.append(i)\n\n\t\t# Barplot\n\t\tplt.bar(x_axis, self.my_protein_rank, width=1, align='center', color='brown')\n\t\tplt.ylabel(\"pageRank\")\n\t\tplt.xlabel(\"proteins (index of proteins)\")\n\t\tplt.title(\"Bar plot of pageRank\")\n\t\tplt.show()\n\n\t\t# Histogram\n\t\tplt.hist(self.my_protein_rank)\n\t\tplt.xlabel(\"pageRank\")\n\t\tplt.ylabel(\"Frequency\")\n\t\tplt.title(\"Histogram of pageRank\")\n\t\tplt.show()\n\n\ndef main():\n\tprotein_data = open(\"test2.txt\", \"r\")\n\tbeta = sys.argv[1]\n\titers = sys.argv[2]\n\tPR_class = PR(protein_data, beta, iters)\n\tPR_class.parse_matrix()\n\tPR_class.create_matrix()\n\t# PR_class.remove_dead_ends()\n\ta_value = []\n\tfor i in range(1, 9):\n\t\tbeta = i/10\n\t\tPR_class.iterate_mat(beta)\n\t\ta_value.append(PR_class.my_protein_rank[0])\n\tplt.scatter([1,2,3,4,5,6,7,8],a_value)\n\tplt.show()\n\tPR_class.num_highest(3)\n\t# PR_class.draw_histogram()\n\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"page_rank/pageRank.py","file_name":"pageRank.py","file_ext":"py","file_size_in_byte":6910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"77681595","text":"import mortgage\n\n# read inputs from command line\nprice = float(input('Home price: '))\ndown_min = float(input('Minimum down payment: '))\ndown_max = float(input('Maximum down payment: '))\nrate = float(input('Interest rate: '))\nterm = float(input('Loan term (years): '))\n\nrate = rate / 100 / 12\n\n# use range function to enumerate down payments\nfor down in range(int(down_min), int(down_max), 1000):\n loan = price - down\n payment = mortgage.mortgage_payment(loan, rate, term*12)\n\n print(down, round(payment, 2))\n","sub_path":"PS_2/s18-a02-solutions-master/table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"649518882","text":"from fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\nimport nest_asyncio\nfrom pyngrok import ngrok\nimport uvicorn\n\napp = FastAPI()\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=['*'],\n allow_credentials=True,\n allow_methods=['*'],\n allow_headers=['*'],\n)\n\n@app.get('/')\nasync def root():\n return {'hello': 'world'}\n\n# Request body\n\nclass Item(BaseModel):\n name: str\n description: str = None\n price: float\n tax: float = None\n\n\n@app.post(\"/items/\")\nasync def create_item(item: Item):\n item_dict = item.dict()\n if item.tax:\n total = item.price + item.tax\n item_dict.update({\"TotalAmount\" : total})\n return item_dict\n\nngrok_tunnel = ngrok.connect(8000)\nprint('Public URL:', ngrok_tunnel.public_url)\nnest_asyncio.apply()\nuvicorn.run(app, port=8000)\n","sub_path":"RequestBody.py","file_name":"RequestBody.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"341652252","text":"from scrapy import Spider\nfrom scrapy.selector import Selector\nfrom scrapy.http import HtmlResponse, Request\nimport json\nfrom techreview.items import TecSpecsItem\n\nclass GsmArenaSpider(Spider):\n\tname = \"phonearena\"\n\tallowed_domains = [\"http://www.phonearena.com/\", \"www.phonearena.com\", \"phonearena.com\"]\n\tstart_urls = [\"http://www.phonearena.com/phones/manufacturers\"]\n\n\tdef parse(self, response):\t\t\n\t\tselector = Selector(response=response)\n\n\t\t# extract brand on current page\n\t\tbrands = selector.xpath('//div[@id=\"brands\"]/div[@class=\"s_listing\"]/div[contains(@class, \"s_block_4\")]/div[@class=\"s_hover\"]')\n\t\tfor brand in brands:\n\t\t\tbrandLink = (brand.xpath('.//a[@class=\"s_thumb\"]/@href').extract())[0]\n\t\t\tbrandName = (brand.xpath('(.//a)[2]//text()').extract())[0]\n\n\t\t\tyield Request(\"http://www.phonearena.com\" + brandLink + \"/?filter_class[]=1223\", meta={'product': 'Cellphones', 'brand': brandName}, callback=self.parseBrandItems)\n\t\t\tyield Request(\"http://www.phonearena.com\" + brandLink + \"/?filter_class[]=1612\", meta={'product': 'Tablets','brand': brandName}, callback=self.parseBrandItems)\n\t\t\n\tdef parseBrandItems(self, response):\n\t\tproduct = response.meta['product']\n\t\tbrand = response.meta['brand']\n\n\t\tselector = Selector(response=response)\n\n\t\tphones = selector.xpath('//div[@id=\"phones\"]/div[@class=\"s_listing\"]/div[contains(@class, \"s_block_4\")]/h3')\n\t\tfor phone in phones:\n\t\t\tphoneLink = (phone.xpath('.//a[not(*)]/@href').extract())[0]\n\t\t\tphoneName = (phone.xpath('.//a[not(*)]//text()').extract())[0]\n\n\t\t\titem = TecSpecsItem()\n\t\t\titem[\"product\"] = product\n\t\t\titem[\"brand\"] = brand\n\t\t\titem[\"name\"] = phoneName\n\t\t\titem[\"source\"] = 0\n\n\t\t\tyield Request(\"http://www.phonearena.com\" + phoneLink, meta={'item': item}, callback=self.parseItemSpecs)\n\n\n\t\tnextPageLink = selector.xpath('//li[@class=\"s_next\"]/a/@href').extract()\n\t\tif len(nextPageLink) > 0:\n\t\t\tyield Request(\"http://www.phonearena.com\" + nextPageLink[0], meta={'product': product, 'brand': brand}, callback=self.parseBrandItems)\n\n\tdef callnext(self, response):\n\t\tmeta = response.request.meta\n\n\t\tif len(meta[\"callstack\"]) > 0:\n\t\t\ttarget = meta[\"callstack\"].pop()\n\t\t\tyield Request(\"http://www.phonearena.com\" + target['url'], meta = meta, callback=target['callback'])\n\t\telse:\n\t\t\tyield meta[\"item\"]\n\n\tdef parseItemSpecs(self, response):\n\t\titem = response.meta[\"item\"]\n\t\t\n\t\tselector = Selector(response=response)\n\n\n\t\t# get pros and cons\n\t\tpros = []\n\t\tcons = []\n\n\t\tproscons_node = selector.xpath('//div[@class=\"proscons\"]')\n\t\tpros_nodes = proscons_node.xpath('.//ul[@class=\"s_pros_list\"]/li')\n\t\tfor node in pros_nodes:\n\t\t\tpros.append((node.xpath('.//text()').extract())[0])\n\n\t\tcons_nodes = proscons_node.xpath('.//ul[@class=\"s_cons_list\"]/li')\n\t\tfor node in cons_nodes:\n\t\t\tcons.append((node.xpath('.//text()').extract())[0])\t\t\n\n\t\titem[\"pros\"] = pros\n\t\titem[\"cons\"] = cons\n\n\t\t# get images\n\t\titem[\"images\"] = selector.xpath('//div[@class=\"lcimg\"]/a[@class=\"pics\"]/@href').extract()\n\t\titem[\"thumbnail\"] = selector.xpath('//div[@class=\"lcimg\"]/a[@class=\"pics\"]/img/@src').extract()\n\n\t\t# get stats\n\t\titem[\"stats\"] = selector.xpath('//div[@id=\"have_it\"]/div/a[contains(@class, \"number\")]//text()').extract()\n\n\t\t# getting urls to parse other information\n\t\tphonetabs = selector.xpath('//div[@class=\"phonetabs\"]/div[contains(@class, \"s_tabs\")]/ul')\n\t\t\n\t\tsizeUrl = phonetabs.xpath('.//li/a[text()[contains(.,\"Size\")]]/@href').extract()\n\t\tbenchmarksUrl = phonetabs.xpath('.//li/a[text()[contains(.,\"Benchmarks\")]]/@href').extract()\n\t\tvideosUrl = phonetabs.xpath('.//li/a[text()[contains(.,\"Video\")]]/@href').extract()\n\n\t\t# building up callstack\n\t\tcallstack = []\n\t\tif len(sizeUrl) > 0 and sizeUrl[0] != \"javascript:;\":\n\t\t\tcallstack.append({'url': sizeUrl[0], 'callback': self.parseItemSize})\n\t\t\n\t\tif len(benchmarksUrl) > 0 and benchmarksUrl[0] != \"javascript:;\":\n\t\t\tcallstack.append({'url': benchmarksUrl[0], 'callback': self.parseItemBenchmarks})\n\t\t\n\t\tif len(videosUrl) > 0 and videosUrl[0] != \"javascript:;\":\n\t\t\tcallstack.append({'url': videosUrl[0], 'callback': self.parseItemVideos})\n\n\t\tresponse.request.meta[\"item\"] = item\n\t\tresponse.request.meta[\"callstack\"] = callstack\n\t\treturn self.callnext(response)\n\n\tdef parseItemSize(self, response):\n\t\titem = response.meta['item']\n\n\t\tselector = Selector(response=response)\n\n\t\tsz_phone = selector.xpath('//div[@class=\"standart_view\"]/ul[contains(@class, \"sizecompare\")]/li[@class=\"sz_phone\"]')\n\t\tif len(sz_phone) > 0:\n\t\t\titem[\"size_images\"] = sz_phone[0].xpath('.//img/@src').extract()\n\n\t\treturn self.callnext(response)\n\n\tdef parseItemBenchmarks(self, response):\n\t\titem = response.meta['item']\n\n\t\tphoneName = \"{0} {1}\".format(item[\"brand\"], item[\"name\"])\n\t\t\n\t\tselector = Selector(response=response)\n\t\tbenchmark_topaccordeon = selector.xpath('//li[a[@class=\"acc_toggle\" and following-sibling::div[contains(@class, \"accordeon \")]]]')\n\n\t\tbenchmarks = []\n\t\tfor i in range(len(benchmark_topaccordeon)):\n\t\t\taccordeon = benchmark_topaccordeon[i]\n\t\t\t\n\t\t\tbench = {}\n\t\t\tbench[\"title\"] = (accordeon.xpath('.//a/span[@class=\"title\"]//text()').extract())[0].strip()\n\t\t\tbench[\"data\"] = []\n\n\t\t\tif i == 0 or i == 1 or i == 4:\n\t\t\t\ttable = accordeon.xpath('.//table[contains(@class, \"benchmark_table\")]')\n\t\t\t\tif table:\n\t\t\t\t\ttb_header = table.xpath('.//thead/tr/th[descendant::*]')\n\t\t\t\t\t\n\t\t\t\t\tphones = table.xpath('.//tbody/tr')\n\t\t\t\t\tfor phone in phones:\n\t\t\t\t\t\tname = (phone.xpath('.//th//text()').extract())[0].strip()\n\t\t\t\t\t\tif name == phoneName:\n\t\t\t\t\t\t\ttb_benchmark = phone.xpath('.//td[@class=\"benchmark_tb\"]')\n\t\t\t\t\t\n\t\t\t\t\t\t\tfor header, benchmark in zip(tb_header, tb_benchmark):\n\t\t\t\t\t\t\t\tscore = benchmark.xpath('.//strong/text()').extract()\n\t\t\t\t\t\t\t\tscore_des = benchmark.xpath('.//span/text()').extract()\n\n\t\t\t\t\t\t\t\ttitle = header.xpath('.//*[self::span[contains(@class,\"title\")] | self::a[contains(@class,\"title\")]]/text()').extract()\n\t\t\t\t\t\t\t\ttitle_des = header.xpath('.//span[@class=\"wichisbetter\"]//text()').extract()\n\n\t\t\t\t\t\t\t\tbench[\"data\"].append({\"title\": title[0].strip() if len(title) > 0 else \"\", \\\n\t\t\t\t\t\t\t\t\t\t\t\"title_des\": title_des[0].strip() if len(title_des) > 0 else \"\", \\\n\t\t\t\t\t\t\t\t\t\t\t\"score\": score[0].strip() if len(score) > 0 else \"\" , \\\n\t\t\t\t\t\t\t\t\t\t\t\"score_des\": score_des[0].strip() if len(score_des) > 0 else \"\"})\n\t\t\telif i == 3 or i == 5:\n\t\t\t\tcharts = accordeon.xpath('.//table/tr')\n\t\t\t\tfor chart in charts:\n\t\t\t\t\tch_header = chart.xpath('.//td[1]')\n\t\t\t\t\tch_benchmark = chart.xpath('.//td[2]')\n\n\t\t\t\t\ttitle = ch_header.xpath('.//div[contains(@class,\"name\")]/text()').extract()\n\t\t\t\t\ttitle_des = ch_header.xpath('.//span[@class=\"wichisbetter\"]//text()').extract()\n\n\t\t\t\t\tphones = ch_benchmark.xpath('.//div[@class=\"score\"]')\n\t\t\t\t\tfor phone in phones:\n\t\t\t\t\t\tname = (phone.xpath('.//span[contains(@class, \"bar\")]//text()').extract())[0].strip()\n\t\t\t\t\t\tif name == phoneName:\n\t\t\t\t\t\t\tscore = (phone.xpath('.//span[contains(@class, \"stext\")]/text()').extract())\n\t\t\t\t\t\t\tbench[\"data\"].append({\"title\": title[0].strip() if len(title) > 0 else \"\",\\\n\t\t\t\t\t\t\t\t\t\t\"title_des\": title_des[0].strip() if len(title_des) > 0 else \"\", \\\n\t\t\t\t\t\t\t\t\t\t\"score\": score[0].strip() if len(score) > 0 else \"\", \"score_des\": \"\"})\n\t\t\t\t\t\t\tbreak\n\t\t\telif i == 6:\n\t\t\t\ttitles = [\"\", \"Battery Life\", \"\", \"Charging Time\"]\n\t\t\t\ttables = accordeon.xpath('.//table')\n\t\t\t\tfor i in range(len(tables)):\n\t\t\t\t\tif i == 0 or i == 2:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t\n\t\t\t\t\ttable = tables[i]\n\t\t\t\t\ttb_benchmark = table.xpath('.//tr')\n\t\t\t\t\tfor benchmark in tb_benchmark:\n\t\t\t\t\t\tname = (benchmark.xpath('.//div[@class=\"name\"]//text()').extract())[0].strip()\n\t\t\t\t\t\tif name == phoneName:\n\t\t\t\t\t\t\tscore = (benchmark.xpath('.//span[contains(@class, \"stext\")]/text()').extract())\n\t\t\t\t\t\t\tscore_des = (benchmark.xpath('.//span[contains(@class, \"stext\")]/span/text()').extract())\n\n\t\t\t\t\t\t\tbench[\"data\"].append({\"score\": score[0].strip() if len(score) > 0 else \"\", \\\n\t\t\t\t\t\t\t\t\t\t\t\t\"score_des\": score_des[0].strip() if len(score_des) > 0 else \"\", \\\n\t\t\t\t\t\t\t\t\t\t\t\t\"title\" : titles[i]})\n\t\t\t\t\t\t\tbreak\n\n\n\n\t\t\tbenchmarks.append(bench)\n\t\t\n\t\titem[\"benchmarks\"] = benchmarks\n\n\t\treturn self.callnext(response)\n\n\tdef parseItemVideos(self, response):\n\t\titem = response.meta['item']\n\t\t\n\t\tselector = Selector(response=response)\n\t\tvideo_nodes = selector.xpath('//*[@id=\"yt-thumbs\"]/div')\n\n\t\tyt_videos = []\n\t\tfor node in video_nodes:\n\t\t\tyt_id = node.xpath('.//a[contains(@class, \"yt_show\")]/@vid').extract()\n\t\t\ttitle = node.xpath('.//a[contains(@class, \"yt_show\")]/@title').extract()\n\t\t\tthumbnail = node.xpath('.//img/@src').extract()\n\n\t\t\tyt_videos.append({'yt_id': yt_id[0] if len(yt_id) > 0 else \"\", \\\n\t\t\t\t\t\t\t'title': title[0] if len(title) > 0 else \"\", \\\n\t\t\t\t\t\t\t'thumbnail': thumbnail[0] if len(thumbnail) > 0 else \"\"})\n\n\t\titem[\"yt_videos\"] = yt_videos\n\n\t\treturn self.callnext(response)","sub_path":"build/lib.linux-x86_64-2.7/techreview/spiders/PhoneArenaSpider.py","file_name":"PhoneArenaSpider.py","file_ext":"py","file_size_in_byte":8677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"625888177","text":"from __future__ import annotations\nfrom datetime import timedelta\nfrom json import load\nfrom os import path\nfrom typing import Any, Mapping\n\nfrom wgups.structures.clock import Clock\nfrom wgups.structures.hash_set import HashSet\nfrom wgups.routing.package import Package\n\nDistances = HashSet[str, HashSet[str, str]]\nPackages = HashSet[int, Package]\nPrompts = HashSet[str, str]\n\n\nclass DataLoader:\n \"\"\"A class for loading external data into the application. Utilizes a cache to ensure\n that data is ever only loaded once.\n\n Class Attributes\n ----------------\n cache : HashSet[str, Any]\n The cache which handles storing file data.\n \"\"\"\n\n cache = HashSet[str, Any]()\n\n @classmethod\n def load_json(cls, filename) -> Mapping[Any, Any]:\n \"\"\"Attempts to retrieve the file from the cache. Loads the file data if it is not\n present in the cache.\n\n Returns\n -------\n Mapping[Any, Any]\n The JSON file data.\n\n Space Complexity\n ---------------\n O(n)\n\n Time Complexity\n ---------------\n O(n)\n \"\"\"\n file_path = path.join(path.dirname(__file__), filename)\n\n with open(file_path, 'r') as file:\n return load(file)\n\n @classmethod\n def get_packages(cls) -> Packages:\n \"\"\"Attempts to retrieve the packages from the cache. Loads the package data from a file\n if it is not present in the cache.\n\n Returns\n -------\n HashSet[int, str]\n The mapping of package identifiers to package objects.\n\n Space Complexity\n ---------------\n O(n)\n\n Time Complexity\n ---------------\n O(n)\n \"\"\"\n if 'packages' not in cls.cache:\n cls.cache.set('packages', cls.load_packages())\n\n return cls.cache.get('packages')\n\n @classmethod\n def load_packages(cls) -> Packages:\n \"\"\"Loads the package data from a file.\n\n Returns\n -------\n HashSet[int, str]\n The mapping of package identifiers to package objects.\n\n Space Complexity\n ---------------\n O(n)\n\n Time Complexity\n ---------------\n O(n)\n \"\"\"\n data = cls.load_json('data/package_data.json')\n size = len(data)\n packages = HashSet(size)\n\n for key, value in data.items():\n identifier = int(key)\n\n (hours, minutes) = map(int, value['deadline'].split(':'))\n deadline = Clock(hours, minutes)\n\n package = Package(\n identifier,\n value['address'],\n value['city'],\n value['state'],\n value['zip'],\n value['kg'],\n deadline,\n )\n\n # Delayed packages - will not arrive at depot until 09:05\n if package.id in [6, 25, 28, 32]:\n package.arrival_time = Clock(9, 5)\n\n # Incorrect address - will be corrected at 10:20\n if package.id == 9:\n package.street = '410 S State St'\n package.arrival_time = Clock(10, 20)\n\n # Package must be delivered via truck two\n if package.id in [3, 18, 36, 38]:\n package.deliverable_by = [2]\n package.is_priority = True\n\n # Package must be delivered with linked packages\n if package.id in [13, 14, 15, 16, 19, 20]:\n package.linked = True\n package.is_priority = True\n\n packages.set(identifier, package)\n\n return packages\n\n @classmethod\n def get_distances(cls) -> Distances:\n \"\"\"Attempts to retrieve the distances from the cache. Loads the distance data from a file\n if it is not present in the cache.\n\n Returns\n -------\n HashSet[str, HashSet[str, str]]\n The mapping of from and to addresses and the corresponding distance between them.\n\n Space Complexity\n ---------------\n O(n)\n\n Time Complexity\n ---------------\n O(n)\n \"\"\"\n if 'distances' not in cls.cache:\n cls.cache.set('distances', cls.load_distances())\n\n return cls.cache.get('distances')\n\n @classmethod\n def load_distances(cls) -> Distances:\n \"\"\"Loads the distance data from a file.\n\n Returns\n -------\n HashSet[str, HashSet[str, str]]\n The mapping of from and to addresses and the corresponding distance between them.\n\n Space Complexity\n ---------------\n O(n)\n\n Time Complexity\n ---------------\n O(n)\n \"\"\"\n data = cls.load_json('data/distance_data.json')\n size = len(data)\n distances = HashSet(size)\n\n for from_address, destinations in data.items():\n if from_address not in distances:\n distances.set(from_address, HashSet(size))\n\n for to_address, miles in destinations.items():\n distances.get(from_address).set(to_address, miles)\n\n return distances\n\n @classmethod\n def get_prompts(cls) -> Prompts:\n \"\"\"Attempts to retrieve the prompts from the cache. Loads the prompt data from a file\n if it is not present in the cache.\n\n Returns\n -------\n HashSet[str, str]\n The mapping of prompt names to prompt values.\n\n Space Complexity\n ---------------\n O(n)\n\n Time Complexity\n ---------------\n O(n)\n \"\"\"\n if 'prompts' not in cls.cache:\n cls.cache.set('prompts', cls.load_prompts())\n\n return cls.cache.get('prompts')\n\n @classmethod\n def load_prompts(cls) -> Prompts:\n \"\"\"Loads the prompt data from a file.\n\n Returns\n -------\n HashSet[str, str]\n The mapping of prompt names to prompt values.\n\n Space Complexity\n ---------------\n O(n)\n\n Time Complexity\n ---------------\n O(n)\n \"\"\"\n data = cls.load_json('data/prompts.json')\n size = len(data)\n prompts = HashSet(size)\n\n for key, value in data.items():\n prompts.set(key, value)\n\n return prompts\n","sub_path":"wgups/data/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":6360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"256487073","text":"from keras.models import Sequential\nfrom keras.layers.convolutional import Conv2D\nfrom keras.layers.convolutional import MaxPooling2D\nfrom keras.layers.core import Activation\nfrom keras.layers.core import Flatten\nfrom keras.layers.core import Dense\nfrom keras.layers import Concatenate\nfrom keras import backend as K\nimport matplotlib\nfrom keras.layers import LeakyReLU\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.callbacks import EarlyStopping\nfrom keras.optimizers import Adam, SGD, RMSprop, Adagrad, Adadelta\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport argparse\nimport sys\nfrom math import ceil\n# sys.path.append('..')\n# matplotlib.use(\"Agg\")\nfrom keras.models import Model\nfrom keras.layers import Input, Dense, concatenate\n\n\ndef args_parse():\n ap = argparse.ArgumentParser()\n ap.add_argument(\"-m\", \"--model\", required=False,\n help=\"path to output model\")\n ap.add_argument(\"-p\", \"--plot\", type=str, default=\"plot.png\",\n help=\"path to output accuracy/loss plot\")\n args = vars(ap.parse_args())\n return args\n\n\nclass LeNet:\n @staticmethod\n def build(width, height, depth, classes = 5):\n model = Sequential()\n inputShape = (height, width, depth)\n if K.image_data_format() == \"channels_first\":\n inputShape = (depth, height, width)\n\n # first set of CONV => RELU => POOL layers\n model.add(Conv2D(20, (5, 5), padding=\"same\", input_shape=inputShape))\n model.add(Activation(\"relu\"))\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n\n # second set of CONV => RELU => POOL layers\n model.add(Conv2D(50, (5, 5), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n\n # first (and only) set of FC => RELU layers\n model.add(Flatten())\n model.add(Dense(500))\n model.add(Activation(\"relu\"))\n\n # activation function\n model.add(Dense(CLASS_NUM))\n model.add(Activation(\"softmax\"))\n return model\n\ndef generator_three_img(gen1):\n\n while True:\n X1i = gen1.next()\n X2i = X1i\n X3i = X1i\n yield [X1i[0], X2i[0], X3i[0]], X1i[1]\n\ndef model1(width, height, depth):\n inputShape = (height, width, depth)\n if K.image_data_format() == \"channels_first\":\n inputShape = (depth, height, width)\n\n\n top_branch_input = Input(shape=inputShape, name='Top')\n top_branch_output = Conv2D(4, (7, 3), padding='same',strides=(2, 2),activation='relu')(top_branch_input)\n\n middle_branch_input = Input(shape=inputShape, name='Middle')\n middle_branch_output = Conv2D(8, (5, 5), padding='same', strides=(2, 2),activation='relu')(middle_branch_input)\n\n bottom_branch_input = Input(shape=inputShape, name='Bottom')\n bottom_branch_output = Conv2D(4, (3, 7), padding='same', strides=(2, 2), activation='relu')(bottom_branch_input)\n\n concat = concatenate([top_branch_output, middle_branch_output,bottom_branch_output], name='Concatenate')\n\n conv1 = Conv2D(32, (3, 3), strides=(2, 2), padding='same', activation='relu')(concat)\n conv2 = Conv2D(64, (3, 3), strides=(2, 2), padding='same', activation='relu')(conv1)\n flattern = Flatten()(conv2)\n dense1 = Dense(500, activation='relu')(flattern)\n dense2 = Dense(128, activation='relu')(dense1)\n final_model_output = Dense(CLASS_NUM, activation='softmax')(dense2)\n final_model = Model(inputs=[top_branch_input, middle_branch_input,bottom_branch_input], outputs=final_model_output,\n name='Final_output')\n return final_model\n \n \ndef model2(width, height, depth):\n inputShape = (height, width, depth)\n if K.image_data_format() == \"channels_first\":\n inputShape = (depth, height, width)\n\n\n top_branch_input = Input(shape=inputShape, name='Top')\n top_branch_output = Conv2D(4, (7, 3), padding='same',strides=(2, 2))(top_branch_input)\n top_branch_output = LeakyReLU(0.2)(top_branch_output)\n\n middle_branch_input = Input(shape=inputShape, name='Middle')\n middle_branch_output = Conv2D(8, (5, 5), padding='same', strides=(2, 2))(middle_branch_input)\n middle_branch_output = LeakyReLU(0.2)(middle_branch_output)\n\n bottom_branch_input = Input(shape=inputShape, name='Bottom')\n bottom_branch_output = Conv2D(4, (3, 7), padding='same', strides=(2, 2))(bottom_branch_input)\n bottom_branch_output = LeakyReLU(0.2)(bottom_branch_output)\n\n concat = concatenate([top_branch_output, middle_branch_output,bottom_branch_output], name='Concatenate')\n\n conv1 = Conv2D(32, (3, 3), strides=(2, 2), padding='same', activation='relu')(concat)\n conv2 = Conv2D(64, (3, 3), strides=(2, 2), padding='same', activation='relu')(conv1)\n flattern = Flatten()(conv2)\n dense1 = Dense(500, activation='relu')(flattern)\n dense2 = Dense(128, activation='relu')(dense1)\n final_model_output = Dense(CLASS_NUM, activation='softmax')(dense2)\n final_model = Model(inputs=[top_branch_input, middle_branch_input,bottom_branch_input], outputs=final_model_output,\n name='Final_output')\n return final_model\n\n\n\nclass AKNet:\n @staticmethod\n def build(width, height, depth, classes):\n kernel1 = Sequential()\n kernel2 = Sequential()\n kernel3 = Sequential()\n model = Sequential()\n\n\n inputShape = (height, width, depth)\n if K.image_data_format() == \"channels_first\":\n inputShape = (depth, height, width)\n\n # first set of CONV => RELU => POOL layers\n kernel1.add(Conv2D(8, (5, 5), padding='same',strides=(2,2), input_shape=inputShape, activation='relu'))\n kernel2.add(Conv2D(4, (3, 7), padding='same',strides=(2,2),input_shape=inputShape, activation='relu'))\n kernel3.add(Conv2D(4, (7, 3), padding='same',strides=(2,2), input_shape=inputShape, activation='relu'))\n\n merged = Concatenate([kernel1, kernel2,kernel3])\n\n model.add(merged)\n model.add(Conv2D(32,(3, 3), padding=\"same\",strides=(2,2), activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n model.add(Conv2D(32, (3, 3), padding=\"same\",strides=(2,2), activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n\n model.add(Flatten())\n model.add(Dense(96))\n model.add(Dense(16))\n\n\n model.add(Dense(CLASS_NUM))\n model.add(Activation(\"softmax\"))\n return model\n\n\n# parameters\nEPOCHS = 2000\nINIT_LR = 1e-3\nBS = 128\nCLASS_NUM = 5\nnorm_size = 32\nsteps_per_epoch = ceil(1126618 / BS)\nvalidation_step= ceil(281651 / BS)\ndef eachFile(filepath):\n out = []\n for allDir in filepath:\n child = allDir\n return out\n\n\n\n\n\nif __name__ == '__main__':\n args = args_parse()\n file_path = '/data2/Lucy_dataset_HEVC/'\n checkpoint_filepath = '/data2/minh_hevc/HEVC_dataset_test/TrainingData/checkpoint/5_classes_Kevin.h5'\n model_checkpoint_callback = ModelCheckpoint(\n filepath=checkpoint_filepath,\n save_weights_only=False,\n monitor='val_acc',\n mode='max',\n save_best_only=True)\n es = EarlyStopping(monitor='val_loss', mode='min', verbose=1,patience=5)\n # train_file_path = './TRAIN/'\n # test_file_path = './TEST/'\n train_datagen = ImageDataGenerator(validation_split=0.25)\n train_generator = train_datagen.flow_from_directory(directory=file_path, target_size=(32, 32),\n classes=eachFile(file_path),subset='training')\n # test_datagen = ImageDataGenerator()\n test_generator = train_datagen.flow_from_directory(directory=file_path, target_size=(32, 32),\n classes=eachFile(file_path),subset='validation')\n\n print(train_generator.class_indices)\n\n # model = AKNet.build(width=norm_size, height=norm_size, depth=3, classes=CLASS_NUM)\n model = LeNet.build(width=norm_size, height=norm_size, depth=3)\n # opt = SGD(lr=0.001, momentum=0.9)\n\n opt = Adam(lr=0.001)\n #opt = RMSprop(lr=0.001, rho=0.9, decay=0.0)\n #opt = Adagrad(lr=0.01, decay=0.0)\n # opt = Adadelta(lr=0.01, rho=0.95, decay=0.0)\n\n model.compile(loss=\"categorical_crossentropy\", optimizer=opt, metrics=[\"accuracy\"])\n model.summary()\n # H = model.fit_generator(generator_three_img(train_generator,), epochs=EPOCHS, validation_data=generator_three_img(test_generator,),steps_per_epoch=steps_per_epoch,validation_steps=validation_step,callbacks=[model_checkpoint_callback,es])\n H = model.fit_generator(train_generator, epochs=EPOCHS,\n validation_data=test_generator, steps_per_epoch=steps_per_epoch,\n validation_steps=validation_step, callbacks=[model_checkpoint_callback, es])\n\n print(\"[INFO] serializing network...\")\n model.save('5_classes_Kevin.h5')\n\n # plot the training loss and accuracy\n plt.style.use(\"ggplot\")\n plt.figure()\n N = es.stopped_epoch + 1\n plt.plot(np.arange(0, N), H.history[\"loss\"], label=\"train_loss\")\n plt.plot(np.arange(0, N), H.history[\"val_loss\"], label=\"val_loss\")\n plt.plot(np.arange(0, N), H.history[\"acc\"], label=\"train_acc\")\n plt.plot(np.arange(0, N), H.history[\"val_acc\"], label=\"val_acc\")\n plt.title(\"Training Loss and Accuracy\")\n plt.xlabel(\"Epoch #\")\n plt.ylabel(\"Loss/Accuracy\")\n plt.legend(loc=\"lower left\")\n plt.savefig(args[\"plot\"])","sub_path":"AK-CNN.py","file_name":"AK-CNN.py","file_ext":"py","file_size_in_byte":9615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"111045665","text":"from flask import Flask,render_template,request\r\nimport pickle\r\nfrom sklearn.linear_model import LogisticRegression\r\n\r\napp=Flask(__name__)\r\n\r\n@app.route(\"/\")\r\ndef home():\r\n return render_template('index.html')\r\n\r\n@app.route('/predict',methods=['POST'])\r\ndef predict():\r\n if request.method=='POST':\r\n spl=request.form['spl']\r\n spw=request.form['spw']\r\n ptl=request.form['ptl']\r\n ptw=request.form['ptw']\r\n\r\n data=[[float(spl),float(spw),float(ptl),float(ptw)]]\r\n lr=pickle.load(open('iris.pkl','rb'))\r\n prediction=lr.predict(data)[0]\r\n\r\n return render_template('index.html',prediction=prediction)\r\n\r\nif __name__=='__main__':\r\n app.run(debug=True)\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"447667353","text":"from django.urls import path\nfrom . import views\n\nfrom django.views.generic import TemplateView\n\napp_name = 'pyconafrica2019'\nurlpatterns = [\n path('', view=views.home19, name='home19'),\n path('about/', view=views.about, name='about'),\n path('schedule/', view=views.schedule, name='schedule'),\n path('conduct/', view=views.conduct, name='conduct'),\n path('coc/eporting-guidelines/', TemplateView.as_view(template_name='conduct/eporting-guidelines/eporting-guidelines.html')),\n path('coc/guidelines/', TemplateView.as_view(template_name='conduct/guidelines/guidelines.html')),\n path('sponsor-us/', view=views.sponsor_us, name='sponsor_us'),\n path('our-sponsors/', view=views.sponsors, name='sponsors'),\n path('register/', view=views.register, name='register'),\n path('travel/', view=views.traveladvice, name='traveladvice'),\n path('fin-aid/', view=views.fin_aid, name='fin_aid'),\n path('team/', view=views.team, name='team'),\n path('report/', view=views.report, name='report'),\n]\n\n","sub_path":"pyconafrica2019/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"324111928","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Oct 10 19:09:44 2019\r\n\r\n@author: CLIENTE\r\n\"\"\"\r\n\r\nfrom sympy import symbols, diff, evalf\r\nimport numpy as np\r\nfrom moresorensen import ms\r\nx1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11 = symbols('x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11')\r\nvar = [x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11]\r\nimport time\r\n\r\ndef MétodoDeRegiãoDeConfiança(dado):\r\n x = dado[4]\r\n função = dado[0]\r\n gradiente = dado[1]\r\n hessiana = dado[2]\r\n n = dado[3]\r\n def f(X):\r\n return função.subs([(var[i],X[i]) for i in range(n)])\r\n def grad(X):\r\n return np.asarray([expr.subs([(var[i],X[i]) for i in range(n)]) for expr in gradiente],dtype=float)\r\n def hess(X):\r\n return np.asarray([[expr.subs([(var[i],X[i]) for i in range(n)]) for expr in hessiana[j]] for j in range(n)],dtype=float) \r\n delta = 1\r\n mi1 = 0.01\r\n mi2 = 0.9\r\n lambda1 = 1/2 \r\n lambda2 = 1/2\r\n k = 0\r\n\r\n while np.dot(grad(x),grad(x)) > 10**(-4):\r\n s = ms(grad(x),hess(x),delta)\r\n p = (-1)*(f(x) - f(x+s))/(np.dot(s,grad(x))+(1/2)*(np.dot(s,np.dot(hess(x),s))))\r\n if p >= mi1:\r\n x = x+s\r\n if p >= mi2:\r\n delta = delta/lambda1\r\n elif p >= mi1:\r\n delta = delta\r\n else:\r\n delta = lambda1*delta\r\n if k >= 50:\r\n break\r\n return [x, f(x),grad(x)]","sub_path":"Método_de_Região_de_Confiança.py","file_name":"Método_de_Região_de_Confiança.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"268401293","text":"import tensorflow as tf\n\n\nclass Shakespeare(object):\n def __init__(self):\n self._vocab_size = 11302\n self._embed_size = 200\n self._cell_size = 300\n self._embedding_matrix = tf.get_variable(\n 'embedding',\n shape=[self._vocab_size, self._embed_size],\n initializer=tf.truncated_normal_initializer())\n\n def BuildTrainModel(self, word_ids):\n '''\n Args:\n words: a Tensor of shape [1, ?], each is a word(token) id.\n Returns:\n loss: a scalar Tensor.\n '''\n single_cell = tf.nn.rnn_cell.BasicLSTMCell(self._cell_size)\n\n concat_words = tf.concat(concat_dim=1, values=word_ids)\n word_embeds = tf.nn.embedding_lookup([self._embedding_matrix],\n concat_words)\n word_embed_list = tf.unstack(word_embeds, num=None, axis=1)\n outputs, final_state = tf.nn.rnn(single_cell,\n inputs=word_embed_list,\n dtype=tf.float32)\n w, b = self._GetWeightsAndBias()\n output_batch = tf.concat(concat_dim=0, values=outputs[:-1])\n labels = tf.reshape(word_ids[0, 1:], [-1, 1])\n loss = self._NceLoss(\n weights=w, biases=b, inputs=output_batch, labels=labels)\n return loss\n\n def BuildInferenceModel(self, word):\n '''\n Args:\n word: a scalar Tensor of int32, representing a word id.\n Returns:\n next_word: a scalar Tensor of int32, representing a word id.\n state_feed: a LSTMStateTuple of two placeholders, c and h.\n state_next: a LSTMStateTuple of two tensors, c and h.\n '''\n\n single_cell = tf.nn.rnn_cell.BasicLSTMCell(self._cell_size)\n state_feed_c = tf.placeholder(\n tf.float32, shape=[1, self._cell_size], name='c_feed')\n state_feed_h = tf.placeholder(\n tf.float32, shape=[1, self._cell_size], name='h_feed')\n state_feed = tf.nn.rnn_cell.LSTMStateTuple(state_feed_c, state_feed_h)\n\n word_embeds = tf.nn.embedding_lookup([self._embedding_matrix], word)\n word_embeds = tf.reshape(word_embeds, [1, self._embed_size])\n w, b = self._GetWeightsAndBias()\n output, state_next = single_cell(\n word_embeds, state_feed, scope='RNN/BasicLSTMCell')\n\n logits = tf.matmul(output, tf.transpose(w)) + b\n next_word_id = tf.argmax(logits, axis=1)\n\n # next_word_id = tf.Print(\n # next_word_id, [state_next.c, state_next.h, logits],\n # message='state')\n\n return next_word_id, state_feed, state_next\n\n def _NceLoss(self, weights, biases, inputs, labels):\n losses = tf.nn.nce_loss(\n weights=weights,\n biases=biases,\n inputs=inputs,\n labels=labels,\n num_sampled=500,\n num_classes=self._vocab_size)\n return tf.reduce_sum(losses)\n\n def _GetWeightsAndBias(self):\n softmax_w = tf.get_variable(\n 'W',\n shape=[self._vocab_size, self._cell_size],\n dtype=tf.float32,\n initializer=tf.truncated_normal_initializer())\n softmax_b = tf.get_variable(\n 'B',\n shape=[self._vocab_size],\n dtype=tf.float32,\n initializer=tf.truncated_normal_initializer())\n return softmax_w, softmax_b","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"98344655","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.linux-x86_64/egg/ditz/editor.py\n# Compiled at: 2016-11-27 06:27:17\n__doc__ = '\\nText editor.\\n'\nfrom __future__ import print_function\nimport os, yaml, tempfile\nfrom . import util\nfrom .files import read_file, read_yaml_file\nfrom .util import DitzError\n\nclass DitzEditor(object):\n \"\"\"\n An editor for Ditz objects.\n \"\"\"\n prefix = 'tmp-'\n suffix = '.yaml'\n textmode = False\n filetag = ''\n\n def __init__(self, path):\n self.original = read_file(path)\n self.text = self.original\n self.error = None\n return\n\n def edit(self):\n \"\"\"Edit the text and return it.\"\"\"\n program = util.editor()\n if not program:\n raise DitzError('no text editor is configured')\n fp, filename = tempfile.mkstemp(prefix=self.prefix, suffix=self.suffix, text=self.textmode)\n os.write(fp, self.text.encode('utf-8'))\n os.close(fp)\n try:\n util.run_editor(program, filename)\n self.text = read_file(filename)\n err = self.validate(filename)\n if err:\n self.error = err.replace(filename, self.filetag)\n else:\n self.error = None\n finally:\n os.remove(filename)\n\n return self.text\n\n def validate(self, path):\n \"\"\"Return validation error text or None.\"\"\"\n try:\n obj = read_yaml_file(path)\n obj.normalize()\n except yaml.error.YAMLError as err:\n return str(err)\n except DitzError as err:\n return str(err)\n\n return\n\n @property\n def modified(self):\n \"\"\"Whether text has been modified.\"\"\"\n return self.text != self.original\n\n\nif __name__ == '__main__':\n path = '../bugs/issue-3d1596d37cbd170f512eb939b97f5f22a3834c79.yaml'\n from ditz.objects import DitzObject\n editor = DitzEditor(path)\n print(editor.edit())\n print('Modified:', editor.modified)\n print('Error:', editor.error)","sub_path":"pycfiles/pydiv-2.1.tar/editor.py","file_name":"editor.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"619148613","text":"import scrapy\nimport re\nimport time\nimport math\nimport random\nfrom scrapy.linkextractors import LinkExtractor\nfrom javbus.items import JavbusItem\n\nclass JavSpider(scrapy.Spider):\n name = 'jav'\n start_urls = ['https://www.fanbus.in']\n web='https://www.fanbus.in'\n\n def parse(self, response):\n le=LinkExtractor(restrict_xpaths='//*[@id=\"waterfall\"]')\n links=le.extract_links(response)\n for link in links:\n yield scrapy.Request(url=link.url,callback=self.parse_info)\n nextpage=response.xpath('//*[@id=\"next\"]/@href').extract_first()\n if nextpage:\n nextpage=self.web+nextpage\n yield scrapy.Request(url=nextpage,callback=self.parse)\n\n\n def parse_info(self,response):\n item=JavbusItem()\n item['jav_sn']=response.xpath('//*[@class=\"row movie\"]/div/p/span[2]/text()').extract_first()\n item['jav_name']=response.xpath('//*[@class=\"container\"]/h3/text()').extract_first()\n\n patten_time=re.compile('長度: (.*?)分鐘')\n item['jav_time']=int(patten_time.search(response.text).group(1))\n item['jav_date']=int(time.strftime('%Y%m%d',time.localtime(time.time())))\n\n patten_open_date=re.compile('發行日期: (.*?)=1:\n for i in range(len(elements)):\n sourceInfo = {}\n #磁力链接\n mangetUrl = elements[i].xpath(\"td[1]/a/@href\").extract_first()\n sourceInfo[\"magnetUrl\"] = mangetUrl\n # #番号\n fanhao = item['jav_sn']\n sourceInfo[\"fanhao\"] = fanhao\n\n #视频大小\n size = elements[i].xpath(\"td[2]/a/text()\").extract_first().strip() if elements[i].xpath(\"td[2]/a/text()\").extract_first() else \"\"\n sourceInfo[\"size\"] = size\n # #时间\n openTime = elements[i].xpath(\"td[3]/a/text()\").extract_first().strip() if elements[i].xpath(\"td[3]/a/text()\").extract_first() else \"\"\n sourceInfo[\"openTime\"] = openTime\n info.append(sourceInfo)\n item[\"jav_cili\"] = info\n yield item\n\n\n","sub_path":"javbus/javbus/spiders/jav.py","file_name":"jav.py","file_ext":"py","file_size_in_byte":2946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"445701659","text":"import tensorflow as tf\nfrom fc_data_ff import get_run_op as get_ff_run_op\nfrom fc_data_ff import get_var_device\nfrom fc_data_ff import get_all_devices\n\nFLAGS = tf.app.flags.FLAGS\n\ndef all_reduce_gradients(tower_grads, devices):\n average_grads = []\n for grad_and_vars in zip(*tower_grads):\n # Note that each grad_and_vars looks like the following:\n # ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN))\n grads = []\n split_grads = []\n assert len(grad_and_vars) == FLAGS.num_workers\n # Each GPU splits its own grad\n for i, (g, _) in enumerate(grad_and_vars):\n with tf.device(devices[i]):\n split_grads.append(tf.split(0, FLAGS.num_workers, g))\n # Each GPU gatheres slices of grad from other GPUs to do average.\n for i, dev in enumerate(devices):\n with tf.device(dev):\n x = split_grads[i][i]\n for j in range(FLAGS.num_workers):\n if i == j:\n continue\n x += split_grads[j][i]\n grads.append(x / FLAGS.num_workers)\n grad = tf.concat(0, grads)\n\n # Keep in mind that the Variables are redundant because they are shared\n # across towers. So .. we will just return the first tower's pointer to\n # the Variable.\n v = grad_and_vars[0][1]\n grad_and_var = (grad, v)\n average_grads.append(grad_and_var)\n return average_grads\n\n\ndef get_run_op():\n losses = get_ff_run_op()\n tower_grads = []\n opt = tf.train.GradientDescentOptimizer(learning_rate=0.5)\n for i in range(FLAGS.num_workers):\n tower_grads.append(opt.compute_gradients(losses[i]))\n grads = all_reduce_gradients(tower_grads, get_all_devices())\n apply_gradient_op = opt.apply_gradients(grads)\n train_op = tf.group(apply_gradient_op)\n return train_op\n","sub_path":"benchmark/mini/models/fc_data_slice.py","file_name":"fc_data_slice.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"84600072","text":"s = input()\nk = int(input())\na = 0 \nb = 0\nfor i in range(len(s)):\n if(s[i] != \"1\"):\n a = s[i]\n b = i + 1\n break\nif(a == 0 or k < b):\n print(1)\nelse:\n print(a)\n","sub_path":"abc/abc106/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"118668149","text":"# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom google.api import resource_pb2\nfrom google.protobuf.descriptor_pb2 import FieldDescriptorProto\nfrom src.findings.finding_container import FindingContainer\nfrom src.findings.utils import FindingCategory\nfrom src.comparator.wrappers import Field\n\n\nclass FieldComparator:\n # global_resources: file-level resource definitions.\n # local_resource: message-level resource definition.\n # We need the resource database information to determine if the resource_reference\n # annotation removal or change is breaking or not.\n def __init__(\n self,\n field_original: Field,\n field_update: Field,\n ):\n self.field_original = field_original\n self.field_update = field_update\n\n def compare(self):\n # 1. If original FieldDescriptor is None, then a\n # new FieldDescriptor is added.\n if self.field_original is None:\n FindingContainer.addFinding(\n category=FindingCategory.FIELD_ADDITION,\n location=f\"{self.field_update.proto_file_name} Line: {self.field_update.source_code_line}\",\n message=f\"A new Field {self.field_update.name} is added.\",\n actionable=False,\n )\n return\n\n # 2. If updated FieldDescriptor is None, then\n # the original FieldDescriptor is removed.\n if self.field_update is None:\n FindingContainer.addFinding(\n category=FindingCategory.FIELD_REMOVAL,\n location=f\"{self.field_original.proto_file_name} Line: {self.field_original.source_code_line}\",\n message=f\"A Field {self.field_original.name} is removed\",\n actionable=True,\n )\n return\n\n self.global_resources_original = self.field_original.file_resources\n self.global_resources_update = self.field_update.file_resources\n self.local_resource_original = self.field_original.message_resource\n self.local_resource_update = self.field_update.message_resource\n\n # 3. If both FieldDescriptors are existing, check\n # if the name is changed.\n if self.field_original.name != self.field_update.name:\n FindingContainer.addFinding(\n category=FindingCategory.FIELD_NAME_CHANGE,\n location=f\"{self.field_update.proto_file_name} Line: {self.field_update.source_code_line}\",\n message=f\"Name of the Field is changed, the original is {self.field_original.name}, but the updated is {self.field_update.name}\",\n actionable=True,\n )\n return\n\n # 4. If the FieldDescriptors have the same name, check if the\n # repeated state of them stay the same.\n # TODO(xiaozhenliu): add location information for field.label\n if self.field_original.label != self.field_update.label:\n FindingContainer.addFinding(\n category=FindingCategory.FIELD_REPEATED_CHANGE,\n location=\"\",\n message=f\"Repeated state of the Field is changed, the original is {self.field_original.label}, but the updated is {self.field_update.label}\",\n actionable=True,\n )\n\n # 5. If the FieldDescriptors have the same repeated state,\n # check if the type of them stay the same.\n # TODO(xiaozhenliu): add location information for field.type\n if self.field_original.proto_type != self.field_update.proto_type:\n FindingContainer.addFinding(\n category=FindingCategory.FIELD_TYPE_CHANGE,\n location=\"\",\n message=f\"Type of the field is changed, the original is {self.field_original.proto_type}, but the updated is {self.field_update.proto_type}\",\n actionable=True,\n )\n # 6. Check the oneof_index of the field.\n if self.field_original.oneof != self.field_update.oneof:\n location = f\"{self.field_update.proto_file_name} Line: {self.field_update.source_code_line}\"\n if self.field_original.oneof:\n msg = f\"The existing field {self.field_original.name} is moved out of One-of.\"\n FindingContainer.addFinding(\n category=FindingCategory.FIELD_ONEOF_REMOVAL,\n location=location,\n message=msg,\n actionable=True,\n )\n else:\n msg = f\"The existing field {self.field_original.name} is moved into One-of.\"\n FindingContainer.addFinding(\n category=FindingCategory.FIELD_ONEOF_ADDITION,\n location=location,\n message=msg,\n actionable=True,\n )\n\n # 6. Check `google.api.resource_reference` annotation.\n # TODO(xiaozhenliu): add location information for field.resource_reference.\n self._compare_resource_reference(self.field_original, self.field_update)\n\n def _compare_resource_reference(self, field_original, field_update):\n resource_ref_original = self.field_original.resource_reference\n resource_ref_update = self.field_update.resource_reference\n # No resource_reference annotations found for the field in both versions.\n if not resource_ref_original and not resource_ref_update:\n return\n # A `google.api.resource_reference` annotation is added.\n if not resource_ref_original and resource_ref_update:\n FindingContainer.addFinding(\n FindingCategory.RESOURCE_REFERENCE_ADDITION,\n \"\",\n f\"A resource reference option is added to the field {field_original.name}\",\n False,\n )\n return\n # Resource annotation is removed, check if it is added as a message resource.\n if resource_ref_original and not resource_ref_update:\n if not self._resource_ref_in_local(resource_ref_original):\n FindingContainer.addFinding(\n FindingCategory.RESOURCE_REFERENCE_REMOVAL,\n \"\",\n f\"A resource reference option of field '{field_original.name}' is removed.\",\n True,\n )\n return\n # Resource annotation is both existing in the field for original and update versions.\n # They both use `type` or `child_type`.\n if field_original.child_type == field_update.child_type:\n original_type = (\n resource_ref_original.type or resource_ref_original.child_type\n )\n update_type = resource_ref_update.type or resource_ref_update.child_type\n if original_type != update_type:\n FindingContainer.addFinding(\n FindingCategory.RESOURCE_REFERENCE_CHANGE,\n \"\",\n f\"The type of resource reference option in field '{field_original.name}' is changed from '{original_type}' to '{update_type}'.\",\n True,\n )\n return\n # The `type` is changed to `child_type` or `child_type` is changed to `type`, but\n # resulting referenced resource patterns can be resolved to be identical,\n # in that case it is not considered breaking.\n # Register the message-level resource into the global resource database,\n # so that we can query the parent resources for child_type.\n self._register_local_resource()\n if field_original.child_type:\n self._is_parent_type(\n resource_ref_original.child_type, resource_ref_update.type, True\n )\n if field_update.child_type:\n self._is_parent_type(\n resource_ref_update.child_type, resource_ref_original.type, False\n )\n\n def _resource_ref_in_local(self, resource_ref):\n \"\"\"Check if the resource type is in the local resources defined by a message option.\"\"\"\n if not self.local_resource_update:\n return False\n checked_type = resource_ref.type or resource_ref.child_type\n if not checked_type:\n raise TypeError(\n \"In a resource_reference annotation, either `type` or `child_type` field should be defined\"\n )\n if self.local_resource_update.type != checked_type:\n return False\n return True\n\n def _register_local_resource(self):\n # Add message-level resource definition to the global resource database for query.\n self.global_resources_original.register_resource(self.local_resource_original)\n self.global_resources_update.register_resource(self.local_resource_update)\n\n def _is_parent_type(self, child_type, parent_type, original_is_child):\n if original_is_child:\n parent_resources = (\n self.global_resources_original.get_parent_resources_by_child_type(\n child_type\n )\n )\n else:\n parent_resources = (\n self.global_resources_update.get_parent_resources_by_child_type(\n child_type\n )\n )\n if parent_type not in [parent.type for parent in parent_resources]:\n # Resulting referenced resource patterns cannot be resolved identical.\n FindingContainer.addFinding(\n FindingCategory.RESOURCE_REFERENCE_CHANGE,\n \"\",\n f\"The child_type '{child_type}' and type '{parent_type}' of \"\n f\"resource reference option in field '{self.field_original.name}' \"\n \"cannot be resolved to the identical resource.\",\n True,\n )\n","sub_path":"src/comparator/field_comparator.py","file_name":"field_comparator.py","file_ext":"py","file_size_in_byte":10262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"639231818","text":"# check whether the result of 2^n+1 is prime number or not when n is a prime number\n# ref. stackoverflow.com\n#\n# pip3 install sympy!\n#\n# 2022.09.15 by neibc96@gmail.com & GD\n\nimport math\nfrom datetime import datetime\nimport sys\nimport platform\nimport sympy\n\n#global variables\nispause = 0\n\ndef is_prime(n):\n if n % 2 == 0 and n > 2: \n return False\n return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))\n \nprint('environment_uname : ', end='')\nprint(platform.platform())\n\nmaxnum = 1000\nmaxsquarenum = 10000\n\n#startnum = 3 \n\nwhile maxnum > 0:\n pnum1 = 0\n noftrue = 0\n noffalse = 0\n\n maxnum = int(input(\"input max target investigation value(>1, 0 to end) ex> 2020123212321223 : \"))\n print('-------------------------------------------------------')\n print('start time : ' + datetime.utcnow().strftime('%Y/%m/%d_%H:%M:%S.%f'))\n starta = datetime.now()\n\n for i in range(2, maxsquarenum):\n if sympy.isprime(i) == True:\n tval = pow(2, i) + 1\n if tval > maxnum:\n break\n pcheckresult = sympy.isprime(tval)\n if pcheckresult == True:\n noftrue=noftrue+1\n else: \n noffalse=noffalse+1\n print('2^%d + 1 = %d : %s' %(i, tval, pcheckresult))\n\n startb = datetime.now()\n print('\\nend time : ' + datetime.utcnow().strftime('%Y/%m/%d_%H:%M:%S.%f'))\n print('-------------------------------------------------------')\n print('time diff : ', end='')\n print(startb-starta)\n print('max number : %d' %maxnum)\n print('\\nnumber of true samples : %d' %noftrue)\n print('number of false samples : %d' %noffalse)\n print('ratio of true samples : %f' %(noftrue/(noftrue+noffalse)))\n\nif ispause > 0:\n input('enter key to end')\n","sub_path":"checkmersenne_prime_plus1.py","file_name":"checkmersenne_prime_plus1.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"489161639","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/10/24 3:28 下午\n# @Author : Frankie\n# @File : leetcode_102_层次遍历.py\n\n\nfrom typing import List\n\n# 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 def levelOrder(self, root: TreeNode) -> List[List[int]]:\n \"\"\"\n 思路:二叉树 => 递归\n :param root:\n :return:\n \"\"\"\n # 递归终止\n if not root:\n return []\n if root.left is None and root.right is None:\n return [[root.val]]\n\n res = []\n left_tree = self.levelOrder(root.left)\n right_tree = self.levelOrder(root.right)\n\n res.append([root.val])\n len_left = len(left_tree)\n len_right = len(right_tree)\n if len_left >= len_right:\n for i in range(len_left):\n right_tem = right_tree[i] if i < len_right else []\n tem = left_tree[i] + right_tem\n res.append(tem)\n else:\n for i in range(len_right):\n left_tem = left_tree[i] if i < len_left else []\n tem = left_tem + right_tree[i]\n res.append(tem)\n return res\n\n\n\n\n","sub_path":"Python/二叉树/二叉树的构造及遍历/leetcode_102_层次遍历.py","file_name":"leetcode_102_层次遍历.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"456540084","text":"from turtle import *\r\nimport math\r\n\r\n# Name your Turtle.\r\nt = Turtle()\r\n\r\n\r\n# Set Up your screen and starting position.\r\nt.penup()\r\nsetup(850,850)\r\nbgcolor(\"black\")\r\n\r\nt.penup()\r\nt.setx(200)\r\nt.sety(200)\r\n\r\n\r\nsides = input('How many sides?: ')\r\nsides= int(sides)\r\nangle = 360 / sides\r\ncolor = input('What color?: ')\r\nscale = input('Big, medium or small? Type B for big, M for medium, S for small: ')\r\nif scale == 'B':\r\n length = 300\r\nelif scale == 'M':\r\n length = 200\r\nelif scale == 'S':\r\n length = 100\r\n\r\n\r\n#define draw shape\r\ndef drawshape(sides, color):\r\n t.pendown()\r\n t.fillcolor(color)\r\n t.begin_fill()\r\n for sides in range(sides):\r\n t.forward(length)\r\n t.right(angle)\r\n t.end_fill()\r\n\r\n#move!\r\ndrawshape(sides, color)\r\n\r\n# Close window on click.\r\nexitonclick()\r\n","sub_path":"draw_polygon_game.py","file_name":"draw_polygon_game.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"112319074","text":"\nfrom tkinter import *\nfrom tkinter import ttk\nfrom trello import TrelloClient\nimport requests\n\n\ndef create_board(board_name):\n url = \"https://api.trello.com/1/boards/\"\n querystring = {\"name\": board_name, \"key\": api_key, \"token\": token}\n response = requests.request(\"POST\", url, params=querystring)\n board_id = response.json()[\"shortUrl\"].split(\"/\")[-1].strip()\n return board_id\n \ndef create_card(list_id, card_name):\n url = \"https://api.trello.com/1/cards\"\n querystring = {\"name\": card_name, \"idList\": list_id, \"key\": key, \"token\": token}\n response = requests.request(\"POST\", url, params=querystring)\n card_id = response.json()[\"id\"]\n return card_id\n \n# on change dropdown value\ndef change_dropdown(*args):\n print( tkvar.get() )\n \ndef clickMe():\n boardName = name.get()\n create_board(boardName)\n\n#last_board = all_boards[-1]\n#print(last_board.name)\n\n#print(all_boards[0].name)\n\n#lists = all_boards[0].all_lists()\n#print(lists)\n\n#all_boards[1].add_label(\"concept\", \"blue\")\n\n#create_board(\"randomTest\")\n\nroot = Tk()\nroot.title(\"Tk dropdown example\")\nroot.geometry('300x400')\n# Add a grid\nmainframe = Frame(root)\nmainframe.grid(column=0,row=0, sticky=(N,W,E,S) )\nmainframe.columnconfigure(0, weight = 2)\nmainframe.rowconfigure(0, weight = 2)\nmainframe.pack(padx = 0, pady = 0)\n\n\n# Create a Tkinter variable\ntkvar = StringVar(root)\n\nall_boards = client.list_boards()\nboardList = []\n\nfor i in all_boards:\n boardList.append(i)\nprint(list)\n\nboardList = list(dict.fromkeys(boardList))\nprint(boardList)\n# Dictionary with options\nchoices = boardList\ntkvar.set(choices[-1]) # set the default option\n\npopupMenu = OptionMenu(mainframe, tkvar, *choices)\ntkvar.trace('w', change_dropdown)\nLabel(mainframe, text=\"Choose a Board:\").grid(row = 0, column = 1)\npopupMenu.grid(row = 1, column =1)\n\n# link function to change dropdown\ntkvar.trace('w', change_dropdown)\n\nlabel = ttk.Label(mainframe, text = \"Create Board:\").grid(column = 0, row = 2)\n\nname = StringVar()\nnameEntered = ttk.Entry(mainframe, width = 15, textvariable = name)\nnameEntered.grid(column = 1, row = 2)\n\nbutton = ttk.Button(mainframe, text = \"Click Me\", command = clickMe).grid(column= 2, row = 2)\n\n\nroot.mainloop()\n\ndel boardList, tkvar, root\n","sub_path":"program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"40839414","text":"from random import sample\nimport time\nfrom getContigs import getContigs\n\n'''\nThis script evaluates the getContigs function I wrote up\nI scale up the length of the list I get contigs from.\nIt's assumed that the list you pass into getContigs()\nis already sorted, so no such check is currently in place\nfor getContigs for sorted state of the list.\n'''\n\n# unit test\nmyList = [1, 2, 4, 6, 8, 9, 10]\nprint(getContigs(myList))\n\n# generative test\nN_iter = [10, 100, 1000]\ncontigsDict = {str(n):{} for n in N_iter}\n# for reproducibility, I'd normally place a seed here.\nfor n in N_iter:\n thisLineup = sorted(sample(range(1,n), round(0.7*n)))\n start = time.perf_counter()\n theseContigs = getContigs(thisLineup)\n end = time.perf_counter()\n delta = end - start\n contigsDict[str(n)] = {\"time\":delta, \"contigs\":theseContigs}\n \nprint([[contigsDict[k][\"time\"], len(contigsDict[k][\"contigs\"])] for k in contigsDict.keys()])\n","sub_path":"getContigs_evaluation.py","file_name":"getContigs_evaluation.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"311186572","text":"from __future__ import print_function # Python 2 and 3 print compatibility\n\nfrom hail.expr.ast import *\nfrom hail.expr.types import *\nfrom hail.utils.java import *\nfrom hail.utils.linkedlist import LinkedList\nfrom hail.genetics import Locus, Variant, Interval, Call, AltAllele\nfrom hail.typecheck import *\nfrom collections import Mapping\n\nclass Indices(object):\n @typecheck_method(source=anytype, axes=setof(strlike))\n def __init__(self, source=None, axes=set()):\n self.source = source\n self.axes = axes\n\n def __eq__(self, other):\n return isinstance(other, Indices) and self.source is other.source and self.axes == other.axes\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n @staticmethod\n def unify(*indices):\n axes = set()\n src = None\n for ind in indices:\n if src is None:\n src = ind.source\n else:\n if ind.source is not None and ind.source is not src:\n raise ExpressionException()\n\n both = axes.intersection(ind.axes)\n left_only = axes - both\n right_only = ind.axes - both\n\n axes = axes.union(ind.axes)\n\n return Indices(src, axes)\n\n def __str__(self):\n return 'Indices(axes={}, source={})'.format(self.axes, self.source)\n\n def __repr__(self):\n return 'Indices(axes={}, source={})'.format(repr(self.axes), repr(self.source))\n\nclass Aggregation(object):\n def __init__(self, indices, refs):\n self.indices = indices\n self.refs = refs\n\n\nclass Join(object):\n def __init__(self, join_function, temp_vars):\n self.join_function = join_function\n self.temp_vars = temp_vars\n\n\n@typecheck(ast=AST, type=Type, indices=Indices, aggregations=LinkedList, joins=LinkedList, refs=LinkedList)\ndef construct_expr(ast, type, indices=Indices(), aggregations=LinkedList(Aggregation), joins=LinkedList(Join),\n refs=LinkedList(tuple)):\n if isinstance(type, TArray) and type.element_type.__class__ in elt_typ_to_array_expr:\n return elt_typ_to_array_expr[type.element_type.__class__](ast, type, indices, aggregations, joins, refs)\n elif isinstance(type, TSet) and type.element_type.__class__ in elt_typ_to_set_expr:\n return elt_typ_to_set_expr[type.element_type.__class__](ast, type, indices, aggregations, joins, refs)\n elif type.__class__ in typ_to_expr:\n return typ_to_expr[type.__class__](ast, type, indices, aggregations, joins, refs)\n else:\n raise NotImplementedError(type)\n\n@typecheck(name=strlike, type=Type, indices=Indices, prefix=nullable(strlike))\ndef construct_reference(name, type, indices, prefix=None):\n if prefix is not None:\n ast = Select(Reference(prefix, True), name)\n else:\n ast = Reference(name, True)\n return construct_expr(ast, type, indices, refs=LinkedList(tuple).push((name, indices)))\n\ndef to_expr(e):\n if isinstance(e, Expression):\n return e\n elif isinstance(e, str) or isinstance(e, unicode):\n return construct_expr(Literal('\"{}\"'.format(Env.jutils().escapePyString(e))), TString())\n elif isinstance(e, bool):\n return construct_expr(Literal(\"true\" if e else \"false\"), TBoolean())\n elif isinstance(e, int):\n return construct_expr(Literal(str(e)), TInt32())\n elif isinstance(e, long):\n return construct_expr(ClassMethod('toInt64', Literal('\"{}\"'.format(e))), TInt64())\n elif isinstance(e, float):\n return construct_expr(Literal(str(e)), TFloat64())\n elif isinstance(e, Variant):\n return construct_expr(ApplyMethod('Variant', Literal('\"{}\"'.format(str(e)))), TVariant(e.reference_genome))\n elif isinstance(e, Locus):\n return construct_expr(ApplyMethod('Locus', Literal('\"{}\"'.format(str(e)))), TLocus(e.reference_genome))\n elif isinstance(e, Interval):\n return construct_expr(ApplyMethod('LocusInterval', Literal('\"{}\"'.format(str(e)))), TInterval(TLocus(e.reference_genome)))\n elif isinstance(e, Call):\n return construct_expr(ApplyMethod('Call', Literal(str(e.gt))), TCall())\n elif isinstance(e, AltAllele):\n return construct_expr(ApplyMethod('AltAllele', to_expr(e.ref)._ast, to_expr(e.alt)._ast), TAltAllele())\n elif isinstance(e, Struct):\n attrs = e._fields.items()\n cols = [to_expr(x) for _, x in attrs]\n names = [k for k, _ in attrs]\n indices, aggregations, joins, refs = unify_all(*cols)\n t = TStruct(names, [col._type for col in cols])\n return construct_expr(StructDeclaration(names, [c._ast for c in cols]),\n t, indices, aggregations, joins, refs)\n elif isinstance(e, list):\n cols = [to_expr(x) for x in e]\n types = list({col._type for col in cols})\n if len(cols) == 0:\n raise ExpressionException('Cannot convert empty list to expression.')\n elif len(types) == 1:\n t = TArray(types[0])\n elif all([is_numeric(t) for t in types]):\n t = TArray(convert_numeric_typ(*types))\n else:\n raise ExpressionException('Cannot convert list with heterogeneous key types to expression.'\n '\\n Found types: {}.'.format(types))\n indices, aggregations, joins, refs = unify_all(*cols)\n return construct_expr(ArrayDeclaration([col._ast for col in cols]),\n t, indices, aggregations, joins, refs)\n elif isinstance(e, set):\n cols = [to_expr(x) for x in e]\n types = list({col._type for col in cols})\n if len(cols) == 0:\n raise ExpressionException('Cannot convert empty set to expression.')\n elif len(types) == 1:\n t = TSet(types[0])\n elif all([is_numeric(t) for t in types]):\n t = TSet(convert_numeric_typ(*types))\n else:\n raise ExpressionException('Cannot convert set with heterogeneous key types to expression.'\n '\\n Found types: {}.'.format(types))\n indices, aggregations, joins, refs = unify_all(*cols)\n return construct_expr(ClassMethod('toSet', ArrayDeclaration([col._ast for col in cols])), t, indices,\n aggregations, joins, refs)\n elif isinstance(e, dict):\n key_cols = []\n value_cols = []\n keys = []\n values = []\n for k, v in e.items():\n key_cols.append(to_expr(k))\n keys.append(k)\n value_cols.append(to_expr(v))\n values.append(v)\n key_types = list({col._type for col in key_cols})\n value_types = list({col._type for col in value_cols})\n\n if len(key_types) == 0:\n raise ExpressionException('Cannot convert empty dictionary to expression.')\n elif len(key_types) == 1:\n key_type = key_types[0]\n elif all([is_numeric(t) for t in key_types]):\n key_type = convert_numeric_typ(*key_types)\n else:\n raise ExpressionException('Cannot convert dictionary with heterogeneous key types to expression.'\n '\\n Found types: {}.'.format(key_types))\n\n if len(value_types) == 1:\n value_type = value_types[0]\n elif all([is_numeric(t) for t in value_types]):\n value_type = convert_numeric_typ(*value_types)\n else:\n raise ExpressionException('Cannot convert dictionary with heterogeneous value types to expression.'\n '\\n Found types: {}.'.format(value_types))\n\n kc = to_expr(keys)\n vc = to_expr(values)\n\n indices, aggregations, joins, refs = unify_all(kc, vc)\n\n assert key_type == kc._type.element_type\n assert value_type == vc._type.element_type\n\n ast = ApplyMethod('Dict',\n ArrayDeclaration([k._ast for k in key_cols]),\n ArrayDeclaration([v._ast for v in value_cols]))\n return construct_expr(ast, TDict(key_type, value_type), indices, aggregations, joins, refs)\n else:\n raise ExpressionException(\"Cannot implicitly convert value '{}' of type '{}' to expression.\".format(\n e, e.__class__))\n\n\n_lazy_int32 = lazy()\n_lazy_numeric = lazy()\n_lazy_array = lazy()\n_lazy_set = lazy()\n_lazy_bool = lazy()\n_lazy_struct = lazy()\n_lazy_string = lazy()\n_lazy_variant = lazy()\n_lazy_locus = lazy()\n_lazy_altallele = lazy()\n_lazy_interval = lazy()\n_lazy_call = lazy()\n_lazy_expr = lazy()\n\nexpr_int32 = transformed((_lazy_int32, identity),\n (integral, to_expr))\nexpr_numeric = transformed((_lazy_numeric, identity),\n (integral, to_expr),\n (float, to_expr))\nexpr_list = transformed((list, to_expr),\n (_lazy_array, identity))\nexpr_set = transformed((set, to_expr),\n (_lazy_set, identity))\nexpr_bool = transformed((bool, to_expr),\n (_lazy_bool, identity))\nexpr_struct = transformed((Struct, to_expr),\n (_lazy_struct, identity))\nexpr_str = transformed((strlike, to_expr),\n (_lazy_string, identity))\nexpr_variant = transformed((Variant, to_expr),\n (_lazy_variant, identity))\nexpr_locus = transformed((Locus, to_expr),\n (_lazy_locus, identity))\nexpr_altallele = transformed((AltAllele, to_expr),\n (_lazy_altallele, identity))\nexpr_interval = transformed((Interval, to_expr),\n (_lazy_interval, identity))\nexpr_call = transformed((Call, to_expr),\n (_lazy_call, identity))\nexpr_any = transformed((_lazy_expr, identity),\n (anytype, to_expr))\n\ndef unify_all(*exprs):\n assert len(exprs) > 0\n try:\n new_indices = Indices.unify(*[e._indices for e in exprs])\n except ExpressionException:\n # source mismatch\n from collections import defaultdict\n sources = defaultdict(lambda: [])\n for e in exprs:\n for name, inds in e._refs:\n sources[inds.source].append(str(name))\n raise ExpressionException(\"Cannot combine expressions from different source objects.\"\n \"\\n Found fields from {n} objects:{fields}\".format(\n n=len(sources),\n fields=''.join(\"\\n {}: {}\".format(src, fds) for src, fds in sources.items())\n ))\n first, rest = exprs[0], exprs[1:]\n agg = first._aggregations\n joins = first._joins\n refs = first._refs\n for e in rest:\n agg = agg.push(*e._aggregations)\n joins = joins.push(*e._joins)\n refs = refs.push(*e._refs)\n return new_indices, agg, joins, refs\n\n\n__numeric_types = [TInt32, TInt64, TFloat32, TFloat64]\n\n\n@typecheck(t=Type)\ndef is_numeric(t):\n return t.__class__ in __numeric_types\n\n\n@typecheck(types=Type)\ndef convert_numeric_typ(*types):\n priority_map = {t: p for t, p in zip(__numeric_types, range(len(__numeric_types)))}\n priority = 0\n for t in types:\n assert (is_numeric(t)), t\n t_priority = priority_map[t.__class__]\n if t_priority > priority:\n priority = t_priority\n return __numeric_types[priority]()\n\n\nclass Expression(object):\n \"\"\"Base class for Hail expressions.\"\"\"\n\n @typecheck_method(ast=AST, type=Type, indices=Indices, aggregations=LinkedList, joins=LinkedList, refs=LinkedList)\n def __init__(self, ast, type, indices=Indices(), aggregations=LinkedList(Aggregation), joins=LinkedList(Join), refs=LinkedList(tuple)):\n self._ast = ast\n self._type = type\n self._indices = indices\n self._aggregations = aggregations\n self._joins = joins\n self._refs = refs\n\n self._init()\n\n def __str__(self):\n return repr(self)\n\n def __repr__(self):\n s = \"{super_repr}\\n Type: {type}\".format(\n super_repr=super(Expression, self).__repr__(),\n type=str(self._type),\n )\n\n indices = self._indices\n if len(indices.axes) == 0:\n s += '\\n Index{agg}: None'.format(agg=' (aggregated)' if self._aggregations else '')\n else:\n s += '\\n {ind}{agg}:\\n {index_lines}'.format(ind=plural('Index', len(indices.axes), 'Indices'),\n agg=' (aggregated)' if self._aggregations else '',\n index_lines='\\n '.join('{} of {}'.format(\n axis, indices.source) for axis in indices.axes))\n if self._joins:\n s += '\\n Dependent on {} {}'.format(len(self._joins),\n plural('broadcast/join', len(self._joins), 'broadcasts/joins'))\n return s\n\n def __lt__(self, other):\n raise NotImplementedError(\"'<' comparison with expression of type {}\".format(str(self._type)))\n\n def __le__(self, other):\n raise NotImplementedError(\"'<=' comparison with expression of type {}\".format(str(self._type)))\n\n def __gt__(self, other):\n raise NotImplementedError(\"'>' comparison with expression of type {}\".format(str(self._type)))\n\n def __ge__(self, other):\n raise NotImplementedError(\"'>=' comparison with expression of type {}\".format(str(self._type)))\n\n def _init(self):\n pass\n\n def __nonzero__(self):\n raise NotImplementedError(\n \"The truth value of an expression is undefined\\n Hint: instead of if/else, use 'f.cond'\")\n\n def _unary_op(self, name):\n return construct_expr(UnaryOperation(self._ast, name),\n self._type, self._indices, self._aggregations, self._joins, self._refs)\n\n def _bin_op(self, name, other, ret_typ):\n other = to_expr(other)\n indices, aggregations, joins, refs = unify_all(self, other)\n return construct_expr(BinaryOperation(self._ast, other._ast, name), ret_typ, indices, aggregations, joins, refs)\n\n def _bin_op_reverse(self, name, other, ret_typ):\n other = to_expr(other)\n indices, aggregations, joins, refs = unify_all(self, other)\n return construct_expr(BinaryOperation(other._ast, self._ast, name), ret_typ, indices, aggregations, joins, refs)\n\n def _field(self, name, ret_typ):\n return construct_expr(Select(self._ast, name), ret_typ, self._indices,\n self._aggregations, self._joins, self._refs)\n\n def _method(self, name, ret_typ, *args):\n args = tuple(to_expr(arg) for arg in args)\n indices, aggregations, joins, refs = unify_all(self, *args)\n return construct_expr(ClassMethod(name, self._ast, *(a._ast for a in args)),\n ret_typ, indices, aggregations, joins, refs)\n\n def _index(self, ret_typ, key):\n key = to_expr(key)\n indices, aggregations, joins, refs = unify_all(self, key)\n return construct_expr(Index(self._ast, key._ast),\n ret_typ, indices, aggregations, joins, refs)\n\n def _slice(self, ret_typ, start=None, stop=None, step=None):\n if start is not None:\n start = to_expr(start)\n start_ast = start._ast\n else:\n start_ast = None\n if stop is not None:\n stop = to_expr(stop)\n stop_ast = stop._ast\n else:\n stop_ast = None\n if step is not None:\n raise NotImplementedError('Variable slice step size is not currently supported')\n\n non_null = [x for x in [start, stop] if x is not None]\n indices, aggregations, joins, refs = unify_all(self, *non_null)\n return construct_expr(Index(self._ast, Slice(start_ast, stop_ast)),\n ret_typ, indices, aggregations, joins, refs)\n\n def _bin_lambda_method(self, name, f, inp_typ, ret_typ_f, *args):\n args = (to_expr(arg) for arg in args)\n new_id = Env._get_uid()\n lambda_result = to_expr(\n f(construct_expr(Reference(new_id), inp_typ, self._indices, self._aggregations, self._joins, self._refs)))\n indices, aggregations, joins, refs = unify_all(self, lambda_result)\n ast = LambdaClassMethod(name, new_id, self._ast, lambda_result._ast, *(a._ast for a in args))\n return construct_expr(ast, ret_typ_f(lambda_result._type), indices, aggregations, joins, refs)\n\n @property\n def dtype(self):\n \"\"\"The data type of the expression.\n\n Returns\n -------\n :class:`.Type`\n Data type.\n \"\"\"\n return self._type\n\n def __eq__(self, other):\n \"\"\"Returns ``True`` if the two epressions are equal.\n\n Examples\n --------\n\n .. doctest::\n\n >>> x = functions.capture(5)\n >>> y = functions.capture(5)\n >>> z = functions.capture(1)\n\n >>> eval_expr(x == y)\n True\n\n >>> eval_expr(x == z)\n False\n\n Notes\n -----\n This method will fail with an error if the two expressions are not\n of comparable types.\n\n Parameters\n ----------\n other : :class:`.Expression`\n Expression for equality comparison.\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the two expressions are equal.\n \"\"\"\n return self._bin_op(\"==\", other, TBoolean())\n\n def __ne__(self, other):\n \"\"\"Returns ``True`` if the two expressions are not equal.\n\n Examples\n --------\n\n .. doctest::\n\n >>> x = functions.capture(5)\n >>> y = functions.capture(5)\n >>> z = functions.capture(1)\n\n >>> eval_expr(x != y)\n False\n\n >>> eval_expr(x != z)\n True\n\n Notes\n -----\n This method will fail with an error if the two expressions are not\n of comparable types.\n\n Parameters\n ----------\n other : :class:`.Expression`\n Expression for inequality comparison.\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the two expressions are not equal.\n \"\"\"\n return self._bin_op(\"!=\", other, TBoolean())\n\n\nclass CollectionExpression(Expression):\n \"\"\"Expression of type :py:class:`hail.expr.types.TArray` or :py:class:`hail.expr.types.TSet`\n\n >>> a = functions.capture([1, 2, 3, 4, 5])\n\n >>> s = functions.capture({'Alice', 'Bob', 'Charlie'})\n \"\"\"\n\n def exists(self, f):\n \"\"\"Returns ``True`` if `f` returns ``True`` for any element.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a.exists(lambda x: x % 2 == 0))\n True\n\n >>> eval_expr(s.exists(lambda x: x[0] == 'D'))\n False\n\n Notes\n -----\n This method always returns ``False`` for empty collections.\n\n Parameters\n ----------\n f : callable\n Function to evaluate for each element of the collection. Must return a\n :py:class:`BooleanExpression`.\n\n Returns\n -------\n :py:class:`BooleanExpression`.\n ``True`` if `f` returns ``True`` for any element, ``False`` otherwise.\n \"\"\"\n return self._bin_lambda_method(\"exists\", f, self._type.element_type, lambda t: TBoolean())\n\n def filter(self, f):\n \"\"\"Returns a new collection containing elements where `f` returns ``True``.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a.filter(lambda x: x % 2 == 0))\n [2, 4]\n\n >>> eval_expr(s.filter(lambda x: ~(x[-1] == 'e')))\n {'Bob'}\n\n Notes\n -----\n Returns a same-type expression; evaluated on a :py:class:`SetExpression`, returns a\n :py:class:`SetExpression`. Evaluated on an :py:class:`ArrayExpression`,\n returns an :py:class:`ArrayExpression`.\n\n Parameters\n ----------\n f : callable\n Function to evaluate for each element of the collection. Must return a\n :py:class:`BooleanExpression`.\n\n Returns\n -------\n :py:class:`CollectionExpression`\n Expression of the same type as the callee.\n \"\"\"\n return self._bin_lambda_method(\"filter\", f, self._type.element_type, lambda t: self._type)\n\n def find(self, f):\n \"\"\"Returns the first element where `f` returns ``True``.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a.find(lambda x: x ** 2 > 20))\n 5\n\n >>> eval_expr(s.find(lambda x: x[0] == 'D'))\n None\n\n Notes\n -----\n If `f` returns ``False`` for every element, then the result is missing.\n\n Parameters\n ----------\n f : callable\n Function to evaluate for each element of the collection. Must return a\n :py:class:`BooleanExpression`.\n\n Returns\n -------\n :py:class:`.Expression`\n Expression whose type is the element type of the collection.\n \"\"\"\n return self._bin_lambda_method(\"find\", f, self._type.element_type, lambda t: self._type.element_type)\n\n def flatmap(self, f):\n \"\"\"Map each element of the collection to a new collection, and flatten the results.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a.flatmap(lambda x: functions.range(0, x)))\n [0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4]\n\n >>> eval_expr(s.flatmap(lambda x: functions.range(0, x.length()).map(lambda i: x[i]).to_set()))\n {'A', 'B', 'C', 'a', 'b', 'c', 'e', 'h', 'i', 'l', 'o', 'r'}\n\n Parameters\n ----------\n f : callable\n Function from the element type of the collection to the type of the\n collection. For instance, `flatmap` on a ``Set[String]`` should take\n a ``String`` and return a ``Set``.\n\n Returns\n -------\n :py:class:`CollectionExpression`\n \"\"\"\n return self._bin_lambda_method(\"flatMap\", f, self._type.element_type, lambda t: t)\n\n def forall(self, f):\n \"\"\"Returns ``True`` if `f` returns ``True`` for every element.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a.forall(lambda x: x < 10))\n True\n\n Notes\n -----\n This method returns ``True`` if the collection is empty.\n\n Parameters\n ----------\n f : callable\n Function to evaluate for each element of the collection. Must return a\n :py:class:`BooleanExpression`.\n\n Returns\n -------\n :py:class:`BooleanExpression`.\n ``True`` if `f` returns ``True`` for every element, ``False`` otherwise.\n \"\"\"\n return self._bin_lambda_method(\"forall\", f, self._type.element_type, lambda t: TBoolean())\n\n def group_by(self, f):\n \"\"\"Group elements into a dict according to a lambda function.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a.group_by(lambda x: x % 2 == 0))\n {False: [1, 3, 5], True: [2, 4]}\n\n >>> eval_expr(s.group_by(lambda x: x.length()))\n {3: {'Bob'}, 5: {'Alice'}, 7: {'Charlie'}}\n\n Parameters\n ----------\n f : callable\n Function to evaluate for each element of the collection to produce a key for the\n resulting dictionary.\n\n Returns\n -------\n :py:class:`DictExpression`.\n Dictionary keyed by results of `f`.\n \"\"\"\n return self._bin_lambda_method(\"groupBy\", f, self._type.element_type, lambda t: TDict(t, self._type))\n\n def map(self, f):\n \"\"\"Transform each element of a collection.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a.map(lambda x: x ** 3))\n [1.0, 8.0, 27.0, 64.0, 125.0]\n\n >>> eval_expr(s.map(lambda x: x.length()))\n {3, 5, 7}\n\n Parameters\n ----------\n f : callable\n Function to transform each element of the collection.\n\n Returns\n -------\n :py:class:`CollectionExpression`.\n Collection where each element has been transformed according to `f`.\n \"\"\"\n return self._bin_lambda_method(\"map\", f, self._type.element_type, lambda t: self._type.__class__(t))\n\n def length(self):\n \"\"\"Returns the size of a collection.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a.length())\n 5\n\n >>> eval_expr(s.length())\n 3\n\n Returns\n -------\n :py:class:`hail.expr.Int32Expression`\n The number of elements in the collection.\n \"\"\"\n return self._method(\"size\", TInt32())\n\n def size(self):\n \"\"\"Returns the size of a collection.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a.size())\n 5\n\n >>> eval_expr(s.size())\n 3\n\n Returns\n -------\n :py:class:`hail.expr.Int32Expression`\n The number of elements in the collection.\n \"\"\"\n return self._method(\"size\", TInt32())\n\n\nclass CollectionNumericExpression(CollectionExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TArray` or :class:`hail.expr.types.TSet` with numeric element type.\n\n >>> a = functions.capture([1, 2, 3, 4, 5])\n \"\"\"\n\n def max(self):\n \"\"\"Returns the maximum element.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a.max())\n 5\n\n Returns\n -------\n :py:class:`NumericExpression`\n The maximum value in the collection.\n \"\"\"\n return self._method(\"max\", self._type.element_type)\n\n def min(self):\n \"\"\"Returns the minimum element.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a.min())\n 1\n\n Returns\n -------\n :py:class:`NumericExpression`\n The miniumum value in the collection.\n \"\"\"\n return self._method(\"min\", self._type.element_type)\n\n def mean(self):\n \"\"\"Returns the mean of all values in the collection.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a.mean())\n 3.0\n\n Note\n ----\n Missing elements are ignored.\n\n Returns\n -------\n :py:class:`Float64Expression`\n The mean value of the collection.\n \"\"\"\n return self._method(\"mean\", TFloat64())\n\n def median(self):\n \"\"\"Returns the median element.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a.median())\n 3\n\n Note\n ----\n Missing elements are ignored.\n\n Returns\n -------\n :py:class:`NumericExpression`\n The median value in the collection.\n \"\"\"\n return self._method(\"median\", self._type.element_type)\n\n def product(self):\n \"\"\"Returns the product of all elements in the collection.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a.product())\n 120\n\n Note\n ----\n Missing elements are ignored.\n\n Returns\n -------\n :py:class:`NumericExpression`\n The product of the collection.\n \"\"\"\n return self._method(\"product\",\n TInt64() if isinstance(self._type.element_type, TInt32) or\n isinstance(self._type.element_type, TInt64) else TFloat64())\n\n def sum(self):\n \"\"\"Returns the sum of all elements in the collection.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a.sum())\n 15\n\n Note\n ----\n Missing elements are ignored.\n\n Returns\n -------\n :py:class:`NumericExpression`\n The sum of the collection.\n \"\"\"\n return self._method(\"sum\", self._type.element_type)\n\n\nclass ArrayExpression(CollectionExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TArray`.\n\n >>> a = functions.capture(['Alice', 'Bob', 'Charlie'])\n \"\"\"\n def __getitem__(self, item):\n \"\"\"Index into or slice the array.\n\n Examples\n --------\n\n Index with a single integer:\n\n .. doctest::\n\n >>> eval_expr(a[1])\n 'Bob'\n\n >>> eval_expr(a[-1])\n 'Charlie'\n\n Slicing is also supported:\n\n .. doctest::\n\n >>> eval_expr(a[1:])\n ['Bob', 'Charlie']\n\n Parameters\n ----------\n item : slice or :class:`Int32Expression`\n Index or slice.\n\n Returns\n -------\n :class:`.Expression`\n Element or array slice.\n \"\"\"\n if isinstance(item, slice):\n return self._slice(self._type, item.start, item.stop, item.step)\n elif isinstance(item, int) or isinstance(item, Int32Expression):\n return self._index(self._type.element_type, item)\n else:\n raise NotImplementedError\n\n @typecheck_method(item=expr_any)\n def contains(self, item):\n \"\"\"Returns a boolean indicating whether `item` is found in the array.\n\n Examples\n --------\n\n .. doctest::\n\n >>> eval_expr(a.contains('Charlie'))\n True\n\n >>> eval_expr(a.contains('Helen'))\n False\n\n Parameters\n ----------\n item : :class:`.Expression`\n Item for inclusion test.\n\n Warning\n -------\n This method takes time proportional to the length of the array. If a\n pipeline uses this method on the same array several times, it may be\n more efficient to convert the array to a set first\n (:meth:`ArrayExpression.to_set`).\n\n Returns\n -------\n :py:class:`BooleanExpression`\n ``True`` if the element is found in the array, ``False`` otherwise.\n \"\"\"\n return self.exists(lambda x: x == item)\n\n @typecheck_method(x=expr_any)\n def append(self, x):\n \"\"\"Append an element to the array and return the result.\n\n Examples\n --------\n\n .. doctest::\n\n >>> eval_expr(a.append('Dan'))\n ['Alice', 'Bob', 'Charlie', 'Dan']\n\n Parameters\n ----------\n x : :class:`.Expression`\n Element to append, same type as the array element type.\n\n Returns\n -------\n :py:class:`ArrayExpression`\n \"\"\"\n return self._method(\"append\", self._type, x)\n\n @typecheck_method(a=expr_list)\n def extend(self, a):\n \"\"\"Concatenate two arrays and return the result.\n\n Examples\n --------\n\n .. doctest::\n\n >>> eval_expr(a.extend(['Dan', 'Edith']))\n ['Alice', 'Bob', 'Charlie', 'Dan', 'Edith']\n\n Parameters\n ----------\n a : :class:`ArrayExpression`\n Array to concatenate, same type as the callee.\n\n Returns\n -------\n :py:class:`ArrayExpression`\n \"\"\"\n return self._method(\"extend\", self._type, a)\n\n def sort_by(self, f, ascending=True):\n \"\"\"Sort the array according to a function.\n\n Examples\n --------\n\n .. doctest::\n\n >>> eval_expr(a.sort_by(lambda x: x, ascending=False))\n ['Charlie', 'Bob', 'Alice']\n\n Parameters\n ----------\n f : callable\n Function to evaluate per element to obtain the sort key.\n ascending : bool or :py:class:`BooleanExpression`\n Sort in ascending order.\n\n Returns\n -------\n :py:class:`ArrayExpression`\n \"\"\"\n return self._bin_lambda_method(\"sortBy\", f, self._type.element_type, lambda t: self._type, ascending)\n\n def to_set(self):\n \"\"\"Convert the array to a set.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a.to_set())\n {'Alice', 'Bob', 'Charlie'}\n\n Returns\n -------\n :py:class:`SetExpression`\n Set of all unique elements.\n \"\"\"\n return self._method(\"toSet\", TSet(self._type.element_type))\n\n\nclass ArrayNumericExpression(ArrayExpression, CollectionNumericExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TArray` with a numeric type.\n\n Numeric arrays support arithmetic both with scalar values and other arrays.\n Arithmetic between two numeric arrays requires that the length of each array\n is identical, and will apply the operation positionally (``a1 * a2`` will\n multiply the first element of ``a1`` by the first element of ``a2``, the\n second element of ``a1`` by the second element of ``a2``, and so on).\n Arithmetic with a scalar will apply the operation to each element of the\n array.\n\n >>> a1 = functions.capture([0, 1, 2, 3, 4, 5])\n\n >>> a2 = functions.capture([1, -1, 1, -1, 1, -1])\n\n \"\"\"\n\n def _bin_op_ret_typ(self, other):\n if isinstance(self, ArrayNumericExpression) and isinstance(other, float):\n return TArray(TFloat64())\n\n elif isinstance(self, ArrayNumericExpression) and isinstance(other, Float64Expression):\n return TArray(TFloat64())\n elif isinstance(self, Float64Expression) and isinstance(other, ArrayNumericExpression):\n return TArray(TFloat64())\n elif isinstance(self, ArrayFloat64Expression) and isinstance(other, ArrayNumericExpression):\n return TArray(TFloat64())\n elif isinstance(self, ArrayNumericExpression) and isinstance(other, ArrayFloat64Expression):\n return TArray(TFloat64())\n\n elif isinstance(self, Float32Expression) and isinstance(other, ArrayNumericExpression):\n return TArray(TFloat32())\n elif isinstance(self, ArrayNumericExpression) and isinstance(other, Float32Expression):\n return TArray(TFloat32())\n elif isinstance(self, ArrayFloat32Expression) and isinstance(other, ArrayNumericExpression):\n return TArray(TFloat32())\n elif isinstance(self, ArrayNumericExpression) and isinstance(other, ArrayFloat32Expression):\n return TArray(TFloat32())\n\n elif isinstance(self, ArrayInt64Expression) and isinstance(other, int):\n return TArray(TInt64())\n elif isinstance(self, Int64Expression) and isinstance(other, ArrayNumericExpression):\n return TArray(TInt64())\n elif isinstance(self, ArrayNumericExpression) and isinstance(other, Int64Expression):\n return TArray(TInt64())\n elif isinstance(self, ArrayInt64Expression) and isinstance(other, ArrayNumericExpression):\n return TArray(TInt64())\n elif isinstance(self, ArrayNumericExpression) and isinstance(other, ArrayInt64Expression):\n return TArray(TInt64())\n\n elif isinstance(self, ArrayInt32Expression) and isinstance(other, int):\n return TArray(TInt32())\n elif isinstance(self, Int32Expression) and isinstance(other, ArrayNumericExpression):\n return TArray(TInt32())\n elif isinstance(self, ArrayNumericExpression) and isinstance(other, Int32Expression):\n return TArray(TInt32())\n elif isinstance(self, ArrayInt32Expression) and isinstance(other, ArrayNumericExpression):\n return TArray(TInt32())\n elif isinstance(self, ArrayNumericExpression) and isinstance(other, ArrayInt32Expression):\n return TArray(TInt32())\n\n else:\n raise NotImplementedError('''Error in return type for numeric conversion.\n self = {}\n other = {}'''.format(type(self), type(other)))\n\n def _bin_op_numeric(self, name, other):\n other = to_expr(other)\n ret_typ = self._bin_op_ret_typ(other)\n return self._bin_op(name, other, ret_typ)\n\n def _bin_op_numeric_reverse(self, name, other):\n other = to_expr(other)\n ret_typ = self._bin_op_ret_typ(other)\n return self._bin_op_reverse(name, other, ret_typ)\n\n def __add__(self, other):\n \"\"\"Positionally add an array or a scalar.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a1 + 5)\n [5, 6, 7, 8, 9, 10]\n\n >>> eval_expr(a1 + a2)\n [1, 0, 3, 2, 5, 4]\n\n Parameters\n ----------\n other : :class:`NumericExpression` or :class:`ArrayNumericExpression`\n Value or array to add.\n\n Returns\n -------\n :class:`ArrayNumericExpression`\n Array of positional sums.\n \"\"\"\n return self._bin_op_numeric(\"+\", other)\n\n def __radd__(self, other):\n return self._bin_op_numeric_reverse(\"+\", other)\n\n def __sub__(self, other):\n \"\"\"Positionally subtract an array or a scalar.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a2 - 1)\n [0, -2, 0, -2, 0, -2]\n\n >>> eval_expr(a1 - a2)\n [-1, 2, 1, 4, 3, 6]\n\n Parameters\n ----------\n other : :class:`NumericExpression` or :class:`ArrayNumericExpression`\n Value or array to subtract.\n\n Returns\n -------\n :class:`ArrayNumericExpression`\n Array of positional differences.\n \"\"\"\n return self._bin_op_numeric(\"-\", other)\n\n def __rsub__(self, other):\n return self._bin_op_numeric_reverse(\"-\", other)\n\n def __mul__(self, other):\n \"\"\"Positionally multiply by an array or a scalar.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a2 * 5)\n [5, -5, 5, -5, 5, -5]\n\n >>> eval_expr(a1 * a2)\n [0, -1, 2, -3, 4, -5]\n\n Parameters\n ----------\n other : :class:`NumericExpression` or :class:`ArrayNumericExpression`\n Value or array to multiply by.\n\n Returns\n -------\n :class:`ArrayNumericExpression`\n Array of positional products.\n \"\"\"\n return self._bin_op_numeric(\"*\", other)\n\n def __rmul__(self, other):\n return self._bin_op_numeric_reverse(\"*\", other)\n\n def __div__(self, other):\n \"\"\"Positionally divide by an array or a scalar.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a1 / 10)\n [0.0, 0.1, 0.2, 0.3, 0.4, 0.5]\n\n >>> eval_expr(a2 / a1)\n [inf, -1.0, 0.5, -0.3333333333333333, 0.25, -0.2]\n\n Parameters\n ----------\n other : :class:`NumericExpression` or :class:`ArrayNumericExpression`\n Value or array to divide by.\n\n Returns\n -------\n :class:`ArrayNumericExpression`\n Array of positional quotients.\n \"\"\"\n return self._bin_op(\"/\", other, TArray(TFloat64()))\n\n def __rdiv__(self, other):\n return self._bin_op_reverse(\"/\", other, TArray(TFloat64()))\n\n def __pow__(self, other):\n \"\"\"Positionally raise to the power of an array or a scalar.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a1 ** 2)\n [0.0, 1.0, 4.0, 9.0, 16.0, 25.0]\n\n >>> eval_expr(a1 ** a2)\n [0.0, 1.0, 2.0, 0.3333333333333333, 4.0, 0.2]\n\n Parameters\n ----------\n other : :class:`NumericExpression` or :class:`ArrayNumericExpression`\n Value or array to exponentiate by.\n\n Returns\n -------\n :class:`ArrayNumericExpression`\n Array of positional exponentiations.\n \"\"\"\n return self._bin_op('**', other, TArray(TFloat64()))\n\n def __rpow__(self, other):\n return self._bin_op_reverse('**', other, TArray(TFloat64()))\n\n def sort(self, ascending=True):\n \"\"\"Returns a sorted array.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a1.sort())\n [-1, -1, -1, 1, 1, 1]\n\n Parameters\n ----------\n ascending : bool or :py:class:`BooleanExpression`\n Sort in ascending order.\n\n Returns\n -------\n :py:class:`ArrayNumericExpression`\n Sorted array.\n \"\"\"\n return self._method(\"sort\", self._type, ascending)\n\n\nclass ArrayFloat64Expression(ArrayNumericExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TArray` with element type :class:`hail.expr.types.TFloat64`.\"\"\"\n pass\n\n\nclass ArrayFloat32Expression(ArrayNumericExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TArray` with element type :class:`hail.expr.types.TFloat32`.\"\"\"\n pass\n\n\nclass ArrayInt32Expression(ArrayNumericExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TArray` with element type :class:`hail.expr.types.TInt32`\"\"\"\n pass\n\n\nclass ArrayInt64Expression(ArrayNumericExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TArray` with element type :class:`hail.expr.types.TInt64`.\"\"\"\n pass\n\n\nclass ArrayStringExpression(ArrayExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TArray` with element type :class:`hail.expr.types.TString`.\n\n >>> a = functions.capture(['Alice', 'Bob', 'Charles'])\n \"\"\"\n def mkstring(self, delimiter):\n \"\"\"Joins the elements of the array into a single string delimited by `delimiter`.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a.mkstring(','))\n 'Alice,Bob,Charles'\n\n Parameters\n ----------\n delimiter : str or :py:class:`StringExpression`\n Field delimiter.\n\n Returns\n -------\n :py:class:`StringExpression`\n Joined string expression.\n \"\"\"\n return self._method(\"mkString\", TString(), delimiter)\n\n def sort(self, ascending=True):\n \"\"\"Returns a sorted array.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a.sort(ascending=False))\n ['Charles', 'Bob', 'Alice']\n\n Parameters\n ----------\n ascending : bool or :py:class:`BooleanExpression`\n Sort in ascending order.\n\n Returns\n -------\n :py:class:`ArrayStringExpression`\n Sorted array.\n \"\"\"\n return self._method(\"sort\", self._type, ascending)\n\n\nclass ArrayStructExpression(ArrayExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TArray` with element type :class:`hail.expr.types.TStruct`.\"\"\"\n pass\n\n\nclass ArrayArrayExpression(ArrayExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TArray` with element type :class:`hail.expr.types.TArray`.\n\n >>> a = functions.capture([[1, 2], [3, 4]])\n \"\"\"\n def flatten(self):\n \"\"\"Flatten the nested array by concatenating subarrays.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(a.flatten())\n [1, 2, 3, 4]\n\n Returns\n -------\n :py:class:`ArrayExpression`\n Array generated by concatenating all subarrays.\n \"\"\"\n return self._method(\"flatten\", self._type.element_type)\n\n\nclass SetExpression(CollectionExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TSet`.\n\n >>> s1 = functions.capture({1, 2, 3})\n >>> s2 = functions.capture({1, 3, 5})\n \"\"\"\n @typecheck_method(x=expr_any)\n def add(self, x):\n \"\"\"Returns a new set including `x`.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(s1.add(10))\n {1, 2, 3, 10}\n\n Parameters\n ----------\n x : :class:`.Expression`\n Value to add.\n\n Returns\n -------\n :class:`SetExpression`\n Set with `x` added.\n \"\"\"\n return self._method(\"add\", self._type, x)\n\n @typecheck_method(x=expr_any)\n def remove(self, x):\n \"\"\"Returns a new set excluding `x`.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(s1.remove(1))\n {2, 3}\n\n Parameters\n ----------\n x : :class:`.Expression`\n Value to remove.\n\n Returns\n -------\n :py:class:`SetExpression`\n Set with `x` removed.\n \"\"\"\n return self._method(\"remove\", self._type, x)\n\n @typecheck_method(x=expr_any)\n def contains(self, x):\n \"\"\"Returns ``True`` if `x` is in the set.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(s1.contains(1))\n True\n\n >>> eval_expr(s1.contains(10))\n False\n\n Parameters\n ----------\n x : :class:`.Expression`\n Value for inclusion test..\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if `x` is in the set.\n \"\"\"\n return self._method(\"contains\", TBoolean(), x)\n\n @typecheck_method(s=expr_set)\n def difference(self, s):\n \"\"\"Return the set of elements in the set that are not present in set `s`.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(s1.difference(s2))\n {2}\n\n >>> eval_expr(s2.difference(s1))\n {5}\n\n Parameters\n ----------\n s : :class:`SetExpression`\n Set expression of the same type.\n\n Returns\n -------\n :class:`SetExpression`\n Set of elements not in `s`.\n \"\"\"\n return self._method(\"difference\", self._type, s)\n\n @typecheck_method(s=expr_set)\n def intersection(self, s):\n \"\"\"Return the intersection of the set and set `s`.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(s1.intersection(s2))\n {1, 3}\n\n Parameters\n ----------\n s : :class:`SetExpression`\n Set expression of the same type.\n\n Returns\n -------\n :class:`SetExpression`\n Set of elements present in `s`.\n \"\"\"\n return self._method(\"intersection\", self._type, s)\n\n @typecheck_method(s=expr_set)\n def is_subset(self, s):\n \"\"\"Returns ``True`` if every element is contained in set `s`.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(s1.is_subset(s2))\n False\n\n >>> eval_expr(s1.remove(2).is_subset(s2))\n True\n\n Parameters\n ----------\n s : :class:`SetExpression`\n Set expression of the same type.\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if every element is contained in set `s`.\n \"\"\"\n return self._method(\"isSubset\", TBoolean(), s)\n\n @typecheck_method(s=expr_set)\n def union(self, s):\n \"\"\"Return the union of the set and set `s`.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(s1.union(s2))\n {1, 2, 3, 5}\n\n Parameters\n ----------\n s : :class:`SetExpression`\n Set expression of the same type.\n\n Returns\n -------\n :class:`SetExpression`\n Set of elements present in either set.\n \"\"\"\n return self._method(\"union\", self._type, s)\n\n def to_array(self):\n \"\"\"Convert the set to an array.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(s1.to_array())\n [1, 2, 3]\n\n Notes\n -----\n The order of elements in the array is not guaranteed.\n\n Returns\n -------\n :class:`ArrayExpression`\n Array of all elements in the set.\n \"\"\"\n return self._method(\"toArray\", TArray(self._type.element_type))\n\n\nclass SetFloat64Expression(SetExpression, CollectionNumericExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TSet` with element type :class:`hail.expr.types.TFloat64`.\"\"\"\n pass\n\n\nclass SetFloat32Expression(SetExpression, CollectionNumericExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TSet` with element type :class:`hail.expr.types.TFloat32`.\"\"\"\n pass\n\n\nclass SetInt32Expression(SetExpression, CollectionNumericExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TSet` with element type :class:`hail.expr.types.TInt32`.\"\"\"\n pass\n\n\nclass SetInt64Expression(SetExpression, CollectionNumericExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TSet` with element type :class:`hail.expr.types.TInt64`.\"\"\"\n pass\n\n\nclass SetStringExpression(SetExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TSet` with element type :class:`hail.expr.types.TString`.\n\n >>> s = functions.capture({'Alice', 'Bob', 'Charles'})\n \"\"\"\n @typecheck_method(delimiter=expr_str)\n def mkstring(self, delimiter):\n \"\"\"Joins the elements of the set into a single string delimited by `delimiter`.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(s.mkstring(','))\n 'Bob,Charles,Alice'\n\n Notes\n -----\n The order of the elements in the string is not guaranteed.\n\n Parameters\n ----------\n delimiter : str or :py:class:`StringExpression`\n Field delimiter.\n\n Returns\n -------\n :py:class:`StringExpression`\n Joined string expression.\n \"\"\"\n return self._method(\"mkString\", TString(), delimiter)\n\n\nclass SetSetExpression(SetExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TSet` with element type :class:`hail.expr.types.TSet`.\n\n >>> s = functions.capture({1, 2, 3}).map(lambda s: {s, 2 * s})\n \"\"\"\n def flatten(self):\n \"\"\"Flatten the nested set by concatenating subsets.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(s.flatten())\n {1, 2, 3, 4, 6}\n\n Returns\n -------\n :py:class:`SetExpression`\n Set generated by concatenating all subsets.\n \"\"\"\n return self._method(\"flatten\", self._type.element_type)\n\n\nclass DictExpression(Expression):\n \"\"\"Expression of type :class:`hail.expr.types.TDict`.\n\n >>> d = functions.capture({'Alice': 43, 'Bob': 33, 'Charles': 44})\n \"\"\"\n def _init(self):\n self._key_typ = self._type.key_type\n self._value_typ = self._type.value_type\n\n @typecheck_method(item=expr_any)\n def __getitem__(self, item):\n \"\"\"Get the value associated with key `item`.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(d['Alice'])\n 43\n\n Notes\n -----\n Raises an error if `item` is not a key of the dictionary. Use\n :meth:`DictExpression.get` to return missing instead of an error.\n\n Parameters\n ----------\n item : :class:`.Expression`\n Key expression.\n\n Returns\n -------\n :class:`.Expression`\n Value associated with key `item`.\n \"\"\"\n return self._index(self._value_typ, item)\n\n @typecheck_method(k=expr_any)\n def contains(self, k):\n \"\"\"Returns whether a given key is present in the dictionary.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(d.contains('Alice'))\n True\n\n >>> eval_expr(d.contains('Anne'))\n False\n\n Parameters\n ----------\n k : :class:`.Expression`\n Key to test for inclusion.\n\n Returns\n -------\n :py:class:`BooleanExpression`\n ``True`` if `k` is a key of the dictionary, ``False`` otherwise.\n \"\"\"\n return self._method(\"contains\", TBoolean(), k)\n\n @typecheck_method(k=expr_any)\n def get(self, k):\n \"\"\"Returns the value associated with key `k`, or missing if that key is not present.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(d.get('Alice'))\n 43\n\n >>> eval_expr(d.get('Anne'))\n None\n\n Parameters\n ----------\n k : :class:`.Expression`\n Key.\n\n Returns\n -------\n :py:class:`.Expression`\n The value associated with `k`, or missing.\n \"\"\"\n return self._method(\"get\", self._value_typ, k)\n\n def key_set(self):\n \"\"\"Returns the set of keys in the dictionary.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(d.key_set())\n {'Alice', 'Bob', 'Charles'}\n\n Returns\n -------\n :py:class:`SetExpression`\n Set of all keys.\n \"\"\"\n return self._method(\"keySet\", TSet(self._key_typ))\n\n def keys(self):\n \"\"\"Returns an array with all keys in the dictionary.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(d.keys())\n ['Bob', 'Charles', 'Alice']\n\n Returns\n -------\n :py:class:`ArrayExpression`\n Array of all keys.\n \"\"\"\n return self._method(\"keys\", TArray(self._key_typ))\n\n def map_values(self, f):\n \"\"\"Transform values of the dictionary according to a function.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(d.map_values(lambda x: x * 10))\n {'Alice': 430, 'Bob': 330, 'Charles': 440}\n\n Parameters\n ----------\n f : callable\n Function to apply to each value.\n\n Returns\n -------\n :py:class:`DictExpression`\n Dictionary with transformed values.\n \"\"\"\n return self._bin_lambda_method(\"mapValues\", f, self._value_typ, lambda t: TDict(self._key_typ, t))\n\n def size(self):\n \"\"\"Returns the size of the dictionary.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(d.size())\n 3\n\n Returns\n -------\n :py:class:`Int32Expression`\n Size of the dictionary.\n \"\"\"\n return self._method(\"size\", TInt32())\n\n def values(self):\n \"\"\"Returns an array with all values in the dictionary.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(d.values())\n [33, 44, 43]\n\n Returns\n -------\n :py:class:`ArrayExpression`\n All values in the dictionary.\n \"\"\"\n return self._method(\"values\", TArray(self._value_typ))\n\n\nclass Aggregable(object):\n \"\"\"Expression that can only be aggregated.\n\n An :class:`Aggregable` is produced by the :meth:`explode` or :meth:`filter`\n methods. These objects can be aggregated using aggregator functions, but\n cannot otherwise be used in expressions.\n \"\"\"\n def __init__(self, ast, type, indices, aggregations, joins, refs):\n self._ast = ast\n self._type = type\n self._indices = indices\n self._aggregations = aggregations\n self._joins = joins\n self._refs = refs\n\n def __nonzero__(self):\n raise NotImplementedError('Truth value of an aggregable collection is undefined')\n\n def __eq__(self, other):\n raise NotImplementedError('Comparison of aggregable collections is undefined')\n\n def __ne__(self, other):\n raise NotImplementedError('Comparison of aggregable collections is undefined')\n\n\nclass StructExpression(Mapping, Expression):\n \"\"\"Expression of type :class:`hail.expr.types.TStruct`.\n\n >>> s = functions.capture(Struct(a=5, b='Foo'))\n\n Struct fields are accessible as attributes and keys. It is therefore\n possible to access field `a` of struct `s` with dot syntax:\n\n .. doctest::\n\n >>> eval_expr(s.a)\n 5\n\n It is possible to have fields whose names violate Python identifier syntax.\n For these, use the :meth:`StructExpression.__getitem__` syntax.\n \"\"\"\n def _init(self):\n self._fields = OrderedDict()\n\n for fd in self._type.fields:\n expr = construct_expr(Select(self._ast, fd.name), fd.typ, self._indices,\n self._aggregations, self._joins, self._refs)\n self._set_field(fd.name, expr)\n\n def _set_field(self, key, value):\n self._fields[key] = value\n if key not in self.__dict__:\n self.__dict__[key] = value\n\n def __len__(self):\n return len(self._fields)\n\n @typecheck_method(item=strlike)\n def __getitem__(self, item):\n \"\"\"Access a field of the struct.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(s['a'])\n 5\n\n Parameters\n ----------\n item : :obj:`str`\n Field name.\n\n Returns\n -------\n :class:`.Expression`\n Struct field.\n \"\"\"\n if not item in self._fields:\n raise KeyError(\"Struct has no field '{}'\\n\"\n \" Fields: [ {} ]\".format(item, ', '.join(\"'{}'\".format(x) for x in self._fields)))\n return self._fields[item]\n\n def __iter__(self):\n return iter(self._fields)\n\n def __hash__(self):\n return object.__hash__(self)\n\n def __eq__(self, other):\n return Expression.__eq__(self, other)\n\n def __ne__(self, other):\n return Expression.__ne__(self, other)\n\n def __nonzero__(self):\n return Expression.__nonzero__(self)\n\nclass AtomicExpression(Expression):\n \"\"\"Abstract base class for numeric and logical types.\"\"\"\n\n def to_float64(self):\n \"\"\"Convert to a 64-bit floating point expression.\n\n Returns\n -------\n :py:class:`Float64Expression`\n \"\"\"\n return self._method(\"toFloat64\", TFloat64())\n\n def to_float32(self):\n \"\"\"Convert to a 32-bit floating point expression.\n\n Returns\n -------\n :py:class:`Float32Expression`\n \"\"\"\n return self._method(\"toFloat32\", TFloat32())\n\n def to_int64(self):\n \"\"\"Convert to a 64-bit integer expression.\n\n Returns\n -------\n :py:class:`Int64Expression`\n \"\"\"\n return self._method(\"toInt64\", TInt64())\n\n def to_int32(self):\n \"\"\"Convert to a 32-bit integer expression.\n\n Returns\n -------\n :py:class:`Int32Expression`\n \"\"\"\n return self._method(\"toInt32\", TInt32())\n\n\nclass BooleanExpression(AtomicExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TBoolean`.\n\n >>> t = functions.capture(True)\n >>> f = functions.capture(False)\n >>> na = functions.null(TBoolean())\n\n .. doctest::\n\n >>> eval_expr(t)\n True\n\n >>> eval_expr(f)\n False\n\n >>> eval_expr(na)\n None\n\n \"\"\"\n\n def _bin_op_logical(self, name, other):\n other = to_expr(other)\n return self._bin_op(name, other, TBoolean())\n\n @typecheck_method(other=expr_bool)\n def __and__(self, other):\n \"\"\"Return ``True`` if the left and right arguments are ``True``.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(t & f)\n False\n\n >>> eval_expr(t & na)\n None\n\n >>> eval_expr(f & na)\n False\n\n The ``&`` and ``|`` operators have higher priority than comparison\n operators like ``==``, ``<``, or ``>``. Parentheses are often\n necessary:\n\n .. doctest::\n\n >>> x = functions.capture(5)\n\n >>> eval_expr((x < 10) & (x > 2))\n True\n\n Parameters\n ----------\n other : :class:`BooleanExpression`\n Right-side operation.\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if both left and right are ``True``.\n \"\"\"\n return self._bin_op_logical(\"&&\", other)\n\n def __or__(self, other):\n \"\"\"Return ``True`` if at least one of the left and right arguments is ``True``.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(t | f)\n True\n\n >>> eval_expr(t | na)\n True\n\n >>> eval_expr(f | na)\n None\n\n The ``&`` and ``|`` operators have higher priority than comparison\n operators like ``==``, ``<``, or ``>``. Parentheses are often\n necessary:\n\n .. doctest::\n\n >>> x = functions.capture(5)\n\n >>> eval_expr((x < 10) | (x > 20))\n True\n\n Parameters\n ----------\n other : :class:`BooleanExpression`\n Right-side operation.\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if either left or right is ``True``.\n \"\"\"\n return self._bin_op_logical(\"||\", other)\n\n def __invert__(self):\n \"\"\"Return the boolean inverse.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(~t)\n False\n\n >>> eval_expr(~f)\n True\n\n >>> eval_expr(~na)\n None\n\n Returns\n -------\n :class:`BooleanExpression`\n Boolean inverse.\n \"\"\"\n return self._unary_op(\"!\")\n\n\nclass NumericExpression(AtomicExpression):\n \"\"\"Expression of numeric type.\n\n >>> x = functions.capture(3)\n\n >>> y = functions.capture(4.5)\n \"\"\"\n def _bin_op_ret_typ(self, other):\n if isinstance(self, NumericExpression) and isinstance(other, float):\n return TFloat64()\n elif isinstance(self, Float64Expression) and isinstance(other, NumericExpression):\n return TFloat64()\n elif isinstance(self, NumericExpression) and isinstance(other, Float64Expression):\n return TFloat64()\n elif isinstance(self, Float32Expression) and isinstance(other, NumericExpression):\n return TFloat32()\n elif isinstance(self, NumericExpression) and isinstance(other, Float32Expression):\n return TFloat32()\n elif isinstance(self, Int64Expression) and (\n isinstance(other, NumericExpression) or isinstance(other, int) or isinstance(other, long)):\n return TInt64()\n elif isinstance(self, NumericExpression) and isinstance(other, Int64Expression):\n return TInt64()\n elif isinstance(self, Int32Expression) and (isinstance(other, NumericExpression) or isinstance(other, int)):\n return TInt32()\n elif isinstance(self, NumericExpression) or isinstance(other, Int32Expression):\n return TInt32()\n else:\n raise NotImplementedError(\"Error in return type for numeric conversion.\",\n \"\\nself =\", type(self),\n \"\\nother =\", type(other))\n\n def _bin_op_numeric(self, name, other):\n ret_typ = self._bin_op_ret_typ(other)\n return self._bin_op(name, other, ret_typ)\n\n def _bin_op_numeric_reverse(self, name, other):\n ret_typ = self._bin_op_ret_typ(other)\n return self._bin_op_reverse(name, other, ret_typ)\n\n @typecheck_method(other=expr_numeric)\n def __lt__(self, other):\n \"\"\"Less-than comparison.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(x < 5)\n True\n\n Parameters\n ----------\n other : :class:`NumericExpression`\n Right side for comparison.\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the left side is smaller than the right side.\n \"\"\"\n return self._bin_op(\"<\", other, TBoolean())\n\n @typecheck_method(other=expr_numeric)\n def __le__(self, other):\n \"\"\"Less-than-or-equals comparison.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(x <= 3)\n True\n\n Parameters\n ----------\n other : :class:`NumericExpression`\n Right side for comparison.\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the left side is smaller than or equal to the right side.\n \"\"\"\n return self._bin_op(\"<=\", other, TBoolean())\n\n @typecheck_method(other=expr_numeric)\n def __gt__(self, other):\n \"\"\"Greater-than comparison.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(y > 4)\n True\n\n Parameters\n ----------\n other : :class:`NumericExpression`\n Right side for comparison.\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the left side is greater than the right side.\n \"\"\"\n return self._bin_op(\">\", other, TBoolean())\n\n @typecheck_method(other=expr_numeric)\n def __ge__(self, other):\n \"\"\"Greater-than-or-equals comparison.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(y >= 4)\n True\n\n Parameters\n ----------\n other : :class:`NumericExpression`\n Right side for comparison.\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the left side is greater than or equal to the right side.\n \"\"\"\n return self._bin_op(\">=\", other, TBoolean())\n\n\n def __pos__(self):\n return self\n\n def __neg__(self):\n \"\"\"Negate the number (multiply by -1).\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(-x)\n -3\n\n Returns\n -------\n :class:`NumericExpression`\n Negated number.\n \"\"\"\n return self._unary_op(\"-\")\n\n def __add__(self, other):\n \"\"\"Add two numbers.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(x + 2)\n 5\n\n >>> eval_expr(x + y)\n 7.5\n\n Parameters\n ----------\n other : :class:`NumericExpression`\n Number to add.\n\n Returns\n -------\n :class:`NumericExpression`\n Sum of the two numbers.\n \"\"\"\n return self._bin_op_numeric(\"+\", other)\n\n def __radd__(self, other):\n return self._bin_op_numeric_reverse(\"+\", other)\n\n def __sub__(self, other):\n \"\"\"Subtract the right number from the left.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(x - 2)\n 1\n\n >>> eval_expr(x - y)\n -1.5\n\n Parameters\n ----------\n other : :class:`NumericExpression`\n Number to subtract.\n\n Returns\n -------\n :class:`NumericExpression`\n Difference of the two numbers.\n \"\"\"\n return self._bin_op_numeric(\"-\", other)\n\n def __rsub__(self, other):\n return self._bin_op_numeric_reverse(\"-\", other)\n\n def __mul__(self, other):\n \"\"\"Multiply two numbers.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(x * 2)\n 6\n\n >>> eval_expr(x * y)\n 9.0\n\n Parameters\n ----------\n other : :class:`NumericExpression`\n Number to multiply.\n\n Returns\n -------\n :class:`NumericExpression`\n Product of the two numbers.\n \"\"\"\n return self._bin_op_numeric(\"*\", other)\n\n def __rmul__(self, other):\n return self._bin_op_numeric_reverse(\"*\", other)\n\n def __div__(self, other):\n \"\"\"Divide two numbers.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(x / 2)\n 1.5\n\n >>> eval_expr(y / 0.1)\n 45.0\n\n Parameters\n ----------\n other : :class:`NumericExpression`\n Dividend.\n\n Returns\n -------\n :class:`NumericExpression`\n The left number divided by the left.\n \"\"\"\n return self._bin_op_numeric(\"/\", other)\n\n def __rdiv__(self, other):\n return self._bin_op_numeric_reverse(\"/\", other)\n\n def __mod__(self, other):\n \"\"\"Compute the left modulo the right number.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(32 % x)\n 2\n\n >>> eval_expr(7 % y)\n 2.5\n\n Parameters\n ----------\n other : :class:`NumericExpression`\n Dividend.\n\n Returns\n -------\n :class:`NumericExpression`\n Remainder after dividing the left by the right.\n \"\"\"\n return self._bin_op_numeric('%', other)\n\n def __rmod__(self, other):\n return self._bin_op_numeric_reverse('%', other)\n\n def __pow__(self, power, modulo=None):\n \"\"\"Raise the left to the right power.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(x ** 2)\n 9.0\n\n >>> eval_expr(x ** -2)\n 0.1111111111111111\n\n >>> eval_expr(y ** 1.5)\n 9.545941546018392\n\n Parameters\n ----------\n power : :class:`NumericExpression`\n modulo\n Unsupported argument.\n\n Returns\n -------\n :class:`Float64Expression`\n Result of raising left to the right power.\n \"\"\"\n return self._bin_op('**', power, TFloat64())\n\n def __rpow__(self, other):\n return self._bin_op_reverse('**', other, TFloat64())\n\n def signum(self):\n \"\"\"Returns the sign of the callee, ``1`` or ``-1``.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(y.signum())\n 1\n\n Returns\n -------\n :py:class:`Int32Expression`\n ``1`` or ``-1``.\n \"\"\"\n return self._method(\"signum\", TInt32())\n\n def abs(self):\n \"\"\"Returns the absolute value of the callee.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(y.abs())\n 4.5\n\n Returns\n -------\n :py:class:`.NumericExpression`\n Absolute value of the number.\n \"\"\"\n return self._method(\"abs\", self._type)\n\n @typecheck_method(other=expr_numeric)\n def max(self, other):\n \"\"\"Returns the maximum value between the callee and `other`.\n\n Parameters\n ----------\n other : :py:class:`NumericExpression`\n Value to compare against.\n\n Returns\n -------\n :py:class:`.NumericExpression`\n Maximum value.\n \"\"\"\n assert (isinstance(other, self.__class__))\n return self._method(\"max\", self._type, other)\n\n @typecheck_method(other=expr_numeric)\n def min(self, other):\n \"\"\"Returns the minumum value between the callee and `other`.\n\n Parameters\n ----------\n other : :py:class:`NumericExpression`\n Value to compare against.\n\n Returns\n -------\n :py:class:`.NumericExpression`\n Minimum value.\n \"\"\"\n assert (isinstance(other, self.__class__))\n return self._method(\"min\", self._type, other)\n\n\nclass Float64Expression(NumericExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TFloat64`.\"\"\"\n pass\n\n\nclass Float32Expression(NumericExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TFloat32`.\"\"\"\n pass\n\n\nclass Int32Expression(NumericExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TInt32`.\"\"\"\n pass\n\n\nclass Int64Expression(NumericExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TInt64`.\"\"\"\n pass\n\n\nclass StringExpression(AtomicExpression):\n \"\"\"Expression of type :class:`hail.expr.types.TString`.\n\n >>> s = functions.capture('The quick brown fox')\n \"\"\"\n @typecheck_method(item=oneof(slice, expr_int32))\n def __getitem__(self, item):\n \"\"\"Slice or index into the string.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(s[:15])\n 'The quick brown'\n\n >>> eval_expr(s[0])\n 'T'\n\n Parameters\n ----------\n item : slice or :class:`Int32Expression`\n Slice or character index.\n\n Returns\n -------\n :class:`StringExpression`\n Substring or character at index `item`.\n \"\"\"\n if isinstance(item, slice):\n return self._slice(TString(), item.start, item.stop, item.step)\n elif isinstance(item, int) or isinstance(item, Int32Expression):\n return self._index(TString(), item)\n else:\n raise NotImplementedError()\n\n def __add__(self, other):\n \"\"\"Concatenate strings.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(s + ' jumped over the lazy dog')\n 'The quick brown fox jumped over the lazy dog'\n\n Parameters\n ----------\n other : :class:`StringExpression`\n String to concatenate.\n\n Returns\n -------\n :class:`StringExpression`\n Concatenated string.\n \"\"\"\n other = to_expr(other)\n if not isinstance(other, StringExpression):\n raise TypeError(\"cannot concatenate 'TString' expression and '{}'\".format(other._type.__class__))\n return self._bin_op(\"+\", other, TString())\n\n def __radd__(self, other):\n assert (isinstance(other, StringExpression) or isinstance(other, str))\n return self._bin_op_reverse(\"+\", other, TString())\n\n def length(self):\n \"\"\"Returns the length of the string.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(s.length())\n 19\n\n Returns\n -------\n :class:`Int32Expression`\n Length of the string.\n \"\"\"\n return self._method(\"length\", TInt32())\n\n @typecheck_method(pattern1=expr_str, pattern2=expr_str)\n def replace(self, pattern1, pattern2):\n \"\"\"Replace substrings matching `pattern1` with `pattern2` using regex.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(s.replace(' ', '_'))\n 'The_quick_brown_fox'\n\n Notes\n -----\n The regex expressions used should follow\n `Java regex syntax `_\n\n Parameters\n ----------\n pattern1 : str or :class:`StringExpression`\n pattern2 : str or :class:`StringExpression`\n\n Returns\n -------\n\n \"\"\"\n return self._method(\"replace\", TString(), pattern1, pattern2)\n\n @typecheck_method(delim=expr_str, n=nullable(expr_int32))\n def split(self, delim, n=None):\n \"\"\"Returns an array of strings generated by splitting the string at `delim`.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(s.split('\\\\s+'))\n ['The', 'quick', 'brown', 'fox']\n\n >>> eval_expr(s.split('\\\\s+', 2))\n ['The', 'quick brown fox']\n\n Notes\n -----\n The delimiter is a regex using the\n `Java regex syntax `_\n delimiter. To split on special characters, escape them with double\n backslash (``\\\\\\\\``).\n\n Parameters\n ----------\n delim : str or :class:`StringExpression`\n Delimiter regex.\n n : :class:`Int32Expression`, optional\n Maximum number of splits.\n\n Returns\n -------\n :class:`ArrayExpression`\n Array of split strings.\n \"\"\"\n if n is None:\n return self._method(\"split\", TArray(TString()), delim)\n else:\n return self._method(\"split\", TArray(TString()), delim, n)\n\n @typecheck_method(regex=strlike)\n def matches(self, regex):\n \"\"\"Returns ``True`` if the string contains any match for the given regex.\n\n Examples\n --------\n\n >>> string = functions.capture('NA12878')\n\n The `regex` parameter does not need to match the entire string:\n\n .. doctest::\n\n >>> eval_expr(string.matches('12'))\n True\n\n Regex motifs can be used to match sequences of characters:\n\n .. doctest::\n\n >>> eval_expr(string.matches(r'NA\\\\\\\\d+'))\n True\n\n Notes\n -----\n The `regex` argument is a\n `regular expression `__,\n and uses\n `Java regex syntax `__.\n\n Parameters\n ----------\n regex: :obj:`str`\n Pattern to match.\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the string contains any match for the regex, otherwise ``False``.\n \"\"\"\n return construct_expr(RegexMatch(self._ast, regex), TBoolean(),\n self._indices, self._aggregations, self._joins, self._refs)\n\n\nclass CallExpression(Expression):\n \"\"\"Expression of type :class:`hail.expr.types.TCall`.\n\n >>> call = functions.capture(Call(1))\n \"\"\"\n @property\n def gt(self):\n \"\"\"Returns the triangle number of :py:meth:`Call.gtj` and :py:meth:`Call.gtk`.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(call.gt)\n 1\n\n Returns\n -------\n :class:`Int32Expression`\n Triangle number of the two alleles.\n \"\"\"\n return self._field(\"gt\", TInt32())\n\n def gtj(self):\n \"\"\"Returns the allele index of the first allele.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(call.gtj())\n 0\n\n Returns\n -------\n :class:`Int32Expression`\n First allele index.\n \"\"\"\n return self._method(\"gtj\", TInt32())\n\n def gtk(self):\n \"\"\"Returns the allele index of the second allele.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(call.gtk())\n 1\n\n Returns\n -------\n :class:`Int32Expression`\n Second allele index.\n \"\"\"\n return self._method(\"gtk\", TInt32())\n\n def is_non_ref(self):\n \"\"\"Evaluate whether the call includes one or more non-reference alleles.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(call.is_non_ref())\n True\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if at least one allele is non-reference, ``False`` otherwise.\n \"\"\"\n return self._method(\"isNonRef\", TBoolean())\n\n def is_het(self):\n \"\"\"Evaluate whether the call includes two different alleles.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(call.is_het())\n True\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the two alleles are different, ``False`` if they are the same.\n \"\"\"\n return self._method(\"isHet\", TBoolean())\n\n def is_het_nonref(self):\n \"\"\"Evaluate whether the call includes two different alleles, neither of which is reference.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(call.is_het_nonref())\n False\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the call includes two different alternate alleles, ``False`` otherwise.\n \"\"\"\n return self._method(\"isHetNonRef\", TBoolean())\n\n def is_het_ref(self):\n \"\"\"Evaluate whether the call includes two different alleles, one of which is reference.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(call.is_het_ref())\n True\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the call includes one reference and one alternate allele, ``False`` otherwise.\n \"\"\"\n return self._method(\"isHetRef\", TBoolean())\n\n def is_hom_ref(self):\n \"\"\"Evaluate whether the call includes two reference alleles.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(call.is_hom_ref())\n False\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the call includes two reference alleles, ``False`` otherwise.\n \"\"\"\n return self._method(\"isHomRef\", TBoolean())\n\n def is_hom_var(self):\n \"\"\"Evaluate whether the call includes two identical alternate alleles.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(call.is_hom_var())\n False\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the call includes two identical alternate alleles, ``False`` otherwise.\n \"\"\"\n return self._method(\"isHomVar\", TBoolean())\n\n def num_alt_alleles(self):\n \"\"\"Returns the number of non-reference alleles (0, 1, or 2).\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(call.num_alt_alleles())\n 1\n\n Returns\n -------\n :class:`Int32Expression`\n The number of non-reference alleles (0, 1, or 2).\n \"\"\"\n return self._method(\"nNonRefAlleles\", TInt32())\n\n @typecheck_method(v=expr_variant)\n def one_hot_alleles(self, v):\n \"\"\"Returns an array containing the summed one-hot encoding of the two alleles.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(call.one_hot_alleles(Variant('1', 1, 'A', 'T')))\n [1, 1]\n\n This one-hot representation is the positional sum of the one-hot\n encoding for each called allele. For a biallelic variant, the one-hot\n encoding for a reference allele is ``[1, 0]`` and the one-hot encoding\n for an alternate allele is ``[0, 1]``. Diploid calls would produce the\n following arrays: ``[2, 0]`` for homozygous reference, ``[1, 1]`` for\n heterozygous, and ``[0, 2]`` for homozygous alternate.\n\n Parameters\n ----------\n v : :class:`hail.genetics.Variant` or :class:`VariantExpression`\n Variant, used to determine the number of possible alleles.\n\n Returns\n -------\n :class:`ArrayInt32Expression`\n An array of summed one-hot encodings of allele indices.\n \"\"\"\n return self._method(\"oneHotAlleles\", TArray(TInt32()), v)\n\n @typecheck_method(v=expr_variant)\n def one_hot_genotype(self, v):\n \"\"\"Returns the triangle number of the genotype one-hot encoded into an integer array.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(call.one_hot_genotype(Variant('1', 1, 'A', 'T')))\n [0, 1, 0]\n\n A one-hot encoding uses a vector to represent categorical data, like a\n genotype call, by using an array with one ``1`` and many ``0`` s. In\n this case, the array will have a ``1`` at the position of the triangle\n number of the genotype (:py:meth:`Call.gt`).\n\n This is useful for manipulating counts of categorical variables.\n\n Parameters\n ----------\n v : :class:`hail.genetics.Variant` or :class:`VariantExpression`\n Variant, used to determine the number of possible alleles.\n Returns\n -------\n :class:`ArrayInt32Expression`\n An array with a one-hot encoding of the call.\n \"\"\"\n return self._method(\"oneHotGenotype\", TArray(TInt32()), v)\n\n\nclass LocusExpression(Expression):\n \"\"\"Expression of type :class:`hail.expr.types.TLocus`.\n\n >>> locus = functions.capture(Locus('1', 100))\n \"\"\"\n @property\n def contig(self):\n \"\"\"Returns the chromosome.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(locus.contig)\n '1'\n\n Returns\n -------\n :class:`StringExpression`\n The chromosome for this locus.\n \"\"\"\n return self._field(\"contig\", TString())\n\n @property\n def position(self):\n \"\"\"Returns the position along the chromosome.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(locus.position)\n 100\n\n Returns\n -------\n :class:`Int32Expression`\n This locus's position along its chromosome.\n \"\"\"\n return self._field(\"position\", TInt32())\n\n\nclass IntervalExpression(Expression):\n \"\"\"Expression of type :class:`hail.expr.types.TInterval`.\n\n >>> interval = functions.capture(Interval.parse('X:1M-2M'))\n \"\"\"\n @typecheck_method(locus=expr_locus)\n def contains(self, locus):\n \"\"\"Tests whether a locus is contained in the interval.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(interval.contains(Locus('X', 3000000)))\n False\n\n >>> eval_expr(interval.contains(Locus('X', 1500000)))\n True\n\n Parameters\n ----------\n locus : :class:`hail.genetics.Locus` or :class:`LocusExpression`\n Locus to test for interval membership.\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if `locus` is contained in the interval, ``False`` otherwise.\n \"\"\"\n locus = to_expr(locus)\n if self._type.point_type != locus._type:\n raise TypeError('expected {}, found: {}'.format(self._type.point_type, locus._type))\n return self._method(\"contains\", TBoolean(), locus)\n\n @property\n def end(self):\n \"\"\"Returns the end locus.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(interval.end)\n Locus(contig=X, position=2000000, reference_genome=GRCh37)\n\n Returns\n -------\n :class:`LocusExpression`\n End locus.\n \"\"\"\n return self._field(\"end\", TLocus())\n\n @property\n def start(self):\n \"\"\"Returns the start locus.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(interval.start)\n Locus(contig=X, position=1000000, reference_genome=GRCh37)\n\n Returns\n -------\n :class:`LocusExpression`\n Start locus.\n \"\"\"\n return self._field(\"start\", TLocus())\n\n\nclass AltAlleleExpression(Expression):\n \"\"\"Expression of type :class:`hail.expr.types.TAltAllele`.\n\n >>> altallele = functions.capture(AltAllele('A', 'AAA'))\n \"\"\"\n @property\n def alt(self):\n \"\"\"Returns the alternate allele string.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(altallele.alt)\n 'AAA'\n\n Returns\n -------\n :class:`StringExpression`\n Alternate base string.\n \"\"\"\n return self._field(\"alt\", TString())\n\n @property\n def ref(self):\n \"\"\"Returns the reference allele string.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(altallele.ref)\n 'A'\n\n Returns\n -------\n :class:`StringExpression`\n Reference base string.\n \"\"\"\n return self._field(\"ref\", TString())\n\n def category(self):\n \"\"\"Returns the string representation of the alternate allele class.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(altallele.category())\n 'Insertion'\n\n Returns\n -------\n :class:`StringExpression`\n One of ``\"SNP\"``, ``\"MNP\"``, ``\"Insertion\"``, ``\"Deletion\"``, ``\"Star\"``, ``\"Complex\"``.\n \"\"\"\n return self._method(\"category\", TString())\n\n def is_complex(self):\n \"\"\"Returns ``True`` if the polymorphism is not a SNP, MNP, star, insertion, or deletion.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(altallele.is_complex())\n False\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the allele is a complex event.\n \"\"\"\n return self._method(\"isComplex\", TBoolean())\n\n def is_deletion(self):\n \"\"\"Returns ``True`` if the polymorphism is a deletion.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(altallele.is_deletion())\n False\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the event is a a deletion.\n \"\"\"\n return self._method(\"isDeletion\", TBoolean())\n\n def is_indel(self):\n \"\"\"Returns ``True`` if the polymorphism is an insertion or deletion.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(altallele.is_insertion())\n True\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the event is an insertion or deletion.\n \"\"\"\n return self._method(\"isIndel\", TBoolean())\n\n def is_insertion(self):\n \"\"\"Returns ``True`` if the polymorphism is an insertion.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(altallele.is_insertion())\n True\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the event is an insertion.\n \"\"\"\n return self._method(\"isInsertion\", TBoolean())\n\n def is_mnp(self):\n \"\"\"Returns ``True`` if the polymorphism is a MNP.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(altallele.is_mnp())\n False\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the event is a multiple nucleotide polymorphism.\n \"\"\"\n return self._method(\"isMNP\", TBoolean())\n\n def is_snp(self):\n \"\"\"Returns ``True`` if the polymorphism is a SNP.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(altallele.is_snp())\n False\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the event is a single nucleotide polymorphism.\n \"\"\"\n return self._method(\"isSNP\", TBoolean())\n\n def is_star(self):\n \"\"\"Returns ``True`` if the polymorphism is a star (upstream deletion) allele.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(altallele.is_star())\n False\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the event is a star (upstream deletion) allele.\n \"\"\"\n return self._method(\"isStar\", TBoolean())\n\n def is_transition(self):\n \"\"\"Returns ``True`` if the polymorphism is a transition SNP.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(altallele.is_transition())\n False\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the event is a SNP and a transition.\n \"\"\"\n return self._method(\"isTransition\", TBoolean())\n\n def is_transversion(self):\n \"\"\"Returns ``True`` if the polymorphism is a transversion SNP.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(altallele.is_transversion())\n False\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the event is a SNP and a transversion.\n \"\"\"\n return self._method(\"isTransversion\", TBoolean())\n\n\nclass VariantExpression(Expression):\n \"\"\"Expression of type :class:`hail.expr.types.TVariant`.\n\n >>> variant = functions.capture(Variant('16', 123055, 'A', 'C'))\n \"\"\"\n def alt(self):\n \"\"\"Returns the alternate allele string.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(variant.alt())\n 'C'\n\n Warning\n -------\n Assumes biallelic. If the variant is multiallelic, throws an error.\n\n Returns\n -------\n :class:`StringExpression`\n Alternate allele base string.\n \"\"\"\n return self._method(\"alt\", TString())\n\n def alt_allele(self):\n \"\"\"Returns the alternate allele.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(variant.alt_allele())\n AltAllele(ref='A', alt='C')\n\n Warning\n -------\n Assumes biallelic. If the variant is multiallelic, throws an error.\n\n Returns\n -------\n :class:`AltAlleleExpression`\n Alternate allele.\n \"\"\"\n return self._method(\"altAllele\", TAltAllele())\n\n @property\n def alt_alleles(self):\n \"\"\"Returns the alternate alleles in the polymorphism.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(variant.alt_alleles)\n [AltAllele(ref='A', alt='C')]\n\n Returns\n -------\n :class:`ArrayExpression` with element type :class:`AltAlleleExpression`\n Alternate alleles.\n \"\"\"\n return self._field(\"altAlleles\", TArray(TAltAllele()))\n\n @property\n def contig(self):\n \"\"\"Returns the chromosome.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(variant.contig)\n '16'\n\n Returns\n -------\n :class:`StringExpression`\n Contig.\n \"\"\"\n return self._field(\"contig\", TString())\n\n def in_x_nonpar(self):\n \"\"\"Returns ``True`` if the polymorphism is in a non-pseudoautosomal region of chromosome X.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(variant.in_x_nonpar())\n False\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the variant is found in a non-pseudoautosomal region of chromosome X.\n \"\"\"\n return self._method(\"inXNonPar\", TBoolean())\n\n def in_x_par(self):\n \"\"\"Returns ``True`` if the polymorphism is in the pseudoautosomal region of chromosome X.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(variant.in_x_par())\n False\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the variant is found in a pseudoautosomal region of chromosome X.\n \"\"\"\n return self._method(\"inXPar\", TBoolean())\n\n def in_y_nonpar(self):\n \"\"\"Returns ``True`` if the polymorphism is in a non-pseudoautosomal region of chromosome Y.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(variant.in_y_nonpar())\n False\n\n Note\n ----\n Many variant callers only generate variants on chromosome X for the\n pseudoautosomal region. In this case, all variants mapped to chromosome\n Y are non-pseudoautosomal.\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the variant is found in a non-pseudoautosomal region of chromosome Y.\n \"\"\"\n return self._method(\"inYNonPar\", TBoolean())\n\n def in_y_par(self):\n \"\"\"Returns ``True`` if the polymorphism is in a pseudoautosomal region of chromosome Y.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(variant.in_y_par())\n False\n\n Note\n ----\n Many variant callers only generate variants on chromosome X for the\n pseudoautosomal region. In this case, all variants mapped to chromosome\n Y are non-pseudoautosomal.\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the variant is found in a pseudoautosomal region of chromosome Y.\n \"\"\"\n return self._method(\"inYPar\", TBoolean())\n\n def is_autosomal(self):\n \"\"\"Returns ``True`` if the polymorphism is found on an autosome.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(variant.is_autosomal())\n True\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the variant is found on an autosome.\n \"\"\"\n return self._method(\"isAutosomal\", TBoolean())\n\n def is_biallelic(self):\n \"\"\"Returns ``True`` if there is only one alternate allele.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(variant.is_biallelic())\n True\n\n Returns\n -------\n :class:`BooleanExpression`\n ``True`` if the variant has only one alternate allele.\n \"\"\"\n return self._method(\"isBiallelic\", TBoolean())\n\n def locus(self):\n \"\"\"Returns the locus at which the polymorphism occurs.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(variant.locus())\n Locus(contig=16, position=123055, reference_genome=GRCh37)\n\n Returns\n -------\n :class:`LocusExpression`\n Locus associated with this variant.\n \"\"\"\n return self._method(\"locus\", TLocus())\n\n def num_alleles(self):\n \"\"\"Returns the number of alleles in the polymorphism, including the reference.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(variant.num_alleles())\n 2\n\n Returns\n -------\n :class:`Int32Expression`\n Total number of alleles, including the reference.\n \"\"\"\n return self._method(\"nAlleles\", TInt32())\n\n def num_alt_alleles(self):\n \"\"\"Returns the number of alleles in the polymorphism, excluding the reference.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(variant.num_alt_alleles())\n 1\n\n Returns\n -------\n :class:`Int32Expression`\n Total number of non-reference alleles.\n \"\"\"\n return self._method(\"nAltAlleles\", TInt32())\n\n def num_genotypes(self):\n \"\"\"Returns the number of possible genotypes given the number of total alleles.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(variant.num_genotypes())\n 3\n\n Returns\n -------\n :class:`Int32Expression`\n Total number of possible diploid genotype configurations.\n \"\"\"\n return self._method(\"nGenotypes\", TInt32())\n\n @property\n def ref(self):\n \"\"\"Returns the reference allele string.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(variant.ref)\n 'A'\n\n Returns\n -------\n :class:`StringExpression`\n Reference base string.\n \"\"\"\n return self._field(\"ref\", TString())\n\n @property\n def start(self):\n \"\"\"Returns the chromosomal position of the polymorphism.\n\n Examples\n --------\n .. doctest::\n\n >>> eval_expr(variant.start)\n 123055\n\n Returns\n -------\n :class:`Int32Expression`\n \"\"\"\n return self._field(\"start\", TInt32())\n\n\ntyp_to_expr = {\n TBoolean: BooleanExpression,\n TInt32: Int32Expression,\n TInt64: Int64Expression,\n TFloat64: Float64Expression,\n TFloat32: Float32Expression,\n TLocus: LocusExpression,\n TInterval: IntervalExpression,\n TVariant: VariantExpression,\n TCall: CallExpression,\n TAltAllele: AltAlleleExpression,\n TString: StringExpression,\n TDict: DictExpression,\n TArray: ArrayExpression,\n TSet: SetExpression,\n TStruct: StructExpression\n}\n\nelt_typ_to_array_expr = {\n TInt32: ArrayInt32Expression,\n TFloat64: ArrayFloat64Expression,\n TInt64: ArrayInt64Expression,\n TFloat32: ArrayFloat32Expression,\n TString: ArrayStringExpression,\n TStruct: ArrayStructExpression,\n TArray: ArrayArrayExpression\n}\n\nelt_typ_to_set_expr = {\n TInt32: SetInt32Expression,\n TFloat64: SetFloat64Expression,\n TFloat32: SetFloat32Expression,\n TInt64: SetFloat32Expression,\n TString: SetStringExpression,\n TSet: SetSetExpression\n}\n\n\nclass ExpressionException(Exception):\n def __init__(self, msg=''):\n self.msg = msg\n super(ExpressionException, self).__init__(msg)\n\n\nclass ExpressionWarning(Warning):\n def __init__(self, msg=''):\n self.msg = msg\n super(ExpressionWarning, self).__init__(msg)\n\n\n@typecheck(caller=strlike, expr=Expression,\n expected_indices=Indices,\n aggregation_axes=setof(strlike))\ndef analyze(caller, expr, expected_indices, aggregation_axes=set()):\n indices = expr._indices\n source = indices.source\n axes = indices.axes\n aggregations = expr._aggregations\n refs = expr._refs\n\n warnings = []\n errors = []\n\n expected_source = expected_indices.source\n expected_axes = expected_indices.axes\n\n if source is not None and source is not expected_source:\n errors.append(\n ExpressionException('{} expects an expression from source {}, found expression derived from {}'.format(\n caller, expected_source, source\n )))\n\n # check for stray indices by subtracting expected axes from observed\n unexpected_axes = axes - expected_axes\n\n if unexpected_axes:\n # one or more out-of-scope fields\n assert len(refs) > 0\n bad_refs = []\n for name, inds in refs:\n bad_axes = inds.axes.intersection(unexpected_axes)\n if bad_axes:\n bad_refs.append((name, inds))\n\n assert len(bad_refs) > 0\n errors.append(ExpressionException(\n \"scope violation: '{caller}' expects an expression indexed by {expected}\"\n \"\\n Found indices {axes}, with unexpected indices {stray}. Invalid fields:{fields}{agg}\".format(\n caller=caller,\n expected=list(expected_axes),\n axes=list(indices.axes),\n stray=list(unexpected_axes),\n fields=''.join(\"\\n '{}' (indices {})\".format(name, list(inds.axes)) for name, inds in bad_refs),\n agg='' if (unexpected_axes - aggregation_axes) else\n \"\\n '{}' supports aggregation over axes {}, \"\n \"so these fields may appear inside an aggregator function.\".format(caller, list(aggregation_axes))\n )))\n\n if aggregations:\n if aggregation_axes:\n\n # the expected axes of aggregated expressions are the expected axes + axes aggregated over\n expected_agg_axes = expected_axes.union(aggregation_axes)\n\n for agg in aggregations:\n agg_indices = agg.indices\n agg_axes = agg_indices.axes\n if agg_indices.source is not None and agg_indices.source is not expected_source:\n errors.append(\n ExpressionException(\n 'Expected an expression from source {}, found expression derived from {}'\n '\\n Invalid fields: [{}]'.format(\n expected_source, source, ', '.join(\"'{}'\".format(name) for name, _ in agg.refs)\n )))\n\n # check for stray indices\n unexpected_agg_axes = agg_axes - expected_agg_axes\n if unexpected_agg_axes:\n # one or more out-of-scope fields\n bad_refs = []\n for name, inds in agg.refs:\n bad_axes = inds.axes.intersection(unexpected_agg_axes)\n if bad_axes:\n bad_refs.append((name, inds))\n\n errors.append(ExpressionException(\n \"scope violation: '{caller}' supports aggregation over indices {expected}\"\n \"\\n Found indices {axes}, with unexpected indices {stray}. Invalid fields:{fields}\".format(\n caller=caller,\n expected=list(aggregation_axes),\n axes=list(agg_axes),\n stray=list(unexpected_agg_axes),\n fields=''.join(\"\\n '{}' (indices {})\".format(\n name, list(inds.axes)) for name, inds in bad_refs)\n )\n ))\n else:\n errors.append(ExpressionException(\"'{}' does not support aggregation\".format(caller)))\n\n for w in warnings:\n warn('{}'.format(w.msg))\n if errors:\n for e in errors:\n error('{}'.format(e.msg))\n raise errors[0]\n\n\n@typecheck(expression=expr_any)\ndef eval_expr(expression):\n \"\"\"Evaluate a Hail expression, returning the result.\n\n This method is extremely useful for learning about Hail expressions and understanding\n how to compose them.\n\n Expressions that refer to fields of :class:`hail.api2.Table` or :class:`hail.api.MatrixTable`\n objects cannot be evaluated.\n\n Examples\n --------\n Evaluate a conditional:\n\n .. doctest::\n\n >>> x = 6\n >>> eval_expr(functions.cond(x % 2 == 0, 'Even', 'Odd'))\n 'Even'\n\n Parameters\n ----------\n expression : :class:`hail.expr.expression.Expression`\n Any expression, or a Python value that can be implicitly interpreted as an expression.\n\n Returns\n -------\n any\n Result of evaluating `expression`.\n \"\"\"\n return eval_expr_typed(expression)[0]\n\n\n@typecheck(expression=expr_any)\ndef eval_expr_typed(expression):\n \"\"\"Evaluate a Hail expression, returning the result and the type of the result.\n\n This method is extremely useful for learning about Hail expressions and understanding\n how to compose them.\n\n Expressions that refer to fields of :class:`hail.api2.Table` or :class:`hail.api.MatrixTable`\n objects cannot be evaluated.\n\n Examples\n --------\n Evaluate a conditional:\n\n .. doctest::\n\n >>> x = 6\n >>> eval_expr_typed(functions.cond(x % 2 == 0, 'Even', 'Odd'))\n ('Odd', TString())\n\n Parameters\n ----------\n expression : :class:`hail.expr.expression.Expression`\n Any expression, or a Python value that can be implicitly interpreted as an expression.\n\n Returns\n -------\n (any, :class:`hail.expr.Type`)\n Result of evaluating `expression`, and its type.\n \"\"\"\n analyze('eval_expr_typed', expression, Indices())\n if not expression._joins.empty():\n raise ExpressionException(\"'eval_expr' methods do not support joins or broadcasts\")\n r, t = Env.hc().eval_expr_typed(expression._ast.to_hql())\n return r, t\n\n\n_lazy_int32.set(Int32Expression)\n_lazy_numeric.set(NumericExpression)\n_lazy_array.set(ArrayExpression)\n_lazy_set.set(SetExpression)\n_lazy_bool.set(BooleanExpression)\n_lazy_struct.set(StructExpression)\n_lazy_string.set(StringExpression)\n_lazy_variant.set(VariantExpression)\n_lazy_locus.set(LocusExpression)\n_lazy_altallele.set(AltAlleleExpression)\n_lazy_interval.set(IntervalExpression)\n_lazy_call.set(CallExpression)\n_lazy_expr.set(Expression)\n","sub_path":"python/hail/expr/expression.py","file_name":"expression.py","file_ext":"py","file_size_in_byte":106717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"350780306","text":"# Import QRCode from pyqrcode\nimport pyqrcode\nimport png\n\n# String which represents the QR code\nurl = \"https://www.youtube.com/watch?v=dQw4w9WgXcQ\"\n\n# Variable conatining link\nurl = \"https://www.youtube.com/watch?v=choF2JRgjHY\"\n\n# Generating QR code\nqrcode = pyqrcode.create(url)\n\n# Create and save the png file naming \"myqr.png\"\nqrcode.png('MustScan.png', scale = 6)\n\n# Create and save the png file\nqrcode.png('QRCODE.png', scale = 6)\n\n","sub_path":"QR.py","file_name":"QR.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"223093062","text":"import re\nline = \"::'''Herr Guld''' (kunnt hinte-n-ine hintersi un schint ebbes z'bschaüe duss).\"\nline1 = \"::'''Herr Kalt.'''\"\nline2 = \"Ich mag noch so nogeh un nolüege, 's hilft alles nit meh!\"\n\nline3 = \"::'''Herr Guld''' (fir sich).\"\nline4 =\"Wie schön as se doch g'wachse-n-isch!\"\n\nregex = r'()(.+)()'\n\nreg_parenthesis = r\"\\(([^)]+)\\)\"\nre_obj = re.compile(reg_parenthesis)\nmatch = re_obj.search(line)\nprint(match)\nprint(match.group())\n# print(match.groups())\n\n\nreg_name = r\"(\\'\\'\\')([^\\']+)(\\'\\'\\')\"\nre_name = re.compile(reg_name)\na = re_name.search(line)\nprint(a.groups())\nprint(a.group(2))\nprint(\"\\nNew stuff\")\nreg_start_line = r\"\\:\\:\"\nmatch = re.match(reg_start_line,line1)\nif match:\n print(re.search(regex, line1).group())\n\n\nt1 = \"::'''Pierrot, Domino.'''\"\nt2 = \"::'''Pierrot''' (no-n-em Nachtesse im Restaurant).\"\nt3 = \"'s isch Zit glaüb, liewer Domino,\"\nt4 = \"== I. Uftritt. ==\"\nt5 = \"::(er b'schaüt's g'naüer)\"\nt6 = \"\"\nt7 = \"{{ImDruckVerbergen|[[Datei:ALustig SämtlicheWerke ZweiterBand page724 725.pdf|thumb|724 - 725]]}}\"\n\nseveral_chars = re.compile(r\"::\\'\\'\\'([^,]+,[^,]+)\\'\\'\\'\")\nact = re.compile(r\"==\\s(.+)\\s==\")\nsingle_char = re.compile(r\"::\\'\\'\\'([^']+)\\'\\'\\'\\s*\"\n r\"(\\([^)]+\\))\\.*\")\nstage_line = r\"[:]*(\\([^)]+\\))\"\nline = r\"[\\:]*([^(<:]+)\"\nre_page = r\"{{.+page(\\d+\\s\\d+)\\.pdf.+]]}}\"\nm = re.match(re_page, t7)\nif m:\n print(m.group(1))\n\n","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"425948667","text":"import os\nimport pandas as pd\nimport numpy as np\n\nclass DataLoader:\n '''\n Splits the raw dataset into windowed chunks of data. Also helps to easily load the chunks into memory\n '''\n def __init__(self, read_chunk_size=20000000, window_size=150000, step=50000, raw_data_path='../input/train.csv', window_data_path='./'):\n '''\n :param int read_chunk_size: The number of sample to read from the raw input in every chunk\n :param int window_size: Number of samples in a single window of data\n :param int step: Step to shift when splitting into windows\n :param str raw_data_path: The path to the raw data\n :param str window_data_path: The path of the dir to place the files with windowed data\n '''\n self.read_chunk_size = read_chunk_size\n self.window_size = window_size\n self.step = step\n self.raw_data_path = raw_data_path\n self.window_data_path = window_data_path\n self.mem = None\n\n def onlineGenerator(self, time_to_failure_dtype=np.float32):\n '''\n Instead of saving splits to memory, this function creates a generator that yields batches in an online way. This\n should prevent loading all data into memory at the same time.\n :return: X, y.\n :rtype: (numpy.array), (numpy.array)\n '''\n data_iterator = pd.read_csv(self.raw_data_path, iterator=True, chunksize=self.read_chunk_size,\n dtype={'acoustic_data': np.int16, 'time_to_failure': time_to_failure_dtype})\n # get features by iterating over all chunks\n for chunk in data_iterator:\n ind_range = np.arange(chunk.shape[0]-self.window_size+1, step=self.step)[:, None]\n indexer = np.arange(self.window_size)[None, :] + ind_range\n X = chunk.acoustic_data.values\n X = X[indexer]\n y = chunk.time_to_failure.values\n y = y[ind_range].flatten()\n yield X, y\n\n def _splitRawChunk(self, index):\n print('Loading data from {} to {}'.format(index*self.read_chunk_size, (index+1)*self.read_chunk_size))\n # Load part of the file\n raw = pd.read_csv(self.raw_data_path, nrows=self.read_chunk_size, skiprows=index*self.read_chunk_size+1, names=['acoustic_data', 'time_to_failure'], dtype={'acoustic_data': np.int16, 'time_to_failure': np.float32})\n\n # Use memory\n if (self.mem is not None) and (index > 0):\n raw = pd.concat([self.mem,raw],axis=0)\n self.mem = raw.tail(self.window_size-1)\n\n # Get features\n ind_range = np.arange(raw.shape[0]-self.window_size+1, step=self.step)[:, None]\n indexer = np.arange(self.window_size)[None, :] + ind_range\n X = raw['acoustic_data'].values\n X = X[indexer]\n y = raw['time_to_failure'].values\n y = y[ind_range].flatten()\n\n return X, y\n\n def splitRaw(self):\n '''\n Splits the original trainset into smaller files of overlapping windows.\n Saves the files in the window_data_path in the format X_{i}.csv and y_{i}.csvself.\n :return: The number of files created\n :rtype: int\n '''\n index = 0\n run = True\n while(run):\n print(' Iteration',index)\n X, y = self._splitRawChunk(index)\n if (X.shape[0] == 0):\n run = False\n else:\n np.savetxt('X_{}.csv'.format(index), X, delimiter=',', fmt='%i')\n np.savetxt('y_{}.csv'.format(index), y, delimiter=',', fmt='%.9e')\n index += 1\n return index-1\n\n def loadData(self, index):\n '''\n Splits the original trainset into smaller files of overlapping windows.\n Saves the files in the window_data_path in the format X_{i}.csv and y_{i}.csvself.\n :param int index: The index of the files to load\n :return: X, y\n :rtype: (numpy.array, numpy.array)\n '''\n X = np.loadtxt(os.path.join(self.window_data_path, 'X_{}.csv'.format(index)), delimiter=',', dtype=np.int16)\n y = np.loadtxt(os.path.join(self.window_data_path, 'y_{}.csv'.format(index)), delimiter=',', dtype=np.float32)\n\n return X, y\n\nif __name__ == \"__main__\":\n d = DataLoader(read_chunk_size=80000000)\n d.splitRaw()\n","sub_path":"lanl/working/dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":4304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"463666318","text":"from odoo import http\nfrom odoo.addons.website.controllers.main import Website\nfrom odoo.http import request\nfrom odoo.addons.portal.controllers.web import Home\n\nclass Website(Website):\n\n @http.route(auth='public')\n def index(self, data={}, **kw):\n super(Website, self).index(**kw)\n return http.request.render('intranet_home.new_homepage_vardhman', data)\n\n\n\nclass Academy(http.Controller):\n\n @http.route('/usefullinks/', auth='public', website=True)\n def index(self, **kw):\n Teachers = http.request.env['vardhman.useful.links']\n Employees = http.request.env['hr.employee']\n return http.request.render('intranet_home.use_links', {\n 'teachers': Teachers.search([])\n })\n\n\nclass home(Home):\n\n @http.route('/', type='http', auth=\"public\", website=True)\n def index(self, **kw):\n print(\"<<<<<<<<<<<<<<<<<<<\")\n links = request.env['vardhman.useful.links'].sudo().search([])\n print(\"----------\",links)\n if links:\n values = [{\n 'name':x['name'],\n 'url':x['url'],\n #'icon':links.icon\n } for x in links]\n return request.render('intranet_home.new_homepage_vardhman', {'values':values})","sub_path":"intranet_home1/controllers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"302364977","text":"import pandas as pd\nfrom functools import reduce\nfrom itertools import chain as ch\nfrom trees.node import Node\n\n'''\ngrow_tree(): an ID3 implementation for binary classification;\n\tgiven a dataset with binary attribute and target labels,\n\tgrow_tree recursively divides the dataset via the\n\tminimal conditional entropy (i.e., maximum gain) heuristic.\n\tEach subdivision creates a node holding attribute name and \n\tdata subset information until division is no longer possible,\n\tat which case the node is a leaf node.\n\tRETURN: a binary decision tree\n'''\n\ndef grow_tree(data, glob_freq_label = None, name = \"root\", branch = None):\n\t\n\t'''\n\tdata: a pandas DataFrame with a subset of the data; \n\t\t the data is corralled by an attribute with minimal \n\t\t conditional entropy in the previous iteration of grow_tree();\n\t\t 1st iteration: all data\n\t\t \n\tglob_freq_label: the most frequent target class;\n\t\t \n\tname: the attribute criterion the node branched from; \n\t\t each name is the attribute with minimal conditional entropy\n\t\t in the previous iteration;\n\t\t 1st iteration: \"root\"\n\t\t \n\tbranch: the attribute criterion's label;\n\t\t T (1) or F (0), from the last iteration's \n\t\t attribute with minimal conditional entropy;\n\t\t 1st iteration: None\n\t'''\n\t\n\tnode = Node(data)\t\t\t\t# node with data subset\n\tnode.name = name\t\t\t\t# name it via its branching attribute & label\n\tnode.branch_case = str(branch) if branch is not None else None\n\trows, cols = node.data.shape\t# grab the dimensions of the ata\n\tH = node.entropy()\t\t\t\t# compute target label entropy\n\t\n\tif name is \"root\":\t\t\t\t\t\t# calculate most common label for entire dataset\n\t\tglob_freq_label = 1 if float(sum(data.iloc[:, cols - 1])) / len(data) >= 0.5 else 0\t\n\tloc_freq_label = (1 if float(sum(node.data.iloc[:, cols - 1])) \n\t\t/ len(node.data) >= .5 else 0)\t\t# calculate most common label within subset of data\n\t\n\tif H == 0:\t\t\t\t\t\t\t\t\t\t\t\t\t\t# if there is 0 uncertainty, then\n\t\tnode.label = 1 if node.data.iloc[0, cols - 1] == 1 else 0 \t# the current node is a leaf, and\n\t\treturn node\t\t\t\t\t\t\t\t\t\t\t\t ### its label is the target label\n\t\t\n\tif cols == 1:\t\t\t\t\t\t\t\t\t\t\t\t\t# if there are no more attributes, then the current\n\t\tnode.label = glob_freq_label if H == 1 else loc_freq_label\t# node's label is the most common label in the data subset,\n\t\treturn node\t\t\t\t\t\t\t\t\t\t\t\t ### unless impurity is maximum, then it is the most common\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# label in the entire data\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\tidentical_attr = (map(lambda x, y: x == y, node.data.iloc[0, :(cols-1)], node.data.iloc[i, :(cols-1)]) for i in range(rows))\n\tidentical_attr = list(ch.from_iterable(identical_attr))\t\t\t# compare each row with the first via map and de-nest\n\tidentical_attr = reduce(lambda x, y: x and y, identical_attr)\t# the nested T and F values via from_iterable so that\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# reduce can determine if all rows are identical\n\tif identical_attr:\n\t\tnode.label = glob_freq_label if H == 1 else loc_freq_label\t# if all examples' attributes are identical,\n\t\treturn node\t\t\t\t\t\t\t\t\t\t\t\t ### return the node and set its label depending on H\n\t\t\n\tbest_attr, H_cond = node.min_conditional_entropy()\t\t\t\t# compute the value and attribute of minimal conditional H\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\tdata_true = pd.DataFrame(node.data[node.data.iloc[:, best_attr] == 1])\t\t\t\t# split data into two new datasets via true and\n\tdata_true = pd.DataFrame(data_true.drop(data_true.columns[best_attr], axis = 1))\t# false labels of the best attribute, then\n\tdata_false = pd.DataFrame(node.data[node.data.iloc[:, best_attr] == 0])\t\t\t\t# drop the attribute from the datasets, preventing\n\tdata_false = pd.DataFrame(data_false.drop(data_false.columns[best_attr], axis = 1))\t# the tree from reusing redundant attributes\n\t\n\tname_true = node.data.columns[best_attr]\t\t\t\t\t# set the branching names for the true \n\tname_false = node.data.columns[best_attr]\t\t\t\t\t# and false branches of the next iteration\t\n\t\n\tnode.branch_1 = grow_tree(data_true, glob_freq_label, name_true, 1)\t\t\t\t\t# and create the branches via grow_tree\n\tnode.branch_0 = grow_tree(data_false, glob_freq_label, name_false, 0)\n\t\n\treturn node\n\t\n\n\t\n","sub_path":"f_growtree.py","file_name":"f_growtree.py","file_ext":"py","file_size_in_byte":4074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"412584327","text":"#!/usr/bin/env python3\n#Author: Suman Sewani\n#Author ID: sksewani\n#Date Created: 2021/01/24\nimport sys\ntimer = 10\nwhile timer != 0:\n\tprint(timer)\n\ttimer = timer - 1\n\nprint('blast off!')\n\n","sub_path":"lab2e.py","file_name":"lab2e.py","file_ext":"py","file_size_in_byte":187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"391456261","text":"# coding: utf-8\n\n'''\n equiv.py\n\n Construct each of the .beleq files, given a particular dataset.\n This involves gathering all the terms and determining whether\n or not there are existing terms that refer to the same thing.\n Terms are either then equivalenced to something else, or given\n a new uuid (but UUIDs should be preserved after the first run).\n\n'''\n\nimport uuid\nimport namespaces\nimport csv\nimport parsed\nimport os\nfrom collections import deque, defaultdict\n\nhgnc_list = []\nmgi_list = []\nrgd_list = []\nsp_list = []\n\nentrez_eq = {}\nhgnc_eq = {}\nmgi_eq = {}\nrgd_eq = {}\nsp_eq = {}\nentrez_converter = {}\naffy_eq = {}\nrefseq = {}\nsd = {}\nchebi_id_eq = {}\nchebi_name_eq = {}\npub_eq_dict = {}\ngobp_eq_dict = {}\ngocc_eq_dict = {}\ndo_eq_dict = {}\n\nref_status = {'REVIEWED' : 0,\n 'VALIDATED' : 1,\n 'PROVISIONAL' : 2,\n 'PREDICTED' : 3,\n 'MODEL' : 4,\n 'INFERRED' : 5,\n '-' : 6}\n\ndelim = '|'\n\n# create a reference, used in MeSH equivalencing\ncurdir = os.getcwd()\nmesh_to_gocc = curdir+'/datasets/meshcs_to_gocc.csv'\nmg_eq = {}\nwith open(mesh_to_gocc, 'r') as meshf:\n mg_eq = dict([(rec[0], rec[2]) for rec in csv.reader(meshf, delimiter=',', quotechar='\"')])\n\n# this method is called once, to build an equivalence dict used by SwissProt\ndef build_equivs():\n\n ns_dicts = [namespaces.hgnc_ns_dict, namespaces.mgi_ns_dict, \\\n namespaces.rgd_ns_dict]\n for d in ns_dicts:\n for k, v in d.items():\n if d is namespaces.hgnc_ns_dict:\n equiv(k, 'hgnc')\n if d is namespaces.mgi_ns_dict:\n equiv(k, 'mgi')\n if d is namespaces.rgd_ns_dict:\n equiv(k, 'rgd')\n\ndef make_eq_dict(d):\n temp_dict = d.get_dictionary()\n for entry in temp_dict:\n entrez_id = entry\n mapping = temp_dict.get(entrez_id)\n tax_id = mapping.get('tax_id')\n symbol = mapping.get('Symbol_from_nomenclature_authority')\n if tax_id == '9606':\n entrez_converter['HGNC:'+symbol] = entrez_id\n if tax_id == '10116':\n entrez_converter['RGD:'+symbol] = entrez_id\n if tax_id == '10090':\n entrez_converter['MGI:'+symbol] = entrez_id\n\n# 'd' is a DataObject, which wraps a nested dictionary. Currently, a copy\n# of each .beleq file is stored in a dictionary as well, (like entrez_eq).\n# This may not be needed in final implementation.\ndef equiv(d, verbose):\n if str(d) == 'entrez_info':\n with open('entrez-gene-ids.beleq', 'w') as fp:\n for gene_id in d.get_eq_values():\n uid = uuid.uuid4()\n fp.write(delim.join((gene_id, str(uid)))+'\\n')\n entrez_eq[gene_id] = uuid.uuid4()\n make_eq_dict(d)\n\n elif str(d) == 'hgnc':\n with open('hgnc-approved-symbols.beleq', 'w') as fp:\n for approved_symbol in d.get_eq_values():\n if '~withdrawn' in approved_symbol:\n continue\n new_id = to_entrez('HGNC:'+approved_symbol)\n if new_id is None:\n # keep track of which hgnc genes need new uuids (dont map to entrez)\n hgnc_list.append(approved_symbol)\n # generate new uuid\n uid = uuid.uuid4()\n fp.write(delim.join((approved_symbol, str(uid)))+'\\n')\n hgnc_eq[approved_symbol] = uid\n else:\n # use the entrez uuid\n uid = entrez_eq.get(new_id)\n fp.write(delim.join((approved_symbol, str(uid)))+'\\n')\n hgnc_eq[approved_symbol] = uid\n\n elif str(d) == 'mgi':\n with open('mgi-approved-symbols.beleq', 'w') as fp:\n for marker_symbol in d.get_eq_values():\n new_id = to_entrez('MGI:'+marker_symbol)\n if new_id is None:\n # keep track of which genes need new uuids (dont map to entrez)\n mgi_list.append(marker_symbol)\n # generate new uuid\n uid = uuid.uuid4()\n fp.write(delim.join((marker_symbol, str(uid)))+'\\n')\n mgi_eq[marker_symbol] = uid\n else:\n # use the entrez uuid\n uid = entrez_eq.get(new_id)\n fp.write(delim.join((marker_symbol, str(uid)))+'\\n')\n mgi_eq[marker_symbol] = uid\n\n elif str(d) == 'rgd':\n with open('rgd-approved-symbols.beleq', 'w') as fp:\n for symbol in d.get_eq_values():\n new_id = to_entrez('RGD:'+symbol)\n if new_id is None:\n # keep track of which genes need new uuids (dont map to entrez)\n rgd_list.append(symbol)\n # generate new uuid\n uid = uuid.uuid4()\n fp.write(delim.join((symbol, str(uid)))+'\\n')\n rgd_eq[symbol] = uid\n else:\n # use the entrez uuid\n uid = entrez_eq.get(new_id)\n fp.write(delim.join((symbol, str(uid)))+'\\n')\n rgd_eq[symbol] = uid\n\n elif str(d) == 'swiss':\n with open('swissprot-entry-names.beleq', 'w') as fp:\n # dbrefs is a dict, i.e { reference_type : id_of_that_gene}\n for name, dbrefs, accessions in d.get_eq_values():\n target_pool = ['HGNC', 'MGI', 'RGD']\n gene_ids = []\n alt_ids = []\n\n if dbrefs is not None:\n for k, v in dbrefs.items():\n if k == 'GeneId':\n gene_ids.extend(v)\n if k in target_pool:\n # could be MGI or RGD or HGNC ids\n alt_ids.extend(v)\n if len(gene_ids) == 1:\n temp_id = entrez_eq.get(gene_ids[0])\n if temp_id is None:\n uid = uuid.uuid4()\n fp.write(delim.join((name, str(uid)))+'\\n')\n sp_eq[name] = uid\n else:\n uid = entrez_eq.get(gene_ids[0])\n fp.write(delim.join((name, str(uid)))+'\\n')\n sp_eq[name] = uid\n elif len(gene_ids) == 0:\n # are there hgnc, mgi or rgd refs?\n if len(alt_ids) == 0:\n uid = uuid.uuid4()\n fp.write(delim.join((name, str(uid)))+'\\n')\n sp_eq[name] = uid\n sp_list.append(name)\n elif len(alt_ids) == 1:\n a_id = alt_ids[0]\n if 'HGNC' in a_id:\n hgnc_key = namespaces.hgnc_map.get(a_id)\n uid = hgnc_eq.get(hgnc_key)\n # SwissProt may be referring to a since-removed gene.\n if uid is None:\n uid = uuid.uuid4()\n fp.write(delim.join((name, str(uid)))+'\\n')\n sp_eq[name] = uid\n else:\n sp_eq[name] = uid\n elif 'MGI' in a_id:\n mgi_key = namespaces.mgi_map.get(a_id)\n uid = mgi_eq.get(mgi_key)\n # SwissProt may be referring to a since-removed gene.\n if uid is None:\n uid = uuid.uuid4()\n fp.write(delim.join((name, str(uid)))+'\\n')\n sp_eq[name] = uid\n else:\n sp_eq[name] = uid\n else:\n rgd_key = namespaces.rgd_map.get(a_id)\n uid = rgd_eq.get(rgd_key)\n # SwissProt may be referring to a since-removed gene.\n if uid is None:\n uid = uuid.uuid4()\n fp.write(delim.join((name, str(uid)))+'\\n')\n sp_eq[name] = uid\n else:\n fp.write(delim.join((name, str(uid)))+'\\n')\n sp_eq[name] = uid\n # > 1 alt_id then generate a new uuid\n else:\n uid = uuid.uuid4()\n fp.write(delim.join((name, str(uid)))+'\\n')\n sp_eq[name] = uid\n # > 1 entrez id than generate a new uuid\n else:\n uid = uuid.uuid4()\n fp.write(delim.join((name, str(uid)))+'\\n')\n sp_eq[name] = uid\n # finally, generate .beleq for accession data also\n build_acc_data(accessions, name)\n swiss_accessions_eq()\n\n elif str(d) == 'affy':\n with open('affy-probeset-ids.beleq', 'w') as fp:\n for probe_id, gene_id in d.get_eq_values():\n\n if gene_id is not None and '---' not in gene_id:\n\n # need the space before and after '///' because that is how it is parsed.\n entrez_ids = gene_id.split(' /// ')\n\n # for 1 entrez mapping, use the entez uuid\n if len(entrez_ids) == 1:\n status = entrez_eq.get(entrez_ids[0])\n if status is None:\n uid = uuid.uuid4()\n fp.write(delim.join((probe_id, str(uid)))+'\\n')\n affy_eq[probe_id] = uid\n else:\n uid = status\n fp.write(delim.join((probe_id, str(uid)))+'\\n')\n affy_eq[probe_id] = uid\n # we have > 1 entrez mapping, resolve to one.\n else:\n adjacent_list = []\n for entrez_gene in entrez_ids:\n refstatus = refseq.get(entrez_gene)\n adjacent_list.append(ref_status.get(refstatus))\n\n # zipping yields a list of tuples like [('5307',0), ('104',2), ('3043',None)]\n # i.e. [(entrez_id, refseq_status)]\n list_of_tuples = list(zip(entrez_ids, adjacent_list))\n\n # get rid of all 'None' tuples (No entrez mapping)\n list_of_tuples = [tup for tup in list_of_tuples if tup[1] is not None]\n\n # no mapping, generate new uuid\n if len(list_of_tuples) == 0:\n uid = uuid.uuid4()\n fp.write(delim.join((probe_id, str(uid)))+'\\n')\n affy_eq[probe_id] = uid\n\n # multiple entrez, resolve by refseq status\n else:\n # min tuple is highest refseq status (0 the best)\n min_tuple = min(list_of_tuples, key=lambda x: x[1])\n min_refseq = min_tuple[1]\n lowest_tuples = []\n\n for item in list_of_tuples:\n if item[1] == min_refseq:\n lowest_tuples.append(item)\n\n # if mutiple genes with same refseq, resolve by lowest gene #\n target_tuple = min(lowest_tuples)\n uid = entrez_eq.get(target_tuple[0])\n fp.write(delim.join((probe_id, str(uid)))+'\\n')\n affy_eq[probe_id] = uid\n # no entrez mapping, create a new uuid\n else:\n uid = uuid.uuid4()\n fp.write(delim.join((probe_id, str(uid)))+'\\n')\n affy_eq[probe_id] = uid\n\n # equiv for alt ids and names relies on the equivalence for\n # primary ids being completely generated.\n elif str(d) == 'chebi':\n with open('chebi-ids.beleq', 'w') as fp, open('chebi-names_eq.beleq', 'w') as f:\n # like Entrez, new uuid for primary ids only the FIRST time.\n for primary_id in d.get_primary_ids():\n uid = uuid.uuid4()\n fp.write(delim.join((primary_id, str(uid)))+'\\n')\n chebi_id_eq[primary_id] = uid\n for alt_id in d.get_alt_ids():\n if alt_id not in chebi_id_eq:\n # get its primary equivalent and use its uuid\n primary = d.alt_to_primary(alt_id)\n uid = chebi_id_eq[primary]\n fp.write(delim.join((alt_id, str(uid)))+'\\n')\n chebi_id_eq[alt_id] = uid\n for name in d.get_names():\n primary = d.name_to_primary(name)\n uid = chebi_id_eq.get(primary)\n f.write(delim.join((name, str(uid)))+'\\n')\n chebi_name_eq[name] = uid\n\n elif str(d) == 'pubchem_equiv':\n with open('pubchem_eq.beleq', 'w') as fp:\n for sid, source, cid in d.get_eq_values():\n if 'ChEBI' in source and cid is not None: # <-- verify that NO PubChem CID == 'None'\n # use the CHEBI uuid\n chebi_equiv = source.split(':')[1]\n uid = chebi_id_eq.get(chebi_equiv)\n fp.write(delim.join((sid, str(uid)))+'\\n')\n pub_eq_dict[sid] = uid\n else:\n # generate a new uuid\n uid = uuid.uuid4()\n fp.write(delim.join((sid, str(uid)))+'\\n')\n\n elif str(d) == 'gobp':\n with open('go-biological-processes-names.beleq', 'w') as gobp, \\\n open('go-biological-processes-ids.beleq', 'w') as gobp_id:\n for vals in d.get_eq_values():\n termid, termname = vals\n uid = uuid.uuid4()\n gobp_id.write(delim.join((termid, str(uid)))+'\\n')\n gobp.write(delim.join((termname, str(uid)))+'\\n')\n gobp_eq_dict[termname] = uid\n\n # GO is the baseline for processes, so new uuids the first time.\n elif str(d) == 'gocc':\n\n with open('go-cellular-component-terms.beleq', 'w') as gocc, \\\n open('go-cellular-component-ids.beleq', 'w') as gocc_id:\n\n for vals in d.get_eq_values():\n termid, termname = vals\n uid = uuid.uuid4()\n gocc_id.write(delim.join((termid, str(uid)))+'\\n')\n gocc.write(delim.join((termname, str(uid)))+'\\n')\n gocc_eq_dict[termid] = uid\n\n elif str(d) == 'do':\n # assign DO a new uuid and use as the primary for diseases\n with open('disease-ontology-names.beleq', 'w') as dn, \\\n open('disease-ontology-ids.beleq', 'w') as di:\n for vals in d.get_eq_values():\n name, id = vals\n uid = uuid.uuid4()\n dn.write(delim.join((name, str(uid)))+'\\n')\n di.write(delim.join((id, str(uid)))+'\\n')\n do_eq_dict[name] = uid\n\n elif str(d) == 'sdis_to_do':\n # try to resolve sdis terms to DO. If there is not one,\n # assign a new uuid.\n count = 0\n sdis = parsed.load_data('sdis')\n with open('selventa-legacy-diseases.beleq', 'w') as dof:\n for vals in sdis.get_eq_values():\n uid = None\n sdis_term = vals\n if d.has_equivalence(sdis_term):\n count = count + 1\n do_term = d.get_equivalence(sdis_term)\n if do_term in do_eq_dict:\n uid = do_eq_dict[do_term]\n else:\n uid = do_eq_dict[do_term.lower()]\n else:\n uid = uuid.uuid4()\n dof.write(delim.join((sdis_term, str(uid)))+'\\n')\n if verbose:\n print('Able to resolve ' +str(count)+ ' legacy disease terms to DO.')\n\n elif str(d) == 'schem_to_chebi':\n # try to resolve schem terms to CHEBI. If there is not one,\n # assign a new uuid.\n count = 0\n schem = parsed.load_data('schem')\n with open('selventa-legacy-chemical-names.beleq', 'w') as schemf:\n for vals in schem.get_eq_values():\n uid = None\n schem_term = vals\n if d.has_equivalence(schem_term):\n count = count + 1\n chebi_term = d.get_equivalence(schem_term)\n if chebi_term in chebi_name_eq:\n uid = chebi_name_eq[chebi_term]\n elif chebi_term.lower() in chebi_name_eq:\n uid = chebi_name_eq[chebi_term.lower()]\n else:\n uid = uuid.uuid4()\n schemf.write(delim.join((schem_term, str(uid)))+'\\n')\n if verbose:\n print('Able to resolve ' +str(count)+ ' legacy chemical terms to CHEBI.')\n\n elif str(d) == 'mesh':\n\n with open('mesh-cellular-locations.beleq', 'w') as mesha, \\\n open('mesh-diseases.beleq', 'w') as meshc, \\\n open('mesh-biological-processes.beleq', 'w') as meshg:\n do_data = parsed.load_data('do')\n for vals in d.get_eq_values():\n ui, mh, mns, synonyms = vals\n if any('A11.284' in branch for branch in mns):\n # get GO equiv if there is one\n uid = None\n go_id = mg_eq.get(mh)\n # meshcs_to_gocc contains OBSOLETE GO terms at the moment.\n # It is possible this lookup will return None, in that\n # case generate a new uuid.\n if go_id is not None:\n uid = gocc_eq_dict.get(go_id)\n # try to find out why lookups fail - maybe OBSOLETE?\n if uid is None:\n if verbose:\n print('Lookup failed for: '+str(go_id))\n uid = uuid.uuid4()\n else:\n uid = uuid.uuid4()\n mesha.write(delim.join((mh, str(uid)))+'\\n')\n elif any('C' in branch for branch in mns):\n # does UI exist as a Xref in DO?\n xref = do_data.get_xrefs('MSH:'+ui)\n if xref:\n uid = do_eq_dict[xref]\n else:\n uid = uuid.uuid4()\n meshc.write(delim.join((mh, str(uid)))+'\\n')\n elif any('G' in branch for branch in mns):\n # synonyms for MeSH\n uid = None\n for syn in synonyms:\n # root 'G' branch in GOBP\n for name in gobp_eq_dict:\n if syn.lower() == name.lower():\n uid = gobp_eq_dict.get(name)\n if uid is None:\n uid = uuid.uuid4()\n meshg.write(delim.join((mh, str(uid)))+'\\n')\n\nacc_helper_dict = defaultdict(list)\nsp_acc_eq = {}\ndef build_acc_data(accessions, gene_name):\n with open('swissprot-accession-numbers.beleq', 'w') as fp:\n # turn list into a queue\n q = deque(accessions)\n # primary accession name is first one on the queue\n primary = q.popleft()\n for item in q:\n acc_helper_dict[item].append(gene_name)\n # map every primary one-to-one with SP entry uuid\n uid = sp_eq.get(gene_name)\n fp.write(delim.join((primary, str(uid)))+'\\n')\n sp_acc_eq[primary] = uid\n\n# try to factor this out and merge into build_acc_data\ndef swiss_accessions_eq():\n with open('swissprot-accession-numbers.beleq', 'a') as fp:\n for sec_acc_id, v in acc_helper_dict.items():\n # only maps to one primary accession, same uuid\n if len(v) == 1:\n uid = sp_eq.get(v[0])\n fp.write(delim.join((sec_acc_id, str(uid)))+'\\n')\n sp_acc_eq[sec_acc_id] = uid\n # maps to > 1 primary accession, give it a new uuid.\n else:\n uid = uuid.uuid4()\n fp.write(delim.join((sec_acc_id, str(uid)))+'\\n')\n sp_acc_eq[sec_acc_id] = uid\n\n# fills a dict mapping (entrez_gene -> refseq status)\ndef build_refseq(d):\n for entrez_gene, status, taxid in d.get_eq_values():\n target_pool = ['9606', '10116', '10090']\n valid_status = ['REVIEWED', 'VALIDATED', 'PROVISIONAL', 'PREDICTED',\n 'MODEL', 'INFERRED']\n\n if taxid in target_pool and status in valid_status:\n refseq[entrez_gene] = status\n\ndef to_entrez(gene_id):\n converted_id = entrez_converter.get(gene_id)\n return converted_id\n","sub_path":"equiv.py","file_name":"equiv.py","file_ext":"py","file_size_in_byte":21292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"497661542","text":"#!/usr/bin/env python\n\n\"\"\"\n\n All Emoncms code is released under the GNU Affero General Public License.\n See COPYRIGHT.txt and LICENSE.txt.\n\n ---------------------------------------------------------------------\n Emoncms - open source energy visualisation\n Part of the OpenEnergyMonitor project:\n http://openenergymonitor.org\n\n\"\"\"\n\n\"\"\"\nTODO : \n- I18n : translate strings (gettext ?)\n- add new parameters instead of hardcoding (log level, sending interval...)\n- allow any number of servers (instead of hardcoding 1 local and 1 remote) ?\n- save samples for later when connection is down\n\"\"\"\n\nimport serial\nimport MySQLdb, MySQLdb.cursors\nimport urllib2, httplib\nimport time, datetime\nimport logging, logging.handlers\nimport re\nimport signal\nimport os\nimport csv\nimport argparse\nimport urlparse\n\n\"\"\"class ServerDataBuffer\n\nStores server parameters and buffers the data between two HTTP requests\n\n\"\"\"\nclass ServerDataBuffer():\n\n def __init__(self, protocol, domain, path, apikey, period, active, logger=None):\n \"\"\"Create a server data buffer initialized with server settings.\n \n domain (string): domain name (eg: 'domain.tld')\n path (string): emoncms path with leading slash (eg: '/emoncms')\n apikey (string): API key with write access\n period (int): sending interval in seconds\n active (bool): whether the data buffer is active\n logger (string): the logger's name (default None)\n \n \"\"\"\n self._protocol = protocol\n self._domain = domain\n self._path = path\n self._apikey = apikey\n self._period = period\n self._data_buffer = []\n self._last_send = time.time()\n self._active = active\n self._logger = logging.getLogger(logger)\n\n def update_settings(self, protocol=None, domain=None, path=None, apikey=None, period=None, active=None):\n \"\"\"Update server settings.\"\"\"\n if protocol is not None:\n self._protocol = protocol\n if domain is not None:\n self._domain = domain\n if path is not None:\n self._path = path\n if apikey is not None:\n self._apikey = apikey\n if period is not None:\n self._period = period\n if active is not None:\n self._active = active\n\n def add_data(self, data):\n \"\"\"Append timestamped dataset to buffer.\n\n data (list): node and values (eg: '[node,val1,val2,...]')\n\n \"\"\"\n \n if not self._active:\n return\n \n self._logger.debug(\"Server \" + self._domain + self._path + \" -> add data: \" + str(data))\n \n # Insert timestamp before data\n dataset = list(data) # Make a distinct copy: we don't want to modify data\n dataset.insert(0,time.time())\n # Append new data set [timestamp, node, val1, val2, val3,...] to _data_buffer\n self._data_buffer.append(dataset)\n\n def send_data(self):\n \"\"\"Send data to server.\"\"\"\n \n if not self._active:\n return\n\n # Prepare data string with the values in data buffer\n now = time.time()\n data_string = '['\n for data in self._data_buffer:\n data_string += '['\n data_string += str(int(round(data[0]-now)))\n for sample in data[1:]:\n data_string += ','\n data_string += str(sample)\n data_string += '],'\n data_string = data_string[0:-1]+']' # Remove trailing comma and close bracket \n self._data_buffer = []\n self._logger.debug(\"Data string: \" + data_string)\n \n # Prepare URL string of the form\n # 'http://domain.tld/emoncms/input/bulk.json?apikey=12345&data=[[-10,10,1806],[-5,10,1806],[0,10,1806]]'\n url_string = self._protocol+self._domain+self._path+\"/input/bulk.json?apikey=\"+self._apikey+\"&data=\"+data_string\n self._logger.debug(\"URL string: \" + url_string)\n\n # Send data to server\n self._logger.info(\"Sending to \" + self._domain + self._path)\n try:\n result = urllib2.urlopen(url_string)\n except urllib2.HTTPError as e:\n self._logger.warning(\"Couldn't send to server, HTTPError: \" + str(e.code))\n except urllib2.URLError as e:\n self._logger.warning(\"Couldn't send to server, URLError: \" + str(e.reason))\n except httplib.HTTPException:\n self._logger.warning(\"Couldn't send to server, HTTPException\")\n except Exception:\n import traceback\n self._logger.warning(\"Couldn't send to server, Exception: \" + traceback.format_exc())\n else:\n if (result.readline() == 'ok'):\n self._logger.info(\"Send ok\")\n else:\n self._logger.warning(\"Send failure\")\n \n # Update _last_send\n self._last_send = time.time()\n\n def check_time(self):\n \"\"\"Check if it is time to send data to server.\n \n Return True if sending interval has passed since last time\n\n \"\"\"\n now = time.time()\n if (now - self._last_send > self._period):\n return True\n \n def has_data(self):\n \"\"\"Check if buffer has data\n \n Return True if data buffer is not empty.\n \n \"\"\"\n return (self._data_buffer != [])\n\n\n\"\"\"class RFM2PiGateway\n\nMonitors the serial port for data from RFM2Pi and sends data to local or remote \nemoncms servers through ServerDataBuffer instances.\n\n\"\"\"\nclass RFM2PiGateway():\n \n def __init__(self, logpath=None, local_url='http://localhost/emoncms'):\n \"\"\"Setup an RFM2Pi gateway.\n \n logpath (path): Path to the file the log should be written into.\n If Null, log to STDERR.\n local_domain (string): domain name of local emonCMS server\n local_path (string): path to emonCMS on local server\n\n \"\"\"\n\n # Initialize exit request flag\n self._exit = False\n\n # Initialize logging\n self.log = logging.getLogger(__name__)\n if (logpath is None):\n # If no path was specified, everything goes to sys.stderr\n loghandler = logging.StreamHandler()\n else:\n # Otherwise, rotating logging over two 5 MB files\n loghandler = logging.handlers.RotatingFileHandler(logpath,\n 'a', 5000 * 1024, 1)\n loghandler.setFormatter(logging.Formatter(\n '%(asctime)s %(levelname)s %(message)s'))\n self.log.addHandler(loghandler)\n self.log.setLevel(logging.DEBUG)\n \n # Initialize local server settings\n url = urlparse.urlparse(local_url)\n self._local_protocol = url.scheme + '://'\n self._local_domain = url.netloc\n self._local_path = url.path\n \n # Open serial port\n self._ser = self._open_serial_port()\n if self._ser is None:\n self.log.critical(\"COM port opening failed. Exiting...\")\n self.close()\n raise Exception('COM port opening failed.')\n \n # Initialize serial RX buffer\n self._serial_rx_buf = ''\n \n # Initialize target emoncms server buffer set\n self._server_buffers = {}\n \n # Declare timers\n self._status_update_timestamp = 0\n self._time_update_timestamp = 0\n\n # Get emoncms server buffers and RFM2Pi settings\n # (force_RFM2Pi_update forces RFM2Pi parameters to be sent)\n self._settings = None\n self._update_settings()\n \n # If settings can't be obtained, exit\n while (self._settings is None):\n self.log.warning(\"Couldn't get settings. Retrying in 10 sec...\")\n time.sleep(10)\n self._update_settings()\n \n def run(self):\n \"\"\"Launch the gateway.\n \n Monitor the COM port and process data.\n Check settings on a regular basis.\n\n \"\"\"\n\n # Set signal handler to catch SIGINT and shutdown gracefully\n signal.signal(signal.SIGINT, self._sigint_handler)\n \n # Until asked to stop\n while not self._exit:\n \n # Update settings and status every second\n now = time.time()\n if (now - self._status_update_timestamp > 1):\n # Update \"running\" status to inform emoncms the script is running\n self._raspberrypi_running()\n # Update settings\n self._update_settings()\n # \"Thanks for the status update. You've made it crystal clear.\"\n self._status_update_timestamp = now\n \n # Broadcast time to synchronize emonGLCD\n if (int(self._settings['sendtimeinterval'])):\n if (now - self._time_update_timestamp > \n int(self._settings['sendtimeinterval'])):\n self._send_time()\n self._time_update_timestamp = now\n\n # Read serial RX\n self._serial_rx_buf = self._serial_rx_buf + self._ser.readline()\n \n # If full line was read, process\n if ((self._serial_rx_buf != '') and \n (self._serial_rx_buf[len(self._serial_rx_buf)-1] == '\\n')):\n \n # Remove CR,LF\n self._serial_rx_buf = re.sub('\\\\r\\\\n', '', self._serial_rx_buf)\n \n # Log data\n self.log.info(\"Serial RX: \" + self._serial_rx_buf)\n \n # Get an array out of the space separated string\n received = self._serial_rx_buf.strip().split(' ')\n \n # Empty serial_rx_buf\n self._serial_rx_buf = ''\n \n # If information message, discard\n if ((received[0] == '>') or (received[0] == '->')):\n continue\n\n # Else,frame should be of the form \n # [node val1_lsb val1_msb val2_lsb val2_msb ...]\n # with number of elements odd and at least 3\n elif ((not (len(received) & 1)) or (len(received) < 3)):\n self.log.warning(\"Misformed RX frame: \" + str(received))\n \n # Else, process frame\n else:\n try:\n received = [int(val) for val in received]\n except Exception:\n self.log.warning(\"Misformed RX frame: \" + str(received))\n else:\n # Get node ID\n node = received[0]\n \n # Recombine transmitted chars into signed int\n values = []\n for i in range(1,len(received),2):\n value = received[i] + 256 * received[i+1]\n if value > 32768:\n value -= 65536\n values.append(value)\n \n self.log.debug(\"Node: \" + str(node))\n self.log.debug(\"Values: \" + str(values))\n \n # Add data to send buffers\n values.insert(0,node)\n for server_buf in self._server_buffers.itervalues():\n server_buf.add_data(values)\n \n # Send data if time has come\n for server_buf in self._server_buffers.itervalues():\n if server_buf.check_time():\n if server_buf.has_data():\n server_buf.send_data()\n \n # Sleep until next iteration\n time.sleep(0.2);\n \n def close(self):\n \"\"\"Close gateway. Do some cleanup before leaving.\"\"\"\n \n # Close serial port\n if self._ser is not None:\n self.log.debug(\"Closing serial port.\")\n self._ser.close()\n\n self.log.info(\"Exiting...\")\n logging.shutdown()\n\n def _sigint_handler(self, signal, frame):\n \"\"\"Catch SIGINT (Ctrl+C).\"\"\"\n \n self.log.debug(\"SIGINT received.\")\n # gateway should exit at the end of current iteration.\n self._exit = True\n\n def get_settings(self):\n \"\"\"Get settings\n \n Returns a dictionnary\n\n \"\"\"\n try:\n result = urllib2.urlopen(self._local_protocol +\n self._local_domain +\n self._local_path +\n \"/raspberrypi/get.json\")\n result = result.readline()\n # result is of the form\n # {\"userid\":\"1\",\"sgroup\":\"210\",...,\"remoteprotocol\":\"http:\\\\/\\\\/\"}\n result = result[1:-1].split(',')\n # result is now of the form\n # ['\"userid\":\"1\"',..., '\"remoteprotocol\":\"http:\\\\/\\\\/\"']\n settings = {}\n # For each setting, separate key and value\n for s in result:\n # We can't just use split(':') as there can be \":\" inside a value \n # (eg: \"http://\")\n s = csv.reader([s], delimiter=':').next() \n settings[s[0]] = s[1].replace(\"\\\\\",\"\")\n return settings\n\n except Exception:\n import traceback\n self.log.warning(\"Couldn't get settings, Exception: \" + traceback.format_exc())\n return\n\n def _set_rfm2pi_setting(self, setting, value):\n \"\"\"Send a configuration parameter to the RFM2Pi through COM port.\n \n setting (string): setting to be sent, can be one of the following:\n baseid, frequency, sgroup\n value (string): value for this setting\n \n \"\"\"\n \n self.log.info(\"Setting RFM2Pi | %s: %s\" % (setting, value))\n if setting == 'baseid':\n self._ser.write(value+'i')\n elif setting == 'frequency':\n self._ser.write(value+'b')\n elif setting == 'sgroup':\n self._ser.write(value+'g')\n time.sleep(1);\n \n def _update_settings(self):\n \"\"\"Check settings and update if needed.\"\"\"\n \n # Get settings\n s_new = self.get_settings()\n\n # If s_new is None, no answer to settings request\n if s_new is None:\n return\n\n # If self._settings is None, this is the first call\n # Send all RFM2Pi settings\n if self._settings is None:\n for param in ['baseid', 'frequency', 'sgroup']:\n self._set_rfm2pi_setting(param,str(s_new[param]))\n\n # General case, send RFM2Pi settings only if they changed\n else:\n for param in ['baseid', 'frequency', 'sgroup']:\n if ((s_new[param] != self._settings[param])):\n self._set_rfm2pi_setting(param,str(s_new[param]))\n\n # Server settings\n if 'local' not in self._server_buffers:\n self._server_buffers['local'] = ServerDataBuffer(\n protocol = self._local_protocol,\n domain = self._local_domain,\n path = self._local_path, \n apikey = s_new['apikey'], \n period = 0, \n active = True,\n logger = __name__)\n else:\n self._server_buffers['local'].update_settings(\n apikey = s_new['apikey'])\n \n if 'remote' not in self._server_buffers:\n self._server_buffers['remote'] = ServerDataBuffer(\n protocol = s_new['remoteprotocol'], \n domain = s_new['remotedomain'], \n path = s_new['remotepath'],\n apikey = s_new['remoteapikey'],\n period = 30,\n active = bool(s_new['remotesend']),\n logger = __name__)\n else: \n self._server_buffers['remote'].update_settings(\n protocol = s_new['remoteprotocol'], \n domain = s_new['remotedomain'],\n path = s_new['remotepath'],\n apikey = s_new['remoteapikey'],\n active = bool(int(s_new['remotesend'])))\n \n self._settings = s_new\n \n def _open_serial_port(self):\n \"\"\"Open serial port.\"\"\"\n\n self.log.debug(\"Opening serial port: /dev/ttyAMA0\")\n \n try:\n ser = serial.Serial('/dev/ttyAMA0', 9600, timeout = 0)\n except serial.SerialException as e:\n self.log.error(e)\n except Exception:\n import traceback\n self.log.error(\n \"Couldn't open serial port, Exception: \" \n + traceback.format_exc())\n else:\n return ser\n\n def _raspberrypi_running(self):\n \"\"\"Update \"script running\" status.\"\"\"\n \n try:\n result = urllib2.urlopen(self._local_protocol +\n self._local_domain +\n self._local_path +\n \"/raspberrypi/setrunning.json\")\n except Exception:\n import traceback\n self.log.warning(\"Couldn't update \\\"running\\\" status, Exception: \" + traceback.format_exc())\n \n def _send_time(self):\n \"\"\"Send time over radio link to synchronize emonGLCD.\"\"\"\n\n now = datetime.datetime.now()\n\n self.log.debug(\"Sending time for emonGLCD: %d:%d\" % (now.hour, now.minute))\n\n self._ser.write(\"%02d,00,%02d,00,s\" % (now.hour, now.minute))\n\n\nif __name__ == \"__main__\":\n\n # Command line arguments parser\n parser = argparse.ArgumentParser(description='RFM2Pi Gateway')\n parser.add_argument('--logfile', action='store', type=argparse.FileType('a'),\n help='path to optional log file (default: log to Standard error stream STDERR)')\n parser.add_argument('--local-url', action='store', default='http://localhost/emoncms',\n help='custom local URL (default: \\'http://localhost/emoncms\\')')\n parser.add_argument('--show-settings', action='store_true',\n help='show RFM2Pi settings and exit (for debugging purposes)')\n args = parser.parse_args()\n \n # If logfile is supplied, argparse opens the file in append mode, \n # this ensures it is writable\n # Close the file for now and get its path\n if args.logfile is None:\n logfile = None\n else:\n args.logfile.close()\n logfile = args.logfile.name\n\n # Create, run, and close RFM2Pi Gateway instance\n try:\n gateway = RFM2PiGateway(logfile, args.local_url)\n except Exception as e:\n print(e)\n else: \n # If in \"Show settings\" mode, print RFM2Pi settings and exit\n if args.show_settings:\n print(gateway.get_settings())\n # Else, run normally\n else:\n gateway.run()\n # When done, close gateway\n gateway.close()\n \n","sub_path":"rfm2pigateway.py","file_name":"rfm2pigateway.py","file_ext":"py","file_size_in_byte":18999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"202711373","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 ('contenttypes', '0002_remove_content_type_name'),\n ('auth', '0006_require_contenttypes_0002'),\n ('organizations', '0001_initial'),\n ('guardian', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='OrganizationObjectPermission',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('object_pk', models.CharField(max_length=255, verbose_name='object ID')),\n ('permission_expiry', models.DateTimeField(null=True, blank=True)),\n ('content_type', models.ForeignKey(to='contenttypes.ContentType', on_delete=models.CASCADE)),\n ('organization', models.ForeignKey(to='organizations.Organization', on_delete=models.CASCADE)),\n ('permission', models.ForeignKey(to='auth.Permission', on_delete=models.CASCADE)),\n ],\n ),\n migrations.AddField(\n model_name='groupobjectpermission',\n name='permission_expiry',\n field=models.DateTimeField(null=True, blank=True),\n ),\n migrations.AddField(\n model_name='userobjectpermission',\n name='permission_expiry',\n field=models.DateTimeField(null=True, blank=True),\n ),\n migrations.AlterUniqueTogether(\n name='organizationobjectpermission',\n unique_together=set([('organization', 'permission', 'object_pk')]),\n ),\n ]\n\n","sub_path":"guardian/migrations/0002_auto_20150922_1355.py","file_name":"0002_auto_20150922_1355.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"368228311","text":"from store.models import *\n\n\n\ndef get_all_possible_filters(item_category):\n\t\"\"\"Returns a list of 'FilterOption' PKs for each 'FilterCategory' set within the\n\tcurrent 'ItemCategory'\n\t\"\"\"\n\n\tpk_lists = []\n\n\tfor filter_category in FilterCategory.objects.filter(item_category=item_category):\n\t\tfilter_option_set = filter_category.filteroption_set.all()\n\t\ttemp_list = list(filter_option_set.values_list('pk', flat=True))\n\n\t\tpk_lists.append(temp_list)\n\n\treturn pk_lists\n\n\ndef filter_item_list(item_category, item_list, chosen_filters):\t\n\t\"\"\"First for loop: 'and' filter.\n\t Second for loop: 'or' filter.\n\t\"\"\"\n\t\n\tfor filter_option_set in get_all_possible_filters(item_category):\n\t\ttemp_list = []\n\n\t\tfor pk in chosen_filters:\n\t\t\tif pk in filter_option_set:\n\t\t\t\ttemp_list.append(pk)\n\n\t\tif len(temp_list) > 0:\n\t\t\titem_list = item_list.filter(filter_option__pk__in=temp_list).distinct()\n\n\treturn item_list","sub_path":"apps/store/utils/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"500721238","text":"# -*- coding: utf-8 -*-\nimport sqlite3 as sq\nimport pymongo\n\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\n\n\nclass OlxSQLitePipeline(object):\n def process_item(self, item, spider):\n self.c.execute(\n 'INSERT INTO cars('\n 'title, year, type, km, fuel, wheel, doors, engine,'\n 'gear, color, plate, price'\n ') VALUES('\n ':title, :year, :type, :km, :fuel,'\n ':wheel, :doors, :engine, :gear, :color,'\n ':plate, :price'\n ')', item\n )\n self.conn.commit()\n return item\n\n def create_table(self):\n res = self.c.execute (\n 'SELECT NAME FROM sqlite_master WHERE TYPE = \"table\" AND NAME = \"cars\"'\n )\n try:\n value = next(res)\n except StopIteration as ex:\n self.c.execute(\n 'CREATE TABLE cars ('\n 'id INTEGER PRIMARY KEY,'\n 'title TEXT,'\n 'year TEXT,'\n 'type TEXT,'\n 'km TEXT,'\n 'fuel TEXT,'\n 'wheel TEXT,'\n 'doors TEXT,'\n 'engine TEXT,'\n 'gear TEXT,'\n 'color TEXT,'\n 'plate TEXT,'\n 'price TEXT'\n ')'\n )\n\n\n\n def open_spider(self, spider):\n self.conn = sq.connect('db.sqlite3')\n self.c = self.conn.cursor()\n self.create_table()\n\n def close_spider(self, spider):\n self.conn.close()\n\n\n\nclass OlxMongoPipeline(object):\n\n collection_name = 'cars'\n\n def __init__(self, mongo_uri, mongo_db):\n self.mongo_uri = mongo_uri\n self.mongo_db = mongo_db\n\n @classmethod\n def from_crawler(cls, crawler):\n return cls(\n mongo_uri=crawler.settings.get('MONGO_URI'),\n mongo_db=crawler.settings.get('MONGO_DATABASE', 'items')\n )\n\n def open_spider(self, spider):\n self.client = pymongo.MongoClient(self.mongo_uri)\n self.db = self.client[self.mongo_db]\n\n def close_spider(self, spider):\n self.client.close()\n\n def process_item(self, item, spider):\n self.db[self.collection_name].insert_one(dict(item))\n return item","sub_path":"olx/olx/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"627858446","text":"\"\"\"\n This file is part of the cream web paste libs.\n See ../paster.py for license details.\n\"\"\"\n\nfrom cream.util import cached_property\n\nfrom basic_service import *\n\nclass DPaste(PasteService):\n __name__ = \"DPaste\"\n fields = ('content', 'language', 'name', 'title', 'hold')\n host = 'http://dpaste.com'\n\n @cached_property\n def languages(self):\n languages_regexp = \"\"\n content = '\\n'.join([line for line in \\\n urllib.urlopen(self.host).read().split(\"\\n\") \\\n if line.startswith(\" 0)\n self.Est = Est\n self.est_params = est_params\n if type(self.est_params) == dict:\n self.est_params = [self.est_params] * self.steps\n\n self.step_models = {(i): self.Est(**p) for i, p\n in enumerate(self.est_params)}\n self.step_cutoffs = {(i): min((i + 1) * self.d, self.n)\n for i, p in enumerate(self.step_models)}\n\n def assert_input(self, features, target=None):\n assert type(features.index.get_level_values(-1)) == DatetimeIndex\n assert int(features.isnull().sum().sum()) == 0\n if target is not None:\n assert type(target.index.get_level_values(-1)) == DatetimeIndex\n assert features.shape[0] == target.shape[0]\n assert int(target.isnull().sum()) == 0\n\n def build_data(self, features, target=None):\n self.build_features(features)\n if target is not None:\n self.build_target(target)\n\n self.step_preds = DataFrame(index=features.index,\n columns=self.step_targets.columns)\n\n def build_features(self, features):\n self.all_fits = DataFrame({'step_{}'.format(i): nan for i in range(1, self.n + 1)},\n index=features.index,\n columns=RangeIndex(self.steps).rename('step'))\n\n def build_target(self, target):\n if hasattr(target.index, 'levels'):\n step_targets = target.groupby(level=range(target.index.nlevels - 1))\\\n .apply(lambda g: lag_multiseries(g.reset_index(level=0, drop=True),\n lags=range(-self.n + 1, 1), freq='H'))\n else:\n step_targets = lag_multiseries(target, lags=range(-self.n + 1, 1), freq='H')\n\n step_targets = step_targets[sorted(step_targets.columns, reverse=True)]\n if self.d > 1:\n step_targets = self.aggregate_step_targets(step_targets)\n\n self.step_targets = step_targets\n self.step_targets.columns = RangeIndex(self.steps)\n\n def aggregate_step_targets(self, step_targets):\n cutoffs = deepcopy(self.step_cutoffs)\n cutoffs[-1] = 0\n aggregated_targets = []\n for step in range(self.steps):\n int_col_slice = slice(cutoffs[step - 1], cutoffs[step])\n col_agg = step_targets.iloc[:, int_col_slice].mean(axis=1).rename(step)\n aggregated_targets.append(col_agg)\n\n return concat(aggregated_targets, axis=1)\n\n def expand_step_preds(self, step_preds):\n expanded_preds = []\n cutoffs = deepcopy(self.step_cutoffs)\n cutoffs[-1] = 0\n for step in range(self.steps):\n expanded_count = cutoffs[step] - cutoffs[step - 1]\n col = step_preds.iloc[:, step]\n expanded_preds.extend([col] * expanded_count)\n\n expanded_preds = concat(expanded_preds, axis=1)\n return expanded_preds\n\n def add_predicted_features(self, features, step, test=False):\n if test:\n pred_features = self.step_preds.loc[features.index, :step - 1]\n else:\n pred_features = self.all_fits.loc[features.index, :step - 1]\n\n return concat([features, pred_features], axis=1)\n\n @measure_time\n def fit(self, features, target):\n self.assert_input(features, target)\n self.build_data(features, target)\n for step in range(self.steps):\n self.fit_step(features, target, step)\n\n def fit_step(self, features, target, step):\n step_features = self.add_predicted_features(features, step).dropna()\n step_target = self.step_targets.loc[step_features.index, step].dropna()\n step_features = step_features.loc[step_target.index.tolist()]\n self.step_models[step]\\\n .fit(*self.preprocess_data(step_features, step_target))\n step_fit = self.step_models[step]\\\n .predict(self.preprocess_data(step_features))\n self.all_fits.loc[step_features.index.tolist(), step] = step_fit\n # fill unpredicted values with 0 (FISHY)\n self.all_fits.loc[:, step].fillna(0, inplace=True)\n\n @measure_time\n def predict(self, features):\n self.assert_input(features)\n self.build_data(features)\n for step in range(self.steps):\n self.predict_step(features, step)\n\n pred = self.step_preds\n if self.d > 1:\n pred = self.expand_step_preds(pred)\n\n pred.columns = RangeIndex(1, self.n + 1)\n return pred\n\n def predict_step(self, features, step):\n step_features = self.add_predicted_features(features, step, test=True)\n step_features = step_features.loc[self.step_preds.index.tolist()]\n self.step_preds.loc[self.step_preds.index, step] =\\\n self.step_models[step].predict(self.preprocess_data(step_features))\n\n # fill unpredicted values with 0 (FISHY)\n self.step_preds.loc[:, step].fillna(0, inplace=True)\n\n @measure_time\n def validate(self, features, target, metric_func=SMAPE, predictions=True):\n self.assert_input(features, target)\n pred = self.predict(features)\n metric = Series(index=RangeIndex(self.n))\n for i in range(self.n):\n metric.iloc[i] = SMAPE(target.loc[pred.index],\n pred.iloc[:, i])\n\n if predictions:\n return metric, pred\n else:\n return metric\n\n\n def preprocess_data(self, features, target=None):\n \"Renames all columns to strings e.g. for `XGBRegressor`\"\n features.columns = [str(c) for c in features.columns]\n if target is not None:\n target = target.to_frame()\n target.columns = [str(c) for c in target.columns]\n return features.values, target.values\n else:\n return features.values\n\n\nclass StepTimeSeriesModelTestCase(TestCase):\n data_datetime_idx = date_range('2018-03-01', '2018-04-01', freq='H')\n data_idx = MultiIndex.from_product([['A', 'B', 'C'],\n data_datetime_idx])\n features = DataFrame({'feature_0': [e * random.normal(1) for e in range(data_idx.shape[0])],\n 'feature_1': [e / 2 * random.normal(1) for e in range(data_idx.shape[0])]},\n index=data_idx)\n target = DataFrame({'target': [e ** 2 for e in range(data_idx.shape[0])]},\n index=data_idx)\n\n def fit_topline(self, **init_args):\n nsm = StepTimeSeriesModel(**init_args)\n nsm.fit(self.features, self.target)\n return nsm\n\n def fit_granular(self, **init_args):\n nsm = StepTimeSeriesModel(**init_args)\n nsm.assert_input(self.features, self.target)\n nsm.build_data(self.features, self.target)\n for step in range(nsm.steps):\n nsm.fit_step(self.features, self.target, step)\n nan_predictions = nsm.all_fits.loc[:, step].isnull().sum()\n self.assertEqual(nan_predictions, 0)\n\n return nsm\n\n def test(self, **init_args):\n if 'Est' not in init_args.keys():\n init_args['Est'] = LinearRegression\n\n nsmI = self.fit_topline(**init_args)\n nsmII = self.fit_granular(**init_args)\n\n for nsm in [nsmI, nsmII]:\n\n if 'n' in init_args.keys():\n self.assertEqual(nsm.n, init_args['n'])\n else:\n self.assertEqual(nsm.n, 3)\n\n if 'd' in init_args.keys():\n self.assertEqual(nsm.d, init_args['d'])\n else:\n self.assertEqual(nsm.d, 1)\n\n expected_steps = int(nsm.n / nsm.d) +\\\n int(nsm.n % nsm.d > 0)\n\n # target\n self.assertEqual(nsm.step_targets.shape[1], expected_steps)\n\n # steps\n self.assertEqual(nsm.steps, expected_steps)\n self.assertEqual(len(nsm.est_params), expected_steps)\n self.assertEqual(len(nsm.step_models), expected_steps)\n self.assertEqual(len(nsm.step_cutoffs), expected_steps)\n\n # fits\n self.assertEqual(nsm.all_fits.transpose()\n .drop_duplicates().shape[0],\n expected_steps)\n self.assertEqual(nsm.all_fits.shape[0], self.features.shape[0])\n self.assertEqual(nsm.all_fits.shape[1], nsm.steps)\n\n # predict\n preds = nsm.predict(self.features)\n self.assertEqual(type(preds.columns), RangeIndex)\n self.assertEqual(preds.columns.min(), 1)\n self.assertEqual(preds.columns.max(), nsm.n)\n self.assertEqual(nsm.step_preds.transpose()\n .drop_duplicates().shape[0],\n expected_steps)\n self.assertEqual(preds.shape[0], self.features.shape[0])\n self.assertEqual(preds.shape[1], nsm.n)\n\n def test_other_n(self):\n self.test(n=1)\n self.test(n=4)\n\n def test_other_d(self):\n self.test(d=2)\n self.test(n=4, d=2)\n self.test(n=8, d=3)\n\n def test_other_freq(self):\n self.test(freq='M')\n\n def test_other_est(self):\n self.test(Est=XGBRegressor)\n","sub_path":"src/models/time_series.py","file_name":"time_series.py","file_ext":"py","file_size_in_byte":9877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"160882593","text":"import pytest\nimport flask\nimport subprocess\nimport multiprocessing\n\nfrom bci.defaults import DEFAULT_SERVER_ACTUAL_HOST, DEFAULT_SERVER_PORT\nfrom bci.client import upload_sample\n\n_HOST = DEFAULT_SERVER_ACTUAL_HOST\n_PORT = DEFAULT_SERVER_PORT\n\n\n@pytest.fixture\ndef get_message():\n parent, child = multiprocessing.Pipe()\n process = multiprocessing.Process(target=_run_server,\n args=(child,))\n process.start()\n parent.recv()\n try:\n def get_message():\n if not parent.poll(1):\n raise TimeoutError()\n return parent.recv()\n\n yield get_message\n finally:\n process.terminate()\n process.join()\n\n\ndef test_upload_sample(get_message, raw_data_and_path):\n data, path = raw_data_and_path\n upload_sample(path=path,\n host=_HOST,\n port=_PORT)\n assert get_message() == data\n\n\ndef test_cli(get_message, raw_data_and_path):\n data, path = raw_data_and_path\n process = subprocess.Popen(\n ['python', '-m', 'bci.client', 'upload-sample',\n '-h', _HOST, '-p', str(_PORT), str(path)],\n stdout=subprocess.PIPE,\n )\n stdout, _ = process.communicate()\n assert b'done' in stdout.lower()\n assert get_message() == data\n\n\ndef test_cli_error(raw_data_and_path):\n data, path = raw_data_and_path\n process = subprocess.Popen(\n ['python', '-m', 'bci.client', 'upload-sample',\n '-h', _HOST, '-p', str(_PORT), str(path)],\n stdout=subprocess.PIPE,\n )\n stdout, _ = process.communicate()\n assert b'error' in stdout.lower()\n\n\ndef _run_server(pipe):\n app = flask.Flask(__name__)\n\n @app.route('/config', methods=['GET'])\n def get_config():\n return flask.jsonify({\n 'fields': ['feelings', 'color_image', 'pose', 'depth_image'],\n 'error': None})\n\n @app.route('/snapshot', methods=['POST'])\n def snapshot():\n pipe.send(flask.request.data)\n return \"\"\n\n pipe.send('read')\n app.run(host=_HOST, port=_PORT)\n","sub_path":"tests/test_client.py","file_name":"test_client.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"131328677","text":"# -*- coding: utf-8 -*-\n'''\nCreated on 04.05.2016\n\n@author: rdebeerst\n'''\n\n\nimport bkt\nimport bkt.library.powerpoint as pplib\n\nimport os #for os.path, listdir and makedirs\nimport shelve\nimport time\n\nimport logging\nimport traceback\n\nfrom System import Array\n\nfrom bkt import dotnet\nDrawing = dotnet.import_drawing()\nBitmap = Drawing.Bitmap\nColorTranslator = Drawing.ColorTranslator\n\nForms = dotnet.import_forms() #required for clipboard functions\n\n\nfrom threading import Thread #used for non-blocking gallery thumbnails refresh\nfrom contextlib import contextmanager\n\n@contextmanager\ndef open_presentation_without_window(context, filename):\n ''' opens and returns presentation file '''\n try:\n presentation = context.app.Presentations.Open(filename, True, False, False) #readonly, untitled, withwindow\n yield presentation\n finally:\n presentation.Saved = True\n presentation.Close()\n\n\n# TODO\n# ChartLib --> ChartLibMenu\n# ChartLib class with\n# file-buttons\n# copy shape/slide action\n\nTHUMBNAIL_POSTFIX = '_thumbnails'\n\n\nclass ChartLibCache(object):\n cache = {}\n\n @classmethod\n def init_cache(cls):\n cache_file = os.path.join( bkt.helpers.get_cache_folder(), \"chartlib.cache\" )\n cls.cache = shelve.open(cache_file, protocol=2)\n\n\n\nclass ChartLib(object):\n \n def __init__(self, copy_shapes=False):\n '''Constructor. Configures options and slide_action'''\n\n # configuration of library\n self.library_folders = []\n self.library_files = []\n \n # option: show gallery or menu for presentations\n self.show_gallery = True\n # callback method for menu-actions\n self.slide_action = None\n \n # caches\n self.cached_presentation_menus = {}\n self.cached_presentation_galleries = {}\n\n # folder for favorites\n # self.fav_folder = os.path.dirname(os.path.realpath(__file__))\n # self.fav_folder = bkt.helpers.get_fav_folder()\n self.fav_folder = None\n \n # init slide_action\n self.copy_shapes_setting = copy_shapes\n # if copy_shapes:\n # # copy shapes\n # self.slide_action = self.copy_shapes_callback\n # self.fav_folder = os.path.join(self.fav_folder, \"shapelib\")\n # else:\n # # copy full slide\n # self.slide_action = self.copy_slide_callback\n # self.fav_folder = os.path.join(self.fav_folder, \"chartlib\")\n \n # # add favorite folder as first folder\n # self.library_folders.insert(0, {'title': \"Favoriten\", 'folder': self.fav_folder} )\n \n\n def init_chartlib(self):\n logging.debug('initializing chartlib')\n\n #load gallery items cache\n ChartLibCache.init_cache()\n\n if self.copy_shapes_setting:\n # copy shapes\n subfolder = \"shapelib\"\n self.slide_action = self.copy_shapes_callback\n\n self.library_folders.extend( bkt.config.shape_library_folders or [] )\n self.library_files.extend( bkt.config.shape_libraries or [] )\n\n else:\n # copy full slide\n subfolder = \"chartlib\"\n self.slide_action = self.copy_slide_callback\n\n self.library_folders.extend( bkt.config.chart_library_folders or [] )\n self.library_files.extend( bkt.config.chart_libraries or [] )\n\n # add from feature-folders\n for folder in bkt.config.feature_folders:\n chartlib_folder = os.path.join(folder, subfolder)\n if os.path.exists(chartlib_folder):\n self.library_folders.append( { 'title':os.path.basename(os.path.realpath(folder)), 'folder':os.path.join(folder, subfolder)})\n \n # add favorite folder as first folder\n self.fav_folder = os.path.join(bkt.helpers.get_fav_folder(), subfolder)\n self.library_folders.insert(0, {'title': \"Favoriten\", 'folder': self.fav_folder} )\n \n \n # ===========\n # = Helpers =\n # ===========\n \n # @classmethod\n # def open_presentation_file(cls, context, file):\n # ''' opens and returns presentation file '''\n # # if self.presentations.has_key(file):\n # # presentation = self.presentations[file]\n # # else:\n # # # # Parameter: schreibgeschützt, ohne Titel, kein Fenster\n # # # presentation = context.app.Presentations.Open(file, True, False, False)\n # # # Parameter: rw-access, ohne Titel, kein Fenster\n # # presentation = context.app.Presentations.Open(file, False, False, False)\n # # self.presentations[file] = presentation\n # return context.app.Presentations.Open(file, True, False, False)\n \n @classmethod\n def create_or_open_presentation(cls, context, file):\n if os.path.exists(file):\n return context.app.Presentations.Open(file, False, False, False)\n else:\n newpres = context.app.Presentations.Add(False) #WithWindow=False\n if not os.path.isdir(os.path.dirname(file)):\n os.makedirs(os.path.dirname(file))\n newpres.SaveAs(file)\n return newpres\n \n @staticmethod\n def _save_paste(obj, *args, **kwargs):\n for _ in range(3):\n try:\n return obj.paste(*args, **kwargs)\n except EnvironmentError:\n logging.debug(\"chartlib pasting error, waiting for 50ms\")\n #wait some time to avoid EnvironmentError (run ahead bug if clipboard is busy, see https://stackoverflow.com/questions/54028910/vba-copy-paste-issues-pptx-creation)\n time.sleep(.50)\n #FIXME: maybe better way to check if clipboard actually contains \"something\"\n else:\n raise EnvironmentError(\"pasting not successfull\")\n \n # ====================================\n # = Menus for folders and subfolders =\n # ====================================\n \n ##Overview of UI parts for chart library\n ###Chartlib-Files\n # - fixed chartlib-menu (Menu) from file/presentation ***Will open presentation***\n # get_chartlib_menu_from_file ***caches***\n # get_chartlib_menu_from_presentation\n # - dynamic chartlib-menu (DynamicMenu) ***Will only open presentation if menu is opened***\n # get_dynamic_file_menu\n # --> maps to get_chartlib_menu_from_file / get_chartlib_menu_callback\n # - dynamic chartlib-gallery (Gallery) ***Will only open presentation if gallery is opened***\n # get_chartlib_gallery_from_file\n # --> uses ChartLibGallery\n ###Chartlib-Folders\n # - fixed folder-menu (Menu) from folder\n # get_folder_menu\n # --> uses get_dynamic_file_menu for files\n # --> uses get_dynamic_folder_menu for subfolders\n # - dynamic folder-menu (DynamicMenu)\n # get_dynamic_folder_menu\n # --> maps to get_folder_menu / get_folder_menu_callback\n # - root library menu (Menu)\n # get_root_menu\n # --> uses get_folder_menu for library folders to create menu-sections\n # --> uses get_dynamic_file_menu for library files\n #\n \n def get_root_menu(self):\n '''\n Returns static menu-control for root-chartlib-dir\n with entries for every root-directory and root-file.\n If just one root-directory is configured, it lists its contents directly instead.\n \n Menu\n --- root-folder 1 ---\n file 1\n file 2\n ...\n --- root-folder 2 ---\n ...\n ---------------------\n root-file 1\n root-file 2\n '''\n \n #initialize chartlib on first call\n if not self.fav_folder:\n self.init_chartlib()\n\n # create menu-items for chartlibrary-directories\n if len(self.library_folders) == 0:\n # create empty menu\n menu = bkt.ribbon.Menu(\n xmlns=\"http://schemas.microsoft.com/office/2009/07/customui\",\n id=None\n )\n elif len(self.library_folders) == 1:\n # create menu with contents of directory\n folder = self.library_folders[0]\n if type(folder) == dict:\n folder = folder['folder']\n menu = self.get_folder_menu(folder, id=None)\n menu.label=None\n else:\n # create menu with sections for each directory\n folders = [ folder if type(folder) == dict else {'folder':folder, 'title':os.path.basename(folder)} for folder in self.library_folders]\n logging.debug(\"ChartLib root menu with folders: %s\" % folders)\n \n children = [ self.get_folder_menu(folder['folder'], label=folder['title']) for folder in folders]\n # make list flat \n flat_children = []\n for folder_menu in children:\n if len(folder_menu.children) > 0:\n flat_children.append( bkt.ribbon.MenuSeparator(title=folder_menu['label'] or None) )\n flat_children += folder_menu.children\n \n menu = bkt.ribbon.Menu(\n xmlns=\"http://schemas.microsoft.com/office/2009/07/customui\",\n id=None,\n children=flat_children\n )\n \n \n # create menu-items for chartlibrary-files\n menu.children.append( bkt.ribbon.MenuSeparator() )\n for filename in self.library_files:\n menu.children.append( self.get_dynamic_file_menu(filename) )\n \n # buttons\n menu.children += [\n bkt.ribbon.MenuSeparator(title=\"Settings\"),\n bkt.ribbon.Button(label=\"Zu Favoriten hinzufügen\",\n screentip=\"Chart zu Favoriten-Library hinzufügen\",\n supertip=\"Ausgewählte Slides/Shapes zu Standard-Favoriten-Library hinzufügen. Falls diese Library noch nicht existiert, wird diese neu angelegt.\",\n image_mso='SourceControlCheckIn',\n on_action=bkt.Callback(self.add_chart_to_lib)\n ),\n bkt.ribbon.Button(label=\"Library erneut indizieren\",\n screentip=\"Library erneut indizieren\",\n supertip=\"Alle Cashes werden zurückgesetzt. Library-Order und -Dateien werden jeweils beim nächsten Öffnen erneut indiziert.\\n\\nEs werden nur Thumbnails bereits geöffneter Libraries aktualisiert. Eine Neugenerierung der Thumbnails kann auch für jede Shape-Library-Datei separat angestoßen werden (im jeweiligen Menü).\",\n image_mso='AccessRefreshAllLists',\n on_action=bkt.Callback(self.update_thumbnails_and_reset_cashes)\n )\n ]\n \n logging.debug(\"ChartLib root menu: %s\" % menu.xml())\n return menu\n \n def get_root_menu_xml(self):\n ''' returns xml of root-chartlib-dir menu'''\n return self.get_root_menu().xml_string()\n \n def get_folder_menu_callback(self, current_control):\n ''' callback for dynamic menu, returns menu-control for folder represented by control '''\n folder = current_control['tag']\n if not self.cached_presentation_menus.has_key(folder):\n folder_menu = self.get_folder_menu(folder, id=None)\n self.cached_presentation_menus[folder] = folder_menu\n # else:\n # logging.debug('get_folder_menu_callback: reuse menu for %s' % folder)\n return self.cached_presentation_menus[folder]\n \n def get_folder_menu(self, folder, **kwargs):\n ''' returns static menu-control for given folder. menu contains entries for subfolders and pptx-files. '''\n\n files = []\n subfolders = []\n \n if os.path.isdir(folder):\n # find pptx-Files\n for filename in os.listdir(folder):\n if filename.endswith(\".pptx\") and not filename.startswith(\"~$\"):\n files.append(filename)\n logging.debug('get_folder_menu files: %s' % files)\n \n # find subfolders\n for filename in os.listdir(folder):\n if os.path.isdir(os.path.join(folder, filename)):\n if not filename.endswith(THUMBNAIL_POSTFIX):\n subfolders.append(filename)\n logging.debug('get_folder_menu folders: %s' % subfolders)\n \n else:\n logging.warning(\"Chartlib. No such directory: %s\" % folder)\n \n # FIXME: no folders which belong to files\n \n if len(files) + len(subfolders) == 0:\n children = []\n else:\n # create DynamicMenus / Galleries\n children = [\n self.get_chartlib_gallery_from_file(folder + \"\\\\\" + filename) if self.show_gallery else self.get_dynamic_file_menu(folder + \"\\\\\" + filename) \n for filename in files\n ] + ([bkt.ribbon.MenuSeparator()] if len(files) > 0 else [] )+ [\n self.get_dynamic_folder_menu(folder + \"\\\\\" + subfolder)\n for subfolder in subfolders\n ]\n \n # return Menu\n return bkt.ribbon.Menu(\n xmlns=\"http://schemas.microsoft.com/office/2009/07/customui\",\n children = children,\n **kwargs\n )\n \n def get_dynamic_folder_menu(self, folder):\n ''' returns dynamic menu for folder. if menu unfolds, menu content is obtained by get_folder_menu '''\n basename = os.path.basename(folder)\n return bkt.ribbon.DynamicMenu(label=basename, tag=folder, get_content=bkt.Callback(self.get_folder_menu_callback, current_control=True))\n\n \n def get_dynamic_file_menu(self, filename):\n ''' returns dynamic menu for file. if menu unfolds, menu content is obtained by get_chartlib_menu_from_file '''\n file_basename = os.path.splitext(os.path.basename(filename))[0]\n return bkt.ribbon.DynamicMenu(\n label=file_basename, tag=filename, \n get_content=bkt.Callback(self.get_chartlib_menu_callback, current_control=True, context=True)\n )\n \n def update_thumbnails_and_reset_cashes(self, context):\n if not bkt.helpers.confirmation(\"Dieser Vorgang kann bei vielen Libraries einige Minuten dauern und nicht abgebrochen werden. Trotzdem fortsetzen?\"):\n return\n\n def loop(worker):\n try:\n total = len(self.cached_presentation_galleries)+1\n current = 1.0\n worker.ReportProgress(1, \"Lade Dateien\")\n for gal in self.cached_presentation_galleries.itervalues():\n if worker.CancellationPending:\n break\n if len(gal.filename) > 50:\n worker.ReportProgress(current/total*100, \"...\" + gal.filename[-50:])\n else:\n worker.ReportProgress(current/total*100, gal.filename)\n \n gal.reset_gallery_items(context)\n current += 1.0\n worker.ReportProgress(100, \"Cache löschen\")\n except:\n logging.error(\"Error on refreshing chartlib libraries\")\n logging.debug(traceback.format_exc())\n finally:\n self.reset_cashes()\n \n bkt.ui.execute_with_progress_bar(loop, context, modal=False) #modal=False important so main thread can handle app events and all presentations close properly\n\n def reset_cashes(self):\n ''' cashes for library menus and galleries are deleted '''\n self.cached_presentation_menus = {}\n self.cached_presentation_galleries = {}\n \n \n \n # ====================================\n # = Quick add to favorites =\n # ====================================\n\n # def add_fav_to_config(self):\n # if not self.copy_shapes_setting:\n # folders = bkt.config.chart_library_folders or []\n # if self.fav_folder not in folders:\n # folders.append(self.fav_folder)\n # self.library_folders.insert(0, self.fav_folder)\n # bkt.config.set_smart(\"chart_library_folders\", folders)\n # else:\n # folders = bkt.config.shape_library_folders or []\n # if self.fav_folder not in folders:\n # folders.append(self.fav_folder)\n # self.library_folders.insert(0, self.fav_folder)\n # bkt.config.set_smart(\"shape_library_folders\", folders)\n\n def add_chart_to_lib(self, context):\n #Open default file\n #FIXME: read list of files in fav folder and ask user to select file\n file = os.path.join(self.fav_folder, \"Favorites.pptx\")\n pres = self.create_or_open_presentation(context, file)\n #Ensure fav folder is in config\n # self.add_fav_to_config()\n \n try:\n if not self.copy_shapes_setting:\n #Copy slides\n context.selection.SlideRange.Copy()\n # pres.Slides.Paste()\n self._save_paste(pres.Slides)\n else:\n #Copy each shape individually\n for shape in context.shapes:\n title = bkt.ui.show_user_input(\"Bitte Shape-Titel eingeben:\", \"Shape-Titel\", shape.Name)\n if title is None:\n break\n shape.Copy()\n slide = pres.Slides.Add(pres.Slides.Count+1, 11) #11=ppTitleOnly\n \n #set slide background color\n slide.FollowMasterBackground = False\n orig_bg = context.slides[0].Background.Fill.ForeColor\n if orig_bg.Type == pplib.MsoColorType['msoColorTypeScheme'] and orig_bg.ObjectThemeColor > 0:\n slide.Background.Fill.ForeColor.ObjectThemeColor = orig_bg.ObjectThemeColor\n slide.Background.Fill.ForeColor.Brightness = orig_bg.Brightness\n else:\n slide.Background.Fill.ForeColor.RGB = orig_bg.RGB\n \n # new_shp = slide.Shapes.Paste()\n new_shp = self._save_paste(slide.Shapes)\n new_shp.Left = (pres.PageSetup.SlideWidth - new_shp.Width)*0.5\n new_shp.Top = (pres.PageSetup.SlideHeight - new_shp.Height)*0.5\n slide.Shapes.Title.Textframe.TextRange.Text = title\n\n pres.Save()\n except:\n bkt.helpers.exception_as_message()\n finally:\n pres.Saved = True\n pres.Close()\n\n #Regenerate thumbnails\n gallery = self.get_chartlib_gallery_from_file(file)\n gallery.reset_gallery_items(context)\n self.reset_cashes()\n\n\n \n # ====================================\n # = Menu-items for ChartLib-sections =\n # ====================================\n \n def reset_chartlib_menu_callback(self, context, current_control):\n ''' callback to reload menu for presentation-file represented by control '''\n return self.reset_chartlib_menu_from_file(context, current_control['tag'])\n \n def reset_chartlib_menu_from_file(self, context, filename):\n ''' reloads menu for presentation-file. resets caches and relads chartlib-menu '''\n self.cached_presentation_menus.pop(filename, None)\n self.get_chartlib_menu_from_file(context, filename)\n return None\n \n def get_chartlib_menu_callback(self, context, current_control):\n ''' callback for dynamic menu, return Menu-control for presentation represented by control '''\n return self.get_chartlib_menu_from_file(context, current_control['tag'])\n \n def get_chartlib_menu_from_file(self, context, filename):\n ''' returns static menu for presentation-file. uses cached menu or generates menu using get_chartlib_menu_from_presentation '''\n if not self.cached_presentation_menus.has_key(filename):\n # presentation = self.open_presentation_file(context, filename)\n with open_presentation_without_window(context, filename) as presentation:\n menu = self.get_chartlib_menu_from_presentation(presentation)\n # presentation.Close()\n self.cached_presentation_menus[filename] = menu\n # else:\n # logging.debug('get_chartlib_menu_from_presentation: reuse menu for %s' % filename)\n return self.cached_presentation_menus[filename]\n \n def get_chartlib_menu_from_presentation(self, presentation):\n ''' returns static menu for presentation. \n Opens prensentation and creates menu-buttons for every slide.\n If presentation has sections, these are reused to structure menu:\n either by menu-sections or sub-menus; latter if presentation has 40 slides or more.\n '''\n children = [ ]\n \n # items per section\n num_sections = presentation.sectionProperties.Count\n if num_sections == 0:\n # only one section, list slide-Buttons\n children += self.get_section_menu(presentation.slides, 1, presentation.slides.count)\n elif presentation.Slides.Count < 40:\n # list-seperator per section, with slide-Buttons\n for idx in range(1,num_sections+1):\n children += [ bkt.ribbon.MenuSeparator(title = presentation.sectionProperties.Name(idx)) ]\n children += self.get_section_menu(presentation.slides,\n presentation.sectionProperties.FirstSlide(idx),\n presentation.sectionProperties.SlidesCount(idx) )\n else:\n # list Menu per section, with slide-Buttons\n children += [\n bkt.ribbon.Menu(\n label = presentation.sectionProperties.Name(idx),\n children = self.get_section_menu(presentation.slides,\n presentation.sectionProperties.FirstSlide(idx),\n presentation.sectionProperties.SlidesCount(idx) )\n )\n for idx in range(1,num_sections+1)\n ]\n\n # open-file-Button\n children += self.get_file_buttons(presentation.FullName)\n \n # return Menu\n menu = bkt.ribbon.Menu(\n #label=presentation.Name,\n xmlns=\"http://schemas.microsoft.com/office/2009/07/customui\",\n id=None,\n children = children\n )\n return menu\n \n \n def get_chartlib_gallery_from_file(self, filename):\n ''' returns dynamic gallery for presentation-file. uses cached gallery or generates gallery using ChartLibGallery class '''\n if not self.cached_presentation_galleries.has_key(filename):\n gallery = ChartLibGallery(filename, copy_shapes=self.copy_shapes_setting)\n self.cached_presentation_galleries[filename] = gallery\n return self.cached_presentation_galleries[filename]\n \n \n \n \n # ==================================\n # = Menu-items for ChartLib-slides =\n # ==================================\n \n def get_section_menu(self, slides, offset, count):\n ''' return menu-buttons for given slide selection '''\n \n # control chars are removed from labels\n control_chars = dict.fromkeys(range(32))\n \n return [\n bkt.ribbon.Button(\n label = slides.item(idx).Shapes.Title.Textframe.TextRange.text[:40].translate(control_chars) if slides.item(idx).Shapes.Title.Textframe.TextRange.text != \"\" else \"slide\" + str(idx),\n tag=slides.parent.FullName + \"|\" + str(idx),\n on_action=bkt.Callback(self.slide_action, context=True, current_control=True)\n )\n for idx in range(offset, offset+count)\n if slides.item(idx).shapes.hastitle != False\n ]\n \n\n\n \n # ===========\n # = actions =\n # ===========\n \n def get_file_buttons(self, filename, show_menu_separator=True):\n return ([bkt.ribbon.MenuSeparator(title = \"Library\")] if show_menu_separator else []) + [\n bkt.ribbon.Button(label=\"Datei öffnen und Library bearbeiten\",\n image_mso='FileSaveAsPowerPointPptx',\n tag=filename,\n on_action=bkt.Callback(self.open_file, context=True, current_control=True)\n ),\n bkt.ribbon.Button(label=\"Datei erneut indizieren\",\n image_mso='AccessRefreshAllLists',\n tag=filename,\n on_action=bkt.Callback(self.reset_chartlib_menu_callback, context=True, current_control=True)\n )\n ]\n \n @classmethod\n def open_file(cls, context, current_control):\n ''' Open library file with window and write access '''\n filename = current_control['tag']\n # Parameter: rw-access, ohne Titel, mit Fenster\n presentation = context.app.Presentations.Open(filename, False, False, True)\n \n @classmethod\n def copy_slide_callback(cls, context, current_control):\n filename, slide_index = current_control['tag'].split(\"|\")\n cls.copy_slide(context, filename, slide_index)\n \n @classmethod\n def copy_slide(cls, context, filename, slide_index):\n ''' Copy slide from chart lib '''\n # open presentation\n # template_presentation = cls.open_presentation_file(context, filename)\n with open_presentation_without_window(context, filename) as template_presentation:\n # copy slide\n template_presentation.slides.item(int(slide_index)).copy()\n # paste slide\n position = context.app.activeWindow.View.Slide.SlideIndex\n # context.app.activeWindow.presentation.slides.paste(position+1)\n cls._save_paste(context.app.activeWindow.presentation.slides, position+1)\n # template_presentation.Close()\n \n @classmethod\n def copy_shapes_callback(cls, context, current_control):\n filename, slide_index = current_control['tag'].split(\"|\")\n cls.copy_shapes(context, filename, slide_index)\n \n @classmethod\n def copy_shapes(cls, context, filename, slide_index):\n ''' Copy shape from shape lib '''\n # open presentation\n # template_presentation = cls.open_presentation_file(context, filename)\n with open_presentation_without_window(context, filename) as template_presentation:\n template_slide = template_presentation.slides.item(int(slide_index))\n # current slide\n cur_slide = context.app.activeWindow.View.Slide\n shape_count = cur_slide.shapes.count\n # find relevant shapes\n shape_indices = []\n shape_index = 1\n for shape in template_slide.shapes:\n if shape.type != 14 and shape.visible == -1:\n # shape is not a placeholder and visible\n shape_indices.append(shape_index)\n shape_index+=1\n # select and copy shapes\n template_slide.shapes.Range(Array[int](shape_indices)).copy()\n # cur_slide.shapes.paste()\n cls._save_paste(cur_slide.shapes)\n \n # group+select shapes\n if cur_slide.shapes.count - shape_count > 1:\n cur_slide.shapes.Range(Array[int](range(shape_count+1, cur_slide.shapes.count+1))).group().select()\n else:\n cur_slide.shapes.item(cur_slide.shapes.count).select()\n # template_presentation.Close()\n \n \n \n\n\ndef filename_as_ui_id(filename):\n from string import maketrans\n ''' creates customui-id from filename by removing unsupported characters '''\n # characters to remove\n chr_numbers = range(45) + range(46,48) + range(58,65) + range(91,95) + [96] + range(123,256)\n # translation tab\n transtab = maketrans(\"\".join( chr(i) for i in chr_numbers ), '|'*len(chr_numbers))\n \n return 'id_' + filename.translate(transtab).replace('|', '__')\n\n\n\nclass ChartLibGallery(bkt.ribbon.Gallery):\n \n # size of items\n # item_width should not be used in chart lib (copy_shapes=False); will be overwritten with respect to slide-format\n item_height = 150\n item_width = 200\n \n def __init__(self, filename, copy_shapes=False, **user_kwargs):\n '''Constructor\n Initializes Gallery for chart/shape-library\n '''\n self.filename = filename\n self.items_initialized = False\n \n self.labels = []\n self.slide_indices = []\n \n parent_id = user_kwargs.get('id') or \"\"\n \n self.this_id = filename_as_ui_id(filename) + \"--\" + str(copy_shapes)\n \n \n \n # default settings\n kwargs = dict(\n #label = u\"Test Gallery\",\n id = self.this_id,\n label = os.path.splitext(os.path.basename(filename))[0],\n show_label=False,\n #screentip=\"\",\n #supertip=\"\",\n get_image=bkt.Callback(lambda: self.get_chartlib_item_image(0)),\n )\n \n self.copy_shapes = copy_shapes\n if self.copy_shapes:\n # shape lib settings\n kwargs.update(dict(\n item_height=50,\n item_width=50,\n columns=3\n ))\n else:\n # slide lib settings\n kwargs.update(dict(\n item_height=100,\n #item_width=177, item_height=100, # 16:9\n #item_width=133, item_height=100, # 4:3\n columns=2\n ))\n \n # user kwargs\n if len(user_kwargs) > 0:\n kwargs.update(user_kwargs)\n \n # initialize gallery\n super(ChartLibGallery, self).__init__(\n children = self.get_file_buttons(),\n **kwargs\n )\n \n \n \n # ================\n # = ui callbacks =\n # ================\n \n def on_action_indexed(self, selected_item, index, context, current_control):\n '''CustomUI-callback: copy shape/slide from library to current presentation'''\n if self.copy_shapes:\n # copy shapes / shape library\n ChartLib.copy_shapes(context, self.filename, self.slide_indices[index])\n else:\n # copy slide / slide library\n ChartLib.copy_slide(context, self.filename, self.slide_indices[index])\n \n def get_item_count(self, context):\n '''CustomUI-callback'''\n if not self.items_initialized:\n self.init_gallery_items(context)\n return len(self.labels)\n\n def get_item_height(self):\n '''CustomUI-callback: return item-height\n item-height is initialized by init_gallery_items\n '''\n return self.item_height\n\n def get_item_width(self):\n '''CustomUI-callback: return item-width\n item-width is initialized by init_gallery_items\n '''\n return self.item_width\n \n def get_item_id(self, index):\n '''CustomUI-callback: returns corresponding item id'''\n return self.this_id + \"--\" + str(index)\n \n def get_item_label(self, index):\n '''CustomUI-callback: returns corresponding item label\n labels are initialized by init_gallery_items\n '''\n if not self.items_initialized:\n self.init_gallery_items(context)\n return self.labels[index][:40]\n \n def get_item_screentip(self, index):\n '''CustomUI-callback'''\n #return \"Shape aus Shape-library einfügen\"\n if self.copy_shapes:\n # copy shapes / shape library\n return \"Shape »\" + self.labels[index] + \"« aus Shape-Library einfügen\"\n else:\n # copy slide / slide library\n return \"Folie »\" + self.labels[index] + \"« aus Chart-Library einfügen\"\n \n # def get_item_supertip(self, index):\n # return \"tbd\"\n \n def get_item_image(self, index):\n '''CustomUI-callback: calls get_chartlib_item_image'''\n if not self.items_initialized:\n self.init_gallery_items(context)\n return self.get_chartlib_item_image(index)\n \n \n \n # ===========\n # = methods =\n # ===========\n \n def get_file_buttons(self):\n return [\n bkt.ribbon.Button(label=\"Datei öffnen und Library bearbeiten\",\n image_mso='FileSaveAsPowerPointPptx',\n tag=self.filename,\n on_action=bkt.Callback(ChartLib.open_file, context=True, current_control=True)\n ),\n bkt.ribbon.Button(label=\"Datei erneut indizieren und Thumbnails aktualisieren\",\n image_mso='AccessRefreshAllLists',\n on_action=bkt.Callback(self.reset_gallery_items, context=True)\n )\n ]\n \n def reset_gallery_items(self, context):\n '''Forces Gallery to re-initialize and generate thumbnail-images'''\n # reset gallery in a separate thread so core thread is still able to handle the app-events (i.e. presentation open/close).\n # otherwise when this function is called in a loop, some presentations remain open and block ppt process from being quit.\n t = Thread(target=self.init_gallery_items, args=(context, True))\n t.start()\n t.join()\n # self.init_gallery_items(context, force_thumbnail_generation=True)\n \n def init_gallery_items(self, context, force_thumbnail_generation=False):\n try:\n if force_thumbnail_generation:\n raise KeyError(\"Thumbnail generation not possible from cache\")\n self.init_gallery_items_from_cache()\n except KeyError as e:\n if str(e) == \"CACHE_FILEMTIME_INVALID\":\n force_thumbnail_generation = True\n with open_presentation_without_window(context, self.filename) as presentation:\n try:\n self.init_gallery_items_from_presentation(presentation, force_thumbnail_generation=force_thumbnail_generation)\n except:\n logging.error('error initializing gallery')\n logging.debug(traceback.format_exc())\n \n # try:\n # presentation = Charlib.open_presentation_file(context, self.filename)\n # # presentation = context.app.Presentations.Open(self.filename, True, False, True) #filename, readonly, untitled, withwindow\n # self.init_gallery_items_from_presentation(presentation, force_thumbnail_generation=force_thumbnail_generation)\n # except:\n # logging.error('error initializing gallery')\n # logging.debug(traceback.format_exc())\n # finally:\n # # logging.debug('closing presentation: %s' % self.filename)\n # presentation.Saved = True\n # presentation.Close()\n \n def init_gallery_items_from_cache(self):\n ''' initialize gallery items from cache if file has not been modified.\n '''\n cache = ChartLibCache.cache[self.filename]\n if os.path.getmtime(self.filename) != cache[\"file_mtime\"]:\n raise KeyError(\"CACHE_FILEMTIME_INVALID\")\n self.item_width = cache[\"item_width\"]\n self.slide_indices = cache[\"slide_indices\"]\n self.labels = cache[\"labels\"]\n self.item_count = cache[\"item_count\"]\n self.items_initialized = True\n \n def init_gallery_items_from_presentation(self, presentation, force_thumbnail_generation=False):\n ''' initialize gallery items (count, labels, item-widht, item-height... ).\n Also generates thumbnail-image-files if needed.\n '''\n \n # item width should respect slide-format\n if not self.copy_shapes:\n self.item_width = int(self.item_height * presentation.SlideMaster.Width / presentation.SlideMaster.Height)\n \n # init labels\n control_chars = dict.fromkeys(range(32))\n item_count = presentation.Slides.Count\n self.slide_indices = [\n idx\n for idx in range(1, 1+item_count)\n if presentation.slides.item(idx).shapes.hastitle != False\n ]\n self.labels = [\n # presentation.slides.item(idx).Shapes.Title.Textframe.TextRange.text[:40].translate(control_chars) \n presentation.slides.item(idx).Shapes.Title.Textframe.TextRange.text.translate(control_chars) \n if presentation.slides.item(idx).Shapes.Title.Textframe.TextRange.text != \"\" else \"slide\" + str(idx)\n for idx in self.slide_indices\n ]\n # logging.debug(\"labels %s\" % self.labels)\n\n # init items\n self.item_count = len(self.labels)\n\n # items are initialized and can be displayed\n self.items_initialized = True\n\n #create cache\n ChartLibCache.cache[self.filename] = dict(\n # cache_time = time.time(),\n file_mtime = os.path.getmtime(self.filename),\n item_width = self.item_width,\n slide_indices = self.slide_indices,\n labels = self.labels,\n item_count = self.item_count,\n )\n ChartLibCache.cache.sync()\n\n # init images, if first thumbnail does not exist\n image_filename = self.get_image_filename(1)\n if force_thumbnail_generation or not os.path.exists(image_filename):\n if self.copy_shapes:\n self.generate_gallery_images_from_shapes(presentation)\n else:\n self.generate_gallery_images_from_slides(presentation)\n \n # # cache items for next call on library\n # # image loading still necessary\n # self.children = [\n # bkt.ribbon.Item(\n # id=self.get_item_id(idx),\n # label=self.get_item_label(idx),\n # #image=self.get_item_image(idx),\n # )\n # for idx in range(self.get_item_count(context=None))\n # ] + self.children\n \n \n \n def get_image_filename(self, index, postfix=\"\"):\n ''' returns path of thumbnail for given chart-lib slide '''\n return os.path.join(os.path.splitext(self.filename)[0] + THUMBNAIL_POSTFIX, str(index) + postfix + '.png')\n \n \n def generate_gallery_images_from_slides(self, presentation):\n ''' generate thumbnail images for all chart-lib items '''\n filename = presentation.FullName\n item_count = presentation.Slides.Count\n control_chars = dict.fromkeys(range(32))\n \n # make sure, directory exists\n directory = os.path.split( self.get_image_filename(1) )[0]\n if not os.path.exists(directory):\n os.makedirs(directory)\n \n for slide in presentation.slides:\n if slide.shapes.hastitle != False:\n # select shapes\n # slide_range = presentation.slides.Range(Array[int]([ slide.SlideIndex ]))\n image_filename = self.get_image_filename(slide.SlideIndex)\n try:\n # export image as PNG, 2 = ppShapeFormatPNG, 0 = ppShapeFormatGIF\n # width 600, auto height (450 for 4:3)\n # slide_range.Export(image_filename, 'PNG', 600)\n # slide.Export(image_filename, 'PNG', 600) #FIXME: this line closes the chartlib menu, so every time the images are generated, the user needs to re-open the chartlib\n slide.Copy()\n Forms.Clipboard.GetImage().Save(image_filename, Drawing.Imaging.ImageFormat.Png)\n except:\n logging.warning('Creation of thumbnail image failed: %s' % image_filename)\n Forms.Clipboard.Clear()\n \n \n def generate_gallery_images_from_shapes(self, presentation, with_placeholders=False):\n ''' generate thumbnail images for all shape-lib items '''\n filename = presentation.FullName\n item_count = presentation.Slides.Count\n control_chars = dict.fromkeys(range(32))\n \n # make sure, directory exists\n directory = os.path.split( self.get_image_filename(1) )[0]\n if not os.path.exists(directory):\n os.makedirs(directory)\n \n for slide in presentation.slides:\n if slide.shapes.hastitle != False:\n # find relevant shapes\n shape_indices = []\n shape_index = 1\n for shape in slide.shapes:\n if shape.visible == -1 and (with_placeholders or shape.type != 14):\n # shape is visible and not a placeholder (or placeholder are allowed)\n shape_indices.append(shape_index)\n shape_index+=1\n # select shapes\n shape_range = slide.shapes.Range(Array[int](shape_indices))\n image_filename = self.get_image_filename(slide.SlideIndex)\n # WAS: image_filename = os.path.join(os.path.splitext(self.filename)[0], str(slide.SlideIndex) + '.png')\n \n try:\n # export image as PNG, \n # ppShapeFormatGIF = 0, ppShapeFormatJPG = 1, ppShapeFormatPNG = 2, ppShapeFormatBMP = 3, ppShapeFormatWMF = 4, ppShapeFormatEMF = 5;\n shape_range.Export(image_filename, 2) \n except:\n logging.warning('Creation of thumbnail image failed: %s' % image_filename)\n \n # resize thumbnail image to square\n if os.path.exists(image_filename):\n try:\n # init croped image\n width = 100\n height = 100\n image = Bitmap(image_filename)\n bmp = Bitmap(width, height)\n graph = Drawing.Graphics.FromImage(bmp)\n #set background color of thumbnails\n background_color = Drawing.ColorTranslator.FromOle(slide.Background.Fill.ForeColor.RGB)\n if background_color != pplib.PowerPoint.XlRgbColor.rgbWhite.value__:\n graph.Clear(background_color)\n # compute scale\n scale = min(float(width) / image.Width, float(height) / image.Height)\n scaleWidth = int(image.Width * scale)\n scaleHeight = int(image.Height * scale)\n # set quality\n graph.InterpolationMode = Drawing.Drawing2D.InterpolationMode.High\n graph.CompositingQuality = Drawing.Drawing2D.CompositingQuality.HighQuality\n graph.SmoothingMode = Drawing.Drawing2D.SmoothingMode.AntiAlias\n # redraw and save\n # logging.debug('crop image from %sx%s to %sx%s. rect %s.%s-%sx%s' % (image.Width, image.Height, width, height, int((width - scaleWidth)/2), int((height - scaleHeight)/2), scaleWidth, scaleHeight))\n graph.DrawImage(image, Drawing.Rectangle(int((width - scaleWidth)/2), int((height - scaleHeight)/2), scaleWidth, scaleHeight))\n cropped_image_filename = self.get_image_filename(slide.SlideIndex, postfix=\"-cropped\")\n bmp.Save(cropped_image_filename)\n # close files\n image.Dispose()\n bmp.Dispose()\n # move files\n original_image_filename = self.get_image_filename(slide.SlideIndex, postfix=\"-original\")\n if os.path.exists(original_image_filename):\n os.remove(original_image_filename)\n os.rename(image_filename, original_image_filename)\n os.rename(cropped_image_filename, image_filename)\n \n except:\n logging.error('Creation of croped thumbnail image failed: %s' % image_filename)\n logging.debug(traceback.format_exc())\n finally:\n if image:\n image.Dispose()\n if bmp:\n bmp.Dispose()\n \n \n def get_chartlib_item_image(self, index):\n ''' load item image from corresponding image-file and return Bitmap-object '''\n #logging.debug('get_chartlib_item_image %s -- %s' % (filename, index))\n image_filename = self.get_image_filename(index+1)\n #logging.debug('get_chartlib_item_image %s' % (image_filename))\n if os.path.exists(image_filename):\n # return empty from file\n #return Bitmap.FromFile(image_filename)\n \n #version that should not lock the file, which prevents updating of thumbnails:\n with Bitmap.FromFile(image_filename) as img:\n new_img = Bitmap(img)\n img.Dispose()\n return new_img\n else:\n # return empty white image\n img = Bitmap(50, 50)\n color = ColorTranslator.FromHtml('#ffffff00')\n img.SetPixel(0, 0, color);\n return img\n\n\n\n\n\ncharts = ChartLib()\n# charts.library_folders.extend( bkt.config.chart_library_folders or [] )\n# charts.library_files.extend( bkt.config.chart_libraries or [] )\n\nshapes = ChartLib( copy_shapes=True )\n# shapes.library_folders.extend( bkt.config.shape_library_folders or [] )\n# shapes.library_files.extend( bkt.config.shape_libraries or [] )\n\n\n# add from feature-folders\n# for folder in bkt.config.feature_folders:\n# chartlib_folder = os.path.join(folder, \"chartlib\")\n# charts.library_folders.append( { 'title':os.path.basename(os.path.realpath(folder)), 'folder':chartlib_folder})\n# shapelib_folder = os.path.join(folder, \"shapelib\")\n# shapes.library_folders.append( { 'title':os.path.basename(os.path.realpath(folder)), 'folder':shapelib_folder})\n\n\n\nchartlib_button = bkt.ribbon.DynamicMenu(\n id='menu-add-chart',\n label=\"Templatefolie einfügen\",\n show_label=False,\n screentip=\"Folie aus Slide-Library einfügen\",\n supertip=\"Aus den hinterlegten Slide-Templates kann ein Template als neue Folie eingefügt werden.\",\n image_mso=\"SlideMasterInsertLayout\",\n #image_mso=\"CreateFormBlankForm\",\n get_content = bkt.Callback(\n charts.get_root_menu\n )\n)\nshapelib_button = bkt.ribbon.DynamicMenu(\n id='menu-add-shape',\n label=\"Personal Shape Library\",\n show_label=False,\n screentip=\"Shape aus Shape-Library einfügen\",\n supertip=\"Aus den hinterlegten Shape-Templates kann ein Shape auf die aktuelle Folie eingefügt werden.\",\n image_mso=\"ActionInsert\",\n #image_mso=\"ShapesInsertGallery\",\n #image_mso=\"OfficeExtensionsGallery\",\n get_content = bkt.Callback(\n shapes.get_root_menu\n )\n)\n\n# chartlibgroup = bkt.ribbon.Group(\n# label=\"chartlib\",\n# children=[ chartlib_button, shapelib_button]\n# )\n\n# bkt.powerpoint.add_tab(\n# bkt.ribbon.Tab(\n# label=\"chartlib\",\n# children = [\n# chartlibgroup\n# ]\n# )\n# )\n\n\n\n\n\n","sub_path":"features/toolbox/chartlib.py","file_name":"chartlib.py","file_ext":"py","file_size_in_byte":47248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"2828393","text":"#import bibliotek\nimport os\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\n#wyświetlenie zawartości katalogu z opiniami\nprint(*os.listdir(\"./opinions_json\"))\n\n#wczytanie identyfikatora produktu, którego opinie będą analizowane\nproduct_id = input(\"Podaj kod produktu: \")\n\n#wczytanie do ramki danych opinii z pliku\nopinions = pd.read_json(\"./opinions_json/\"+product_id+'.json') \nopinions = opinions.set_index(\"opinion_id\") \n\n#częstość występowania poszczególnej liczby gwiazdek\nstars = opinions[\"stars\"].value_counts().sort_index().reindex(list(np.arange(0, 5.1, 0.5)), fill_value=0)\nfig, ax = plt.subplots()\nstars.plot.bar(color=\"deepskyblue\")\nplt.xticks(rotation=0)\nax.set_title(\"Częstość występowania poszczególnych ocen\")\nax.set_xlabel(\"liczba gwiazdek\")\nax.set_ylabel(\"liczba opinii\")\nplt.savefig(\"./figures_png/\"+product_id+'_bar.png')\nplt.close()\n\n#udział poszczególnych rekomandacji w ogólnej liczbie opinii\nrecommendation = opinions[\"recommendation\"].value_counts()\nfig, ax = plt.subplots()\nrecommendation.plot.pie(label=\"\", autopct=\"%.1f%%\", colors=['mediumseagreen', 'coral'])\nax.set_title(\"Udział poszczególnych rekomandacji w ogólnej liczbie opinii\")\nplt.savefig(\"./figures_png/\"+product_id+'_pie.png')\nplt.close()\n\n#podstawowe startstyki\nstars_everage = opinions[\"stars\"].mean()\npros = opinions[\"pros\"].count()\ncons = opinions[\"cons\"].count()\npurchased = opinions[\"purchased\"].sum()\nprint(stars_everage, pros, cons, purchased)\n\nstars_purchased = pd.crosstab(opinions[\"stars\"],opinions[\"purchased\"])\nprint(stars_purchased)","sub_path":"app/analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"420692689","text":"'''\nutils.py: part of singularity package\n\nThe MIT License (MIT)\n\nCopyright (c) 2016-2017 Vanessa Sochat\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'''\n\nimport collections\nimport os\nimport re\nimport requests\n\nimport shutil\nimport json\nfrom singularity.logger import bot\nfrom singularity.utils import (\n write_json,\n write_file\n)\nimport sys\n\nimport subprocess\n\nimport tempfile\nimport zipfile\n\n\n############################################################################\n## FILE OPERATIONS #########################################################\n############################################################################\n\n\ndef zip_up(file_list,zip_name,output_folder=None):\n '''zip_up will zip up some list of files into a package (.zip)\n :param file_list: a list of files to include in the zip.\n :param output_folder: the output folder to create the zip in. If not \n :param zip_name: the name of the zipfile to return.\n specified, a temporary folder will be given.\n '''\n tmpdir = tempfile.mkdtemp()\n \n # Make a new archive \n output_zip = \"%s/%s\" %(tmpdir,zip_name)\n zf = zipfile.ZipFile(output_zip, \"w\", zipfile.ZIP_DEFLATED, allowZip64=True)\n\n # Write files to zip, depending on type\n for filename,content in file_list.items():\n\n bot.debug(\"Adding %s to package...\" %filename)\n\n # If it's the files list, move files into the archive\n if filename.lower() == \"files\":\n if not isinstance(content,list): \n content = [content]\n for copyfile in content:\n zf.write(copyfile,os.path.basename(copyfile))\n os.remove(copyfile)\n\n else:\n\n output_file = \"%s/%s\" %(tmpdir, filename)\n \n # If it's a list, write to new file, and save\n if isinstance(content,list):\n write_file(output_file,\"\\n\".join(content))\n \n # If it's a dict, save to json\n elif isinstance(content,dict):\n write_json(content,output_file)\n\n # If bytes, need to decode\n elif isinstance(content,bytes):\n write_file(output_file,content.decode('utf-8'))\n \n # String or other\n else: \n output_file = write_file(output_file,content)\n\n if os.path.exists(output_file):\n zf.write(output_file,filename)\n os.remove(output_file)\n\n # Close the zip file \n zf.close()\n\n if output_folder is not None:\n shutil.copyfile(output_zip,\"%s/%s\"%(output_folder,zip_name))\n shutil.rmtree(tmpdir)\n output_zip = \"%s/%s\"%(output_folder,zip_name)\n\n return output_zip\n\n\n\n############################################################################\n## OTHER MISC. #############################################################\n############################################################################\n\n\ndef get_container_contents(container=None,gets=None,split_delim=None,image_package=None):\n '''get_container_contents will return a list of folders and or files\n for a container. The environmental variable SINGULARITY_HUB being set\n means that container objects are referenced instead of packages\n :param container: the container to get content for\n :param gets: a list of file names to return, without parent folders\n :param split_delim: if defined, will split text by split delimiter\n :param image_package: if defined, user has provided an image_package\n '''\n from singularity.package import package, load_package\n\n if container == None and image_package == None:\n bot.error(\"You must define an image package or container.\")\n sys.exit(1)\n\n # Default returns are the list of files and folders\n if gets == None:\n gets = ['files.txt','folders.txt']\n if not isinstance(gets,list):\n gets = [gets]\n\n # We will look for everything in guts, then return it\n guts = dict()\n\n SINGULARITY_HUB = os.environ.get('SINGULARITY_HUB',\"False\")\n\n # Visualization deployed local or elsewhere\n if SINGULARITY_HUB == \"False\":\n tmpdir = tempfile.mkdtemp()\n if image_package == None:\n image_package = package(image_path=container,\n output_folder=tmpdir,\n remove_image=True)\n \n guts = load_package(image_package,get=gets)\n shutil.rmtree(tmpdir)\n\n # Visualization deployed by singularity hub\n else: \n \n # user has provided a package, but not a container\n if container == None:\n guts = load_package(image_package,get=gets)\n\n # user has provided a container, but not a package\n else:\n for sfile in container.files:\n for gut_key in gets: \n if os.path.basename(sfile['name']) == gut_key:\n if split_delim == None:\n guts[gut_key] = requests.get(sfile['mediaLink']).text\n else:\n guts[gut_key] = requests.get(sfile['mediaLink']).text.split(split_delim)\n\n return guts\n","sub_path":"singularity/package/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"281604479","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 6 20:16:56 2017\n\n@author: wuxiong\n\"\"\"\n#得到AER每一期issues的url\nimport requests\nfrom bs4 import BeautifulSoup\nfrom requests.exceptions import RequestException\nfrom multiprocessing import Pool\nimport re\nimport json\ndef get_onepage_url(url):\n try:\n user_agent = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36\"\n headers = {\"User-Agent\": user_agent}\n response = requests.get(url,headers=headers)\n if response.status_code==200:\n return response.content\n return None\n except RequestException:\n return None\ndef parse_one_page(url_html):\n soup = BeautifulSoup(url_html,'lxml')\n text = soup.find_all('div',style=\"margin-top:5px;\")\n pattern = re.compile('',re.S)\n new_results = re.findall(pattern,str(text))\n text = []\n print(new_results)\n print(len(new_results))\n url = 'https://www.aeaweb.org'\n for result in new_results:\n text.append( url + str(result))\n return text\ndef write_to_file(content):\n with open('AER_urls_only.txt','a') as f:\n f.write(content + '\\n')\n f.close()\n# def main(number):\ndef main(url_real):\n '''\n url = \"https://www.aeaweb.org/issues/\"\n url_real = url + str(number)\n html = get_onepage_url(url_real)\n urls = parse_one_page(html)\n for item in urls:\n write_to_file(item)\n '''\n html = get_onepage_url(url_real)\n for item in parse_one_page(html):\n write_to_file(item)\nif __name__==\"__main__\":\n url = \"https://www.aeaweb.org/journals/aer/issues\"\n #pool = Pool()\n #pool.map(main,[i for i in range(0,500,1)])\n main(url)\n print('Done')\n\n","sub_path":"Spider_AER_1_GetEveryAerIssuesUrls.py","file_name":"Spider_AER_1_GetEveryAerIssuesUrls.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"334862145","text":"import numpy as np\nimport os\n\nfpath = ''\nfile_list = os.listdir(fpath)\nras_files = [f[:-3] for f in file_list if f[-3:] == 'ras']\nxye_files = [f[:-3] for f in file_list if f[-3:] == 'xye']\nras_notxye = [rf for rf in ras_files if rf not in xye_files]\nsizes = [(os.stat(r + 'ras')).st_size for r in ras_notxye]\nras_todo = [rn for i, rn in enumerate(ras_notxye) if sizes[i] > 0]\n\nfor rf in ras_todo:\n fname = rf + 'ras'\n new_fname = fname[:-3] + 'xye'\n data = np.genfromtxt(fname, comments='*', usecols=[0, 1])\n new_data = np.column_stack((data, data[:, 1]**0.5))\n np.savetxt(new_fname, new_data)\n print(f'Written {new_fname}')\n\n","sub_path":"ras_to_xye.py","file_name":"ras_to_xye.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"543335770","text":"import json\n\nimport numpy as np\n\nfrom sklearn.preprocessing import MinMaxScaler\n\nsc = MinMaxScaler(feature_range=(-.5, .5))\n\n\ndef noise_norm():\n r = corpus_normus()\n k, v = zip(*r.items())\n v = sc.fit_transform(np.asarray(v).reshape(-1, 1))\n v = [_.tolist()[0] for _ in v]\n return dict(zip(k, v))\n # s = sum(r.values())\n # return {k: v / s for k, v in r.items()}\n\n\ndef corpus_normus():\n r = json.load(open('./noise_200.json'))\n return {k: v - r['corpus'] for k, v in r.items()}\n\n\nprint(noise_norm())\n# print(corpus_normus())\n","sub_path":"get_process_data/calc_noise_ratio.py","file_name":"calc_noise_ratio.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"611657800","text":"#!/usr/bin/env python3\nimport time\nimport re\nimport sys\nimport textwrap\n\nimport mailsh\nimport mailsh.mail\n\n\n@mailsh.register_command(\"head\", dry_run_safe=True)\ndef head_command(mdc, inputs, argv):\n \"\"\"\n Usage: head [COUNT]\n\n Return, at most, the specified number of messages or lines. When\n unspecified, this defaults to 10.\n \"\"\"\n if argv:\n if len(argv) > 1:\n raise ValueError(\"Command expects one argumnet or none.\")\n try:\n limit = int(argv[0])\n except ValueError:\n raise ValueError(\"%r is not a number.\" % (argv[0],))\n else:\n limit = 10\n\n for index, item in enumerate(inputs):\n if index >= limit:\n break\n yield item\n\n\n@mailsh.register_command(\"invert\", dry_run_safe=True)\ndef invert_command(mdc, inputs, argv):\n inputs = set(inputs)\n for message in mdc.listmessages(poll_new=False):\n if message not in inputs:\n yield message\n\n\n@mailsh.register_command(\"help\", dry_run_safe=True)\ndef help_command(mdc, inputs, argv):\n \"\"\"\n Usage: help [COMMAND]...\n\n Display documentation for interpreter commands.\n \"\"\"\n if argv:\n for command in argv or (\"help\",):\n yield command + \":\"\n if command in mailsh.runtime.Interpreter.commands:\n function = mailsh.runtime.Interpreter.commands[command]\n docstring = function.__doc__ or \"This command is undocumented.\"\n dedented = textwrap.dedent(docstring)\n formatted = dedented.replace(\"\\n\", \"\\n \").strip()\n else:\n formatted = \" Unrecognized command.\"\n\n yield formatted\n else:\n yield \"Valid commands:\"\n for command in sorted(mailsh.runtime.Interpreter.commands):\n yield \"- \" + command\n\n\n@mailsh.register_command(\"count\", dry_run_safe=True)\ndef count_command(mdc, inputs, argv):\n \"\"\"\n Usage: count\n\n Display number of items piped into command.\n \"\"\"\n yield len(tuple(inputs))\n\n\n@mailsh.register_command(\"cd\")\ndef cd_command(mdc, inputs, argv):\n \"\"\"\n Usage: cd FOLDER\n\n Change current working directory.\n \"\"\"\n if not argv:\n raise Exception(\"Expected argument.\")\n elif len(argv) != 1:\n raise Exception(\"Too many arguments passed.\")\n else:\n mdc.chdir(argv[0])\n\n\n@mailsh.register_command(\"dirs\", dry_run_safe=True)\ndef dirs_command(mdc, inputs, argv):\n \"\"\"\n Usages: dirs [FOLDER]\n\n List directories in folder. If FOLDER is unspecified, the current working\n directory is used.\n \"\"\"\n yield from mdc.listdirs()\n\n\n@mailsh.register_command(\"pwd\", dry_run_safe=True)\ndef pwd_command(mdc, inputs, argv):\n \"\"\"\n Usage: pwd\n\n Display current (present) working directory.\n \"\"\"\n yield mdc.cwd\n\n\n@mailsh.register_filter(\"grep\", dry_run_safe=True)\ndef grep_filter(mdc, value, argv):\n if argv:\n expression = \"|\".join(argv)\n else:\n return True\n\n if isinstance(value, mailsh.mail.Message):\n value = str(value.headers)\n\n return bool(re.search(expression, value, re.I | re.U))\n\n\ndef message_date(message):\n date = message.headers.get(\"date\", \"\")\n timestamps = mailsh.mail.extract_timestamps(date)\n if timestamps:\n return timestamps[0]\n else:\n return 0\n\n\ndef time_received(message):\n received = message.headers.get_all(\"received\", tuple())\n timestamps = mailsh.mail.extract_timestamps(\" \".join(received))\n if timestamps:\n return max(timestamps)\n else:\n return 0\n\n\n@mailsh.register_command(\"sort\", dry_run_safe=True)\ndef sort_command(mdc, inputs, argv):\n if not argv:\n raise Exception(\"Expected argument.\")\n elif len(argv) != 1:\n raise Exception(\"Too many arguments passed.\")\n else:\n field = argv[0].lower()\n\n if field == \"date\":\n key = message_date\n elif field == \"received\":\n key = time_received\n else:\n key = lambda m: m.headers.get(field, \"\")\n\n yield from sorted(inputs, key=key, reverse=True)\n\n\n@mailsh.register_command(\"pick\")\ndef pick_command(mdc, inputs, argv):\n choices = set(map(int, argv))\n if choices:\n for i, item in enumerate(inputs, 1):\n if i in choices:\n yield item\n else:\n yield from inputs\n","sub_path":"src/runcontrol.py","file_name":"runcontrol.py","file_ext":"py","file_size_in_byte":4304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"161019393","text":"#!/usr/bin/env python3.7\n# -*- coding: utf-8 -*-\n\n\"\"\"\nAdd a description ....\n\n\"\"\"\n\n__author__ = \"Dylan Hamel\"\n__maintainer__ = \"Dylan Hamel\"\n__version__ = \"1.0\"\n__email__ = \"dylan.hamel@protonmail.com\"\n__status__ = \"Prototype\"\n__copyright__ = \"Copyright 2019\"\n\n########################################################################################################################\n#\n# HEADERS\n#\n\nERROR_HEADER = \"Error import [mtu_gets.py]\"\nHEADER_GET = \"[netests - get_mtu]\"\n\n########################################################################################################################\n#\n# Import Library\n#\n\ntry:\n from const.constants import *\nexcept ImportError as importError:\n print(f\"{ERROR_HEADER} const.constants\")\n exit(EXIT_FAILURE)\n print(importError)\n\ntry:\n from functions.mtu.mtu_converters import _napalm_mtu_converter\n from functions.mtu.mtu_converters import _ios_mtu_converter\n from functions.mtu.mtu_converters import _nexus_mtu_converter\n from functions.mtu.mtu_converters import _cumulus_mtu_converter\n from functions.mtu.mtu_converters import _iosxr_mtu_converter\n from functions.mtu.mtu_converters import _arista_mtu_converter\n from functions.mtu.mtu_converters import _juniper_mtu_converter\n from functions.mtu.mtu_converters import _extreme_vsp_mtu_converter\nexcept ImportError as importError:\n print(f\"{ERROR_HEADER} functions.mtu.mtu_converters\")\n print(importError)\n exit(EXIT_FAILURE)\n\ntry:\n from nornir.core import Nornir\n # To use advanced filters\n from nornir.core.filter import F\n # To execute netmiko commands\n from nornir.plugins.tasks.networking import netmiko_send_command\n # To execute napalm get config\n from nornir.plugins.tasks.networking import napalm_get\n # To print task results\n from nornir.plugins.functions.text import print_result\nexcept ImportError as importError:\n print(f\"{ERROR_HEADER} nornir\")\n print(importError)\n exit(EXIT_FAILURE)\n\ntry:\n import json\nexcept ImportError as importError:\n print(f\"{ERROR_HEADER} json\")\n exit(EXIT_FAILURE)\n print(importError)\n\ntry:\n import textfsm\nexcept ImportError as importError:\n print(f\"{ERROR_HEADER} textfsm\")\n exit(EXIT_FAILURE)\n print(importError)\n\n########################################################################################################################\n#\n# Functions\n#\ndef get_mtu(nr: Nornir, filters={}, level=None, own_vars={}):\n\n devices = nr.filter()\n\n if len(devices.inventory.hosts) == 0:\n raise Exception(f\"[{HEADER_GET}] no device selected.\")\n\t\t\n data = devices.run(\n task=generic_mtu_get,\n on_failed=True,\n num_workers=10\n )\n #print_result(data)\n\n# ----------------------------------------------------------------------------------------------------------------------\n#\n# Generic function\n#\ndef generic_mtu_get(task):\n\n use_ssh = False\n\n if NEXUS_PLATEFORM_NAME in task.host.platform or ARISTA_PLATEFORM_NAME in task.host.platform or \\\n CISCO_IOSXR_PLATEFORM_NAME in task.host.platform or CISCO_IOS_PLATEFORM_NAME in task.host.platform or \\\n JUNOS_PLATEFORM_NAME in task.host.platform:\n if 'connexion' in task.host.keys():\n if task.host.data.get('connexion', NOT_SET) == 'ssh' or task.host.get('connexion', NOT_SET):\n use_ssh = True\n\n if task.host.platform == CUMULUS_PLATEFORM_NAME:\n _cumulus_get_mtu(task)\n\n elif task.host.platform == EXTREME_PLATEFORM_NAME:\n _extreme_vsp_get_mtu(task)\n\n elif task.host.platform in NAPALM_COMPATIBLE_PLATEFORM :\n if use_ssh and NEXUS_PLATEFORM_NAME == task.host.platform:\n _nexus_get_mtu(task)\n\n elif use_ssh and CISCO_IOS_PLATEFORM_NAME == task.host.platform:\n _ios_get_mtu(task)\n\n elif use_ssh and CISCO_IOSXR_PLATEFORM_NAME == task.host.platform:\n _iosxr_get_mtu(task)\n\n elif use_ssh and ARISTA_PLATEFORM_NAME == task.host.platform:\n _arista_get_mtu(task)\n \n elif use_ssh and JUNOS_PLATEFORM_NAME == task.host.platform:\n _juniper_get_mtu(task)\n\n else:\n _generic_mtu_napalm(task)\n\n else:\n # RAISE EXCEPTIONS\n print(f\"{HEADER_GET} No plateform selected for {task.host.name}...\")\n\n# ----------------------------------------------------------------------------------------------------------------------\n#\n# Generic Napalm\n#\ndef _generic_mtu_napalm(task):\n pass\n \"\"\"\n print(f\"Start _generic_mtu_napalm with {task.host.name} \")\n\n output = task.run(\n name=f\"NAPALM get_interfaces {task.host.platform}\",\n task=napalm_get,\n getters=[\"interfaces\"],\n retrieve=\"all\"\n )\n # print(output.result)\n\n if output.result != \"\":\n bgp_sessions = _napalm_mtu_converter(\n task.host.name,\n output.result\n )\n\n task.host[MTU_DATA_HOST_KEY] = bgp_sessions\n \"\"\"\n# ----------------------------------------------------------------------------------------------------------------------\n#\n# Cumulus Networks\n#\ndef _cumulus_get_mtu(task):\n\n output = task.run(\n name=f\"{CUMULUS_GET_MTU}\",\n task=netmiko_send_command,\n command_string=CUMULUS_GET_MTU\n )\n # print_result(output)\n\n mtu_interfaces = _cumulus_mtu_converter(\n hostname=task.host.name,\n cmd_output=json.loads(output.result)\n )\n\n task.host[MTU_DATA_HOST_KEY] = mtu_interfaces\n\n# ----------------------------------------------------------------------------------------------------------------------\n#\n# Cisco Nexus (NXOS)\n#\ndef _nexus_get_mtu(task):\n\n output = task.run(\n name=f\"{NEXUS_GET_MTU}\",\n task=netmiko_send_command,\n command_string=NEXUS_GET_MTU\n )\n # print_result(output)\n\n mtu_interfaces = _nexus_mtu_converter(\n hostname=task.host.name,\n cmd_output=json.loads(output.result)\n )\n\n task.host[MTU_DATA_HOST_KEY] = mtu_interfaces\n\t\n# ----------------------------------------------------------------------------------------------------------------------\n#\n# Cisco IOS\n#\ndef _ios_get_mtu(task):\n\n output = task.run(\n name=f\"{IOS_GET_MTU}\",\n task=netmiko_send_command,\n command_string=IOS_GET_MTU\n )\n #print_result(output)\n\n if output.result != \"\":\n template = open(\n f\"{TEXTFSM_PATH}cisco_ios_show_interface.textfsm\")\n results_template = textfsm.TextFSM(template)\n \n parsed_results = results_template.ParseText(output.result)\n # Result Example =\n #\n #\n # type = list() of list()\n\n mtu_interfaces = _ios_mtu_converter(\n hostname=task.host.name,\n cmd_output=parsed_results\n )\n\n task.host[MTU_DATA_HOST_KEY] = mtu_interfaces\n\n\n# ----------------------------------------------------------------------------------------------------------------------\n#\n# Cisco IOSXR\n#\ndef _iosxr_get_mtu(task):\n pass\n\n# ----------------------------------------------------------------------------------------------------------------------\n#\n# Arista vEOS\n#\ndef _arista_get_mtu(task):\n\n output = task.run(\n name=f\"{ARISTA_GET_MTU}\",\n task=netmiko_send_command,\n command_string=ARISTA_GET_MTU\n )\n # print_result(output)\n\n mtu_interfaces = _arista_mtu_converter(\n hostname=task.host.name,\n cmd_output=json.loads(output.result)\n )\n\n task.host[MTU_DATA_HOST_KEY] = mtu_interfaces\n\n# ----------------------------------------------------------------------------------------------------------------------\n#\n# Juniper Networks\n#\ndef _juniper_get_mtu(task):\n\n output = task.run(\n name=f\"{JUNOS_GET_MTU}\",\n task=netmiko_send_command,\n command_string=JUNOS_GET_MTU\n )\n # print_result(output)\n\n mtu_interfaces = _juniper_mtu_converter(\n hostname=task.host.name,\n cmd_output=json.loads(output.result)\n )\n\n task.host[MTU_DATA_HOST_KEY] = mtu_interfaces\n\t\n# ----------------------------------------------------------------------------------------------------------------------\n#\n# Extreme Networks\n#\ndef _extreme_vsp_get_mtu(task):\n\n output = task.run(\n name=f\"{EXTREME_VSP_GET_MTU}\",\n task=netmiko_send_command,\n command_string=EXTREME_VSP_GET_MTU,\n enable=True\n )\n # print_result(output)\n\n if output.result != \"\":\n template = open(\n f\"{TEXTFSM_PATH}extreme_vsp_show_interfaces_gigabitethernet.textfsm\")\n results_template = textfsm.TextFSM(template)\n\n parsed_results = results_template.ParseText(output.result)\n # Result Example =\n #\n #\n # type = list() of list()\n\n mtu_interfaces = _extreme_vsp_mtu_converter(\n hostname=task.host.name,\n cmd_output=parsed_results\n )\n\n task.host[MTU_DATA_HOST_KEY] = mtu_interfaces\n \n# ----------------------------------------------------------------------------------------------------------------------\n#\n# Next Device\n#\n","sub_path":"functions/mtu/mtu_get.py","file_name":"mtu_get.py","file_ext":"py","file_size_in_byte":9092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"504843632","text":"from io import BytesIO\n\nimport numpy\nimport networkx as nx\n\nimport matplotlib as mpl\n\nmpl.use(\"svg\")\nfrom matplotlib import pyplot as plt\n\n\ndef render(\n g, request_nodes, subgraph_nodes, xs=None, ys=None, node_size=None, zoom=None\n):\n if xs is None:\n xs = 1\n if ys is None:\n ys = 1\n if node_size is None:\n node_size = 10\n if zoom is None:\n zoom = 1\n\n ns = numpy.pi * ((node_size * zoom) ** 2) / 4\n\n fig, ax = plt.subplots(figsize=(8 * zoom, 8 * zoom))\n\n ax.set_aspect(float(ys) / float(xs))\n ax.set_xticks([])\n ax.set_yticks([])\n ax.axis(\"off\")\n\n pos = nx.nx_pydot.pydot_layout(g, prog=\"dot\")\n\n sgs = [[n[\"id\"] for n in ng[\"nodes\"]] for ng in subgraph_nodes]\n req = [n[\"id\"] for n in request_nodes]\n\n basenodes = nx.draw_networkx(\n g,\n pos=pos,\n ax=ax,\n node_size=ns,\n node_color=\"lightsteelblue\",\n with_labels=True,\n font_size=5 * zoom,\n label=\"all nodes\",\n )\n\n for i, _nodes in enumerate(sgs):\n subgraphs = nx.draw_networkx_nodes(\n g.subgraph(_nodes),\n ax=ax,\n pos=pos,\n node_size=ns,\n node_color=f\"C{i}\",\n with_labels=True,\n font_size=5 * zoom,\n label=f\"subgraph {i+1}\",\n )\n\n selection = nx.draw_networkx_nodes(\n g.subgraph(req),\n ax=ax,\n pos=pos,\n node_shape=\"o\",\n node_color=\"none\",\n node_size=ns * 2,\n with_labels=False,\n label=\"requested nodes\",\n )\n\n selection.set_edgecolor(\"firebrick\")\n selection.set_linewidths(1.5)\n\n ax.legend(loc=\"upper center\", ncol=4, bbox_to_anchor=(0.5, -0.05))\n ax.set_title(\"User requested nodes: \" + \", \".join(req))\n\n return fig\n\n\ndef fig_to_image(fig):\n img = BytesIO()\n fig.savefig(img, bbox_inches=\"tight\")\n img.seek(0)\n\n return img\n","sub_path":"nereid/nereid/network/render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"552630821","text":"from __future__ import absolute_import\nimport types\nimport re\nimport cgi\nfrom functools import wraps\nimport datetime\n\nfrom decorators import FuncDecorator\n\nfrom ..exception import CallError, AccessDenied\nfrom . import auth\nfrom .base import TargetDecorator\n\n\nclass ratelimit(TargetDecorator):\n \"\"\"Rate limit a certain endpoint\n\n example --\n\n from endpoints import Controller\n from endpoints.decorators import ratelimit\n\n class Default(Controller):\n @ratelimit(10, 3600) # you can make 10 requests per hour\n def GET(self):\n return \"hello world\"\n \"\"\"\n def target(self, request, key, limit, ttl):\n \"\"\"this is what is run to check if requests should be throttled\n\n you should override this method if you want to customize the implementation\n\n request -- Request -- the request instance\n key -- string -- the unique key for the endpoint\n limit -- int -- max requests that should be received in ttl\n ttl -- int -- how many seconds they should be throttled for (3600 = 1 hour)\n \"\"\"\n now = datetime.datetime.utcnow()\n count = 1\n calls = getattr(self, \"_calls\", {})\n if not calls:\n calls = {}\n\n if key in calls:\n count = calls[key][\"count\"] + 1\n if count > limit:\n td = now - calls[key][\"date\"]\n if td.total_seconds() < ttl:\n raise ValueError(\n \"Please wait {} seconds to make another request\".format(ttl - td.seconds)\n )\n\n else:\n count = 1 # we are starting over\n\n calls[key] = {\n \"count\": count,\n \"date\": now,\n }\n\n self._calls = calls\n return True\n\n def normalize_target_params(self, request, controller_args, controller_kwargs):\n kwargs = {\n \"request\": request,\n \"key\": self.normalize_key(\n request,\n controller_args=controller_args,\n controller_kwargs=controller_kwargs,\n ),\n \"limit\": self.limit,\n \"ttl\": self.ttl,\n }\n return [], kwargs\n\n def normalize_key(self, request, *args, **kwargs):\n \"\"\"if you don't want to override target but do want to customize the key,\n override this method, this is mainly for convenience of child classes\"\"\"\n return \"{}.{}\".format(request.ip, request.path)\n\n def handle_error(self, e):\n \"\"\"all exceptions should generate 429 responses\"\"\"\n raise CallError(429, e.message)\n\n def decorate(self, func, limit, ttl, *anoop, **kwnoop):\n \"\"\"see target for an explanation of limit and ttl\"\"\"\n self.limit = int(limit)\n self.ttl = int(ttl)\n return super(ratelimit, self).decorate(func, target=None, *anoop, **kwnoop)\n\n\nclass httpcache(FuncDecorator):\n \"\"\"\n sets the cache headers so the response can be cached by the client\n\n link -- https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching\n\n ttl -- integer -- how many seconds to have the client cache the request\n \"\"\"\n def decorate(self, func, ttl):\n def decorated(self, *args, **kwargs):\n self.response.add_headers({\n \"Cache-Control\": \"max-age={}\".format(ttl),\n })\n return func(self, *args, **kwargs)\n # TODO -- figure out how to set ETag\n #if not self.response.has_header('ETag')\n\n return decorated\n\n\nclass nohttpcache(FuncDecorator):\n \"\"\"\n sets all the no cache headers so the response won't be cached by the client\n \"\"\"\n def decorate(self, func):\n def decorated(self, *args, **kwargs):\n self.response.add_headers({\n \"Cache-Control\": \"no-cache, no-store, must-revalidate\",\n \"Pragma\": \"no-cache\", \n \"Expires\": \"0\"\n })\n return func(self, *args, **kwargs)\n\n return decorated\n\n\nclass _property(object):\n \"\"\"A memoized @property that is only evaluated once, and then stored at _property\n and retrieved from there unless deleted, in which case this would be called\n again and stored in _property again.\n\n See http://www.reddit.com/r/Python/comments/ejp25/cached_property_decorator_that_is_memory_friendly/\n see https://docs.python.org/2/howto/descriptor.html\n see http://stackoverflow.com/questions/17330160/python-how-does-the-property-decorator-work\n see https://docs.python.org/2/howto/descriptor.html\n\n options you can use to further customize the property\n\n read_only -- boolean (default False) -- set to de-activate set and del methods\n allow_empty -- boolean (default True) -- False to not cache empty values (eg, None, \"\")\n setter -- boolean -- set this to true if you want the decorated method to act as the setter\n instead of the getter, this will cause a default getter to be created that just returns\n _name (you should set self._name in your setter)\n deleter -- boolean -- same as setter, set to True to have the method act as the deleter\n \"\"\"\n def __init__(self, *args, **kwargs):\n self.allow_empty = kwargs.get('allow_empty', True)\n self.has_setter = kwargs.get('setter', False)\n self.has_deleter = kwargs.get('deleter', False)\n\n has_no_write = not self.has_setter and not self.has_deleter\n self.has_getter = kwargs.get('getter', has_no_write)\n\n # mutually exclusive to having defined a setter or deleter\n self.read_only = kwargs.get('read_only', False) and has_no_write\n\n if args:\n if isinstance(args[0], bool):\n self.read_only = args[0]\n\n else:\n # support _property(fget, fset, fdel, desc) also\n total_args = len(args)\n self.set_method(args[0])\n if total_args > 1:\n self.setter(args[1])\n if total_args > 2:\n self.deleter(args[2])\n if total_args > 3:\n self.__doc__ = args[3]\n\n # support _property(fget=getter, fset=setter, fdel=deleter, doc=\"\")\n if \"fget\" in kwargs:\n self.set_method(kwargs[\"fget\"])\n if \"fset\" in kwargs:\n self.setter(kwargs[\"fset\"])\n if \"fdel\" in kwargs:\n self.deleter(kwargs[\"fdel\"])\n if \"doc\" in kwargs:\n self.__doc__ = kwargs[\"doc\"]\n\n def set_method(self, method):\n self.fget = method if self.has_getter else self.default_get\n self.fset = method if self.has_setter else self.default_set\n self.fdel = method if self.has_deleter else self.default_del\n self.__doc__ = method.__doc__\n self.__name__ = method.__name__\n self.name = '_{}'.format(self.__name__)\n\n def __call__(self, *args, **kwargs):\n if args:\n self.set_method(args[0])\n\n return self\n\n def __get__(self, instance, cls):\n # return the cached value if it exists\n val = None\n name = self.name\n if name in instance.__dict__:\n val = instance.__dict__[name]\n\n else:\n try:\n val = self.fget(instance)\n if val or self.allow_empty:\n # We don't do fset here because that causes unexpected bahavior\n # if you ever override the setter, causing the setter to be fired\n # every time the getter is called, which confused me for about\n # an hour before I figured out what was happening\n self.default_set(instance, val)\n\n except Exception:\n # make sure no value gets set no matter what\n instance.__dict__.pop(name, None)\n raise\n\n return val\n\n def default_get(self, instance):\n try:\n return instance.__dict__[self.name]\n except KeyError:\n raise AttributeError(\"can't get attribute {}\".format(self.__name__))\n\n def default_set(self, instance, val):\n instance.__dict__[self.name] = val\n\n def __set__(self, instance, val):\n if self.read_only:\n raise AttributeError(\"can't set attribute {}\".format(self.__name__))\n\n if val or self.allow_empty:\n self.fset(instance, val)\n\n def default_del(self, instance):\n instance.__dict__.pop(self.name, None)\n\n def __delete__(self, instance, *args):\n if self.read_only:\n raise AttributeError(\"can't delete attribute {}\".format(self.__name__))\n\n self.fdel(instance)\n\n def getter(self, fget):\n self.fget = fget\n self.has_getter = True\n return self\n\n def setter(self, fset):\n self.fset = fset\n self.has_setter = True\n return self\n\n def deleter(self, fdel):\n self.fdel = fdel\n self.has_deleter = True\n return self\n\n\nclass _propertyset(_property):\n def set_method(self, method):\n super(_propertyset, self).set_method(method)\n\n # switch get and set since this method is \n self.fget = self.default_get\n self.fset = method\n\n def set_method(self, method):\n self.fget = method\n self.fset = self.default_set\n self.fdel = self.default_del\n self.__doc__ = method.__doc__\n self.__name__ = method.__name__\n self.name = '_{}'.format(self.__name__)\n\n\n\nclass param(object):\n \"\"\"\n decorator to allow setting certain expected query/body values and options\n\n this tries to be as similar to python's built-in argparse as possible\n\n This checks both POST and GET query args, if you would like to only check POST,\n use post_param, if you only want to check GET, then use get_param\n\n example --\n\n @decorators.param('name', type=int, nargs='+', action='store_list')\n\n name -- string -- the name of the query_param\n **flags -- dict\n type -- type -- a python type like int or float\n action -- string --\n store -- default\n store_false -- set if you want default to be true, and false if param is\n passed in\n store_true -- opposite of store_false\n store_list -- set to have a value like 1,2,3 be blown up to ['1', '2', '3']\n append -- if multiple param values should be turned into an array\n eg, foo=1&foo=2 would become foo=[1, 2]\n append_list -- it's store_list + append, so foo=1&foo=2,3 would be foo=[1, 2, 3]\n default -- mixed -- the value that should be set if query param isn't there, if this is\n callable (eg, time.time or datetime.utcnow) then it will be called every time the\n decorated method is called\n required -- boolean -- True if param is required, default is true\n choices -- set() -- a set of values to be in tested against (eg, val in choices)\n matches -- regex -- TODO -- a regular expression that the value needs to match\n allow_empty -- boolean -- True allows values like False, 0, '' through,\n default False, this will also let through any empty value that was set\n via the default flag\n max_size -- int -- the maximum size of the param\n min_size -- int -- the minimum size of the param\n regex -- regexObject -- if you would like the param to be validated with a regular\n exception, uses the re.search() method\n\n raises -- \n CallError -- with 400 status code on any param validation failures\n \"\"\"\n def __init__(self, *names, **flags):\n self.name = names[0]\n self.names = names\n self.flags = flags\n\n def normalize_default(self, default):\n ret = default\n if isinstance(default, dict):\n ret = dict(default)\n\n elif isinstance(default, list):\n ret = list(default)\n\n return ret\n\n def find_param(self, names, required, default, request, args, kwargs):\n \"\"\"actually try to retrieve names key from params dict\"\"\"\n val = default\n found_name = ''\n for name in names:\n if name in kwargs:\n val = kwargs[name]\n found_name = name\n break\n\n if not found_name and required:\n raise CallError(400, \"required param {} was not present\".format(self.name))\n\n return found_name, val\n\n def normalize_param(self, slf, args, kwargs):\n \"\"\"this is where all the magic happens, this will try and find the param and\n put its value in kwargs if it has a default and stuff\"\"\"\n flags = self.flags\n name = self.name\n dest_name = flags.get('dest', name)\n ptype = flags.get('type', None)\n paction = flags.get('action', 'store')\n if paction == 'store_false':\n flags['default'] = True \n ptype = bool\n\n elif paction == 'store_true':\n flags['default'] = False\n ptype = bool\n\n pdefault = self.normalize_default(flags.get('default', None))\n if callable(pdefault): pdefault = pdefault()\n\n prequired = False if 'default' in flags else flags.get('required', True)\n pchoices = flags.get('choices', None)\n allow_empty = flags.get('allow_empty', False)\n min_size = flags.get('min_size', None)\n max_size = flags.get('max_size', None)\n regex = flags.get('regex', None)\n\n normalize = True\n request = slf.request\n found_name, val = self.find_param(self.names, prequired, pdefault, request, args, kwargs)\n if found_name:\n kwargs.pop(found_name)\n else:\n normalize = 'default' in flags\n\n if normalize:\n if paction in set(['store_list']):\n if isinstance(val, list) and len(val) > 1:\n raise CallError(400, \"too many values for param {}\".format(name))\n\n if isinstance(val, basestring):\n val = val.split(',')\n\n else:\n val = list(val)\n\n elif paction in set(['append', 'append_list']):\n if not isinstance(val, list):\n val = [val]\n\n if paction == 'append_list':\n vs = []\n for v in val:\n if isinstance(v, basestring):\n vs.extend(v.split(','))\n else:\n vs.append(v)\n\n val = vs\n\n else:\n if paction not in set(['store', 'store_false', 'store_true']):\n raise ValueError('unknown param action {}'.format(paction))\n\n if ptype:\n if isinstance(val, list) and ptype != list:\n val = map(ptype, val)\n\n else:\n if isinstance(ptype, type):\n if issubclass(ptype, bool):\n if val in set(['true', 'True', '1']):\n val = True\n elif val in set(['false', 'False', '0']):\n val = False\n else:\n val = ptype(val)\n\n elif issubclass(ptype, str):\n charset = request.charset\n if charset and isinstance(val, unicode):\n val = val.encode(charset)\n else:\n val = ptype(val)\n\n else:\n val = ptype(val)\n\n else:\n val = ptype(val)\n\n if pchoices:\n if val not in pchoices:\n raise CallError(400, \"param {} with value {} not in choices {}\".format(name, val, pchoices))\n\n # at some point this if statement is just going to be too ridiculous\n # FieldStorage check is because of this bug https://bugs.python.org/issue19097\n if not allow_empty and val is not False and not val and not isinstance(val, cgi.FieldStorage):\n if 'default' not in flags:\n raise CallError(400, \"param {} was empty\".format(name))\n\n if min_size is not None:\n failed = False\n if isinstance(val, (int, float)):\n if val < min_size: failed = True\n else:\n if len(val) < min_size: failed = True\n\n if failed:\n raise CallError(400, \"param {} was smaller than {}\".format(name, min_size))\n\n if max_size is not None:\n failed = False\n if isinstance(val, (int, float)):\n if val > max_size: failed = True\n else:\n if len(val) > max_size: failed = True\n\n if failed:\n raise CallError(400, \"param {} was bigger than {}\".format(name, max_size))\n\n if regex:\n failed = False\n if isinstance(regex, basestring):\n if not re.search(regex, val): failed = True\n else:\n if not regex.search(val): failed = True\n\n if failed:\n raise CallError(400, \"param {} failed regex check\".format(name))\n\n kwargs[dest_name] = val\n\n return slf, args, kwargs\n\n def __call__(slf, func):\n position = func.__dict__.get('param_position', 0)\n @wraps(func)\n def wrapper(self, *args, **kwargs):\n slf.position = wrapper.__dict__.get('param_position', 0)\n self, args, kwargs = slf.normalize_param(self, args, kwargs)\n return func(self, *args, **kwargs)\n\n position = wrapper.__dict__.setdefault('param_position', position + 1)\n return wrapper\n\n\nclass get_param(param):\n \"\"\"same as param, but only checks GET params\"\"\"\n def find_param(self, names, required, default, request, args, kwargs):\n try:\n return super(get_param, self).find_param(\n names,\n required,\n default,\n request,\n args,\n request.query_kwargs\n )\n\n except CallError:\n raise CallError(400, \"required param {} was not present in GET params\".format(self.name))\n\n\nclass post_param(param):\n \"\"\"same as param but only checks POST params\"\"\"\n def find_param(self, names, required, default, request, args, kwargs):\n try:\n return super(post_param, self).find_param(\n names,\n required,\n default,\n request,\n args,\n request.body_kwargs\n )\n\n except CallError:\n raise CallError(400, \"required param {} was not present in POST params\".format(self.name))\n\n\nclass require_params(object):\n \"\"\"\n if you want to make sure that certain params are present in the request\n\n If the request is a GET request, then the params checked are in the query string,\n if the method is POST, PUT, then the params checked are in the body\n\n example --\n # make request fail if foo and bar aren't in the request body\n @require_params(\"foo\", \"bar\")\n def POST(self, *args, **kwargs):\n pass\n\n **param_options -- dict\n allow_empty -- boolean -- True if passed in param names can have values\n that evaluate to False (like 0 or \"\")\n \"\"\"\n def __init__(self, *req_param_names, **param_options):\n self.req_param_names = req_param_names\n self.param_options = param_options\n\n def __call__(slf, func):\n param_options = slf.param_options\n req_param_names = slf.req_param_names\n not_empty = not param_options.pop('allow_empty', False)\n\n @wraps(func)\n def decorated(self, *args, **kwargs):\n for req_param_name in req_param_names:\n if req_param_name not in kwargs:\n raise CallError(400, \"required param {} was not present\".format(req_param_name))\n\n if not_empty and not kwargs[req_param_name]:\n raise CallError(400, \"required param {} was empty\".format(req_param_name))\n\n return func(self, *args, **kwargs)\n\n return decorated\n\n","sub_path":"endpoints/decorators/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":20427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"573060564","text":"import matplotlib.pyplot as plt\nfrom tensorflow import keras\nimport numpy as np\nimage_number = 23 \ndata = keras.datasets.mnist\n(train_images, train_labels), (test_images, test_labels) = data.load_data()\nmodel = keras.Sequential([\n keras.layers.Flatten(input_shape=(28, 28)),\n keras.layers.Dense(128, activation=\"relu\"),\n keras.layers.Dense(10, activation=\"softmax\")\n])\nmodel.compile(optimizer=\"adam\", loss=\"sparse_categorical_crossentropy\", metrics=[\"accuracy\"])\nmodel.fit(train_images, train_labels, epochs=1)\nloss, acc = model.evaluate(test_images, test_labels)\nprint(f\"{acc*100}% accuracy\")\npredictions = model.predict(test_images)\nprint(np.argmax(predictions[image_number]))\nplt.imshow(test_images[image_number].reshape(28, 28), cmap='gray')\nplt.show()\n\n","sub_path":"numbers_tensorflow.py","file_name":"numbers_tensorflow.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"601592895","text":"import os\nimport six\n\nimport traitlets\nimport itk\nimport numpy as np\ntry:\n import zstandard as zstd\nexcept ImportError:\n import zstd\ntry:\n from functools import reduce\nexcept ImportError:\n pass\n\ndef is_arraylike(arr):\n return hasattr(arr, 'shape') and \\\n hasattr(arr, 'dtype') and \\\n hasattr(arr, '__array__') and \\\n hasattr(arr, 'ndim')\n\nhave_imglyb = False\ntry:\n import imglyb\n have_imglyb = True\nexcept ImportError:\n pass\nhave_vtk = False\ntry:\n import vtk\n have_vtk = True\nexcept ImportError:\n pass\n\nclass ITKImage(traitlets.TraitType):\n \"\"\"A trait type holding an itk.Image object\"\"\"\n\n info_text = 'An N-dimensional, potentially multi-component, scientific ' + \\\n 'image with origin, spacing, and direction metadata'\n\n # Hold a reference to the source object to use with shallow views\n _source_object = None\n\n def validate(self, obj, value):\n if is_arraylike(value):\n array = np.asarray(value)\n self._source_object = array\n if array.flags['OWNDATA']:\n image_from_array = itk.GetImageViewFromArray(array)\n else:\n image_from_array = itk.GetImageFromArray(array)\n return image_from_array\n elif have_vtk and isinstance(value, vtk.vtkImageData):\n from vtk.util import numpy_support as vtk_numpy_support\n array = vtk_numpy_support.vtk_to_numpy(value.GetPointData().GetScalars())\n array.shape = tuple(value.GetDimensions())[::-1]\n self._source_object = array\n image_from_array = itk.GetImageViewFromArray(array)\n image_from_array.SetSpacing(value.GetSpacing())\n image_from_array.SetOrigin(value.GetOrigin())\n return image_from_array\n elif have_imglyb and isinstance(value,\n imglyb.util.ReferenceGuardingRandomAccessibleInterval):\n array = imglyb.to_numpy(value)\n self._source_object = array\n image_from_array = itk.GetImageViewFromArray(array)\n return image_from_array\n\n try:\n # an itk.Image or a filter that produces an Image\n # return itk.output(value)\n # Working around traitlets / ipywidgets update mechanism to\n # force an update. While the result of __eq__ can indicate it is\n # the same object, the actual contents may have changed, as\n # indicated by image.GetMTime()\n value = itk.output(value)\n self._source_object = value\n grafted = value.__New_orig__()\n grafted.Graft(value)\n return grafted\n except:\n self.error(obj, value)\n\ndef _image_to_type(itkimage):\n component_str = repr(itkimage).split('itkImagePython.')[1].split(';')[0][8:]\n if component_str[:2] == 'UL':\n if os.name == 'nt':\n return 'uint32_t',\n else:\n return 'uint64_t',\n mangle = None\n pixelType = 1\n if component_str[:2] == 'SL':\n if os.name == 'nt':\n return 'int32_t', 1,\n else:\n return 'int64_t', 1,\n if component_str[0] == 'V':\n # Vector\n mangle = component_str[1]\n pixelType = 5\n elif component_str[:2] == 'CF':\n # complex flot\n return 'float', 10\n elif component_str[:2] == 'CD':\n # complex flot\n return 'double', 10\n elif component_str[0] == 'C':\n # CovariantVector\n mangle = component_str[1]\n pixelType = 7\n elif component_str[0] == 'O':\n # Offset\n return 'int64_t', 4\n elif component_str[:2] == 'FA':\n # FixedArray\n mangle = component_str[2]\n pixelType = 11\n elif component_str[:4] == 'RGBA':\n # RGBA\n mangle = component_str[4:-1]\n pixelType = 3\n elif component_str[:3] == 'RGB':\n # RGB\n mangle = component_str[3:-1]\n pixelType = 2\n elif component_str[:4] == 'SSRT':\n # SymmetricSecondRankTensor\n mangle = component_str[4:-1]\n pixelType = 8\n else:\n mangle = component_str[:-1]\n _python_to_js = {\n 'SC':'int8_t',\n 'UC':'uint8_t',\n 'SS':'int16_t',\n 'US':'uint16_t',\n 'SI':'int32_t',\n 'UI':'uint32_t',\n 'F':'float',\n 'D':'double',\n 'B':'uint8_t'\n }\n return _python_to_js[mangle], pixelType\n\ndef itkimage_to_json(itkimage, manager=None):\n \"\"\"Serialize a Python itk.Image object.\n\n Attributes of this dictionary are to be passed to the JavaScript itkimage\n constructor.\n \"\"\"\n if itkimage is None:\n return None\n else:\n direction = itkimage.GetDirection()\n directionMatrix = direction.GetVnlMatrix()\n directionList = []\n dimension = itkimage.GetImageDimension()\n pixelArr = itk.GetArrayViewFromImage(itkimage)\n compressor = zstd.ZstdCompressor(level=3)\n compressed = compressor.compress(pixelArr.data)\n pixelArrCompressed = memoryview(compressed)\n for col in range(dimension):\n for row in range(dimension):\n directionList.append(directionMatrix.get(row, col))\n componentType, pixelType = _image_to_type(itkimage)\n imageType = dict(\n dimension=dimension,\n componentType=componentType,\n pixelType=pixelType,\n components=itkimage.GetNumberOfComponentsPerPixel()\n )\n return dict(\n imageType=imageType,\n origin=tuple(itkimage.GetOrigin()),\n spacing=tuple(itkimage.GetSpacing()),\n size=tuple(itkimage.GetBufferedRegion().GetSize()),\n direction={'data': directionList,\n 'rows': dimension,\n 'columns': dimension},\n compressedData=pixelArrCompressed\n )\n\n\ndef _type_to_image(jstype):\n _pixelType_to_prefix = {\n 1:'',\n 2:'RGB',\n 3:'RGBA',\n 4:'O',\n 5:'V',\n 7:'CV',\n 8:'SSRT',\n 11:'FA'\n }\n pixelType = jstype['pixelType']\n dimension = jstype['dimension']\n if pixelType == 10:\n if jstype['componentType'] == 'float':\n return itk.Image[itk.complex, itk.F], np.float32\n else:\n return itk.Image[itk.complex, itk.D], np.float64\n\n def _long_type():\n if os.name == 'nt':\n return 'LL'\n else:\n return 'L'\n prefix = _pixelType_to_prefix[pixelType]\n _js_to_python = {\n 'int8_t':'SC',\n 'uint8_t':'UC',\n 'int16_t':'SS',\n 'uint16_t':'US',\n 'int32_t':'SI',\n 'uint32_t':'UI',\n 'int64_t':'S' + _long_type(),\n 'uint64_t':'U' + _long_type(),\n 'float': 'F',\n 'double': 'D'\n }\n _js_to_numpy_dtype = {\n 'int8_t': np.int8,\n 'uint8_t': np.uint8,\n 'int16_t': np.int16,\n 'uint16_t': np.uint16,\n 'int32_t': np.int32,\n 'uint32_t': np.uint32,\n 'int64_t': np.int64,\n 'uint64_t': np.uint64,\n 'float': np.float32,\n 'double': np.float64\n }\n dtype = _js_to_numpy_dtype[jstype['componentType']]\n if pixelType != 4:\n prefix += _js_to_python[jstype['componentType']]\n if pixelType not in (1, 2, 3, 10):\n prefix += str(dimension)\n prefix += str(dimension)\n return getattr(itk.Image, prefix), dtype\n\ndef itkimage_from_json(js, manager=None):\n \"\"\"Deserialize a Javascript itk.js Image object.\"\"\"\n if js is None:\n return None\n else:\n ImageType, dtype = _type_to_image(js['imageType'])\n decompressor = zstd.ZstdDecompressor()\n if six.PY2:\n asBytes = js['compressedData'].tobytes()\n pixelBufferArrayCompressed = np.frombuffer(asBytes, dtype=dtype)\n else:\n pixelBufferArrayCompressed = np.frombuffer(js['compressedData'], dtype=dtype)\n pixelCount = reduce(lambda x, y: x*y, js['size'], 1)\n numberOfBytes = pixelCount * js['imageType']['components'] * np.dtype(dtype).itemsize\n pixelBufferArray = \\\n np.frombuffer(decompressor.decompress(pixelBufferArrayCompressed,\n numberOfBytes),\n dtype=dtype)\n pixelBufferArray.shape = js['size'][::-1]\n image = itk.PyBuffer[ImageType].GetImageFromArray(pixelBufferArray)\n Dimension = image.GetImageDimension()\n image.SetOrigin(js['origin'])\n image.SetSpacing(js['spacing'])\n direction = image.GetDirection()\n directionMatrix = direction.GetVnlMatrix()\n directionJs = js['direction']['data']\n for col in range(Dimension):\n for row in range(Dimension):\n directionMatrix.put(row, col, directionJs[col + row * Dimension])\n return image\n\nitkimage_serialization = {\n 'from_json': itkimage_from_json,\n 'to_json': itkimage_to_json\n}\n","sub_path":"itkwidgets/trait_types.py","file_name":"trait_types.py","file_ext":"py","file_size_in_byte":8916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"383991699","text":"# -*- coding: utf-8 -*- \r\nimport numpy as np\r\n\r\nn = int(input())\r\nt = list(map(int,input().split()))\r\nv = list(map(int,input().split()))\r\n\r\n\r\n#dp = [[0 for i in range(w+1)] for j in range(n+1)]\r\ndp = np.zeros((n+1,w+1),dtype='int')\r\n\r\nfor i in range(1,n+1):\r\n for j in range(1,w+1):\r\n if(j < a[i-1]):\r\n dp[i][j] = dp[i-1][j]\r\n else:\r\n dp[i][j] = max(dp[i-1][j],dp[i-1][j-a[i-1]]+b[i-1])\r\nprint(dp) ","sub_path":"BeginnerContest/077D.py","file_name":"077D.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"358898368","text":"#!/usr/bin/env python3\n# encoding: utf-8\n\nimport os\nimport sys\n\nfrom mock import MagicMock, patch\n\nfrom splunk_eventgen.__main__ import parse_args\nfrom splunk_eventgen.eventgen_core import EventGenerator\nfrom splunk_eventgen.lib.plugins.output.syslogout import SyslogOutOutputPlugin\n\nFILE_DIR = os.path.dirname(os.path.abspath(__file__))\n\n\nclass TestSyslogOutputPlugin(object):\n def test_output_data_to_syslog(self):\n configfile = \"tests/sample_eventgen_conf/medium_test/eventgen.conf.syslogoutput\"\n testargs = [\"eventgen\", \"generate\", configfile]\n with patch.object(sys, \"argv\", testargs):\n with patch(\"logging.getLogger\"):\n pargs = parse_args()\n assert pargs.subcommand == \"generate\"\n assert pargs.configfile == configfile\n eventgen = EventGenerator(args=pargs)\n\n sample = MagicMock()\n sample.name = \"test\"\n sample.syslogDestinationHost = \"127.0.0.1\"\n sample.syslogDestinationPort = 9999\n syslogoutput = SyslogOutOutputPlugin(sample)\n\n eventgen.start()\n for i in range(1, 6):\n appearance = False\n for logger_call in syslogoutput._l.info.call_args_list:\n if \"WINDBAG Event {} of 5\".format(i) in str(logger_call):\n appearance = True\n if not appearance:\n assert False\n","sub_path":"tests/medium/plugins/test_syslog_output.py","file_name":"test_syslog_output.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"354720650","text":"'''\nConvert the raw ID3.txt to a csv file\nRemove the boolean value\n'''\n\nfile = open(\"Raw_Data\\\\ID3.txt\", \"r\")\ndest = open(\"Trans_Data\\\\ID3_new.csv\", \"w\")\ndest.write(\"latitude,longitude,time\\n\")\ndestList= []\n# Number of line to keep\nnbLineTODo = 10000000\ni = 0\n\nfor l in file:\n if i > nbLineTODo:\n break\n elif i == 0:\n i += 1\n continue\n pieces = l.split(\",\")\n newL = \"+\" + \",\".join([x for i, x in enumerate(pieces) if i in (0, 1, 3)])\n destList.append(newL)\n\ndestList.reverse()\nfor l in destList:\n dest.write(l)\n\nfile.close()\ndest.close()\n","sub_path":"convertID3.py","file_name":"convertID3.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"135090912","text":"name = 'Река'\n\nactions = [ 'Грести руками' ]\n\n\n\n\ndef get_actions(user):\n if user.has_item('m79'):\n actions.append('Использовать М79')\n if user.has_item('m-16'):\n actions.append('Использовать М-16')\n return actions\n\n\ndef enter(user, reply):\n reply( 'Дверь, через которую вы вошли, магическим образом исчезла.\\n'\n 'Вы решаете осмотреться и замечаете лодку, стоящую неподалёку.\\n'\n 'Вам ничего не остаётся, кроме как сесть в лодку и переплыть препятствие.\\n')\n user.set_room_temp('rvr', 0)\n\n\ndef action(user, reply, text):\n global rvr\n if text == actions[0]:\n rvr += 1\n reply('Вы гребёте руками. Кажется, что скоро конец')\n print(rvr)\n if rvr > 8:\n msg = ''\n if user.has_item('m-16'):\n user.remove_item('m-16')\n msg += 'Вы уронили свой М-16, пока плыли. Ну хоть себя не выронили.\\n'\n msg += 'Вы пристаёте к другому концу берега, вылезаете из лодки.\\n'\n msg += 'Единственное место, куда вы можете пойти здесь - едва приоткрытая дверь.\\n'\n msg += 'Вы открываете дверь... И выхо��ите в коридор!'\n reply(msg)\n rvr = 0\n user.leave(reply)\n elif user.has_item('m79'):\n rvr += 1\n reply('Вы вспоминаете, что у вас есть М79, берёте его в руки и гребёте им.')\n if rvr > 8:\n msg = ''\n if user.has_item('m-16'):\n user.remove_item('m-16')\n msg += 'Вы уронили свой М-16, пока плыли. Ну хоть себя не выронили.\\n'\n msg += 'Вы пристаёте к другому концу берега, вылезаете из лодки.\\n'\n msg += 'Единственное место, куда вы можете пойти здесь - едва приоткрытая дверь.\\n'\n msg += 'Вы открываете дверь... И выходите в коридор!'\n reply(msg)\n rvr = 0\n user.leave(reply)\n else:\n rvr += 1\n reply('Вы вспоминаете, что у вас есть М-16, берёте его в руки и гребёте им.')\n if rvr > 8:\n user.remove_item('m-16')\n reply('Вы пристаёте к другому концу берега, вылезаете из лодки. Ваш М-16 не выдержал такого нахальства и рассыпался прямо у вас в руках.\\n'\n '- Ну и чёрт с ним, - подумали вы.\\n'\n 'Единственное место, куда вы можете пойти здесь - едва приоткрытая дверь.\\n'\n 'Вы открываете дверь... И выходите в коридор!')\n user.leave(reply)\n rvr = 0\n","sub_path":"rooms/monster/vietnam/river.py","file_name":"river.py","file_ext":"py","file_size_in_byte":3637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"325678333","text":"\nfrom odoo import models, fields, api\n\n\nclass ProductAttributeWizard(models.TransientModel):\n _name = 'product.attribute.wizard'\n\n value_ids = fields.Many2many('product.attribute.value')\n attribute_id = fields.Many2one('product.attribute')\n\n def action_create_attribute(self):\n model = self.env.context.get('active_model')\n rec_model = self.env[model].browse(self.env.context.get('active_id'))\n if rec_model.attribute_line_ids:\n for rec in rec_model.attribute_line_ids:\n if rec.attribute_id.id == self.attribute_id.id:\n att_list = []\n for attr in rec.value_ids:\n att_list.append(attr.id)\n for x in self.value_ids:\n att_list.append(x.id)\n rec.write({\n 'value_ids': att_list,\n })\n else:\n vals = {\n 'attribute_id': self.attribute_id.id,\n 'value_ids': self.value_ids.ids,\n 'product_tmpl_id': rec_model.id\n }\n # rec_model.attribute_line_ids = val_list\n # for res in rec_model.attribute_line_ids:\n # if res.attribute_id.id == self.attribute_id.id:\n # # att_list = []\n # # for attr in rec.value_ids:\n # # att_list.append(attr.id)\n # # for x in self.value_ids:\n # # att_list.append(x.id)\n # res.update({\n # 'value_ids': self.value_ids.ids,\n # })\n pro = self.env['product.template.attribute.line'].create(vals)\n self.assign_sequence_in_variant()\n\n def assign_sequence_in_variant(self):\n model = self.env.context.get('active_model')\n rec_model = self.env[model].browse(self.env.context.get('active_id'))\n count = 0\n print(rec_model.product_variant_ids)\n for variant in rec_model.product_variant_ids:\n count += 1\n variant.product_seq = str(00) + str(00) + str(0) + str(count)\n variant.item_code = rec_model.product_temp_seq + variant.product_seq\n return\n\n","sub_path":"product_sequence/models/product_attribute_wizard.py","file_name":"product_attribute_wizard.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"513553385","text":"def copy_path(root_src_dir, root_dst_dir, exclude_files=[]):\r\n\r\n from shutil import copy\r\n import os\r\n\r\n for src_dir, dirs, files in os.walk(root_src_dir):\r\n dst_dir = src_dir.replace(root_src_dir, root_dst_dir)\r\n if not os.path.exists(dst_dir):\r\n os.makedirs(dst_dir)\r\n for f in files:\r\n if f not in exclude_files:\r\n src_file = os.path.join(src_dir, f)\r\n dst_file = os.path.join(dst_dir, f)\r\n copy(src_file, dst_file)\r\n","sub_path":"project/SciProgHF/test/runtest/copy.py","file_name":"copy.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"283971547","text":"\"\"\"\nProblem:\n\nGiven a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.\n\nNote: You can only move either down or right at any point in time.\n\"\"\"\n\n\"\"\"\nSolution:\n\nThis is a typical dynamic programming problem. \n\nThe minimum path to position (i,j) is the minimum among the choice of going down from (i-1,j) and going right from (i,j-1).\n\nIn order to reduce the space for the problem, only a row of the dynamic table is needed instead of the whole dynamic programming table\nwith the same size of grid.\n\"\"\"\n\nclass Solution(object):\n def minPathSum(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n m = len(grid)\n n = len(grid[0])\n pathSum = [[None]*n for _ in range(m)]\n pathSum[0][0] = grid[0][0]\n for j in range(1,n):\n pathSum[0][j] = grid[0][j] + pathSum[0][j-1]\n for i in range(1,m):\n pathSum[i][0] = grid[i][0] + pathSum[i-1][0]\n for i in range(1,m):\n for j in range(1,n):\n pathSum[i][j] = min(pathSum[i-1][j], pathSum[i][j-1]) + grid[i][j]\n return pathSum[-1][-1]\n \n","sub_path":"64_Minimum_Path_Sum.py","file_name":"64_Minimum_Path_Sum.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"246452759","text":"import sys\nimport CheshirePy as c\n\nif c.init('../index/testconfig.new') == 0:\n print (\"Opened Cheshire config file %s\" % c.showconfig())\nelse:\n print(\"failed to open configuration file - exiting\")\n exit()\n \nif c.setdb('bibfile') == 0:\n print (\"Set database to bibfile\")\nelse:\n print(\"failed to set database\")\n exit()\n\nsearchstr = 'topic @ mathematics programming'\n\nprint (\"searching for '%s'\" % searchstr)\n\nr = c.Search(searchstr)\n\nn = c.getnumfound(r)\nprint (\"%d records found\" % n)\n\ni = 0\n\nwhile i < n :\n rec = c.getrecord(r,i)\n rel = c.getrelevance(r,i)\n print(\"*********************************************\")\n print(\"Rank: %d Relevance: %f\" % (i, rel))\n print(rec)\n print(\"*********************************************\")\n i += 1\n\nc.closeresult(r)\nprint(\"End of record set\")\n\nexit()\n","sub_path":"CheshirePy/testscp.py","file_name":"testscp.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"151736200","text":"\"\"\"\nGiven 3 int values, a, b, c, return their sum.\nHowever, if one of the values is 13 then it does not count towards the sum and values to its right do not count.\n\"\"\"\n\ndef lucky_sum(a, b, c):\n l = [a, b, c]\n total = 0\n i = 0\n while i < 3:\n if l[i] == 13:\n break\n else:\n total += l[i]\n i += 1\n return total\n\nprint(lucky_sum(1, 13, 2))","sub_path":"Logic-2/3. lucky_sum.py","file_name":"3. lucky_sum.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"589365815","text":"import pandas as pd\nfrom scipy.stats import trim_mean, kurtosis\nfrom fastai.imports import *\nfrom fastai.structured import *\nfrom tabulate import tabulate\nfrom sklearn.ensemble import RandomForestClassifier\nfrom matplotlib import pyplot\nfrom sklearn.metrics import f1_score,\\\n accuracy_score, confusion_matrix,\\\n precision_score, recall_score,\\\n roc_curve, roc_auc_score,\\\n cohen_kappa_score, mean_absolute_error,\\\n precision_recall_curve, auc,\\\n average_precision_score\n\n# Constants\nPROBABILITY_CUTOFF = 0.50\n\ndef split_vals(a,n): return a[:n], a[n:]\n\ndef display_all(df):\n with pd.option_context(\"display.max_rows\", 1000, \"display.max_columns\", 1000):\n display(df)\n\ndef general_stats(df, feature):\n array = data_summary_feature(df, feature)\n print(array[0])\n print(\"\")\n count = 1\n for heading in ['Min', 'Max', 'Mean', 'Trimmed Mean', 'Median', 'Std', 'CV']:\n print(f\"{heading}: {array[count]}\")\n count += 1\n\n# Utility functions\ndef plot_roc_pr(m, X_valid, y_valid):\n # Generate the probabilities\n #y_pred_prob = generate_predictions(X_valid)\n y_pred_prob = m.predict_proba(X_valid)\n y_pred_prob = y_pred_prob[:, 1]\n\n # Calculate the roc metrics\n fpr, tpr, thresholds = roc_curve(y_valid, y_pred_prob)\n\n fig, ax = plt.subplots(figsize=(10,10))\n\n # Add labels and diagonal line\n plt.xlabel(\"False Positive Rate / Recall\")\n plt.ylabel(\"True Positive Rate / Precision\")\n plt.plot([0, 1], [0, 1], \"k--\", label='no skill')\n plt.plot([0,0,1,1],[0,1,1,1],'g-',label='perfect')\n\n # Plot a precision-recall curve\n precision, recall, thresholds = precision_recall_curve(y_valid, y_pred_prob)\n area_under_curve = auc(recall, precision)\n ap = average_precision_score(y_valid, y_pred_prob)\n\n # Plot the ROC curve\n plt.plot(fpr,tpr, label='AUC: %.3f'%area_under_curve)\n\n # plot no skill\n pyplot.plot([0, 1], [0.5, 0.5], linestyle='--', color='magenta', label='no skill')\n # plot the precision-recall curve for the model\n pyplot.plot(recall, precision, marker='.', color='orange', label='precision-recall')\n\n legend = ax.legend(loc='best', shadow=True, fontsize='medium')\n\n # show the plot\n pyplot.show()\n\n # Output AUC and average precision score\n print('auc=%.3f ap=%.3f' % (area_under_curve, ap))\n\ndef uber_score(y_valid, validate_predictions):\n print(f\"Precision: {precision_score(y_valid,validate_predictions)}\")\n print(f\"Recall: {recall_score(y_valid,validate_predictions)}\")\n print(f\"f1_score: {f1_score(y_valid,validate_predictions)}\")\n print(f\"Accuracy: {accuracy_score(y_valid,validate_predictions)}\")\n print(f\"kappa: {cohen_kappa_score(y_valid,validate_predictions)}\")\n print(f\"mean abs error: {mean_absolute_error(y_valid,validate_predictions)}\")\n\ndef graph_corr(data_frame):\n fig, ax = plt.subplots(figsize=(20,10))\n corr = data_frame.corr()\n sns.heatmap(corr, cmap='YlGnBu', annot_kws={'size':30}, ax=ax)\n ax.set_title(\"Correlation Matrix\", fontsize=14)\n plt.show()\n\ndef data_summary_feature(data_frame, feature):\n \"\"\"\n Doc string\n \"\"\"\n\n max_value = data_frame[feature].max()\n min_value = data_frame[feature].min()\n mean = data_frame[feature].mean()\n median = data_frame[feature].median()\n mode = data_frame[feature].mode()\n std = data_frame[feature].std()\n co_variant = data_frame[feature].std()/data_frame[feature].mean()\n trimmed_mean = trim_mean(data_frame[feature].values, 0.1)\n return [feature, min_value, max_value, mean, trimmed_mean, median, mode, std, co_variant]\n\ndef data_summary_dataframe(data_frame):\n array = []\n for feature in data_frame.select_dtypes(include=['float64', 'int64']).columns:\n array.append(data_summary_feature(data_frame, feature))\n\n print(tabulate(array, headers=['Column', 'Min', 'Max',\n 'Mean', 'Trimmed Mean',\n 'Median', 'Std', 'cv'], tablefmt=\"simple\"))\n\ndef conf_matrix(y_valid, validate_predictions):\n confusion_matrix_data = confusion_matrix(y_valid, validate_predictions)\n print(\"tp, fn, fp, tn\")\n print(confusion_matrix_data)\n","sub_path":"lib/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"63739303","text":"# coding=utf-8\n\nfrom datetime import datetime\nfrom dateutil import rrule\nfrom django.utils.encoding import python_2_unicode_compatible\nfrom django.utils.functional import cached_property\nfrom django.db import models\nfrom django.core.urlresolvers import reverse\nfrom imagekit.models import ImageSpecField\nfrom imagekit.processors import ResizeToFill\nfrom connection.models import EnjoyTodayUser\nfrom location.models import City\nfrom core.models import Topic\nfrom django.contrib.sites.models import Site\nfrom django.contrib.sites.managers import CurrentSiteManager\n\n\n__all__ = (\n 'EventType',\n 'Event',\n 'Occurrence',\n)\n\n\n# ==============================================================================\n@python_2_unicode_compatible\nclass EventType(models.Model):\n \"\"\"\n Simple ``Event`` classification.\n \"\"\"\n topic = models.ForeignKey(Topic,\n verbose_name='Thematique',\n default=None,\n null=True,\n on_delete=models.SET_DEFAULT)\n\n label = models.CharField(verbose_name='label',\n max_length=50,\n default='autres')\n\n image = models.ImageField(default=None,\n null=True,\n upload_to='event_types/')\n\n #image_main = ImageSpecField(source='image',\n #processors=[ResizeToFit(450, 300)],\n #format='JPEG',\n #options={'quality': 100})\n\n # ==========================================================================\n class Meta:\n verbose_name = 'event type'\n verbose_name_plural = 'event types'\n\n # --------------------------------------------------------------------------\n def __str__(self):\n return self.label\n\n def get_absolute_url(self):\n return reverse('topic:event_type_coming_days',\n kwargs={'event_type_id_string': str(self.pk)},\n current_app=self.topic.name)\n\n# ==============================================================================\n@python_2_unicode_compatible\nclass Event(models.Model):\n \"\"\"\n Container model for general metadata and associated ``Occurrence`` entries.\n \"\"\"\n image = models.ImageField(verbose_name=\"Image\",\n default=None,\n null=True,\n upload_to='events/')\n\n title = models.CharField(verbose_name=\"Titre\",\n max_length=100,\n default=None,\n null=True)\n\n description = models.TextField(verbose_name=\"Description\",\n default=None,\n null=True)\n\n event_type = models.ForeignKey(EventType,\n verbose_name=\"Catégorie\",\n default=None,\n null=True,\n on_delete=models.SET_DEFAULT,\n )\n\n price = models.PositiveSmallIntegerField(verbose_name=\"Prix en euros\",\n default=0)\n\n contact = models.CharField(verbose_name=\"Coordonnées du contact éventuel\",\n max_length=150,\n default=\"non précisé\",\n null=True,\n blank=True)\n\n website = models.CharField(verbose_name=\"Lien vers le site officiel de l'événement\",\n max_length=150,\n default=\"non précisé\",\n null=True,\n blank=True)\n\n image_main = ImageSpecField(source='image',\n processors=[ResizeToFill(800, 300)],\n format='JPEG',\n options={'quality': 100},\n )\n\n event_planner = models.ForeignKey(EnjoyTodayUser,\n on_delete=models.CASCADE,\n default=None,\n null=True,\n verbose_name='annonceur',\n )\n\n address = models.CharField(verbose_name=\"Adresse\",\n max_length=150,\n default=\"non précisé\")\n\n #public_transport = models.CharField(verbose_name=\"Arrêt transport en commun (métro,...)\",\n # max_length=150,\n # default=\"non précisé\",\n # null=True,\n # blank=True\n # )\n\n site = models.ForeignKey(Site,\n default=None,\n null=True,\n on_delete=models.SET_DEFAULT,\n # if affected, breaks\n # default=None,\n )\n\n objects = models.Manager()\n on_site = CurrentSiteManager()\n\n # ===========================================================================\n class Meta:\n verbose_name = 'event'\n verbose_name_plural = 'events'\n ordering = ('title', )\n\n # ---------------------------------------------------------------------------\n def __str__(self):\n return self.title\n\n # --------------------------------------------------------------------------\n #def get_absolute_url(self):\n #return reverse('', kwargs={'event_id': self.pk})\n\n def delete_url(self):\n return reverse('catho:crud:delete_event', kwargs={'event_id': self.pk})\n\n def update_url(self):\n return reverse('catho:crud:update_event', kwargs={'event_id': self.pk})\n\n\n # --------------------------------------------------------------------------\n def add_occurrences(self, start_time, end_time, is_multiple, **rrule_params):\n \"\"\"\n Add one or more occurences to the event using a comparable API to\n ``dateutil.rrule``.\n\n Because ``rrule.rrule`` returns an iterator that can essentially be\n unbounded, we need to slightly alter the expected behavior here in order\n to enforce a finite number of occurrence creation.\n\n If ``until`` entry is missing from ``rrule_params``,\n only a single ``Occurrence`` instance will be created using the exact\n ``start_time`` and ``end_time`` values.\n \"\"\"\n\n until = rrule_params.get('until')\n if not until:\n self.occurrence_set.create(start_time=start_time, end_time=end_time)\n else:\n delta_hour = end_time - start_time\n occurrences = []\n for ev in rrule.rrule(dtstart=start_time, **rrule_params):\n occurrences.append(Occurrence(start_time=ev,\n end_time=ev + delta_hour,\n event=self,\n is_multiple=is_multiple))\n self.occurrence_set.bulk_create(occurrences)\n\n # --------------------------------------------------------------------------\n def upcoming_occurrences(self):\n \"\"\"\n Return all occurrences that are set to start on or after the current\n time.\n \"\"\"\n return self.occurrence_set.filter(start_time__gte=datetime.now())\n\n # --------------------------------------------------------------------------\n def next_occurrence(self):\n \"\"\"\n Return the single occurrence set to start on or after the current time\n if available, otherwise ``None``.\n \"\"\"\n upcoming = self.upcoming_occurrences()\n return upcoming[0] if upcoming else None\n\n\n\n# ==============================================================================\nclass OccurrenceManager(models.Manager):\n\n use_for_related_fields = True\n\n # --------------------------------------------------------------------------\n def daily_occurrences(self, dt=None, event=None):\n \"\"\"\n Returns a queryset of for instances that have any overlap with a\n particular day.\n\n * ``dt`` may be either a datetime.datetime, datetime.date object, or\n ``None``. If ``None``, default to the current day.\n\n * ``event`` can be an ``Event`` instance for further filtering.\n \"\"\"\n\n dt = dt or datetime.now()\n start = datetime(dt.year, dt.month, dt.day)\n end = start.replace(hour=23, minute=59, second=59)\n qs = self.filter(\n models.Q(\n start_time__gte=start,\n start_time__lte=end,\n ) |\n models.Q(\n end_time__gte=start,\n end_time__lte=end,\n ) |\n models.Q(\n start_time__lt=start,\n end_time__gt=end\n )\n )\n\n return qs.filter(event=event) if event else qs\n\n\n# ==============================================================================\n@python_2_unicode_compatible\nclass Occurrence(models.Model):\n \"\"\"\n Represents the start end time for a specific occurrence of a master ``Event``\n object.\n \"\"\"\n start_time = models.DateTimeField()\n end_time = models.DateTimeField()\n event = models.ForeignKey(Event,\n editable=False,\n on_delete=models.CASCADE)\n objects = OccurrenceManager()\n is_multiple = models.BooleanField(default=False)\n\n # ==========================================================================\n class Meta:\n verbose_name = 'occurrence'\n verbose_name_plural = 'occurrences'\n ordering = ('start_time', 'end_time')\n\n # --------------------------------------------------------------------------\n def __str__(self):\n return u'{}: {}'.format(self.event.title, self.start_time.isoformat())\n\n # --------------------------------------------------------------------------\n def get_absolute_url(self):\n return reverse('topic:get_occurrence', kwargs={'pk': self.pk}, current_app=self.event.event_type.topic.name)\n\n def delete_url(self):\n return reverse('topic:crud:delete_occurrence', kwargs={'occurrence_id': self.pk}, current_app=self.event.event_type.topic.name)\n\n def update_url(self):\n return reverse('topic:crud:update_occurrence', kwargs={'occurrence_id': self.pk}, current_app=self.event.event_type.topic.name)\n\n # --------------------------------------------------------------------------\n def __lt__(self, other):\n return self.start_time < other.start_time\n","sub_path":"topic/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":10906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"220636450","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 31 13:38:44 2019\n\n@author: tyler\n\"\"\"\n\n\nimport pandas as pd\nimport numpy as np\n\n\ndata = pd.read_csv('/home/tyler/Desktop/Dolezal_Python_Practice/rome_data.csv', index_col = 'DATE', dtype={'TempF':str, 'WEATHER':str}, parse_dates=True)\n\n''' Like the AZ data our temp readings have 's' attached to them as well as a few columns marked '*', we can\neliminate these items and then plot the data '''\n\ntemp_data = data['TempF']\nrmv = temp_data == '*'\ntemp_data.loc[rmv] = np.nan\ntemp_data = temp_data.dropna() \ntemp_data = temp_data.map(lambda x: x.rstrip('s'))\n\ntemp_data = temp_data.astype(float)\n\n\ntemp = temp_data.resample('M').apply(np.median)\n\n#temp_data.plot(title = 'Rome NY Temp (F) Data over 10 Years', figsize = (15,7.5))\n\n\n''' Now lets look at snowfall over the past 10 years '''\n\nsnow = data['WEATHER'].str.contains('SN')\nsnow = snow.dropna()\nmost_snow = snow.astype(float).resample('M').apply(np.mean)\n\nmost_snow.plot(title = 'Snowiest times of the year')","sub_path":"rome_climate.py","file_name":"rome_climate.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"516342049","text":"class Solution:\n def countPrimes(self, n: int) -> int:\n counter = 0\n isPrime = [True] * (n+1)\n for i in range(2, n):\n if isPrime[i]:\n counter += 1\n for j in range(1, (n // i)+1):\n isPrime[i * j] = False\n \n return counter","sub_path":"204. Count Primes/solution1.py","file_name":"solution1.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"630119248","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport sys\n\nfrom flask import Flask\n\n\nCONFIG_NAME_MAPPER = {\n 'development': 'config.DevelopmentConfig',\n 'testing': 'config.TestingConfig',\n 'production': 'config.ProductionConfig',\n 'local': 'local_config.LocalConfig',\n}\n\n\ndef create_app(flask_env=None, *args, **kwargs) -> Flask:\n \"\"\"\n Create a Flask application using the app factory pattern\n \"\"\"\n\n # create the base app\n app = Flask(__name__, instance_relative_config=True)\n\n # load correct flask env definition\n if not flask_env:\n env_flask_env = os.getenv('FLASK_ENV')\n\n if env_flask_env:\n flask_env = env_flask_env\n else:\n msg = 'could not identify which environment the application should use'\n app.logger.error(msg)\n sys.exit(1)\n\n # load app configurations\n app.config.from_object(CONFIG_NAME_MAPPER[flask_env])\n\n # initialize modules\n from app import modules\n\n modules.init_app(app)\n\n return app\n","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"99488070","text":"from main.server import db\nfrom main.server.models import Announcement, MultiGallery, Gallery, Games, Message, Video, SetMetadata\nfrom main.utils.dto import AnnouncementDTO, MultiGalleryDTO, GalleryDTO, GameDTO, MessageDTO, VideoDTO\nfrom main.server.status import Status\nfrom main.utils.blur import getBlurCodeFromImage\n\ndef insertAnnouncement(data):\n if not isinstance(data, AnnouncementDTO):\n raise TypeError('data must be of type AnnouncementDTO')\n if not data.message: \n return Status.FAIL\n res = Announcement.query.filter_by(message=data.message).first() \n if res:\n return Status.WARN\n res = Announcement(message=data.message)\n db.session.add(res) \n return Status.OK\n\ndef insertMultiGallery(data): \n if not isinstance(data, MultiGalleryDTO):\n raise TypeError('data must be of type MultiGalleryDTO')\n if not data.artworkLink:\n return Status.FAIL\n if not SetMetadata.query.filter_by(setID=data.setID).first():\n metadata_entry = SetMetadata(\n setID=data.setID,\n artistLink=data.artistLink,\n username=data.username,\n message=data.message,\n )\n db.session.add(metadata_entry)\n \n if not MultiGallery.query.filter_by(artworkLink=data.artworkLink).first():\n multigallery_entry = MultiGallery(\n setID=data.setID,\n artworkLink=data.artworkLink,\n blurhash=getBlurCodeFromImage(data.artworkLink),\n )\n db.session.add(multigallery_entry)\n else:\n # return from this insert with dupe warn\n return Status.WARN\n\n return Status.OK\n\ndef insertGallery(data): \n if not isinstance(data, GalleryDTO):\n raise TypeError('data must be of type GalleryDTO')\n if not data.artworkLink:\n return Status.FAIL\n res = Gallery.query.filter_by(artworkLink=data.artworkLink).first() \n if res:\n return Status.WARN\n res = Gallery(artworkLink=data.artworkLink,\n blurhash=getBlurCodeFromImage(data.artworkLink),\n artistLink=data.artistLink,\n username=data.username,\n title=data.title)\n db.session.add(res)\n return Status.OK\n\ndef insertGame(data):\n if not isinstance(data, GameDTO):\n raise TypeError('data must be of type GameDTO')\n if not data.gameLink:\n return Status.FAIL\n res = Games.query.filter_by(gameLink=data.gameLink).first()\n if res:\n return Status.WARN\n res = Games(gameLink=data.gameLink,\n gitLink=data.gitLink,\n description=data.description,\n title=data.title,\n thumbnail=data.thumbnail,\n blurhash=getBlurCodeFromImage(data.thumbnail))\n db.session.add(res)\n\ndef insertMessage(data):\n if not isinstance(data, MessageDTO):\n raise TypeError('data must be of type MessageDTO')\n if not data.orig_msg:\n return Status.FAIL\n res = Message.query.filter_by(orig_msg=data.orig_msg).first()\n if res:\n return Status.WARN\n res = Message(orig_msg=data.orig_msg,\n tl_msg=data.tl_msg,\n country=data.country,\n username=data.username)\n db.session.add(res)\n return Status.OK\n\ndef insertVideo(data):\n if not isinstance(data, VideoDTO):\n raise TypeError('data must be of type VideoDTO')\n if not data.videoLink:\n return Status.FAIL\n res = Video.query.filter_by(\n videoLink=data.videoLink).first()\n if res:\n return Status.WARN\n res = Video(videoLink=data.videoLink,\n artistLink=data.artistLink,\n username=data.username,\n title=data.title)\n db.session.add(res)\n","sub_path":"backend/main/utils/insert.py","file_name":"insert.py","file_ext":"py","file_size_in_byte":4063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"416549418","text":"import sys \r\nimport pandas as pd\r\nimport numpy as np\r\nimport math\r\nimport matplotlib.pyplot as plt\r\nimport pickle\r\n\r\n\r\nclass Solution:\r\n \r\n \r\n def __init__(self,df_TSP,filename):\r\n self.filename = filename\r\n self.df_TSP = df_TSP\r\n self.n = len(self.df_TSP) # nr of cities\r\n root = math.sqrt(self.n)\r\n if (int(root + 0.5)**2 != self.n):\r\n print(\"n=\" + str(self.n) + \" is not a perfect square!\")\r\n sys.exit() \r\n # distance from each city to the depot\r\n self.dist_depot = [((self.df_TSP.iloc[i,1]- 0)**2 + (self.df_TSP.iloc[i,2]-0)**2)**0.5 for i in range(self.n)]\r\n # symmetric nxn matrix with distances between each city\r\n self.dist = [[((self.df_TSP.iloc[i,1]-self.df_TSP.iloc[j,1])**2+(self.df_TSP.iloc[i,2]-self.df_TSP.iloc[j,2])**2)**0.5 for j in range(self.n)] for i in range(self.n)]\r\n self.dim = int(self.n**0.5) # nr of rows and columns\r\n self.sol = [[ (-1) for i in range(self.dim)] for j in range(self.dim)] # solution\r\n \r\n # This function intialises the solution using the algorithm GREEDY\r\n # the first column of my solution is first filled with random cities (without replacement)\r\n # then each row is filled with the city that is closest in location to the previous city \r\n # with respect to each row (without replacement)\r\n def InitialSolution(self):\r\n print(\"n\",self.n)\r\n if (self.n == 1):\r\n self.sol = [0]\r\n print(\"sol\",self.sol)\r\n print(self.dist)\r\n print(self.dist_depot)\r\n return \r\n cities = list(range(self.n)) # this is a list I store my cities in in order to be able to fill in \r\n # unique cities in my solution\r\n li = np.random.choice(self.n,self.dim, replace = False) # dim random cities to fill first column of my solution\r\n # here li stands for list but do not want to confuse this \r\n # variable with function list so called it li\r\n for i in range(self.dim):\r\n cities[li[i]] = -1 # when cities are allocated to my solution\r\n # set these cities equal to -1 in cities array to be able to draw without permuation\r\n for i in range(self.dim):\r\n self.sol[i][0] = li[i] # filling in first column of my solution with cities\r\n city0 = 0 # this will be my first city of reference from cities \r\n for c in cities:\r\n if c >= 0:\r\n city0 = c\r\n break \r\n d0 = self.dist[self.sol[0][0]][city0] # this will be the corresponding distance with respect to city0\r\n count = self.n - self.dim # count nr of cities left that have not been allocated to solution\r\n while (count != 0): # as long as there are still cities to allocate\r\n for i in range(self.dim): # for each column\r\n for j in range(self.dim-1): # for each row\r\n if (count == 2): # this is to check when there are only 2 cities left to allocate\r\n count = 0\r\n if (self.dim > 2): # if dimension of solution is greater than 2\r\n city3 = 0 # this variable stores last city \r\n dist3 = 0 # this variable stores last distance\r\n for c in cities: \r\n if ((c >= 0) and (c != city0)):\r\n city3 = c \r\n dist3 = self.dist[self.sol[self.dim-1][-3]][city3]\r\n break \r\n # compare the distances of the last 2 cities and allocate these to solution \r\n if dist3 < d0:\r\n self.sol[self.dim-1][-2] = city3 \r\n self.sol[self.dim-1][-1] = city0 \r\n else:\r\n self.sol[self.dim-1][-2] = city0 \r\n self.sol[self.dim-1][-1] = city3 \r\n elif (self.dim == 2): # if dimension of solution is 2x2 matrix \r\n city3 = 0\r\n for c in cities: \r\n if (c>= 0 and c!= city0):\r\n city3 = c \r\n break \r\n dist3 = self.dist[self.sol[0][0]][city3]\r\n d0 = self.dist[self.sol[0][0]][city0]\r\n # compare distances of last 2 cities and allocate these to solution\r\n if (dist3 < d0):\r\n self.sol[0][1] = city3 \r\n self.sol[1][1] = city0 \r\n else: \r\n self.sol[0][1] = city0 \r\n self.sol[1][1] = city3 \r\n # else: # if dimension of solution is 1\r\n # p = 0 \r\n if count > 2: # if there are more than 2 cities to allocate\r\n # find smallest distance and allocate city to solution\r\n for c in cities:\r\n if (c >= 0): \r\n dist1 = self.dist[self.sol[i][j]][c] \r\n if dist1 < d0:\r\n city0 = c \r\n d0 = dist1\r\n cities[city0] = -1 \r\n self.sol[i][j+1] = city0 \r\n count = count - 1\r\n for c in cities: \r\n if c >= 0:\r\n city0 = c\r\n d0 = self.dist[self.sol[i][j+1]][c] \r\n break \r\n if (j+1 == self.dim-1): \r\n for c in cities: \r\n if c >= 0:\r\n city0 = c\r\n d0 = self.dist[self.sol[i+1][0]][c] \r\n break \r\n else: \r\n for c in cities: \r\n if c >= 0:\r\n city0 = c \r\n d0 = self.dist[self.sol[i][j+1]][c] \r\n print(\"\\nSolution initialised according to greedy algorithm\")\r\n test = self.Test()\r\n if (test == True):\r\n print(\"Initial solution is unique!\") \r\n \r\n \r\n # swap operation over rows and columns\r\n def Swap(self,x1, y1, x2, y2): \r\n temp = self.sol[x1][y1]\r\n self.sol[x1][y1] = self.sol[x2][y2]\r\n self.sol[x2][y2] = temp\r\n \r\n # insert operation over rows only\r\n def Insert(self,x,y1,y2): \r\n # y2 will be inserted \r\n # if cities are adjacent or equal \r\n if (y2 == y1 or abs(y2 -y1) == 1):\r\n self.Swap(x,y1,x,y2)\r\n # if y1 is to the left of y2 \r\n elif y1 > y2: # elements of solution will have to be shifted left when y2 is inserted at y1\r\n temp = self.sol[x][y2]\r\n for i in range(abs(y2-y1)): \r\n self.sol[x][y2+i] = self.sol[x][y2+1+i]\r\n self.sol[x][y1] = temp\r\n else: # y1 is to the right of y2 so elements in solution will have to be shifted to the right\r\n # when y2 is inserted at y1\r\n temp = self.sol[x][y2] \r\n for i in range(abs(y2-y1)): \r\n self.sol[x][y2-i] = self.sol[x][y2-1-i]\r\n self.sol[x][y1] = temp\r\n\r\n # reverse operation\r\n def Reverse(self,y1,y2,x):\r\n if( abs(y2 - y1) == 1 or abs(y2-y1) == 2 or abs(y2 - y1) == 0): # 1 or no elements in between y1 and y2\r\n # normal swap \r\n self.Swap(x,y1,x,y2)\r\n else: \r\n if (abs(y2 -y1)%2 != 0): # nr of elements between y1 and y2 is even\r\n for i in range(abs(y2-y1)-2):\r\n if y1 < y2:\r\n self.Swap(x,y1+i,x,y2-i)\r\n else: \r\n self.Swap(x,y1-i,x,y2+i)\r\n else: # nr of elements between y1 and y2 is uneven \r\n for i in range(abs(y2-y1)-3):\r\n if y1 < y2:\r\n self.Swap(x,y1+i,x,y2-i)\r\n else: \r\n self.Swap(x,y1-i,x,y2+i) \r\n\r\n # calculate cost\r\n def Cost(self):\r\n cost = 0 # total cost \r\n if (self.n == 1):\r\n cost = self.dist_depot[0] + self.dist_depot[0]\r\n else: \r\n TotalCost = [0 for x in range(len(self.sol[0]))] # to stor sums of distances of each column\r\n count = 0 # to retrieve index to store sums of costs for each row of solution\r\n for j in range(len(self.sol[0])): # for each row of solution\r\n cost = cost +self.dist_depot[self.sol[j][0]] # add distance from depot to first city\r\n for i in range(len(self.sol[0])-1): \r\n cost = cost + self.dist[self.sol[j][i]][self.sol[j][i+1]] # then add distances between cities\r\n cost = cost + self.dist_depot[self.sol[j][-1]] # distance from last city to depot\r\n TotalCost[count] = cost\r\n count = count + 1\r\n cost = 0\r\n cost = sum(TotalCost) + max(TotalCost) - min(TotalCost) \r\n return cost\r\n\r\n # Calculate feasibility\r\n def Feasibility(self):\r\n f = 0 # feasibility\r\n if (self.n == 1):\r\n f = 1 \r\n else: \r\n for i in range(len(self.sol)): # i = 0,1\r\n if (self.sol[i][0]%2 == 0):\r\n f = f + 1\r\n if (self.sol[i][-1]%2 != 0):\r\n f = f + 1 \r\n return f\r\n\r\n # Method 1: Hill Climbing method\r\n def HC(self):\r\n x = int(100000/100)\r\n X = list(range(1,(x+1))) \r\n Y = [0 for i in range(x)] \r\n count = 0\r\n cost = self.Cost()\r\n if (self.n == 1):\r\n test = True\r\n Y = [cost for i in range(x)]\r\n else: \r\n x = int(100000/100)\r\n X = list(range(1,(x+1))) \r\n Y = [0 for i in range(x)] \r\n count = 0\r\n cost = self.Cost()\r\n for i in range(100000):\r\n x1 = np.random.randint(0,self.dim)\r\n y1 = np.random.randint(0,self.dim)\r\n x2 = np.random.randint(0,self.dim)\r\n y2 = np.random.randint(0,self.dim)\r\n self.Swap(x1, y1, x2, y2)\r\n new_cost = self.Cost()\r\n if new_cost <= cost:\r\n cost = new_cost\r\n else:\r\n self.Swap(x2, y2, x1, y1)\r\n if ((i+1)%100 == 0):\r\n Y[count] =cost\r\n count = count + 1\r\n test = self.Test() \r\n print(\"\\n HILL CLIMBING METHOD: \")\r\n print(\"Is solution correct: \",test)\r\n print(\"Cost: \",cost)\r\n f = self.Feasibility()\r\n print(\"Feasibility: \",f)\r\n answer1 = self.Write()\r\n if (answer1 == 1): \r\n self.WriteToFile(cost,f)\r\n elif (answer1 == 2): \r\n self.WB_to_file(cost,f)\r\n elif (answer1 == 3): \r\n self.WriteToFile(cost,f) \r\n self.WB_to_file(cost,f) \r\n answer2 = self.GraphSol()\r\n if (answer2 == 1):\r\n self.Graph_Fig1(\" hill climbing method\") \r\n if (answer2 == 2):\r\n self.Graph_Fig2(X,Y,\" hill climbing method\") \r\n if (answer2 == 3): \r\n self.Graph_Fig1(\" hill climbing method\")\r\n self.Graph_Fig2(X,Y,\" hill climbing method\") \r\n return cost, self.sol,test\r\n\r\n # User input/output for graphing solution\r\n def GraphSol(self):\r\n print(\"\\nWould you like see graphs of solution ? \")\r\n print(\"Input <0>: NO\")\r\n print(\"Input <1>: Fig (1): Visual representation of solution\")\r\n print(\"Input <2>: Fig (2): Iterations vs Cost line graph\")\r\n print(\"Input <3>: Fig (1) and Fig (2) \")\r\n try: \r\n answer = input(\"INPUT: \") \r\n answer = int(answer)\r\n except ValueError:\r\n print(\"Wrong input given!\")\r\n exit() \r\n return answer\r\n\r\n # User input/output for writing solution to csv/bs files\r\n def Write(self):\r\n print(\"\\nWould you like to save solution? \")\r\n print(\"Input <0>: No saving of file\")\r\n print(\"Input <1>: Save file as csv file\")\r\n print(\"Input <2>: Save file as binary file\")\r\n print(\"Input <3>: Save both binary and csv file\")\r\n try: \r\n answer = input(\"INPUT: \") \r\n answer = int(answer)\r\n except ValueError:\r\n print(\"Wrong input given!\")\r\n sys.exit() \r\n return answer\r\n \r\n\r\n # Method 2: HC by using swap, insert and revert operations at random\r\n def HC_Swap_Insert_Reverse(self): \r\n x = int(100000/100)\r\n X = list(range(1,(x+1))) \r\n Y = [0 for i in range(x)] \r\n count = 0\r\n cost = self.Cost()\r\n if (self.n == 1):\r\n test = True\r\n Y = [cost for i in range(x)]\r\n else: \r\n for i in range(100000):\r\n operation = np.random.randint(0,4)\r\n # 1: swap \r\n # 2: insert \r\n # 3: reverse\r\n x1 = np.random.randint(0,self.dim)\r\n y1 = np.random.randint(0,self.dim)\r\n x2 = np.random.randint(0,self.dim)\r\n y2 = np.random.randint(0,self.dim)\r\n x = np.random.randint(0,self.dim)\r\n if (operation == 1):\r\n self.Swap(x1, y1, x2, y2)\r\n elif (operation == 2):\r\n self.Insert(x,y1,y2)\r\n else: \r\n self.Reverse(y1,y2,x) \r\n new_cost = self.Cost()\r\n if new_cost <= cost:\r\n cost = new_cost\r\n else:\r\n if (operation == 1):\r\n self.Swap(x2, y2, x1, y1)\r\n elif (operation == 2):\r\n self.Reverse(y2,y1,x)\r\n else: \r\n self.Insert(x,y2,y1) \r\n if ((i+1)%100 == 0):\r\n Y[count] =cost\r\n count = count + 1 \r\n test = self.Test()\r\n print(\"\\n HILL CLIMBING METHOD USING SWAP INSERT REVERT \")\r\n print(\"Is solution correct: \",test)\r\n print(\"Cost: \",cost)\r\n f = self.Feasibility()\r\n print(\"Feasibility: \",f)\r\n answer1 = self.Write()\r\n if (answer1 == 1): \r\n self.WriteToFile(cost,f)\r\n elif (answer1 == 2): \r\n self.WB_to_file(cost,f)\r\n elif (answer1 == 3): \r\n self.WriteToFile(cost,f) \r\n self.WB_to_file(cost,f) \r\n answer2 = self.GraphSol()\r\n if (answer2 == 1):\r\n self.Graph_Fig1(\" hill climbing with swap insert revert\") \r\n if (answer2 == 2):\r\n self.Graph_Fig2(X,Y,\" hill climbing with swap insert revert\") \r\n if (answer2 == 3): \r\n self.Graph_Fig1(\" hill climbing with swap insert revert\")\r\n self.Graph_Fig2(X,Y,\" hill climbing with swap insert revert\") \r\n return cost,self.sol,test \r\n\r\n # Method 3: HC by implementing simulated annealing\r\n def SimulatedAnnealing(self):\r\n X = list(0 for i in range(1037)) \r\n for i in range(1037):\r\n X[i] = (i*2002 + 1)\r\n Y = [0 for i in range(1037)] # cost\r\n T0 = 10000\r\n coolingRate = 0.99999\r\n index = 0 # index to insert cost in Y \r\n value = 0 # variable to help store cost at index t\r\n NrIter = 0 # nr of iterations \r\n absoluteTemp = 0.00001\r\n cost0 = self.Cost() # initial cost\r\n if (self.n == 1):\r\n test = True\r\n Y = [cost0 for i in range(1037)]\r\n else: \r\n while (T0 > absoluteTemp):\r\n # count = count + 1\r\n x1 = np.random.randint(0,self.dim)\r\n y1 = np.random.randint(0,self.dim)\r\n x2 = np.random.randint(0,self.dim)\r\n y2 = np.random.randint(0,self.dim)\r\n self.Swap(x1, y1, x2, y2)\r\n cost1 = self.Cost() # new cost\r\n if cost1 < cost0:\r\n cost0 = cost1 #accept new solution\r\n else: \r\n q = np.random.randint(0,2)\r\n if q < math.exp(-(cost1-cost0)/T0): # accept solution if relation holds\r\n cost0 = cost1 \r\n else:\r\n self.Swap(x2,y2,x1,y1) \r\n T0 = T0*coolingRate # cool temperature\r\n if (NrIter == value):\r\n value = value + 2001 \r\n Y[index] = cost0\r\n index = index + 1\r\n NrIter = NrIter + 1 \r\n test = self.Test() \r\n X[-1] = NrIter\r\n Y[-1] = cost0\r\n print(\"\\n HILL CLIMBING METHOD USING SIMULATED ANNEALING \")\r\n print(\"Is solution correct \",test)\r\n print(\"Cost: \",cost0)\r\n f = self.Feasibility()\r\n print(\"Feasibility: \",f)\r\n answer1 = self.Write()\r\n if (answer1 == 1): \r\n self.WriteToFile(cost0,f)\r\n elif (answer1 == 2): \r\n self.WB_to_file(cost0,f)\r\n elif (answer1 == 3): \r\n self.WriteToFile(cost0,f) \r\n self.WB_to_file(cost0,f) \r\n answer2 = self.GraphSol()\r\n if (answer2 == 1):\r\n self.Graph_Fig1( \" simulated annealing\") \r\n if (answer2 == 2):\r\n self.Graph_Fig2(X,Y,\" simulated annealing\") \r\n if (answer2 == 3): \r\n self.Graph_Fig1(\" simulated annealing\")\r\n self.Graph_Fig2(X,Y,\" simulated annealing\") \r\n return cost0,self.sol,test \r\n\r\n # To test whether the solution has unique elements\r\n def Test(self):\r\n test = True \r\n cities = list(range(self.n))\r\n count = [0 for i in range(self.n)]\r\n for i in range(self.dim):\r\n for j in range(self.dim):\r\n for c in cities:\r\n if c == self.sol[i][j]:\r\n count[c] = count[c] + 1\r\n if count[c] > 1: \r\n test = False\r\n return test\r\n \r\n # Fig 2: Iterations Vs Cost line-graph \r\n def Graph_Fig2(self,X,Y,title):\r\n fig2 = plt.figure()\r\n plt.grid(b = \"True\",axis = \"both\",color=\"lightgrey\",linestyle = \"-\", linewidth = 0.5)\r\n plt.plot(X,Y,linestyle=\"-\",linewidth = 1)\r\n plt.title(\"Iterations Vs Cost line-graph for\" + title)\r\n plt.xlabel(\"Nr of iterations\")\r\n plt.ylabel(\"Cost\") \r\n print(\"\\nFig (2): Iterations Vs Cost line-graph for\" + title)\r\n filename = input(\"Save file as: \")\r\n plt.savefig(filename)\r\n\r\n # Fig 1: Visual representation of solution\r\n def Graph_Fig1(self,title): \r\n fig1 = plt.figure()\r\n colors = []\r\n for i in range(self.dim):\r\n colors.append('#%06X' % np.random.randint(0, 0xFFFFFF))\r\n x = [[0 for i in range(self.dim + 2)] for j in range(self.dim)]\r\n y = [[0 for i in range(self.dim + 2)] for j in range(self.dim)]\r\n if (self.n == 1):\r\n x[0][1] = self.df_TSP.iloc[self.sol[0],1] \r\n y[0][1] = self.df_TSP.iloc[self.sol[0],2] \r\n else: \r\n for i in range(self.dim):\r\n for j in range(self.dim): \r\n x[i][j+1] = self.df_TSP.iloc[self.sol[i][j],1]\r\n y[i][j+1] = self.df_TSP.iloc[self.sol[i][j],2] \r\n plt.grid(b = \"True\",axis = \"both\",color=\"lightgrey\",linestyle = \"-\", linewidth = 0.5)\r\n plt.axhline(y=0,color = \"grey\", linewidth = 1)\r\n plt.axvline(x = 0, color = \"grey\", linewidth = 1)\r\n trucks = [\"\" for i in range(self.dim)]\r\n for i in range(self.dim):\r\n trucks[i] = \"Truck \" + str(i+1)\r\n for i in range(self.dim): \r\n plt.plot(x[i][:],y[i][:], linestyle =\"-\", marker = \"o\", color = colors[i], linewidth = 1,label = trucks[i]) \r\n plt.legend(loc = \"upper left\")\r\n plt.title(\"Visual representation of solution for\" + title)\r\n print(\"\\nFig (1): Visual representation of solution\" + title)\r\n filename = input(\"Save file as: \")\r\n plt.savefig(filename)\r\n \r\n \r\n # write to csv file \r\n def WriteToFile(self,cost,f):\r\n filename = input(\"\\nSave file as < filename.csv >\")\r\n with open(filename,'w') as writeFile:\r\n if (self.n == 1):\r\n writeFile.write(str(0) + \"\\n\")\r\n else: \r\n for i in range(self.dim):\r\n writeFile.write(','.join(str(s) for s in self.sol[i]))\r\n writeFile.write(\"\\n\") \r\n writeFile.write(str(cost) +\"\\n\" + str(f)) \r\n\r\n # write to binary file\r\n def WB_to_file(self,cost,f):\r\n filename = input(\"\\nSave file as \")\r\n found = False\r\n try :\r\n file = open(filename,\"rb\")\r\n prev_run = pickle.load(file)\r\n found = True\r\n except FileNotFoundError :\r\n print(\"New file with name \" + filename + \" is created!\")\r\n file = open(filename,\"wb\")\r\n if (found == True):\r\n pickle.dump(prev_run,file)\r\n pickle.dump(self.sol,file)\r\n pickle.dump(f,file)\r\n pickle.dump(cost,file)\r\n file.close()\r\n \r\n\r\n\r\n ","sub_path":"Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":22138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"163360922","text":"\"\"\"\nClass that handles logins.\n\"\"\"\nimport typing\n\nimport functools\n\nimport asyncio\n\nfrom kyokai import Kyokai, Request\nfrom kyokai.response import redirect, Response\n\ntry:\n import itsdangerous\nexcept ImportError:\n raise ImportError(\"itsdangerous is not installed - cannot use session extension\")\n\n\nclass SessionUser(object):\n \"\"\"\n This is a stub class, that is used for KyoukaiSession.\n\n You can override this class and use it with KyoukaiSession.\n \"\"\"\n def __init__(self):\n \"\"\"\n The only attribute that is required here is `self.id`.\n \"\"\"\n self.id = None\n\n\nclass KyoukaiSession(object):\n \"\"\"\n A KyoukaiSession object provides a few useful methods for handling client logins.\n\n The class takes a callable, which will then be called to get a user upon a request.\n\n This user will be passed in to your route, as the second argument.\n\n To require login on a route, decorate the route with `@sess.login_required`, for example:\n\n ```python\n @app.route(\"/\")\n @session.login_required\n async def index(request: Request, user: User):\n return \"You are \" + repr(user)\n ```\n\n If the user is not logged in, then it will redirect them to `redirect_uri`. This can be passed as the second param.\n\n This ext is Flask-like in terms of handling the application object - you can either pass it as the last item of\n the args, or call `init_app` later to initialize it.\n\n To login a user, return `session.login(id, redirect_uri=\"/\")`, which will return a response that logs in the\n specified ID, and redirects them.\n \"\"\"\n def __init__(self, user_f, redirect_uri: str=\"/login\", app: Kyokai=None):\n \"\"\"\n Create a new KyoukaiSession object.\n \"\"\"\n\n self._callable_f = user_f\n self.redirect_uri = redirect_uri\n\n self.secret_key = b\"\"\n self.signer = None\n\n if app:\n self.init_app(app)\n\n def init_app(self, app: Kyokai):\n \"\"\"\n Loads the secret key from the config.\n \"\"\"\n try:\n self.secret_key = app.config[\"secret_key\"].encode()\n except KeyError:\n raise Exception(\"You must set a secret key in `config.yml` for sessions to work.\")\n\n self.signer = itsdangerous.Signer(self.secret_key)\n\n def _get_id(self, request: Request):\n \"\"\"\n Checks a request for the cookie headers.\n \"\"\"\n cook = request.cookies.get(\"KySess\")\n if not cook:\n return None\n # Load, and unsign.\n try:\n id = self.signer.unsign(cook)\n except itsdangerous.BadSignature:\n return None\n else:\n return id\n\n def login_required(self, func):\n \"\"\"\n Decorator for checking if the login is correct.\n \"\"\"\n @functools.wraps(func)\n async def _login_required_fake_func(request: Request, *args):\n \"\"\"\n You will never see this.\n\n Enforces login.\n \"\"\"\n id = self._get_id(request)\n if not id:\n return redirect(self.redirect_uri)\n # Get the user object.\n if asyncio.iscoroutine(self._callable_f):\n # Don't know why, but ok\n u = await self._callable_f\n elif asyncio.iscoroutinefunction(self._callable_f):\n u = await self._callable_f(id)\n else:\n u = self._callable_f(id)\n # Await the underlying function.\n return await func(request, u, *args)\n\n return _login_required_fake_func\n\n def login(self, id, redirect_uri=\"/\"):\n \"\"\"\n Logs in a user, and returns a Response.\n \"\"\"\n r = redirect(redirect_uri)\n r.cookies[\"KySess\"] = self.signer.sign(id)\n return r","sub_path":"kyokai/ext/sessions/sessionhandler.py","file_name":"sessionhandler.py","file_ext":"py","file_size_in_byte":3812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"642017241","text":"import csv\nimport os\nfrom functools import partial\n\nimport pytest\n\nfrom finance.web import create_app\nfrom finance.importers import import_stock_values\nfrom finance.models import db as _db\nfrom finance.models import (\n Account,\n AccountType,\n Asset,\n AssetType,\n CurrencyAsset,\n FundAsset,\n P2PBondAsset,\n Portfolio,\n StockAsset,\n)\n\n\n@pytest.fixture(scope=\"session\")\ndef app(request):\n \"\"\"Session-wide test `Flask` application.\"\"\"\n settings_override = {\n \"TESTING\": True,\n }\n settings_override[\"SQLALCHEMY_DATABASE_URI\"] = os.environ[\"TEST_DB_URL\"]\n app = create_app(__name__, config=settings_override)\n\n # Establish an application context before running the tests.\n # ctx = app.app_context()\n # ctx.push()\n\n # def teardown():\n # ctx.pop()\n\n # request.addfinalizer(teardown)\n return app\n\n\n@pytest.fixture\ndef testapp(app, db):\n with app.app_context():\n yield app.test_client()\n\n\n@pytest.fixture(scope=\"module\", autouse=True)\ndef db(app, request):\n \"\"\"Session-wide test database.\"\"\"\n\n def teardown():\n with app.app_context():\n _db.session.close()\n _db.drop_all()\n\n request.addfinalizer(teardown)\n\n _db.app = app\n with app.app_context():\n _db.create_all()\n\n yield _db\n\n\n@pytest.fixture(scope=\"module\")\ndef stock_assets():\n with open(\"tests/samples/stocks.csv\") as fin:\n reader = csv.reader(fin, delimiter=\",\")\n for row in reader:\n isin, code, name = row\n if isin.startswith(\"#\"):\n continue\n Asset.create(type=AssetType.stock, isin=isin, code=code, name=name)\n\n\n@pytest.fixture(scope=\"function\")\ndef account_checking(request, db):\n account = Account.create(type=\"checking\", name=\"신한은행 입출금\")\n request.addfinalizer(partial(teardown, db=db, record=account))\n return account\n\n\n@pytest.fixture(scope=\"function\")\ndef account_savings(request, db):\n account = Account.create(type=\"savings\", name=\"신한은행 적금\")\n request.addfinalizer(partial(teardown, db=db, record=account))\n return account\n\n\n@pytest.fixture(scope=\"function\")\ndef account_8p(request, db):\n account = Account.create(type=\"virtual\", name=\"8퍼센트\")\n request.addfinalizer(partial(teardown, db=db, record=account))\n return account\n\n\n@pytest.fixture(scope=\"function\")\ndef account_hf(request, db):\n account = Account.create(type=\"virtual\", name=\"어니스트펀드\")\n request.addfinalizer(partial(teardown, db=db, record=account))\n return account\n\n\n@pytest.fixture(scope=\"function\")\ndef account_sp500(request, db):\n account = Account.create(type=\"investment\", name=\"S&P500 Fund\")\n request.addfinalizer(partial(teardown, db=db, record=account))\n return account\n\n\n@pytest.fixture(scope=\"function\")\ndef account_stock(request, db):\n account = Account.create(\n type=AccountType.investment,\n institution=\"Miraeasset\",\n number=\"ACCOUNT1\",\n name=\"미래에셋대우 1\",\n )\n request.addfinalizer(partial(teardown, db=db, record=account))\n return account\n\n\n@pytest.fixture(scope=\"module\")\ndef asset_hf1(request, db):\n asset = P2PBondAsset.create(name=\"포트폴리오 투자상품 1호\")\n request.addfinalizer(partial(teardown, db=db, record=asset))\n assert asset.type == \"p2p_bond\"\n return asset\n\n\n@pytest.fixture(scope=\"module\")\ndef asset_krw(request, db):\n asset = CurrencyAsset.create(code=\"KRW\", description=\"Korean Won\")\n request.addfinalizer(partial(teardown, db=db, record=asset))\n return asset\n\n\n@pytest.fixture(scope=\"module\")\ndef asset_sp500(request, db):\n asset = FundAsset.create(\n name=\"KB Star S&P500\", description=\"\", data={\"code\": \"KR5223941018\"}\n )\n request.addfinalizer(partial(teardown, db=db, record=asset))\n return asset\n\n\n@pytest.fixture(scope=\"module\")\ndef asset_usd(request, db):\n asset = CurrencyAsset.create(code=\"USD\", description=\"United States Dollar\")\n request.addfinalizer(partial(teardown, db=db, record=asset))\n return asset\n\n\n@pytest.fixture(scope=\"module\")\ndef stock_asset_ncsoft(request, db):\n asset = StockAsset.create(\n name=\"NCsoft Corporation\",\n code=\"036570.KS\",\n description=\"NCsoft Corporation\",\n data={\"bps\": 88772, \"eps\": 12416},\n )\n request.addfinalizer(partial(teardown, db=db, record=asset))\n return asset\n\n\n@pytest.fixture(scope=\"module\")\ndef stock_asset_spy(request, db, asset_usd):\n asset = StockAsset.create(\n name=\"SPY\",\n code=\"SPY\",\n isin=\"US78462F1030\",\n description=\"SPDR S&P 500 ETF Trust Fund\",\n )\n request.addfinalizer(partial(teardown, db=db, record=asset))\n\n with open(\"tests/samples/SPY.csv\") as fin:\n for av in import_stock_values(fin, \"SPY\", base_asset=asset_usd):\n request.addfinalizer(partial(teardown, db=db, record=av))\n\n return asset\n\n\n@pytest.fixture(scope=\"module\")\ndef stock_asset_amd(request, db, asset_usd):\n asset = StockAsset.create(\n name=\"AMD\",\n code=\"AMD\",\n isin=\"US0079031078\",\n description=\"Advanced Micro Devices, Inc\",\n )\n request.addfinalizer(partial(teardown, db=db, record=asset))\n\n with open(\"tests/samples/AMD.csv\") as fin:\n for av in import_stock_values(fin, \"AMD\", base_asset=asset_usd):\n request.addfinalizer(partial(teardown, db=db, record=av))\n\n return asset\n\n\n@pytest.fixture(scope=\"module\")\ndef stock_asset_nvda(request, db, asset_usd):\n asset = StockAsset.create(\n name=\"NVDA\", code=\"NVDA\", isin=\"US67066G1040\", description=\"NVIDIA Corporation\"\n )\n request.addfinalizer(partial(teardown, db=db, record=asset))\n\n with open(\"tests/samples/NVDA.csv\") as fin:\n for av in import_stock_values(fin, \"NVDA\", base_asset=asset_usd):\n request.addfinalizer(partial(teardown, db=db, record=av))\n\n return asset\n\n\n@pytest.fixture(scope=\"module\")\ndef stock_asset_amzn(request, db, asset_usd):\n asset = StockAsset.create(\n name=\"AMZN\", code=\"AMZN\", isin=\"US0231351067\", description=\"Amazon\"\n )\n request.addfinalizer(partial(teardown, db=db, record=asset))\n\n with open(\"tests/samples/AMZN.csv\") as fin:\n for av in import_stock_values(fin, \"AMZN\", base_asset=asset_usd):\n request.addfinalizer(partial(teardown, db=db, record=av))\n\n return asset\n\n\n@pytest.fixture(scope=\"module\")\ndef stock_asset_sbux(request, db, asset_usd):\n asset = StockAsset.create(\n name=\"SBUX\", code=\"SBUX\", isin=\"US8552441094\", description=\"Starbucks\"\n )\n request.addfinalizer(partial(teardown, db=db, record=asset))\n\n with open(\"tests/samples/SBUX.csv\") as fin:\n for av in import_stock_values(fin, \"SBUX\", base_asset=asset_usd):\n request.addfinalizer(partial(teardown, db=db, record=av))\n\n return asset\n\n\n@pytest.fixture(scope=\"function\")\ndef portfolio(request, db, asset_krw, account_checking, account_sp500):\n p = Portfolio.create(base_asset=asset_krw)\n p.add_accounts(account_checking, account_sp500)\n\n def teardown():\n # NOTE: The following statement is necessary because the scope of\n # `asset_krw` is a module, whereas the scope of `p` is a function.\n p.base_asset = None\n db.session.delete(p)\n db.session.commit()\n\n request.addfinalizer(teardown)\n return p\n\n\ndef teardown(db, record):\n db.session.delete(record)\n db.session.commit()\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":7436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"256495441","text":"# Copyright 2020, 2021 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\nimport argparse\n\nimport dpctl\nimport numba\nimport numpy as np\n\nimport numba_dppy as dppy\n\n\ndef func(param_a, param_b):\n param_c = param_a + 10 # Set breakpoint\n param_d = param_b * 0.5\n result = param_c + param_d\n return result\n\n\ndppy_func = dppy.func(debug=True)(func)\nnumba_func = numba.njit(debug=True)(func)\n\n\n@dppy.kernel(debug=True)\ndef dppy_kernel(a_in_kernel, b_in_kernel, c_in_kernel):\n i = dppy.get_global_id(0)\n c_in_kernel[i] = dppy_func(a_in_kernel[i], b_in_kernel[i])\n\n\n@numba.njit(debug=True)\ndef numba_func_driver(a, b, c):\n for i in range(len(c)):\n c[i] = numba_func(a[i], b[i])\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--api\",\n required=False,\n default=\"numba\",\n choices=[\"numba\", \"numba-dppy\"],\n help=\"Start the version of functions using numba or numba-dppy API\",\n )\n\n args = parser.parse_args()\n\n print(\"Using API:\", args.api)\n\n global_size = 10\n N = global_size\n\n a = np.arange(N, dtype=np.float32)\n b = np.arange(N, dtype=np.float32)\n c = np.empty_like(a)\n\n if args.api == \"numba-dppy\":\n device = dpctl.select_default_device()\n with dppy.offload_to_sycl_device(device):\n dppy_kernel[global_size, dppy.DEFAULT_LOCAL_SIZE](a, b, c)\n else:\n numba_func_driver(a, b, c)\n\n print(\"Done...\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"numba_dppy/examples/debug/dppy_numba_basic.py","file_name":"dppy_numba_basic.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"612796420","text":"from collections import Counter\nimport spacy\n\n\ndef complex_words_PoS_count(dataset):\n tag_count = Counter()\n for sent in dataset:\n word = sent['target_word']\n tokenized_word = word.split()\n sentence = sent['sentence']\n gold_label = sent['gold_label']\n nlp = spacy.load('en_core_web_sm')\n doc = nlp(sentence)\n\n tags = [(token.text, token.tag_) for token in doc]\n if gold_label == \"1\":\n if len(tokenized_word) == 1:\n tokenized_word = word\n for tag in tags:\n if tag[0] == word:\n tag_count[tag[1]] += 1\n # And sometimes you get more than one word\n elif (len(tokenized_word) > 1):\n for word in tokenized_word:\n for tag in tags:\n if tag[0] == word:\n tag_count[tag[1]] += 1\n\n return tag_count\n","sub_path":"pos_counts.py","file_name":"pos_counts.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"439891390","text":"import numpy as np\nimport pandas as pd\n\ndef mirror_mat(matrix):\n grid = [row[:] for row in matrix]\n n = len(grid)\n m = len(grid[0])\n m2 = round(m/2)\n for i in range(n):\n for j in range(m2):\n temp = grid[i][j]\n grid[i][j] = grid[i][m-j-1]\n grid[i][m-j-1] = temp\n return grid\n\ndef transpose_mat(matrix):\n grid = [row[:] for row in matrix]\n n = len(grid)\n m = len(grid[0])\n for i in range(n):\n for j in range(m):\n if(i= threshold)\n corners = [[0,0],[0,m-1],[n-1,0],[n-1,m-1]]\n score = 0\n for r in range(len(relevant)):\n dists = []\n for c in range(len(corners)):\n a = relevant[r]\n b = corners[c]\n dists.append(np.linalg.norm(a-b))\n print(dists)\n min_distance = min(dists)\n score += min_distance\n return score\n\ndef avg_dist_between_largest(matrix, num_sigma=2):\n grid = np.array(matrix)\n miu = grid.mean()\n sigma = grid.std()\n threshold = round(miu + num_sigma * sigma)\n relevant = np.argwhere(grid >= threshold)\n distances = []\n done = []\n for r0 in range(len(relevant)):\n for r1 in range(len(relevant)):\n if [r0,r1] not in done and [r1,r0] not in done:\n distances.append(np.linalg.norm(relevant[r0]-relevant[r1]))\n done.append([[r0,r1]])\n avg_dist = sum(distances)/len(distances)\n return avg_dist\n\ngrid = [[4, 8, 8, 64],\n [0, 0, 0, 0 ],\n [0, 0, 0, 2 ],\n [4, 0, 0, 2 ]]\n\n\n\nprint(avg_dist_between_largest(grid))","sub_path":"other/2048.py","file_name":"2048.py","file_ext":"py","file_size_in_byte":3644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"575347638","text":"from django.shortcuts import render, redirect, get_object_or_404\r\nfrom django.contrib import messages\r\nfrom django.contrib.auth.models import User\r\nfrom django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView\r\nfrom django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\r\nfrom .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm\r\nfrom .models import Post\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.views import View\r\nfrom django.http import HttpResponse\r\n\r\n\r\n\r\ndef index(request):\r\n return render(request, 'bashmycode/index.html')\r\n\r\nclass PostListViewBash(ListView):\r\n model = Post\r\n queryset = Post.objects.filter(post_type='BASH').order_by('-likes')\r\n template_name = 'bashmycode/bash.html' # /_.html\r\n context_object_name = 'posts'\r\n paginate_by = 5\r\n\r\n# SOMETHING WRONG WITH PAGINATION ON HELP\r\nclass PostListViewHelp(ListView):\r\n model = Post\r\n queryset = Post.objects.filter(post_type='HELP').order_by('-likes')\r\n template_name = 'bashmycode/help.html' # /_.html\r\n context_object_name = 'posts'\r\n paginate_by = 5\r\n\r\n\r\nclass UserPostListView(ListView):\r\n model = Post\r\n template_name = 'bashmycode/user_posts.html' # /_.html\r\n context_object_name = 'posts'\r\n paginate_by = 5\r\n\r\n def get_queryset(self):\r\n user = get_object_or_404(User, username=self.kwargs.get('username'))\r\n return Post.objects.filter(author=user).order_by('-likes')\r\n\r\nclass PostDetailView(DetailView):\r\n model = Post\r\n\r\nclass PostCreateView(LoginRequiredMixin, CreateView):\r\n model = Post\r\n fields = ['title', 'content', 'post_type']\r\n\r\n def form_valid(self, form):\r\n form.instance.author = self.request.user\r\n return super().form_valid(form)\r\n\r\nclass PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):\r\n model = Post\r\n fields = ['title', 'content', 'post_type']\r\n\r\n def form_valid(self, form):\r\n form.instance.author = self.request.user\r\n return super().form_valid(form)\r\n \r\n def test_func(self):\r\n post = self.get_object()\r\n if self.request.user == post.author:\r\n return True\r\n return False\r\n\r\nclass PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):\r\n model = Post\r\n success_url = '/bashmycode/'\r\n\r\n def test_func(self):\r\n post = self.get_object()\r\n if self.request.user == post.author:\r\n return True\r\n return False\r\n\r\n\r\nclass LikePostView(View):\r\n def get(self, request):\r\n post_id = request.GET['post_id']\r\n try:\r\n post = Post.objects.get(id=int(post_id))\r\n except Post.DoesNotExist:\r\n return HttpResponse(-1)\r\n except ValueError:\r\n return HttpResponse(-1)\r\n post.likes = post.likes + 1\r\n post.save()\r\n \r\n return HttpResponse(post.likes)\r\n\r\n\r\ndef bash(request):\r\n context = {\r\n 'posts': Post.objects.filter(post_type='BASH').order_by('-date_posted')\r\n }\r\n return render(request, 'bashmycode/bash.html', context)\r\n\r\ndef help(request):\r\n context = {\r\n 'posts': Post.objects.filter(post_type='HELP').order_by('-date_posted')\r\n }\r\n return render(request, 'bashmycode/bash.html', context)\r\ndef register(request):\r\n if request.method == 'POST':\r\n form = UserRegisterForm(request.POST)\r\n if form.is_valid():\r\n form.save()\r\n username = form.cleaned_data.get('username')\r\n messages.success(request, f'Account created for {username}!')\r\n return redirect('/bashmycode/login')\r\n else:\r\n form = UserRegisterForm()\r\n return render(request, 'bashmycode/register.html', {'form': form})\r\n\r\n@login_required\r\ndef profile(request):\r\n if request.method == 'POST':\r\n u_form = UserUpdateForm(request.POST, instance=request.user)\r\n p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)\r\n if u_form.is_valid() and p_form.is_valid():\r\n u_form.save()\r\n p_form.save()\r\n messages.success(request, f'Your account has been updated!')\r\n return redirect('/bashmycode/profile')\r\n else:\r\n u_form = UserUpdateForm(instance=request.user)\r\n p_form = ProfileUpdateForm(instance=request.user.profile)\r\n\r\n context = {\r\n 'u_form': u_form,\r\n 'p_form': p_form\r\n }\r\n\r\n return render(request, 'bashmycode/profile.html', context)","sub_path":"bashmycode/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"645230283","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\nimport os\nimport random\nimport sys\nimport time\n\nimport numpy as np\nfrom six.moves import xrange # pylint: disable=redefined-builtin\nimport tensorflow as tf\nfrom tensorflow.contrib import learn\nimport logging\nimport data_utils\nfrom cnnLstmSerialModel import SerialModel\n\nimport data_iterator\nfrom data_iterator import DataIterator\nfrom tensorflow.python.client import timeline\n\nfrom summary import ModelSummary, variable_summaries\n\nimport argparse\n\n############################\n######## MARK:FLAGS ########\n############################\nparser = argparse.ArgumentParser(description=\"Sequence to Sequence Using Tensorflow.\")\n# mode\nparser.add_argument(\"--mode\", type=str, default=\"TRAIN\", help=\"TRAIN|DECODE\")\n\n# datasets, paths, and preprocessing\nparser.add_argument(\"--model_dir\", type=str, default=\"./model\", help=\"model_dir/data_cache/n model_dir/saved_model; model_dir/log.txt .\")\nparser.add_argument(\"--train_path_from\", type=str, default=\"./train.src\", help=\"the absolute path of raw source train file.\")\nparser.add_argument(\"--dev_path_from\", type=str, default=\"./dev.src\", help=\"the absolute path of raw source dev file.\")\nparser.add_argument(\"--test_path_from\", type=str, default=\"./test.src\", help=\"the absolute path of raw source test file.\")\nparser.add_argument(\"--word_vec_path\", type=str, default=\"./word2vec.txt\", help=\"the absolute path of word vectors file.\")\n\nparser.add_argument(\"--train_path_to\", type=str, default=\"./train.tgt\", help=\"the absolute path of raw target train file.\")\nparser.add_argument(\"--dev_path_to\", type=str, default=\"./dev.tgt.tgt\", help=\"the absolute path of raw target dev file.\")\nparser.add_argument(\"--test_path_to\", type=str, default=\"./test.tgt\", help=\"the absolute path of raw target test file.\")\n\nparser.add_argument(\"--decode_output\", type=str, default=\"./test.output\", help=\"beam search decode output.\")\n\n# tuning hypers\nparser.add_argument(\"--learning_rate\", type=float, default=0.5, help=\"Learning rate.\")\nparser.add_argument(\"--learning_rate_decay_factor\", type=float, default=0.83, help=\"Learning rate decays by this much.\")\nparser.add_argument(\"--max_gradient_norm\", type=float, default=5.0, help=\"Clip gradients to this norm.\")\nparser.add_argument(\"--keep_prob\", type=float, default=0.8, help=\"dropout rate.\")\nparser.add_argument(\"--batch_size\", type=int, default=128, help=\"Batch size to use during training/evaluation.\")\nparser.add_argument(\"--dilation_rate\",type=int,default=1,help=\"the dilatation of dilated convoluational kernel\")\n\nparser.add_argument(\"--from_vocab_size\", type=int, default=10000, help=\"from vocabulary size.\")\nparser.add_argument(\"--to_vocab_size\", type=int, default=10000, help=\"to vocabulary size.\")\n\nparser.add_argument(\"--size\", type=int, default=128, help=\"Size of each model layer.\")\nparser.add_argument(\"--num_layers\", type=int, default=2, help=\"Number of layers in the model.\")\nparser.add_argument(\"--n_epoch\", type=int, default=50, help=\"Maximum number of epochs in training.\")\n\nparser.add_argument(\"--L\", type=int, default=2000, help=\"max length\")\nparser.add_argument(\"--patience\", type=int, default=10, help=\"exit if the model can't improve for $patence / 2 epochs\")\n\n# devices\nparser.add_argument(\"--N\", type=str, default=\"000\", help=\"GPU layer distribution: [input_embedding, lstm, output_embedding]\")\n\n# training parameter\nparser.add_argument(\"--withAdagrad\", type=bool, default=True, help=\"withAdagrad.\")\nparser.add_argument(\"--fromScratch\", type=bool, default=True, help=\"fromScratch.\")\nparser.add_argument(\"--saveCheckpoint\", type=bool, default=False, help=\"save Model at each checkpoint.\")\nparser.add_argument(\"--profile\", type=bool, default=False, help=\"False = no profile, True = profile\")\n\n# GPU configuration\nparser.add_argument(\"--allow_growth\", type=bool, default=False, help=\"allow growth\")\n\n# Summary\nparser.add_argument(\"--with_summary\", type=bool, default=False, help=\"with_summary\")\nparser.add_argument(\"--data_cache_dir\", type=str, default=\"data_cache\", help=\"data_cache\")\n\nFLAGS = parser.parse_args()\n\ndef mylog(msg):\n print(msg)\n sys.stdout.flush()\n logging.info(msg)\n\n\ndef mylog_section(section_name):\n mylog(\"======== {} ========\".format(section_name)) \n\ndef mylog_subsection(section_name):\n mylog(\"-------- {} --------\".format(section_name)) \n\ndef mylog_line(section_name, message):\n mylog(\"[{}] {}\".format(section_name, message))\n\n\ndef get_device_address(s):\n add = []\n if s == \"\":\n for i in xrange(3):\n add.append(\"/cpu:0\")\n else:\n add = [\"/gpu:{}\".format(int(x)) for x in s]\n\n return add\n\ndef show_all_variables():\n all_vars = tf.global_variables()\n for var in all_vars:\n mylog(var.name)\n\n\ndef log_flags():\n mylog_section(\"FLAGS\")\n for attr, value in sorted(FLAGS.__dict__.items()):\n mylog(\"{}={}\".format(attr.upper(), value))\n\ndef create_model(session, run_options, run_metadata, max_len):\n devices = get_device_address(FLAGS.N)\n dtype = tf.float32\n model = SerialModel(FLAGS.size,\n FLAGS.real_vocab_size_from,\n FLAGS.real_vocab_size_to,\n FLAGS.num_layers,\n FLAGS.max_gradient_norm,\n FLAGS.batch_size,\n max_len,\n FLAGS.learning_rate,\n FLAGS.learning_rate_decay_factor,\n withAdagrad = FLAGS.withAdagrad,\n dropoutRate = FLAGS.keep_prob,\n dtype = dtype,\n devices = devices,\n run_options = run_options,\n run_metadata = run_metadata,\n word_vector = FLAGS.word_vector,\n dilation_rate=FLAGS.dilation_rate,\n )\n\n ckpt = tf.train.get_checkpoint_state(FLAGS.saved_model_dir)\n\n if FLAGS.mode == \"DECODE\":\n mylog(\"Reading model parameters from %s\" % ckpt.model_checkpoint_path)\n model.saver.restore(session, ckpt.model_checkpoint_path)\n else:\n mylog(\"Created model with fresh parameters.\")\n session.run(tf.global_variables_initializer())\n return model\n\ndef train():\n\n # Read Data\n mylog_section(\"READ DATA\")\n\n from_train = None\n to_train = None\n from_dev = None\n to_dev = None\n \n from_train, to_train, from_dev, to_dev, _, _ = data_utils.prepare_data(\n FLAGS.data_cache_dir,\n FLAGS.train_path_from,\n FLAGS.train_path_to,\n FLAGS.dev_path_from,\n FLAGS.dev_path_to,\n FLAGS.from_vocab_size,\n FLAGS.to_vocab_size)\n\n train_data, train_max_len = data_utils.read_data(from_train,to_train)\n dev_data, dev_max_len = data_utils.read_data(from_dev,to_dev)\n max_len = max(train_max_len, dev_max_len)\n _,_,real_vocab_size_from,real_vocab_size_to = data_utils.get_vocab_info(FLAGS.data_cache_dir)\n \n FLAGS.real_vocab_size_from = real_vocab_size_from\n FLAGS.real_vocab_size_to = real_vocab_size_to\n\n if FLAGS.word_vector:\n \tword_embedding, _ = data_utils.read_word_vec(FLAGS.word_vec_path, FLAGS.data_cache_dir)\n else:\n \tword_embedding = None\n\n train_n_tokens = np.sum([len(items[1]) for items in train_data])\n train_total_size = len(train_data)\n dev_total_size = len(dev_data)\n\n mylog_section(\"REPORT\")\n # steps\n batch_size = FLAGS.batch_size\n n_epoch = FLAGS.n_epoch\n steps_per_epoch = int(train_total_size / batch_size)\n steps_per_dev = int(dev_total_size / batch_size)\n steps_per_checkpoint = int(steps_per_epoch / 2)\n total_steps = steps_per_epoch * n_epoch\n\n # reports\n mylog(\"from_vocab_size: {}\".format(FLAGS.from_vocab_size))\n mylog(\"to_vocab_size: {}\".format(FLAGS.to_vocab_size))\n mylog(\"Train:\")\n mylog(\"total: {}\".format(train_total_size))\n mylog(\"Dev:\")\n mylog(\"total: {}\".format(dev_total_size))\n mylog(\"Steps_per_epoch: {}\".format(steps_per_epoch))\n mylog(\"Total_steps:{}\".format(total_steps))\n mylog(\"Steps_per_checkpoint: {}\".format(steps_per_checkpoint))\n\n\n mylog_section(\"IN TENSORFLOW\")\n \n with tf.Graph().as_default():\n tf.set_random_seed(23)\n config = tf.ConfigProto(allow_soft_placement=True, log_device_placement = False)\n config.gpu_options.allow_growth = FLAGS.allow_growth\n config.gpu_options.per_process_gpu_memory_fraction = 1.0\n with tf.Session(config=config) as sess:\n \n # runtime profile\n if FLAGS.profile:\n run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n run_metadata = tf.RunMetadata()\n else:\n run_options = None\n run_metadata = None\n \n mylog_section(\"MODEL/SUMMARY/WRITER\")\n \n mylog(\"Creating Model.. (this can take a few minutes)\")\n model = create_model(sess, run_options, run_metadata, max_len)\n \n if FLAGS.with_summary:\n mylog(\"Creating ModelSummary\")\n modelSummary = ModelSummary()\n \n mylog(\"Creating tf.summary.FileWriter\")\n summaryWriter = tf.summary.FileWriter(os.path.join(FLAGS.summary_dir , \"train.summary\"), sess.graph)\n \n mylog_section(\"All Variables\")\n show_all_variables() #convenient for checking model variables\n \n # Data Iterators\n mylog_section(\"Data Iterators\")\n \n dite = DataIterator(model, train_data, batch_size)\n \n iteType = 0\n if iteType == 0:\n mylog(\"Itetype: withRandom\")\n ite = dite.next_random()\n elif iteType == 1:\n mylog(\"Itetype: withSequence\")\n ite = dite.next_sequence()\n \n # statistics during training\n step_time, loss = 0.0, 0.0\n correct = 0\n current_step = 0\n previous_losses = []\n high_acc = -1\n high_acc_step = 0\n steps_per_report = 30\n n_targets_report = 0\n report_time = 0\n n_valid_sents = 0\n n_valid_words = 0\n patience = FLAGS.patience\n \n mylog_section(\"TRAIN\")\n \n \n while current_step < total_steps:\n \n # start\n start_time = time.time()\n \n # data and train\n source_inputs, source_lengths, target_outputs = ite.next()\n\n L, unary_scores, transition_matrix = model.step(sess, source_inputs, target_outputs, source_lengths, word_embedding)\n \n # loss and time\n step_time += (time.time() - start_time) / steps_per_checkpoint\n \n _, correct_labels = CRF_viterbi_decode(unary_scores, transition_matrix, source_lengths, target_outputs)\n correct += correct_labels\n loss += L\n \n current_step += 1\n n_valid_sents += np.sum(np.sign(source_lengths))\n n_valid_words += np.sum(source_lengths)\n \n # for report\n report_time += (time.time() - start_time)\n n_targets_report += np.sum(source_lengths)\n \n if current_step % steps_per_report == 0:\n sect_name = \"STEP {}\".format(current_step)\n msg = \"StepTime: {:.2f} sec Speed: {:.2f} targets/s Total_targets: {}\".format(report_time/steps_per_report, n_targets_report*1.0 / report_time, train_n_tokens)\n mylog_line(sect_name,msg)\n \n report_time = 0\n n_targets_report = 0\n \n \n # Create the Timeline object, and write it to a json\n if FLAGS.profile:\n tl = timeline.Timeline(run_metadata.step_stats)\n ctf = tl.generate_chrome_trace_format()\n with open('timeline.json', 'w') as f:\n f.write(ctf)\n exit()\n\n \n if current_step % steps_per_checkpoint == 0:\n \n i_checkpoint = int(current_step / steps_per_checkpoint)\n \n # train_acc\n loss = loss / n_valid_words\n train_acc = correct * 1.0 / n_valid_words\n learning_rate = model.learning_rate.eval()\n \n # dev_acc\n dev_loss, dev_acc = evaluate(sess, model, dev_data, word_embedding)\n \n # report\n sect_name = \"CHECKPOINT {} STEP {}\".format(i_checkpoint, current_step)\n msg = \"Learning_rate: {:.4f} Dev_acc: {:.4f} Train_acc: {:.4f}\".format(learning_rate, dev_acc, train_acc)\n mylog_line(sect_name, msg)\n \n if FLAGS.with_summary:\n # save summary\n _summaries = modelSummary.step_record(sess, train_acc, dev_acc)\n for _summary in _summaries:\n summaryWriter.add_summary(_summary, i_checkpoint)\n \n # save model per checkpoint\n if False: # FLAGS.saveCheckpoint\n checkpoint_path = os.path.join(FLAGS.saved_model_dir, \"model\")\n s = time.time()\n model.saver.save(sess, checkpoint_path, global_step=i_checkpoint, write_meta_graph = False)\n msg = \"Model saved using {:.2f} sec at {}\".format(time.time()-s, checkpoint_path)\n mylog_line(sect_name, msg)\n \n # save best model\n if dev_acc > high_acc:\n patience = FLAGS.patience\n high_acc = dev_acc\n high_acc_step = current_step\n checkpoint_path = os.path.join(FLAGS.saved_model_dir, \"model\")\n s = time.time()\n model.saver.save(sess, checkpoint_path, global_step=i_checkpoint, write_meta_graph = False)\n msg = \"Model saved using {:.2f} sec at {}\".format(time.time()-s, checkpoint_path)\n mylog_line(sect_name, msg)\n \n else:\n patience -= 1\n \n if patience <= 0:\n mylog(\"Training finished. Running out of patience.\")\n break\n \n \n # Save checkpoint and zero timer and loss.\n step_time, loss, n_valid_sents, n_valid_words, correct = 0.0, 0.0, 0, 0, 0\n \n\ndef evaluate(sess, model, data_set, word_embedding):\n # Run evals on development set and print their perplexity/loss or accuracy.\n dropoutRateRaw = FLAGS.keep_prob\n\n start_id = 0\n loss = 0.0\n n_steps = 0\n n_valids = 0\n n_correct = 0\n batch_size = FLAGS.batch_size\n \n dite = DataIterator(model, data_set, batch_size)\n ite = dite.next_sequence()\n\n for sources, lengths, outputs in ite:\n L, unary_scores, transition_matrix= model.step(sess, sources, outputs, lengths, word_embedding, forward_only = True)\n _, correct_labels = CRF_viterbi_decode(unary_scores, transition_matrix, lengths, outputs)\n n_correct += correct_labels\n loss += L\n n_steps += 1\n n_valids += np.sum(lengths)\n\n loss = loss/(n_valids)\n acc = n_correct * 1.0 /(n_valids)\n\n\n return loss, acc\n\n\ndef CRF_viterbi_decode(unary_scores, transition_matrix, lengths, target_outputs=None):\n correct_labels = 0\n viterbi_seqs = []\n for i, (unary_score, length) in enumerate(zip(unary_scores, lengths)):\n unary_score = unary_score[:length]\n if length:\n viterbi_seq, _ = tf.contrib.crf.viterbi_decode(unary_score, transition_matrix)\n else:\n viterbi_seq = []\n viterbi_seqs.append(viterbi_seq)\n if target_outputs is not None:\n target = target_outputs[i][:length]\n correct_labels += np.sum(np.equal(viterbi_seq, target))\n return viterbi_seqs, correct_labels\n\n\ndef decode(ans=False):\n mylog_section(\"READ DATA\")\n\n from_vocab_path, to_vocab_path, real_vocab_size_from, real_vocab_size_to = data_utils.get_vocab_info(FLAGS.data_cache_dir)\n FLAGS.real_vocab_size_from = real_vocab_size_from\n FLAGS.real_vocab_size_to = real_vocab_size_to\n\n from_test = data_utils.prepare_test_data(FLAGS.data_cache_dir, FLAGS.test_path_from, from_vocab_path)\n if ans:\n to_test = os.path.join(FLAGS.data_cache_dir, \"test.tgt.ids\")\n data_utils.data_to_token_ids(FLAGS.test_path_to, to_test, to_vocab_path)\n test_data, test_max_len = data_utils.read_data(from_test, to_test)\n else:\n test_data, test_max_len = data_utils.read_test_data(from_test)\n\n test_total_size = len(test_data)\n\n # reports\n mylog_section(\"REPORT\")\n mylog(\"from_vocab_size: {}\".format(FLAGS.from_vocab_size))\n mylog(\"to_vocab_size: {}\".format(FLAGS.to_vocab_size))\n mylog(\"DECODE:\")\n mylog(\"total: {}\".format(test_total_size))\n \n config = tf.ConfigProto(allow_soft_placement=True, log_device_placement = False)\n config.gpu_options.allow_growth = FLAGS.allow_growth\n config.gpu_options.per_process_gpu_memory_fraction = 1.0\n\n mylog_section(\"IN TENSORFLOW\")\n with tf.Session(config=config) as sess:\n\n # runtime profile\n if FLAGS.profile:\n run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n run_metadata = tf.RunMetadata()\n else:\n run_options = None\n run_metadata = None\n\n mylog(\"Creating Model\")\n model = create_model(sess, run_options, run_metadata, test_max_len)\n \n mylog_section(\"All Variables\")\n show_all_variables()\n \n #sess.run(model.dropoutRate.assign(1.0))\n\n start_id = 0\n n_steps = 0\n batch_size = FLAGS.batch_size\n\n mylog_section(\"Data Iterators\")\n dite = DataIterator(model, test_data, batch_size)\n ite = dite.next_sequence(test = (not ans))\n\n i_sent = 0\n\n mylog_section(\"DECODING\")\n results = []\n sources = []\n targets = []\n\n n_valids = 0\n n_correct = 0\n\n if ans:\n n_valids = 0\n n_correct = 0\n for inputs, lengths, outputs in ite:\n \n mylog(\"--- decoding {}/{} sent ---\".format(i_sent, test_total_size))\n i_sent += 1\n \n L, unary_scores,transition_matrix = model.step(sess, inputs, outputs, lengths, forward_only = True)\n viterbi_seqs, correct_labels = CRF_viterbi_decode(unary_scores, transition_matrix, lengths, outputs)\n results += viterbi_seqs\n n_correct += correct_labels\n n_valids += np.sum(lengths)\n\n mylog(\"Correct Labels / Total Labels: {} / {}\".format(correct_labels, np.sum(lengths)))\n n_valids += np.sum(lengths)\n n_correct += correct_labels\n \n sources += [inputs[i][:length] for i, length in enumerate(lengths)]\n targets += [outputs[i][:length] for i, length in enumerate(lengths)]\n\n else:\n outputs = np.zeros([batch_size, test_max_len], dtype=int)\n for inputs, lengths in ite:\n # inputs: [[_GO],[1],[2],[3],[_EOS],[pad_id],[pad_id]]\n # positions: [4]\n mylog(\"--- decoding {}/{} sent ---\".format(i_sent, test_total_size))\n i_sent += 1\n \n L, unary_scores,transition_matrix = model.step(sess, inputs, outputs, lengths, forward_only = True)\n viterbi_seqs, _ = CRF_viterbi_decode(unary_scores, transition_matrix, lengths)\n results += viterbi_seqs\n mylog(\"LOSS: {}\".format(L))\n \n sources += [inputs[i][:length] for i, length in enumerate(lengths)]\n \n # do the following convert:\n # inputs: [[pad_id],[1],[2],[pad_id],[pad_id],[pad_id]]\n # positions:[2]\n data_utils.ids_to_tokens(results, to_vocab_path, FLAGS.decode_output)\n data_utils.ids_to_tokens(sources, from_vocab_path, FLAGS.decode_output+'.src')\n if ans:\n data_utils.ids_to_tokens(targets, to_vocab_path, FLAGS.decode_output+'.tgt')\n msg = \"Test_acc: {:.4f}\".format(n_correct * 1.0 /(n_valids))\n mylog(msg)\n mylog(\"Decoding finished.\")\n\n\ndef mkdir(path):\n if not os.path.exists(path):\n os.mkdir(path)\n\n\ndef parsing_flags():\n # saved_model\n\n FLAGS.data_cache_dir = os.path.join(FLAGS.model_dir, \"data_cache\")\n FLAGS.saved_model_dir = os.path.join(FLAGS.model_dir, \"saved_model\")\n FLAGS.summary_dir = FLAGS.saved_model_dir\n FLAGS.word_vector = True if os.path.exists(FLAGS.word_vec_path) else False\n\n mkdir(FLAGS.model_dir)\n mkdir(FLAGS.data_cache_dir)\n mkdir(FLAGS.saved_model_dir)\n mkdir(FLAGS.summary_dir)\n\n # for logs\n log_path = os.path.join(FLAGS.model_dir,\"log.{}.txt\".format(FLAGS.mode))\n filemode = 'w' if FLAGS.fromScratch else \"a\"\n logging.basicConfig(filename=log_path,level=logging.DEBUG, filemode = filemode)\n \n log_flags()\n\ndef main(_):\n \n parsing_flags()\n\n os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(FLAGS.N)\n \n if FLAGS.mode == \"TRAIN\":\n train()\n\n \n if FLAGS.mode == 'DECODE': \n FLAGS.batch_size = 1\n FLAGS.word_vector = False\n answer = True if os.path.exists(FLAGS.test_path_to) else False\n decode(answer)\n \n logging.shutdown()\n \nif __name__ == \"__main__\":\n tf.app.run()\n","sub_path":"chenhangting/py/runCNNLSTMSerial.py","file_name":"runCNNLSTMSerial.py","file_ext":"py","file_size_in_byte":22047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"289002657","text":"import tkinter\r\nfrom tkinter import *\r\n\r\n#Características de wroot\r\n\r\nclass frame():\r\n \r\n \r\n def __init__(self):\r\n \r\n \r\n #CREACIÓN DE LA VENANA PRINCIPAL\r\n self.wroot = tkinter.Tk()\r\n self.wroot.title('calculadora')\r\n self.wroot.geometry('300x450+800+150')\r\n self.wroot.pack_propagate(False)\r\n \r\n \r\n self.createLayout()\r\n \r\n def createLayout(self):\r\n \r\n \r\n \r\n \r\n #CREACIÓN DE CUADRO DE TEXTO\r\n\r\n #self.entrada = tk.Entry(self.wroot ,textvariable = self.caracter, width = 300, height = 75, bg = 'lightgreen').place(x = 0, y=0)\r\n \r\n #CREACIÓN DE LOS FRAMES. VOY A CREAR 7 FRAMES.\r\n\r\n self.fr_text = tkinter.Frame(self.wroot, width=300, height=75, bg ='lightgreen')\r\n self.fr_text.place(x=0,y=0)\r\n self.fr_text.pack_propagate(False)\r\n\r\n self.fr_hor = tkinter.Frame(self.wroot,width=300, height = 75, bg = 'orange')\r\n self.fr_hor.place(x=0, y=75)\r\n self.fr_hor.pack_propagate(False)\r\n\r\n self.fr_ver = tkinter.Frame(self.wroot,width=75, height = 300, bg = 'orange')\r\n self.fr_ver.place(x=225, y=150)\r\n self.fr_ver.pack_propagate(False)\r\n\r\n self.fr_1 = tkinter.Frame(self.wroot, width =225, height = 75, bg ='black')\r\n self.fr_1.place(x=0, y= 150)\r\n self.fr_1.pack_propagate(False)\r\n\r\n self.fr_2 = tkinter.Frame(self.wroot, width =225, height = 75, bg ='black')\r\n self.fr_2.place(x=0, y= 225)\r\n self.fr_2.pack_propagate(False)\r\n\r\n self.fr_3 = tkinter.Frame(self.wroot, width =225, height = 75, bg ='black')\r\n self.fr_3.place(x=0, y= 300)\r\n self.fr_3.pack_propagate(False)\r\n\r\n self.fr_4 = tkinter.Frame(self.wroot, width =225, height = 75, bg ='black')\r\n self.fr_4.place(x=0, y= 375)\r\n self.fr_4.pack_propagate(False)\r\n\r\n\r\n #BOTONES DE LA PRIMERA HORIZONTAL // C / X DELETE\r\n self.btn_c = tkinter.Button(self.fr_hor, text ='C', fg ='black', bg = 'orange')\r\n self.btn_c.pack(side= tkinter.LEFT, expand = True, fill = tkinter.BOTH)\r\n\r\n self.btn_dividir = tkinter.Button(self.fr_hor, text ='/', fg ='black', bg = 'orange')\r\n self.btn_dividir.pack(side= tkinter.LEFT, expand = True, fill = tkinter.BOTH)\r\n\r\n self.btn_multiplicar = tkinter.Button(self.fr_hor, text ='x', fg ='black', bg = 'orange')\r\n self.btn_multiplicar.pack(side= tkinter.LEFT, expand = True, fill = tkinter.BOTH)\r\n\r\n self.btn_delete = tkinter.Button(self.fr_hor, text ='«', fg ='black', bg = 'orange')\r\n self.btn_delete.pack(side= tkinter.LEFT, expand = True, fill = tkinter.BOTH)\r\n\r\n #BOTONES DE LA VERTICAL // - + =\r\n\r\n self.btn_suma = tkinter.Button(self.fr_ver, text ='+', fg ='black', bg = 'orange')\r\n self.btn_suma.pack(side= tkinter.TOP, expand = True, fill = tkinter.BOTH)\r\n\r\n self.btn_resta = tkinter.Button(self.fr_ver, text ='-', fg ='black', bg = 'orange')\r\n self.btn_resta.pack(side= tkinter.TOP, expand = True, fill = tkinter.BOTH)\r\n\r\n self.btn_result = tkinter.Button(self.fr_ver, text ='=', fg ='black', bg = 'orange')\r\n self.btn_result.pack(side= tkinter.TOP, expand = True, fill = tkinter.BOTH)\r\n\r\n #BOTONES PRIMER LÍNEA DE NUMEROS // 7 8 9\r\n\r\n self.btn_7 = tkinter.Button(self.fr_1, text ='7', fg ='white', bg = 'black')\r\n self.btn_7.pack(side= tkinter.LEFT, expand = True, fill = tkinter.BOTH)\r\n\r\n\r\n self.btn_8 = tkinter.Button(self.fr_1, text ='8', fg ='white', bg = 'black')\r\n self.btn_8.pack(side= tkinter.LEFT, expand = True, fill = tkinter.BOTH)\r\n\r\n self.btn_9 = tkinter.Button(self.fr_1, text ='9', fg ='white', bg = 'black')\r\n self.btn_9.pack(side= tkinter.LEFT, expand = True, fill = tkinter.BOTH)\r\n\r\n #BOTONES SEGUNDA LÍNEA DE NUMEROS // 4 5 6\r\n\r\n self.btn_4 = tkinter.Button(self.fr_2, text ='4', fg ='white', bg = 'black')\r\n self.btn_4.pack(side= tkinter.LEFT, expand = True, fill = tkinter.BOTH)\r\n\r\n self.btn_5 = tkinter.Button(self.fr_2, text ='5', fg ='white', bg = 'black')\r\n self.btn_5.pack(side= tkinter.LEFT, expand = True, fill = tkinter.BOTH)\r\n\r\n self.btn_6 = tkinter.Button(self.fr_2, text ='6', fg ='white', bg = 'black')\r\n self.btn_6.pack(side= tkinter.LEFT, expand = True, fill = tkinter.BOTH)\r\n\r\n #BOTONES TERCERA LÍNEA DE NUMEROS // 1 2 3\r\n\r\n self.btn_1 = tkinter.Button(self.fr_3, text ='1', fg ='white', bg = 'black')\r\n self.btn_1.pack(side= tkinter.LEFT, expand = True, fill = tkinter.BOTH)\r\n\r\n self.btn_2 = tkinter.Button(self.fr_3, text ='2', fg ='white', bg = 'black')\r\n self.btn_2.pack(side= tkinter.LEFT, expand = True, fill = tkinter.BOTH)\r\n\r\n self.btn_3 = tkinter.Button(self.fr_3, text ='3', fg ='white', bg = 'black')\r\n self.btn_3.pack(side= tkinter.LEFT, expand = True, fill = tkinter.BOTH)\r\n\r\n\r\n #BOTONES CUARTA LÍNEA DE NUMEROS // % 0 ,\r\n\r\n self.btn_percent = tkinter.Button(self.fr_4, text ='%', fg ='white', bg = 'black')\r\n self.btn_percent.pack(side= tkinter.LEFT, expand = True, fill = tkinter.BOTH)\r\n\r\n self.btn_0 = tkinter.Button(self.fr_4, text ='0 ', fg ='white', bg = 'black')\r\n self.btn_0.pack(side= tkinter.LEFT, expand = True, fill = tkinter.BOTH)\r\n\r\n self.btn_coma = tkinter.Button(self.fr_4, text =' , ', fg ='white', bg = 'black')\r\n self.btn_coma.pack(side= tkinter.LEFT, expand = True, fill = tkinter.BOTH)\r\n\r\n \r\n def press(self, *args):\r\n \r\n self.entrada.config(textvariable = key)\r\n \r\n \r\n def start(self):\r\n \r\n self.wroot.mainloop()\r\n\r\nclass main():\r\n \r\n def __init__(self):\r\n \r\n self.f = frame()\r\n self.f.press()\r\n self.f.start()\r\n \r\n\r\nif __name__ == '__main__':\r\n \r\n juego= main()","sub_path":"calculadoraInterfaz.py","file_name":"calculadoraInterfaz.py","file_ext":"py","file_size_in_byte":5922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"631862719","text":"from .room import SlackChannel, SlackGroup, SlackIM\nfrom .user import SlackUser\n\n\nclass SlackEvent(object):\n \"\"\"Encapsulates an event received from the RTM socket\"\"\"\n def __init__(self, sc=None, **kwargs):\n\n self._sc = sc\n self._channel = None\n self._user = None\n\n for k, v in kwargs.iteritems():\n setattr(self, k, v)\n\n @property\n def channel(self):\n return self._channel\n\n @channel.setter\n def channel(self, value):\n if isinstance(value, basestring):\n if value[0] == 'G':\n # Slack groups have an ID starting with 'G'\n self._channel = SlackGroup(value, sc=self._sc)\n elif value[0] == 'D':\n # Slack IMs have an ID starting with 'D'\n self._channel = SlackIM(value, sc=self._sc)\n else:\n self._channel = SlackChannel(value, sc=self._sc)\n else:\n self._channel = value\n\n @property\n def user(self):\n return self._user\n\n @user.setter\n def user(self, value):\n if isinstance(value, basestring):\n self._user = SlackUser(value, sc=self._sc)\n else:\n self._user = value\n","sub_path":"slackminion/slack/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"255944518","text":"from logger import *\nimport os\nimport json\n\nfrom lib.db import MemeChainDB\nfrom lib.blockchain import *\nfrom lib.memechain import MemeTx, Validate\n\n# Load configuration file\nwith open(\"config.json\", \"r\") as f:\n config = json.loads(f.read())\n\n\nclass MemechainParser(object):\n \"\"\"\n Wrapper class for various blockchain parsing functions\n used to construct the local memechain metadata database\n \"\"\"\n\n def __init__(self, block_height):\n self.block_height = block_height\n self._memetxs_raw = []\n self.memetxs = []\n\n def collect_memetxs(self):\n \"\"\"\n Method used to parse the op_return data\n for the transactions in the block\n \"\"\"\n block_txs = get_block_txs(block_height)\n\n for txid in block_txs:\n memetx = get_op_return_data(txid)\n self._memetxs_raw.append(memetx)\n\n def parse_memetxs(self):\n \"\"\"\n Method used to parse the raw memetx metadata\n \"\"\"\n for memetx in self._memetxs_raw:\n if memetx[:4] == '3ae4':\n ipfs_id = memetx[4:][:len(memetx) - 4 - 16]\n hashlink = memetx[4:][len(memetx) - 4 - 16:]\n\n self.memetxs.append({\n 'ipfs_id': ipfs_id,\n 'hashlink': hashlink\n })\n\n def return_memetxs(self):\n \"\"\"\n Method used to return the potentially valid memetxs\n\n Returns:\n Memetxs at block_height (array)\n \"\"\"\n return self.memetxs\n\n\nif __name__ == '__main__':\n # Sync logic\n pass\n","sub_path":"sync.py","file_name":"sync.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"232009823","text":"\"\"\"Utility functions used by the CLI.\"\"\"\n\nimport os\nimport fnmatch\nfrom pathlib import Path\n\nimport click\nimport re\nfrom google.cloud import bigquery\n\nfrom bigquery_etl.util.common import project_dirs\n\n\ndef is_valid_dir(ctx, param, value):\n \"\"\"Check if the parameter provided via click is an existing directory.\"\"\"\n if not os.path.isdir(value) or not os.path.exists(value):\n raise click.BadParameter(f\"Invalid directory path to {value}\")\n return value\n\n\ndef is_valid_file(ctx, param, value):\n \"\"\"Check if the parameter provided via click is an existing file.\"\"\"\n if not os.path.isfile(value) or not os.path.exists(value):\n raise click.BadParameter(f\"Invalid file path to {value}\")\n return value\n\n\ndef is_authenticated(project_id=None):\n \"\"\"Check if the user is authenticated to GCP and can access the project.\"\"\"\n client = bigquery.Client()\n\n if project_id:\n return client.project == project_id\n\n return True\n\n\ndef is_valid_project(ctx, param, value):\n \"\"\"Check if the provided project_id corresponds to an existing project.\"\"\"\n if value is None or value in [Path(p).name for p in project_dirs()]:\n return value\n raise click.BadParameter(f\"Invalid project {value}\")\n\n\ndef table_matches_patterns(pattern, invert, table):\n \"\"\"Check if tables match pattern.\"\"\"\n pattern = re.compile(fnmatch.translate(pattern))\n return (pattern.match(table) is not None) != invert\n","sub_path":"bigquery_etl/cli/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"221266842","text":"#!/usr/bin/python3\nimport RPi.GPIO as GPIO\nimport subprocess\nimport shlex\nimport time, datetime\nimport telepot\nfrom telepot.loop import MessageLoop\nfrom telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton\n\nnow = datetime.datetime.now()\ntelegram_bot = telepot.Bot('597228802:AAGHvtTRo3LWoP3gI4BdddvpHxGhC5iPsYM')\nbandera = \"False\"\n\n\ndef greeting():\n command_line = 'aplay --device plughw:CARD=Device,DEV=0 /home/pi/greeting.wav'\n args = shlex.split(command_line)\n subprocess.call(args)\n print(\"Preguntando quien es\")\n\ndef answer():\n\tcommand_line = 'sudo arecord -D plughw:1 --duration=3 -f cd /home/pi/answer.wav'\n\targs = shlex.split(command_line)\n\tsubprocess.call(args)\n\tgetCurrentPicture()\n\n\ttelegram_bot.sendPhoto(569563829, photo=open('/home/pi/visitante.jpg','rb'))\n\ttelegram_bot.sendAudio(569563829, audio=open('/home/pi/answer.wav','rb'))\n\t\n#Cuando el intercom no esta en automatico \ndef telegram():\n\ttelegram_bot.sendMessage (569563829, str(\"Estan tocando el intercom!!! y el automatico esta\" + str(bandera)))\n\ttelegram_bot.sendAudio(569563829, audio=open('/home/pi/answer.wav','rb'))\n\ndef action(msg):\n\tchat_id = msg['chat']['id']\n\tcommand = msg['text']\n\tglobal bandera\n\tif command == '/hi':\n\t telegram_bot.sendMessage (chat_id, str(\"IntercomPI Funcionando\"))\n\telif command == 'Abrir':\n\t\tGPIO.output(11, 0)\n\t\tGPIO.output(7, 0)\n\t\tGPIO.output(13, 1)\n\t\ttime.sleep(2)\n\t\tGPIO.output(13, 0)\n\t\tprint(\"tamo abriendo\")\n\t\ttelegram_bot.sendMessage (chat_id, str(\"Abriendo intercom!!!\"))\n\telif command == '/on':\n\t\tbandera = \"True\"\n\t\tprint(\"Automatico: \" + str(bandera))\n\t\ttelegram_bot.sendMessage (chat_id, str(\"Automatico: \" + str(bandera)))\n\telif command == '/off':\n\t\tbandera = \"False\"\n\t\tprint(\"Automatico: \" + str(bandera))\n\t\ttelegram_bot.sendMessage (chat_id, str(\"Automatico: \" + str(bandera)))\n\telif command == 'Status':\n\t\tprint(\"Automatico: \" + str(bandera))\n\t\ttelegram_bot.sendMessage (chat_id, str(\"Automatico: \" + str(bandera)))\n\telif command == 'Repetir':\n\t\tprint(\"Enviando Nota de Voz\")\n\t\tanswer()\n\telif command == '/probando':\n\t\tanswer()\n\t\tprint(\"Grabando y Enviando\")\n\t\ttelegram_bot.sendAudio(chat_id, audio=open('/home/pi/answer.wav','rb'))\n\t\tprint(\"Enviado\")\n\n#lee una imagen del url de la camara de seguridad\ndef getCurrentPicture():\n\timport requests\n\tfrom requests.auth import HTTPBasicAuth\n\n\timage_url = 'http://10.0.0.246/ISAPI/Streaming/channels/0700/picture?videoResolutionWidth=1920&videoResolutionHeight=1080'\n\timg_data = requests.get(image_url, auth=HTTPBasicAuth('admin', 'Acropolis12')).content\n\twith open('/home/pi/visitante.jpg', 'wb') as handler:\n\t handler.write(img_data)\n\t\n\n \ndef pulsador():\n\tif (GPIO.input(16)):\n\t\tprint(\"Tocaron la puerta\")\n\t\tGPIO.output(11, 1)\n\t\tGPIO.output(7, 1)\n\t\ttime.sleep(2)\n\t\tgreeting()\n\t\tprint(\"Respondi\")\n\t\tanswer()\n\t\tGPIO.output(11, 0)\n\t\tGPIO.output(7, 0)\n\t\tif (bandera == \"False\"):\n\t\t\tprint(\"Esperando telegram para abir\")\n\t\t\ttelegram()\n\t\tif (bandera == \"True\"):\n\t\t\tGPIO.output(13, 1)\n\t\t\ttime.sleep(2)\n\t\t\tGPIO.output(13, 0)\n\t\t\ttelegram_bot.sendMessage (569563829, str(\"Abriendo intercom!!!\"))\n\t\t\tprint(\"Abriendo\")\n\n \n \nif __name__ == '__main__':\n MessageLoop(telegram_bot, action).run_as_thread()\n try: \n GPIO.setmode(GPIO.BOARD)\n GPIO.setup(16, GPIO.IN)\n GPIO.setwarnings(False)\n GPIO.setup(7, GPIO.OUT, initial=0) \n GPIO.setup(11, GPIO.OUT, initial=0)\n GPIO.setup(13, GPIO.OUT, initial=0)\n print(\"Try\")\n telegram_bot.sendMessage (569563829, str(\"Bienvenido a Ana Paula 801A v2\"), \n\t\treply_markup=ReplyKeyboardMarkup(\n\t\tkeyboard=[[KeyboardButton(text=\"Abrir\"), KeyboardButton(text=\"China\"), KeyboardButton(text=\"Repetir\")],[KeyboardButton(text=\"Status\"), KeyboardButton(text=\"/on\"), KeyboardButton(text=\"/off\")]])\n \t)\n while True:\n pulsador()\n \n except KeyboardInterrupt:\n GPIO.cleanup()\n exit(0)\n except Exception as e:\n print(\"Error durante ejecucion:\")\n print(e) \n finally:\n GPIO.cleanup()\n exit(1)","sub_path":"s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":4088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"276564275","text":"from django.conf import settings\nfrom django.urls import include, path\n\nfrom shared.oidc.views.eauth_views import (\n EauthAuthenticationCallbackView,\n EauthAuthenticationRequestView,\n)\nfrom shared.oidc.views.hki_views import (\n HelsinkiOIDCAuthenticationCallbackView,\n HelsinkiOIDCAuthenticationRequestView,\n HelsinkiOIDCBackchannelLogoutView,\n HelsinkiOIDCLogoutView,\n HelsinkiOIDCUserInfoView,\n)\n\nurlpatterns = []\n\nif settings.MOCK_FLAG:\n from shared.oidc.views.mock_views import (\n MockAuthenticationRequestView,\n MockLogoutView,\n MockUserInfoView,\n )\n\n urlpatterns += [\n path(\n \"authenticate/\",\n MockAuthenticationRequestView.as_view(),\n name=\"oidc_authentication_init\",\n ),\n path(\n \"logout/\",\n MockLogoutView.as_view(),\n name=\"oidc_logout\",\n ),\n path(\n \"userinfo/\",\n MockUserInfoView.as_view(),\n name=\"oidc_userinfo\",\n ),\n ]\nelse:\n urlpatterns += [\n path(\n \"authenticate/\",\n HelsinkiOIDCAuthenticationRequestView.as_view(),\n name=\"oidc_authentication_init\",\n ),\n path(\n \"callback/\",\n HelsinkiOIDCAuthenticationCallbackView.as_view(),\n name=\"oidc_authentication_callback\",\n ),\n path(\n \"logout/\",\n HelsinkiOIDCLogoutView.as_view(),\n name=\"oidc_logout\",\n ),\n path(\n \"userinfo/\",\n HelsinkiOIDCUserInfoView.as_view(),\n name=\"oidc_userinfo\",\n ),\n path(\n \"backchannel/logout/\",\n HelsinkiOIDCBackchannelLogoutView.as_view(),\n name=\"oidc_backchannel_logout\",\n ),\n path(\"\", include(\"mozilla_django_oidc.urls\")),\n path(\n \"eauthorizations/authenticate/\",\n EauthAuthenticationRequestView.as_view(),\n name=\"eauth_authentication_init\",\n ),\n path(\n \"eauthorizations/callback/\",\n EauthAuthenticationCallbackView.as_view(),\n name=\"eauth_authentication_callback\",\n ),\n ]\n","sub_path":"backend/shared/shared/oidc/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"74415845","text":"from setuptools import setup, find_packages\nfrom tag_manager import __version__\n\nversion_str = \".\".join(str(n) for n in __version__)\n\nrequires = ['django>=1.8']\n\nsetup(name='django-tag-manager',\n version=version_str,\n description='Tag management system for Django',\n url='https://github.com/cvng/django-tag-manager',\n author='cvng',\n author_email='mail@cvng.io',\n license='MIT',\n packages=find_packages(),\n install_requires=requires,\n zip_safe=False,\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Environment :: Web Environment\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n \"Framework :: Django\",\n ])\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"590132210","text":"import json\nimport logging\n\nfrom channels import Channel, Group\nfrom channels.auth import channel_session_user_from_http, channel_session_user\nfrom channels.generic.websockets import JsonWebsocketConsumer\n\nfrom .conf import MSG, ERR\nfrom .models import Game\nfrom .exceptions import ClientError\nfrom .decorators import catch_client_error\nfrom .serializers import GameUpdateSerializer\n\nlogger = logging.getLogger('game')\n\n\nclass BaseWSConsumer(JsonWebsocketConsumer):\n http_user = True\n channel_session_user = True\n\n command_handlers = {\n 'send': 'chat_send',\n 'role': 'choose_role',\n 'move': 'game_move',\n 'reset': 'game_reset',\n }\n\n def get_command_handler(self, text, **kwargs):\n handler = self.command_handlers[text['command']]\n handler = getattr(self, handler)\n return handler(text, **kwargs)\n\n def connection_groups(self, **kwargs):\n if Game.objects.get(pk=kwargs.get('room')):\n return ['game-%s' % kwargs['room'], ]\n return []\n\n @catch_client_error\n def connect(self, message, **kwargs):\n if message.user.is_anonymous:\n raise ClientError(ERR.UNAUTHENTICATED)\n\n try:\n game = kwargs.get('room')\n except AttributeError:\n raise ClientError(ERR.NO_ROOM_ID)\n\n try:\n game = Game.objects.get(pk=game)\n except Game.DoesNotExist():\n raise ClientError(ERR.ROOM_ID_INCORRECT)\n\n super().connect(message, **kwargs)\n\n if not all(game.players_dict.values()) and message.user.username not in game.players_dict.values():\n # if there are vacant roles and the user has no role, offer them to pick a role\n self.send(dict(\n type=MSG.ROLE_CHOICE,\n board=game.board,\n players=game.players_dict\n ))\n else:\n # just send an update\n self.send_update(game, individual=True)\n\n @catch_client_error\n def receive(self, text=None, bytes=None, **kwargs):\n self.get_command_handler(text, **kwargs)\n\n def chat_send(self, message, **kwargs):\n \"\"\"\n Send a message to game chat.\n \"\"\"\n message.update({'type': MSG.CHAT,\n 'user': self.message.user.username})\n\n for group in self.connection_groups(**kwargs):\n Group(group).send({'text': json.dumps(message)})\n\n def choose_role(self, message, **kwargs):\n \"\"\"\n Set a given role field (red/black) of the game to the current session\n user if it is vacant.\n \"\"\"\n game = Game.objects.get(pk=kwargs['room'])\n role = message.get('role')\n\n vacant_roles = [r for (r, p) in game.players_dict.items() if not p]\n\n if role in vacant_roles:\n setattr(game, role, self.message.user)\n game.save()\n response = dict(type=MSG.ROLE_GRANTED, role=role)\n self.send(response)\n else:\n raise ClientError(ERR.WRONG_ROLE_CHOICE)\n\n def game_move(self, message, **kwargs):\n \"\"\"\n Perform a move.\n \"\"\"\n game = Game.objects.get(pk=kwargs['room'])\n try:\n x, y = message['x'], message['y']\n for i in (x, y):\n if not (isinstance(i, int) and i < 12):\n raise KeyError\n except KeyError:\n raise ClientError(ERR.WRONG_COORDINATES)\n\n if (game.red == self.message.user and game.red_turn) or \\\n (game.black == self.message.user and not game.red_turn):\n game.move(x, y)\n\n else:\n raise ClientError(ERR.ROLE_INACTIVE)\n\n def send_update(self, game, individual=False):\n \"\"\"\n Update clients' game data. If individual == True, send message only\n to the current reply channel. Otherwise, broadcast it to\n everyone in the group.\n \"\"\"\n serializer = GameUpdateSerializer(game)\n response = dict(type=MSG.GAME_UPDATE, **serializer.data)\n\n if individual:\n self.send(response)\n else:\n game.send(**response)\n","sub_path":"game/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":4126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"446571009","text":"import os\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\nfrom utils.trainer import *\nfrom nets.my_vgg import vgg_diy\nfrom nets.resnet_pre_activation import *\nfrom nets.se_resnet import *\nfrom utils.convert_DataParallel_Model import convert_DataParallel_Model_to_Common_Model\nfrom command_parameter import *\nfrom dataset_factory import dataset_factory\n\n\n# parser from command_parameter\nargs = parser.parse_args()\n\n# setting command parameters\nargs.cuda = (not args.no_cuda) and torch.cuda.is_available()\ntorch.manual_seed(args.seed)\nif args.cuda:\n torch.cuda.manual_seed(args.seed)\ncudnn.benchmark = True\n\n# loading model and choose model\nmodel_class = [vgg_diy,preactivation_resnet164,se_resnet_34]\nmodel_dict = dict(list(zip(model_name,model_class)))\nif args.fine_tune:\n load_pkl = torch.load(args.fine_tune)\n model = model_dict[args.model](\n num_classes=args.num_classes, cfg=load_pkl['cfg'])\n model.load_state_dict(load_pkl['model_state_dict'])\n if args.teacher_model is not None:\n teacher_model = model_dict[args.model](\n num_classes=args.num_classes)\n teacher_model.load_state_dict(torch.load(args.teacher_model))\n else:\n pass\n #model = model_dict[args.model](num_classes=args.num_classes)\n # model.load_state_dict(load_pkl)\n args.save_path = os.path.join(\n args.save_path,\n 'fine_tune/' + args.model,\n args.dataset)\nelse:\n model = model_dict[args.model](num_classes=args.num_classes)\n args.save_path = os.path.join(args.save_path, args.model, args.dataset)\n\n\n# dataset choice\nkwargs = {'num_workers': args.num_workers,\n 'pin_memory': True} if args.cuda else {}\n'''\nif args.dataset == 'cifar10':\n normalize = transforms.Normalize(\n mean=[0.491, 0.482, 0.447],\n std=[0.247, 0.243, 0.262])\n train_loader = torch.utils.data.DataLoader(\n datasets.CIFAR10('./data', train=True, download=False,\n transform=transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n #transforms.ColorJitter(brightness=1),\n transforms.ToTensor(),\n normalize\n ])\n ), batch_size=args.batch_size, shuffle=True, **kwargs\n )\n validate_loader = torch.utils.data.DataLoader(\n datasets.CIFAR10('./data', train=False,\n transform=transforms.Compose([\n transforms.ToTensor(),\n normalize\n ])\n ),\n batch_size=args.validate_batch_size, shuffle=False, **kwargs\n )\nelif args.dataset == 'cifar100':\n normalize = transforms.Normalize(\n mean=[0.507, 0.487, 0.441],\n std=[0.267, 0.256, 0.276])\n # normalize = transforms.Normalize(mean=[.5,.5,.5], std=[.5,.5,.5])\n # normalize = transforms.Normalize((.5,.5,.5),(.5,.5,.5))\n train_loader = torch.utils.data.DataLoader(\n datasets.CIFAR100('./data', train=True, download=True,\n transform=transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize\n ])\n ), batch_size=args.batch_size, shuffle=True, **kwargs\n )\n validate_loader = torch.utils.data.DataLoader(\n datasets.CIFAR100('./data', train=False,\n transform=transforms.Compose([\n transforms.ToTensor(),\n normalize\n ])\n ),\n batch_size=args.validate_batch_size, shuffle=False, **kwargs\n )\nelse:\n train_loader = torch.utils.data.DataLoader(\n ImageList(root=args.image_root_path, fileList=args.image_train_list,\n transform=transforms.Compose([\n transforms.Resize(size=(args.img_size, args.img_size)),\n transforms.RandomCrop(args.crop_size),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n ])\n ),\n batch_size=args.batch_size, shuffle=True, **kwargs\n )\n validate_loader = torch.utils.data.DataLoader(\n ImageList(\n root=args.image_root_path, fileList=args.image_validate_list,\n transform=transforms.Compose(\n [transforms.Resize(\n size=(args.crop_size, args.crop_size)),\n transforms.ToTensor(), \n ])\n ),\n batch_size=args.validate_batch_size, shuffle=False, **kwargs\n )\n'''\n\ntest_path = '/home/leolau/pytorch/data' #just for test, when parameter confirm this might delete\ndataset_f = dataset_factory(args.dataset,args.batch_size,args.validate_batch_size,kwargs,root_path=test_path)\ntrain_loader = dataset_f.train_loader\nvalidate_loader = dataset_f.validate_loader\n\noptimizer = optim.SGD(\n filter(\n lambda p: p.requires_grad,\n model.parameters()),\n lr=args.lr,\n weight_decay=args.weight_decay,\n momentum=args.momentum,\n nesterov=True)\n# optimizer = optim.Adam(\n# filter(\n# lambda p: p.requires_grad,\n# model.parameters()),\n# lr=args.lr,\n# weight_decay=args.weight_decay)\ncriterion = nn.CrossEntropyLoss()\ntransfer_criterion = nn.MSELoss()\nif args.sr:\n print('\\nSparsity Training \\n')\n trainer = Network_Slimming_Trainer(\n model=model,\n optimizer=optimizer,\n lr=args.lr,\n criterion=criterion,\n start_epoch=args.start_epoch,\n epochs=args.epochs,\n cuda=args.cuda,\n log_interval=args.log_interval,\n train_loader=train_loader,\n validate_loader=validate_loader,\n root=args.save_path,\n penalty=args.p,\n )\nelif args.se:\n print('\\nSE_ResNet Training \\n')\n trainer = SE_Trainer(\n model=model,\n optimizer=optimizer,\n lr=args.lr,\n criterion=criterion,\n start_epoch=args.start_epoch,\n epochs=args.epochs,\n cuda=args.cuda,\n log_interval=args.log_interval,\n train_loader=train_loader,\n validate_loader=validate_loader,\n root=args.save_path,\n SEBlock=SEBlock\n )\n\nelif args.fine_tune is not None and args.teacher_model is not None: # other 3 00 01 10\n print('\\nTraining with Knowledge Distillation \\n')\n trainer = Trainer(\n model=model,\n teacher_model=teacher_model,\n optimizer=optimizer,\n lr=args.lr,\n criterion=criterion,\n start_epoch=args.start_epoch,\n epochs=args.epochs,\n cuda=args.cuda,\n log_interval=args.log_interval,\n train_loader=train_loader,\n validate_loader=validate_loader,\n root=args.save_path,\n loss_ratio=args.loss_ratio,\n transfer_criterion=transfer_criterion,\n\n )\n\nelse:\n print('\\nNormal Training \\n')\n trainer = Trainer(\n model=model,\n optimizer=optimizer,\n lr=args.lr,\n criterion=criterion,\n start_epoch=args.start_epoch,\n epochs=args.epochs,\n cuda=args.cuda,\n log_interval=args.log_interval,\n train_loader=train_loader,\n validate_loader=validate_loader,\n root=args.save_path,\n\n )\ntrainer.start()\n","sub_path":"main_bk.py","file_name":"main_bk.py","file_ext":"py","file_size_in_byte":7752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"340640825","text":"from selenium import selenium\nimport unittest, time, re\n\nclass abc(unittest.TestCase):\n def setUp(self):\n self.verificationErrors = []\n self.selenium = selenium(\"localhost\", 4444, \"*chrome\", \"http://www.alpha.ablesky.com/\")\n self.selenium.start()\n \n def test_abc(self):\n sel = self.selenium\n sel.open(\"/index.do\")\n sel.click(\"id=J_PopupLogin\")\n time.sleep(2)\n sel.type(\"id=login_username\", \"lyang_test\")\n sel.type(\"id=login_password\", \"2165165\")\n sel.click(\"id=ext-gen63\")\n time.sleep(2)\n sel.click(\"id=headMyOffice\")\n sel.wait_for_page_to_load(\"30000\")\n sel.click(\"id=headLogoutId\")\n sel.wait_for_page_to_load(\"30000\")\n \n def tearDown(self):\n self.selenium.stop()\n self.assertEqual([], self.verificationErrors)\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"new python/testscripts/ab.py","file_name":"ab.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"167706218","text":"# Example of a gizmo that activates an operator\n# using the predefined dial gizmo to change the camera roll.\n#\n# Usage: Run this script and select a camera in the 3D view.\n#\nimport bpy\nfrom bpy.types import (\n GizmoGroup,\n)\n\n\nclass MyCameraWidgetGroup(GizmoGroup):\n bl_idname = \"OBJECT_GGT_test_camera\"\n bl_label = \"Object Camera Test Widget\"\n bl_space_type = 'VIEW_3D'\n bl_region_type = 'WINDOW'\n bl_options = {'3D', 'PERSISTENT'}\n\n @classmethod\n def poll(cls, context):\n ob = context.object\n return (ob and ob.type == 'CAMERA')\n\n def setup(self, context):\n # Run an operator using the dial gizmo\n ob = context.object\n mpr = self.gizmos.new(\"GIZMO_GT_dial_3d\")\n props = mpr.target_set_operator(\"transform.rotate\")\n props.constraint_axis = False, False, True\n props.constraint_orientation = 'LOCAL'\n props.release_confirm = True\n\n mpr.matrix_basis = ob.matrix_world.normalized()\n mpr.line_width = 3\n\n mpr.color = 0.8, 0.8, 0.8\n mpr.alpha = 0.5\n\n mpr.color_highlight = 1.0, 1.0, 1.0\n mpr.alpha_highlight = 1.0\n\n self.roll_widget = mpr\n\n def refresh(self, context):\n ob = context.object\n mpr = self.roll_widget\n mpr.matrix_basis = ob.matrix_world.normalized()\n\n\nbpy.utils.register_class(MyCameraWidgetGroup)\n","sub_path":"engine/2.80/scripts/templates_py/gizmo_operator_target.py","file_name":"gizmo_operator_target.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"319058681","text":"import calendar\n\nfrom django.http import JsonResponse\nfrom django.shortcuts import render\nfrom .models import Feedback, Giver, ENTRUSTABILITY_SCORES, ACTIVITIES\n\n\n# primary view, calls the html script\ndef bootstrap_view(request):\n # no filtering done on initial request\n qs_inputs = filter_request(request, 'None')\n # store the filter input from the form so users will not have to reenter data upon each filter request\n url_filter = request.META['QUERY_STRING']\n context = {\n 'queryset': qs_inputs['qs'],\n 'activities': qs_inputs['activities'],\n 'givers': qs_inputs['givers'],\n 'url_filter': url_filter,\n 'selected_inputs': qs_inputs['selected_inputs'],\n 'entrustability_dict': qs_inputs['entrustability_dict'],\n 'activities_dict': qs_inputs['activities_dict']\n }\n return render(request, \"bootstrap_form.html\", context)\n\n\n# primary filtering method used by views\n# request is the html request\n# config is to disable certain filtering for specific chart types, can be empty, 'GiverPie', or 'ActivityType'\ndef filter_request(request, config):\n # order by date and store all queries\n qs = Feedback.objects.order_by('feedbackDate').all()\n start_date_query = request.GET.get('startDate')\n end_date_query = request.GET.get('endDate')\n giver_name_query = request.GET.get('giverName')\n complicated_query = request.GET.get('complicated')\n complex_query = request.GET.get('complex')\n not_complicated_query = request.GET.get('notComplicated')\n not_complex_query = request.GET.get('notComplex')\n activity_query = request.GET.get('activity')\n sorting_query = request.GET.get('byTime')\n\n # save initial inputs\n selected_start_date = start_date_query\n selected_end_date = end_date_query\n selected_giver = giver_name_query\n selected_complicated = complicated_query\n selected_complex = complex_query\n selected_not_complicated = not_complicated_query\n selected_not_complex = not_complex_query\n selected_activity = activity_query\n selected_sorting = sorting_query\n\n # filtering\n if is_valid_queryparam(giver_name_query) and giver_name_query != 'All' and config != 'GiverPie':\n qs = qs.filter(giver__name__icontains=giver_name_query)\n else:\n selected_giver = 'All'\n if is_valid_queryparam(start_date_query):\n qs = qs.filter(feedbackDate__gte=start_date_query)\n else:\n selected_start_date = \"2017-01-01\" # preset date for filling\n if is_valid_queryparam(end_date_query):\n qs = qs.filter(feedbackDate__lt=end_date_query)\n else:\n selected_end_date = \"2019-12-31\" # preset date for filling\n # if complicated is on, set complicated to true (regardless of if not_complicated is also on)\n if complicated_query == 'on':\n qs = qs.filter(complicated=True)\n elif not_complicated_query == 'on':\n qs = qs.filter(complicated=False)\n else:\n selected_complicated = 'off'\n selected_not_complicated = 'off'\n if complex_query == 'on':\n qs = qs.filter(complex=True)\n elif not_complex_query == 'on':\n qs = qs.filter(complex=False)\n else:\n selected_complex = 'off'\n selected_not_complex = 'off'\n if is_valid_queryparam(activity_query) and activity_query != 'All' and config != 'ActivityRadar':\n qs = qs.filter(activity=activity_query)\n else:\n selected_activity = 'All'\n\n activities = Feedback.objects.order_by('activity').values('activity').distinct()\n givers = Feedback.objects.order_by('giver__name').values('giver__name').distinct()\n\n # store selected inputs\n selected_inputs = {\n 'selected_start_date': selected_start_date,\n 'selected_end_date': selected_end_date,\n 'selected_giver': selected_giver,\n 'selected_complicated': selected_complicated,\n 'selected_complex': selected_complex,\n 'selected_not_complicated': selected_not_complicated,\n 'selected_not_complex': selected_not_complex,\n 'selected_activity': selected_activity,\n 'selected_sorting': selected_sorting\n }\n qs_inputs = {\n 'qs': qs,\n 'selected_inputs': selected_inputs,\n 'entrustability_dict': dict(ENTRUSTABILITY_SCORES),\n 'activities_dict': dict(ACTIVITIES),\n 'givers': givers,\n 'activities': activities\n }\n return qs_inputs\n\n\n# primary method for generating the appropriate data for the feedback chart\ndef feedback_chart(request):\n # run all filters\n qs_inputs = filter_request(request, 'None')\n qs = qs_inputs['qs']\n selected_inputs = qs_inputs['selected_inputs']\n data = []\n labels = []\n # averages the entrustability score by year and month\n data_month, data_year, labels_month, labels_year = averaging_helper(qs, selected_inputs['selected_start_date'],\n selected_inputs['selected_end_date'])\n\n # display appropriate output based on user input, default to month\n if selected_inputs['selected_sorting'] == 'byYear':\n data = data_year\n labels = labels_year\n elif selected_inputs['selected_sorting'] == 'byIndividual':\n for entry in qs:\n data.append(entry.entrustability)\n labels.append(entry.to_month_day_year())\n else:\n data = data_month\n labels = labels_month\n\n return JsonResponse(data={\n 'labels': labels,\n 'data': data,\n 'selected_inputs': selected_inputs,\n 'entrustability_dict': qs_inputs['entrustability_dict'],\n 'activities_dict': qs_inputs['activities_dict']\n })\n\n\n# primary method for generating the appropriate data for the giver pie chart\ndef giver_pie_chart(request):\n # run all filters using config: 'GiverPie'\n qs_inputs = filter_request(request, 'GiverPie')\n qs = qs_inputs['qs']\n selected_inputs = qs_inputs['selected_inputs']\n\n # primary helper function that counts the amount of feedback given be each giver\n labels, data_count = count_by_giver(qs, qs_inputs['givers'])\n\n return JsonResponse(data={\n 'labels': labels,\n 'data': data_count,\n 'selected_inputs': selected_inputs,\n 'entrustability_dict': qs_inputs['entrustability_dict'],\n 'activities_dict': qs_inputs['activities_dict']\n })\n\n\n# primary method for generating the appropriate data for the activity radar chart\ndef activity_radar_chart(request):\n # run all filters using config: 'ActivityRadar'\n qs_inputs = filter_request(request, 'ActivityRadar')\n qs = qs_inputs['qs']\n selected_inputs = qs_inputs['selected_inputs']\n\n # primary helper function that averages entrustability scores by activities\n labels, data = average_by_activity(qs, qs_inputs['activities'])\n\n return JsonResponse(data={\n 'labels': labels,\n 'data': data,\n 'selected_inputs': selected_inputs,\n 'entrustability_dict': qs_inputs['entrustability_dict'],\n 'activities_dict': qs_inputs['activities_dict']\n })\n\n\n# primary helper function for generating the average entrustability score by year and month\ndef averaging_helper(qs, start_date, end_date):\n # this only works for the given data model\n start_year = int(start_date[0:4])\n end_year = int(end_date[0:4])\n start_month = int(start_date[5:7])\n end_month = int(end_date[5:7])\n labels_month = []\n labels_year = []\n data_month = []\n data_year = []\n\n # exception handling\n if start_year == end_year and start_month > end_month:\n return data_month, data_year, labels_month, labels_year\n if start_year > end_year:\n return data_month, data_year, labels_month, labels_year\n\n # creating labels\n cur_year = start_year\n cur_month = start_month\n labels_year_temp = []\n while cur_year != end_year or cur_month != end_month:\n labels_month.append(calendar.month_abbr[cur_month] + ' ' + str(cur_year))\n labels_year_temp.append(str(cur_year))\n if cur_month == 12:\n cur_month = 1\n cur_year = cur_year + 1\n else:\n cur_month = cur_month + 1\n labels_month.append(calendar.month_abbr[cur_month] + ' ' + str(cur_year))\n labels_year_temp.append(str(cur_year))\n for i in labels_year_temp:\n if i not in labels_year:\n labels_year.append(i)\n\n data_sum_year = [0] * len(labels_year)\n data_sum_month = [0] * len(labels_month)\n data_count_year = [0] * len(labels_year)\n data_count_month = [0] * len(labels_month)\n\n # iterating through queryset to sum entrustability scores\n for entry in qs:\n index_year = labels_year.index(entry.to_year())\n data_sum_year[index_year] = data_sum_year[index_year] + entry.entrustability\n data_count_year[index_year] = data_count_year[index_year] + 1\n index_month = labels_month.index(entry.to_month_year())\n data_sum_month[index_month] = data_sum_month[index_month] + entry.entrustability\n data_count_month[index_month] = data_count_month[index_month] + 1\n\n # average the values ofr month and year\n for index in range(0, len(labels_year)):\n if data_count_year[index] == 0:\n data_year.append(None)\n else:\n data_year.append(data_sum_year[index] / data_count_year[index])\n for index in range(0, len(labels_month)):\n if data_count_month[index] == 0:\n data_month.append(None)\n else:\n data_month.append(data_sum_month[index] / data_count_month[index])\n\n return data_month, data_year, labels_month, labels_year\n\n\n# primary helper function for the giver pie chart, counts the amount of feedback given by each giver\ndef count_by_giver(qs, givers):\n labels = []\n for giver in givers:\n labels.append(giver['giver__name'])\n data_count = [0] * len(givers)\n\n for entry in qs:\n index = labels.index(entry.giver.name)\n data_count[index] = data_count[index] + 1\n\n return labels, data_count\n\n\n# primary helper function for the activity radar chart, calculates the average entrustability score by activity\ndef average_by_activity(qs, activities):\n # creating initial variables\n labels = []\n labels_temp = []\n for activity in activities:\n labels.append(dict(ACTIVITIES)[activity['activity']])\n labels_temp.append(activity['activity'])\n data_sum = [0] * len(activities)\n data_count = [0] * len(activities)\n data = []\n\n # iterating through all entries and queryset and summing the entrustability\n for entry in qs:\n index = labels_temp.index(entry.activity)\n data_sum[index] = data_sum[index] + entry.entrustability\n data_count[index] = data_count[index] + 1\n\n # averaging the scores\n for index in range(0, len(labels)):\n if data_count[index] == 0:\n data.append(None)\n else:\n data.append(data_sum[index] / data_count[index])\n\n return labels, data\n\n\n# checks if the given query parameter is valid\ndef is_valid_queryparam(param):\n return param != '' and param is not None\n","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"427436655","text":"N = int(input())\narr = []\nfor i in range(N):\n arr.append(list(map(int, input())))\n\nfor h in range(1, N): #높이를 1씩 높여가면서 맵을 반복적으로 탐색\n flag=0\n for i in range(1, N - 1):\n for j in range(1, N - 1):\n if arr[i][j]==h:\n flag = 1 #현재 높이가 있으면 체크\n if arr[i-1][j]>=h and arr[i+1][j]>=h and arr[i][j-1]>=h and arr[i][j+1]>=h:\n arr[i][j]+=1\n\n if flag==0: break\nprint (h-1)\n\n\n","sub_path":"algorithm/codexpert/마을인공위성.py","file_name":"마을인공위성.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"308983261","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\nimport argparse\nimport sys\nimport os\nimport glob\nimport subprocess\nimport pandas as pd\nimport pdb\n\n\n\n#Arguments for argparse module:\nparser = argparse.ArgumentParser(description = '''A program that runs TMalign and tree-puzzle and\n\t\t\t\t\t\treceives the resulting output.''')\n\nparser.add_argument('outdir', nargs=1, type= str, default=sys.stdin, help = 'Path to output directory.')\nparser.add_argument('hgroup_file', nargs=1, type= str, default=sys.stdin, help = 'File with selected uids for the specific H-group.')\nparser.add_argument('puzzle', nargs=1, type= str, default=sys.stdin, help = 'Path to tree-puzzle.')\nparser.add_argument('TMalign', nargs=1, type= str, default=sys.stdin, help = 'Path to TMalign.')\nparser.add_argument('address', nargs=1, type= str, default=sys.stdin, help = 'Web adress to download from.') #www.cathdb.info/version/v4_2_0/api/rest/id/\n\n#FUNCTIONS\ndef run_TMalign(outdir, TMalign, hgroup, hgroup_file, address):\n\t'''Download pdb files from CATH api and run TMalign.\n\t'''\n\t\n\tmeasures = {} #Save RMSD to add with MLAA distance from tree-puzzle\n\tuids = pd.read_csv(hgroup_file, sep ='\\n', header=None)\n\tuids = uids[0]\n\t#Get pdb files for domains\n\tfor uid in uids:\n\t\t#Get pdb file. Make sure they are saved to outdir\n\t\tsubprocess.call([\"wget\",address+uid+'.pdb'])\t\t\t\n\n\t#Run TMalign\n\tfor i in range(len(uids)):\n\t\tstr_i = outdir+uids[i]+'.pdb'\n\t\tfor j in range(i+1, len(uids)):\n\t\t\tstr_j = outdir+uids[j]+'.pdb'\n\t\t\t#Run TMalign and parse output\n\t\t\ttmalign_out = subprocess.check_output([TMalign, str_i , str_j]) #Performs optimal structural alignment \n\t\t\t(tm_aligned_len, rmsd, tmscores, tm_identity, chain_lens, tm_sequences)= parse_tm(tmalign_out)\t\n\t\t\tmeasures[uids[i]+'_'+uids[j]] = [rmsd, tmscores[0], tmscores[1]]\n\t\t\t#Make .phy file of aligned sequences\n\t\t\tmake_phylip([uids[i], uids[j]], tm_sequences[0], tm_sequences[1]) \n\n\treturn measures\n\ndef parse_tm(tmalign_out):\n\t'''A function that gets the uids and the corresponding scores\n\tand prints them in tsv.\n\t'''\n\t\n\ttmalign_out = tmalign_out.decode(\"utf-8\")\n\ttmalign_out = tmalign_out.split('\\n')\n\ttmscores = [] #Save TMscores\n\tfor i in range(0, len(tmalign_out)): #Step through all items in list\n\t\t\t\n\t\tif 'Aligned length' and 'RMSD' and 'Seq_ID' in tmalign_out[i]:\n\t\t\trow = tmalign_out[i].split(',')\n\t\t\taligned_len = row[0].split('=')[1].lstrip()\n\t\t\trmsd = row[1].split('=')[1].lstrip()\n\t\t\tidentity = row[2].split('=')[2].lstrip() \n\t\t\n\t\tif 'Length of Chain_1:' in tmalign_out[i]:\n\t\t\tlen_1 = tmalign_out[i].split(':')[1].split()[0]\n\t\t\t\t\n\t\tif 'Length of Chain_2:' in tmalign_out[i]:\n len_2 = tmalign_out[i].split(':')[1].split()[0]\n\t\tif 'TM-score=' in tmalign_out[i]:\n\t\t\ttmscores.append(tmalign_out[i].split('(')[0].split('=')[1].strip())\n\n\t#Get per residue sequence alignments from structural alignment\n\tsequences = [tmalign_out[-5], tmalign_out[-3]]\n\n\tchain_lens = [int(len_1), int(len_2)]\n\treturn(aligned_len, rmsd, tmscores, identity, chain_lens, sequences)\n\ndef make_phylip(uids, query_aln, template_aln):\n '''Print phylip format for tree-puzzle calculations\n '''\n #Create text in phylip format\n text = (' 4 ' + str(len(query_aln)) + '\\n'\n + uids[0] + '00|' + query_aln + '\\n'\n + 'copy11111' + '|' + query_aln + '\\n'\n + uids[1] + '00|' + template_aln + '\\n'\n + 'copy22222' + '|' + template_aln + '\\n')\n\n #Define file name\n file_name = uids[0] + '_' + uids[1] + '.phy'\n #Open file and write text to it\n with open(file_name, \"w\") as file:\n file.write(text)\n\n return None\n\ndef run_puzzle(indir, puzzle):\n '''Run tree-puzzle and retrieve output\n '''\n for name in glob.glob(indir+\"*.phy\"): #Use all .phy files\n uid_pairs = name.split('/')[-1].split('.')[0].split('_')\n try:\n p = subprocess.Popen([puzzle, name], stdin=subprocess.PIPE)\n p.communicate(b'y\\nn\\n')[0]\n except:\n raise IOError(name)\n\n\n return None\n\ndef parse_puzzle(measures, indir):\n\t'''Parse output from tree-puzzle and write to dict\n\t'''\n\tkeys = [*measures] #Make list of keys in dict\n\tfor key in keys:\n\t\tuids = key.split('_')\n\t\trmsd, tmscore1, tmscore2 = measures[key] #Get rmsd\n\t\ttry:\n\t\t\tdist_file = open(indir + key + '.phy.dist')\n\t\texcept:\n\t\t\tuids = key.split('_')\n\t\t\tdist_file = open(indir + uids[1] + '_' + uids[0] + '.phy.dist')\n\t\t\tmeasures.pop(key)\n\t\t\t#change key to match other file names\n\t\t\tkey = uids[1] + '_' + uids[0]\n\t\tfor line in dist_file:\n\t\t\tline = line.rstrip()\n\t\t\tline = line.split(\" \") #split on double space\n\t\t\tline = list(filter(None, line)) #Filter away empty strings\n\n\t\t\tif len(line)>2:\n\t\t\t\tseq_dist = line[-1] #Get ML evolutionary distance between sequences\n\t\t\t\tmeasures[key] = [rmsd, tmscore1, tmscore2, seq_dist] \n\t\t\t\tbreak\n\t\tdist_file.close()\n\n\treturn measures\n\n\ndef print_tsv(measures, hgroup):\n\t'''Print measures in tsv to file\n\t'''\n\twith open(hgroup+'.tsv', 'w') as file:\n\t\tfile.write('uid1\\tuid2\\tMLAAdist\\tRMSD\\tTMscore_high\\tTMscore_low\\n')\n\t\tfor key in measures:\n\t\t\tuids = key.split('_')\n\t\t\trmsd, tmscore1, tmscore2, seq_dist = measures[key]\n\t\t\thigh_score = max(float(tmscore1), float(tmscore2))\n\t\t\tlow_score = min(float(tmscore1), float(tmscore2)) \n\t\t\tfile.write(uids[0]+'\\t'+uids[1]+'\\t'+seq_dist+'\\t'+rmsd+'\\t'+str(high_score)+'\\t'+str(low_score)+'\\n')\n\n\treturn None\n\n#####MAIN#####\nargs = parser.parse_args()\n\noutdir = args.outdir[0]\nhgroup_file = args.hgroup_file[0]\npuzzle = args.puzzle[0]\nTMalign = args.TMalign[0]\naddress = args.address[0]\n\n#Download pdb files from CATH api and run TMalign\nhgroup = hgroup_file.split('/')[-1].split('.txt')[0]\nmeasures = run_TMalign(outdir, TMalign, hgroup, hgroup_file, address)\n#Run tree-puzzle on .phy files created from extracted sequence alignments from TMalign struvtural alignments\nrun_puzzle(outdir, puzzle)\n#Parse dist files from tree-puzzle and match to TMalign results\nmeasures = parse_puzzle(measures, outdir)\nprint_tsv(measures, hgroup)\n","sub_path":"CATH/str_aln/str_match.py","file_name":"str_match.py","file_ext":"py","file_size_in_byte":6151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"163738201","text":"# coding=utf-8\n\"\"\"Launch several services in a Rancher platform.\"\"\"\nimport json\nimport requests\nimport itertools\nfrom subprocess import Popen, PIPE\nimport threading\nimport yaml\nimport numpy\nimport os\nimport signal\nimport shutil\nfrom operator import methodcaller\nimport time\nimport re\nfrom launcherApp.dbConnection import dbConnector\nimport datetime\nfrom bson.objectid import ObjectId\n\n# TO SEE DEBUG AND INFO\n# TODO: Check Error Handling\n# TODO: Fix it for local usage.\n# TODO: reformta del nombre de las colecciones\n# NOTE: name of the collections -> experiments, queue, execution\n\n\nclass lanzador:\n \"\"\".\"\"\"\n\n def __init__(self, url_entradas, access_key, secret_key, db_password, logger):\n \"\"\"Init the object.\"\"\"\n self.url_entradas = url_entradas\n self.access_key = access_key\n self.secret_key = secret_key\n self.logger = logger\n self.namespaces_running = 0\n self.namespaces_limit = 0\n self.time_out = 0\n self.db_password = db_password\n self.db = None\n self.MODULE_DIR = os.path.dirname(__file__)\n self.logger.info(self.MODULE_DIR)\n self.connect_db()\n self.clean_directories()\n\n def launch_experiment(self, experiment_id):\n \"\"\"Launch the experiments in the execution queue.\"\"\"\n self.logger.info(type(experiment_id))\n experiment = self.db.get_document(\n doc_query={'_id': experiment_id},\n coll_name='experiments')\n self.logger.debug(type(experiment))\n self.logger.info(experiment['files'])\n\n # for file_name, text in experiment['files']:\n # self.logger.info(name + '=' + value)\n for file_name in experiment['files']:\n if(file_name != 'rancher-compose.yml'):\n with open(\n self.MODULE_DIR + '/files/'\n + experiment['experiment_group'] + '/'\n + file_name,\n 'r') as f:\n text = f.read()\n for name, value in experiment['parameters'].items():\n text = text.replace('${' + name + '}', value)\n # Set by default the namespace\n text = text.replace(\n '${' + 'NAMESPACE' + '}',\n experiment['name'])\n text = text.replace(\n '${' + 'ROOT_TOPIC' + '}',\n experiment['name'])\n with open(\n self.MODULE_DIR + '/files/'\n + experiment['experiment_group']\n + '/launch/' + file_name,\n 'w') as f:\n f.write(text)\n self.logger.info(\n 'Preparado para lanzar namespace ' + experiment['name'])\n # Se crea un namespace por cada combinacion\n self.create_namespace(experiment['name'])\n for file_name in experiment['files']:\n if(file_name != 'rancher-compose.yml'):\n self.start_service(\n experiment['name'],\n self.MODULE_DIR + '/files/'\n + experiment['experiment_group']\n + '/launch/' + file_name)\n # NOTE: Guarda cada experimento como documento en la coll de executions\n self.db.update_document(\n doc_query={'_id': experiment_id},\n doc_update={'launch_time': datetime.datetime.utcnow()},\n coll_name='experiments')\n self.db.push_document(\n doc_query={}, key='running',\n element=experiment_id, coll_name='execution')\n pid = self.startKafka(experiment['name'])\n thread = threading.Thread(\n target=self.checkResults,\n args=[experiment['name'], pid])\n thread.start()\n\n def launch_experiments(self):\n \"\"\".\"\"\"\n print('COMIENZA PROCESO DE LANZAMIENTO EXPERIMENTOS')\n entradas = requests.get(url=self.url_entradas, verify=False)\n entradas = yaml.load(entradas.text)\n self.logger.info('Obtenido el fichero de configuracion ' +\n 'para los parametros')\n self.logger.debug(entradas)\n self.time_out = entradas[\"time_out\"]\n self.namespaces_limit = entradas[\"limit_namespaces\"]\n\n for catalog_name, catalog_param in entradas['catalog_services'].items():\n self.create_directories(catalog_name)\n files, url_rancher = self.getConfiguration(\n catalog_param,\n catalog_name)\n self.configurateKubectl(url_rancher)\n parametros_nombre, parametros = self.getDefinedParams(\n catalog_param['PARAMS'])\n parametros_nombre, parametros = self.addDefaultParams(\n parametros_nombre,\n parametros,\n catalog_name)\n self.save_grid_combinations(\n catalog_name,\n files,\n parametros,\n parametros_nombre)\n self.logger.info('Combinations save for the catalog')\n # while(self.namespaces_running >= self.namespaces_limit):\n # continue\n experiment_id = self.db.pop_document({}, 'queue', 'queue')\n\n while (experiment_id and self.namespaces_running < self.namespaces_limit):\n self.launch_experiment(experiment_id)\n self.namespaces_running += 1\n # while(self.namespaces_running >= self.namespaces_limit):\n # continue\n experiment_id = self.db.pop_document({}, 'queue', 'queue')\n\n def connect_db(self):\n \"\"\"Establish a connection with the database.\"\"\"\n cont = 0\n while cont < 10:\n try:\n self.db = dbConnector(\n db_name='automodelingDB')\n except Exception:\n self.logger.warning('NO DATABASE CONNECTION')\n cont += 1\n time.sleep(5)\n else:\n self.logger.info('Database succesfuly connected')\n break\n if cont is 10:\n self.logger.critical('FAILED TO CONNECT THE DATABASE')\n\n def create_directories(self, dir_name):\n \"\"\"Create the directory with the specified name.\"\"\"\n if not os.path.isdir(self.MODULE_DIR + '/files/' + dir_name):\n os.mkdir(self.MODULE_DIR + '/files/' + dir_name)\n if not os.path.isdir(self.MODULE_DIR + '/files/' + dir_name + '/launch'):\n os.mkdir(self.MODULE_DIR + '/files/' + dir_name + '/launch')\n\n def clean_directories(self):\n \"\"\"Clean the files directory.\"\"\"\n if(os.path.isdir(self.MODULE_DIR + '/files')):\n shutil.rmtree(self.MODULE_DIR + '/files')\n os.mkdir(self.MODULE_DIR + '/files')\n\n def getConfiguration(self, configuration, catalog_name):\n \"\"\"\n Extrae de un yaml toda la configuracion para el lanzador.\n\n Devuelve la lista de archivos necesarios para la plantilla del catalogo\n y escribe en una subcarpeta dentro de files con el nombre del catalogo\n los archivos necesarios para lanzar los experimentos.\n \"\"\"\n # Peticion a la API para obtener el dockercompose\n url_catalog = configuration[\"URL_API\"]\n url_rancher = configuration[\"URL_RANCHER\"]\n auth = requests.auth.HTTPBasicAuth(self.access_key, self.secret_key)\n r = requests.get(url=url_catalog, auth=auth)\n content_all = r.json()\n self.logger.info('Obtenido el objeto JSON de la API')\n self.logger.debug(content_all)\n\n # Obtención de los ficheros de los servicios que hay que arrancar\n files = content_all['files']\n for file_name in files:\n with open(\n self.MODULE_DIR + '/files/'\n + catalog_name + '/' + file_name,\n 'w') as file_service:\n file_service.write(str(content_all['files'][file_name]))\n\n return (files, url_rancher)\n\n def configurateKubectl(self, rancher_url):\n \"\"\"Configurate the kubectl client in the container.\"\"\"\n # TODO: Dejar configurable los parametros que llevan el nombre ml-kube\n\n # Configuramos kubectl\n self.logger.debug('Empezamos a configurar kubectl')\n\n # calculo de la ruta relativa donde se encuentra la carpeta .kube\n ##filepath = '/root/.kube/'\n # if args.local: #TODO: New local configuration needed\n filepath = '/home/ignacio/.kube/'\n\n os.system('cp ' + self.MODULE_DIR + '/config ' + filepath)\n\n # Obtenemos la plantilla para el config\n with open(filepath + 'config', 'r') as f:\n text = f.read()\n self.logger.debug('Plantilla del config\\n' + text)\n kubeConfig = yaml.load(text)\n\n # https://rancher.default.svc.cluster.local:80/r/projects/1a8238/kubernetes\n kubeConfig['clusters'][0]['cluster']['server'] = rancher_url\n kubeConfig['users'][0]['user']['username'] = self.access_key\n kubeConfig['users'][0]['user']['password'] = self.secret_key\n\n self.logger.info('Configuration set')\n\n with open(filepath + 'config', 'w') as f:\n yaml.dump(kubeConfig, f)\n\n def getDefinedParams(self, parametros_yml):\n \"\"\"\n Obtiene los parametros para un stack del catalogo.\n\n Devuelve los parametros en forma de dos listas: una con el nombre de\n los parametros y otra con los parametros en si.\n \"\"\"\n # FIXME: En vez de devolver una tupla devolver diccionario???\n parametros_nombre = []\n parametros = []\n self.logger.debug(parametros_yml)\n # Las distintas formas que se consideran son: parametroNombre->n\n # 1. [valorInicial:valorFinal:Salto] -> Lineal\n # 2. TODO: [valorInicial:valorFinal:Función] -> Otro tipo de funcion\n # 3. TODO: HIDDEN_SIZE debe aceptar parametros que no fueran absolute\n for parametro in parametros_yml:\n self.logger.info(parametro)\n self.logger.debug(type(parametro))\n parametros_nombre.append(parametro)\n # Obtiene el parametro HIDDEN_SIZE, que es especial\n if(parametro == 'HIDDEN_SIZE'):\n layers = [parametros_yml[parametro]['number_units'] for i in\n range(parametros_yml[parametro]['number_layers'][0])]\n combinations = []\n for combination in itertools.product(*layers):\n combination = ','.join(map(str, combination))\n combinations.append(combination)\n parametros.append(combinations)\n continue\n\n self.logger.info(\"LOS PARAMETROS RECIBIDOS EN GETDEFINEDPARAMS:\")\n self.logger.info(parametros_yml)\n\n opcion = parametros_yml[parametro]['type']\n # parametro[parametro.index(\"{\"):parametro.index(\"}\")]\n if(opcion == 'lineal'):\n valorInicial = parametros_yml[parametro]['initial-value']\n valorFinal = parametros_yml[parametro][\"final-value\"]\n valorSalto = parametros_yml[parametro][\"interval\"]\n opcionesParametro = numpy.arange(\n valorInicial, valorFinal, valorSalto)\n parametros.append(opcionesParametro.tolist())\n elif(opcion == 2):\n # opcionesParametro\n pass\n elif(opcion == \"absolute\"):\n parametros.append(parametros_yml[parametro][\"param\"])\n else:\n self.logger.critical('ERROR: FORMATO DE PARAMETROS INCORRECTO')\n raise SyntaxError('Parametros en el yml incorectos')\n\n parametros_nombre = parametros_nombre[::-1]\n parametros = parametros[::-1]\n self.logger.info('Obtenida la lista de posibles parametros')\n\n return (parametros_nombre, parametros)\n\n def addDefaultParams(self, parametros_nombre, parametros, catalog_name):\n \"\"\"\n Add default values to the params remaining.\n\n The func adds the defaults values in the parameters not specified in\n the parameter list given in the arguments.\n \"\"\"\n with open(\n self.MODULE_DIR + '/files/'\n + catalog_name + '/rancher-compose.yml',\n 'r') as f:\n fileContent = f.read()\n rancherComposeContent = yaml.load(fileContent)\n\n questions = rancherComposeContent['.catalog']['questions']\n\n for element in questions:\n if(element['variable'] in parametros_nombre\n or element['variable'] == 'NAMESPACE'\n or element['variable'] == 'ROOT_TOPIC'):\n continue\n else:\n parametros_nombre.append(element['variable'])\n listElem = list()\n listElem.append(element['default'])\n parametros.append(listElem)\n\n return (parametros_nombre, parametros)\n\n def save_grid_combinations(\n self, catalog_name, files, parametros, parametros_nombre):\n \"\"\"Store in the db the execution queue and the parameters.\"\"\"\n cont = 1\n for param in itertools.product(*parametros):\n # Substitucion de las variables en los ficheros\n # NOTE: Los nombres de los paramentros deben ser exactamente\n # los mismos que en los ficheros.\n # El namespace no admite mayusculas\n namespace = ''.join([catalog_name, 'model{num}'.format(num=cont)])\n namespace_document = {}\n namespace_document['files'] = []\n namespace_document['name'] = namespace\n namespace_document['experiment_group'] = catalog_name\n namespace_document['parameters'] = {}\n for index in range(len(parametros_nombre)):\n self.logger.info(\n parametros_nombre[index] + '=' +\n str(param[index]) + '\\n')\n namespace_document['parameters'][\n parametros_nombre[index]] = str(param[index])\n namespace_document['create_time'] = datetime.datetime.utcnow()\n for file_name in files:\n namespace_document['files'].append(file_name)\n self.logger.debug(namespace_document)\n id_experiment = self.db.save_document(\n namespace_document,\n coll_name='experiments').inserted_id\n self.db.push_document(\n doc_query={},\n key='queue',\n element=id_experiment,\n coll_name='queue')\n cont += 1\n # FIXME: Comprobar la forma de hacer esto\n\n def get_execution_queue(self):\n \"\"\"Return the execution queue in a list form.\"\"\"\n return self.db.get_document({}, 'queue')['queue']\n\n def get_running_list(self):\n \"\"\"Return the current running experiments in a list form.\"\"\"\n return self.db.get_document({}, 'running')['running']\n\n def create_namespace(self, namespace):\n \"\"\"Crea un namespace con el nombre dado.\"\"\"\n os.system(\n self.MODULE_DIR + '/exec/kubectl create namespace ' + namespace)\n self.namespaces_running += 1\n\n def rm_namespace(self, namespace, pid):\n \"\"\"Borra el namespace con el nombre dado y su contenido.\"\"\"\n self.killProcess(pid)\n # Llama a kafka para obtener los resultados\n self.getResults(namespace, 1)\n # Delete namespace content\n os.system(\n self.MODULE_DIR + '/exec/kubectl delete ' +\n '--all service,rc,ingress,pod --namespace=' +\n namespace +\n ' --now'\n )\n # Delete the namespace itself\n os.system(\n self.MODULE_DIR + '/exec/kubectl delete namespace ' + namespace)\n self.namespaces_running -= 1\n\n def start_service(self, namespace, serviceFile):\n \"\"\"Launch one service or rc from one file.\"\"\"\n self.logger.info(\n 'Lanzando servicio ' + serviceFile +\n ' en el namespace ' + namespace)\n os.system(self.MODULE_DIR + '/exec/kubectl --namespace=' + namespace +\n ' create -f ' + serviceFile)\n\n def startKafka(self, namespace):\n \"\"\"Start the kafka consumer process.\"\"\"\n pid = 0\n with open(self.MODULE_DIR + '/results/' + namespace, 'w') as file_results:\n kafkaConsumer = Popen(\n [self.MODULE_DIR + '/exec/kafka-console-consumer'],\n env={\"KAFKA_SERVICE\": \"kafka.default.svc.cluster.local\",\n \"TOPIC\": namespace+\"-metrics\",\n \"OFFSET\": \"oldest\",\n \"KAFKA_GROUP\": namespace},\n stdout=file_results,\n shell=True,\n preexec_fn=os.setsid)\n pid = kafkaConsumer.pid\n self.logger.info(pid)\n return pid\n\n def checkResults(self, namespace, pid):\n \"\"\"Check the results till it reaches accuracy 1.\"\"\"\n time_finish = time.time() + self.time_out\n last_time = time.time()\n start_time = time.time()\n while (time.time() <= time_finish):\n self.logger.debug('Está en le bucle de acceso a resultados')\n lastResults = self.getResults(namespace, 10)\n if(len(lastResults) == 0):\n time.sleep(10)\n continue\n if(lastResults[len(lastResults)-1]['accuracy'] == 1.0):\n self.logger.info('Resultados:')\n self.logger.info(lastResults)\n break\n time.sleep(10)\n last_time = time.time()\n\n self.db.pull_document(\n doc_query={}, key='running',\n element=namespace, coll_name='execution')\n self.rm_namespace(namespace, pid)\n self.logger.debug('Debería pasar por aquí para guardar los resultados')\n results = {\n 'time': last_time - start_time, 'last_results': lastResults}\n self.logger.info('Guardando resultados:')\n self.logger.info(results)\n self.db.update_document(\n doc_query={'name': namespace},\n doc_update=results,\n coll_name='experiments')\n\n def getResults(self, namespace, numberResults):\n \"\"\"Obtiene el numero de resultados especificadas como parametro.\"\"\"\n process1 = Popen(['cat', self.MODULE_DIR + '/results/'+namespace], stdout=PIPE)\n process2 = Popen(\n ['tail', '-'+str(numberResults)],\n stdin=process1.stdout,\n stdout=PIPE)\n (out, err) = process2.communicate()\n out = out.decode('UTF-8')\n self.logger.info(out)\n\n results = str(out).split('\\n')[:-1]\n self.logger.info(results)\n\n if(len(results) <= 1):\n return []\n\n prog = re.compile('[(\\d|\\.)+\\s]+')\n if(not (prog.match(results[len(results)-1]) and\n prog.match(results[0]))):\n self.logger.warning(\"Incorrect results format\")\n self.logger.warning(results[0])\n self.logger.warning(results[len(results)-1])\n return []\n\n results = list(map(methodcaller(\"split\"), results))\n\n if(len(results) <= 1):\n return []\n\n self.logger.info(results)\n resultsList = [{'cost': float(result[3]),\n 'accuracy': float(result[4])} for result in results]\n self.logger.info(resultsList)\n return resultsList\n\n # self.logger.info(\"Ejecutando cat directamente:\")\n # os.system('cat ./results/'+namespace+' | tail -'+str(numberResults))\n\n def killProcess(self, pid):\n \"\"\"Mata el proceso kafka creado por popen.\"\"\"\n os.killpg(os.getpgid(pid), signal.SIGTERM)\n\n# TODO: funcion que envie al monitor la orden de dejar de escuchar.\n# A esta funcion hay que llamarla desde el rm_namespace\n\n def stop_experiment(self, id):\n \"\"\"Stop one of the current experiments execution and start the next.\"\"\"\n # Llama a rm_namespace\n # Primero obtiene el nombre del namespace\n namespace = self.db.get_document(\n {\"_id\": ObjectId(id)}, \"experiments\")[\"name\"]\n self.rm_namespace(namespace)\n # Elimina de la lista de experimentos ejecutandose\n self.db.delete_document({\"id_experiment\": ObjectId(id)}, \"running\")\n self.execute_next(id)\n\n def execute_next(self, id):\n \"\"\"Launch the first experiment in the queue.\"\"\"\n # Primero lo saca de la cola de espera\n experiment = self.db.pop_document(\n {\"id_experiment\": ObjectId(id)}, \"queue\")\n if not experiment:\n return False\n # Luego lo guarda en la cola de ejecución\n self.db.push_document(\n {}, \"running\", experiment[\"id_experiment\"], \"running\")\n # Ejecuta el experimento nuevo\n self.launch_experiment(experiment[\"id_experiment\"])\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n # def launchExperiments(self, files, catalog_name, parametros, parametros_nombre):\n # \"\"\"\n # Lanza las combinaciones entre los parametros de entrada.\n #\n # Guarda cada combinacion de parametros como un documento en la misma\n # coleccion. No debe devolver nada. Gestiona la cola?\n # (Inicializa la cola?).\n # \"\"\"\n # cont = 1\n # threadsCheckResults = []\n # # Se guardan los parametros en el fichero answers.txt\n # for param in itertools.product(*parametros):\n # # Substitucion de las variables en los ficheros\n # # Check -> Los nombres de los paramentros deben ser exactamente\n # # los mismos que en los ficheros.\n # # El namespace no admite mayusculas\n # namespace = ''.join([catalog_name, 'model{num}'.format(num=cont)])\n # # param_record[namespace] = {}\n # namespace_document = {}\n # namespace_document['name'] = namespace\n # for file_name in files:\n # if(file_name != 'rancher-compose.yml'):\n # with open('./files/' + file_name, 'r') as f:\n # text = f.read()\n # for index in range(len(parametros_nombre)):\n # self.logger.info(\n # parametros_nombre[index] + '=' +\n # str(param[index]) + '\\n')\n # text = text.replace(\n # '${' + parametros_nombre[index] + '}',\n # str(param[index]))\n # namespace_document['parameters'][\n # parametros_nombre[index]] = param[index]\n # # Set by default the namespace\n # text = text.replace(\n # '${' + 'NAMESPACE' + '}',\n # namespace)\n # text = text.replace(\n # '${' + 'ROOT_TOPIC' + '}',\n # namespace)\n # with open('./files/launch/' + file_name, 'w') as f:\n # f.write(text)\n # self.db.save_document(namespace_document, coll_name='experiments')\n # while(self.namespaces_running >= self.namespaces_limit):\n # continue\n #\n # self.logger.info('Preparado para lanzar namespace ' + namespace)\n # # Llamadas a kubectl\n # # Se crea un namespace por cada combinacion\n # self.create_namespace(namespace)\n # # Por cada fichero en ./files, se lanza un start_service\n # # dentro de un namespace\n # for file in files:\n # if(file != 'rancher-compose.yml'):\n # self.start_service(namespace, './files/launch/' + file)\n #\n # pid = self.startKafka(namespace)\n #\n # threadsCheckResults.append(threading.Thread(\n # target=self.checkResults,\n # args=[namespace, pid]))\n # threadsCheckResults[cont-1].start()\n #\n # cont = cont + 1\n #\n # return namespace_document # FIXME: Return innecesario ahora\n\n\n\n\n\n # def main(self):\n # \"\"\"Main execution of the class.\"\"\"\n # print('COMIENZA PROCESO DE LANZAMIENTO EXPERIMENTOS')\n # entradas = requests.get(url=self.url_entradas, verify=False)\n # entradas = yaml.load(entradas.text)\n # self.logger.info('Obtenido el fichero de configuracion ' +\n # 'para los parametros')\n # self.logger.debug(entradas)\n # self.time_out = entradas[\"time_out\"]\n # self.namespaces_limit = entradas[\"limit_namespaces\"]\n #\n # self.prepareDirectories()\n # catalogs = [catalog for catalog in entradas[\"catalog_services\"]][::-1]\n # self.logger.info(catalogs)\n # param_record = {}\n #\n # for catalog in catalogs:\n # self.logger.info(catalog)\n # files, url, url_catalog = self.getConfiguration(\n # configuration=entradas[\"catalog_services\"][catalog])\n # self.configurateKubectl(rancher_url=url)\n # os.system(self.MODULE_DIR + '/exec/kubectl version')\n # parametros_nombre, parametros = self.getDefinedParams(\n # entradas[\"catalog_services\"][catalog]['PARAMS'])\n # parametros_nombre, parametros = self.addDefaultParams(\n # parametros_nombre, parametros)\n # param_record[catalog] = self.launchExperiments(\n # files=files,\n # catalog_name=catalog,\n # parametros=parametros,\n # parametros_nombre=parametros_nombre)\n # # self.db.save_document(param_record, coll_name='parameter_records')\n","sub_path":"service/webApp/launcherApp/lanzadorServicios.py","file_name":"lanzadorServicios.py","file_ext":"py","file_size_in_byte":25840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"430286659","text":"# A Python interpretation of Steve Jackson's Zombie Dice\n# Rules for the game can be found at http://www.sjgames.com/dice/zombiedice/img/ZDRules_English.pdf\n# This script has been written such that the entire game is completely customisable.\n\nimport random\n\n# Number of players\nnum_players=2\n\n# The total number of turns in a game\nmax_turns=num_players * 500\n\n# The score required to win\nwinning_score=13\n\n# The total number of dice\nmax_dice=13\n\n# The maximum number of sides a die has\nmax_sides=6\n\n# Initialise the scores (assuming a two player game)\nscores = [0] * num_players\n\n# The number of dice selected each turn\ndice_per_turn = 3\n\n# Define the different basic dice types\n# The final element in the array is the die colour\nmaster_green_die = [\"brain\", \"runner\", \"shotgun\", \"brain\", \"brain\", \"runner\", \"green\"]\nmaster_yellow_die = [\"runner\", \"brain\", \"shotgun\", \"runner\", \"shotgun\", \"brain\", \"yellow\"]\nmaster_red_die = [\"shotgun\", \"runner\", \"brain\", \"shotgun\", \"shotgun\", \"runner\", \"red\"]\n\n# Define the dice that the game will use based on the maximum number of die sides\ngreen_die = []\nyellow_die = []\nred_die = []\nfor i in range(0, max_sides):\n green_die.append(master_green_die[i % (len(master_green_die) - 1)])\n yellow_die.append(master_yellow_die[i % (len(master_yellow_die) - 1)])\n red_die.append(master_red_die[i % (len(master_red_die) - 1)])\ngreen_die.append(\"green\")\nyellow_die.append(\"yellow\")\nred_die.append(\"red\")\n\n# Define the available dice in the game\n# Typically, six green dice, four yellow dice and three red dice\ndice=[green_die, green_die, green_die, green_die, green_die, green_die, yellow_die, yellow_die, yellow_die, yellow_die, red_die, red_die, red_die]\n\n# Ensure that the values selected for the game variables won't seriously break anything\nif dice_per_turn > max_dice:\n print (\"The number of dice selected per turn exceeds the total number of dice in the game (\", dice_per_turn, \">\", max_dice, \")\")\n raise SystemExit\n\nfor j in range(0, max_turns):\n print (\"SCORES\")\n for i in range(0, num_players):\n print (\"Player\", i+1, \":\", scores[i])\n print (\"Player \",(j%num_players)+1,\"'s turn...\")\n input (\"Press Enter to continue...\")\n \n brains = 0\n shotguns = 0\n\n # Dice selections are predetermined, but the players are unaware of this\n dice_selections = random.sample(range(0, max_dice), max_dice)\n\n # Select the dice to roll\n # The first time the dice being rolled are simply the first three selected\n dice_to_roll = []\n for dice_pulled in range(0, dice_per_turn):\n dice_to_roll.append(dice_selections[dice_pulled])\n\n roll_again = \"yes\"\n # While the player wants to keep rolling...\n while roll_again == \"yes\" or roll_again == \"y\":\n # Roll the three dice...\n print (\"You rolled: \")\n for i in range(0, dice_per_turn):\n roll = dice[dice_to_roll[i]][(random.randint(0, max_sides - 1))]\n print(dice[dice_to_roll[i]][max_sides], \" - \", roll)\n # If the player got a brain, add one to their brain total for this round and select another die\n # If the player got a shotgun, add one to their shotgun total for this round and select another die\n # If the player got a runner, do nothing and do not select another die\n if roll == \"brain\":\n brains+=1\n dice_to_roll[i] = dice_selections[dice_pulled]\n dice_pulled+=1\n elif roll == \"shotgun\":\n shotguns+=1\n dice_to_roll[i] = dice_selections[dice_pulled]\n dice_pulled+=1\n \n print (\"brains = \", brains, \"; shotguns = \", shotguns)\n # If the player has not rolled three shotguns, then ask them if they want to keep rolling\n if shotguns < 3:\n roll_again = input(\"Do you want to roll again?\")\n else:\n break\n \n # If the player has not rolled three shotguns, then add the number of brains they rolled to their total score\n if shotguns < 3:\n scores[j%num_players]+=brains\n # Check whether the player has enough brains to win\n if scores[j%num_players] >= winning_score:\n print (\"Player\", j%num_players+1, \"wins!\")\n raise SystemExit\n else:\n print (\"Your score is\", scores[j%num_players])\n else:\n print(\"Argh! You got shot!!!\")\n\n print (\"\")\n","sub_path":"zd.py","file_name":"zd.py","file_ext":"py","file_size_in_byte":4405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"275373629","text":"from tkinter import messagebox\n\nfrom selenium.webdriver import ActionChains\n\nfrom features.Locators.Locators import Locators\n\n\nclass ConfirmationPage():\n def __init__(self, driver):\n self.driver = driver\n\n self.Booking_summary_location_xpath = Locators.Booking_summary_location_xpath\n self.Booking_summary_pickup_xpath = Locators.Booking_summary_pickup_xpath\n self.Booking_summary_dropoff_xpath = Locators.Booking_summary_dropoff_xpath\n self.GPS_item_xpath = Locators.GPS_item_xpath\n self.Baby_seat_xpath = Locators.Baby_seat_xpath\n self.Booking_summary_item_price_xpath = Locators.Booking_summary_item_price_xpath\n self.Booking_summary_subtotal_xpath = Locators.Booking_summary_subtotal_xpath\n self.Booking_summary_total_amount_xpath = Locators.Booking_summary_total_amount_xpath\n\n def booking_summary_maintained(self, location, pickup, dropoff):\n pickup_location = self.driver.find_element_by_xpath(self.Booking_summary_location_xpath).text\n pickup_date = self.driver.find_element_by_xpath(self.Booking_summary_pickup_xpath).text\n drop_off_date = self.driver.find_element_by_xpath(self.Booking_summary_dropoff_xpath).text\n assert (pickup_location, pickup_date, drop_off_date) == (location, pickup, dropoff)\n\n def add_extra_item(self, driver):\n gps = self.driver.find_element_by_xpath(self.GPS_item_xpath)\n baby_seat = self.driver.find_element_by_xpath(self.Baby_seat_xpath)\n move = ActionChains(driver)\n move.click_and_hold(gps).move_by_offset(10, 0).release().perform()\n move.click_and_hold(baby_seat).move_by_offset(10, 0).release().perform()\n\n def adding_item_price(self):\n item = self.driver.find_element_by_xpath(self.Booking_summary_item_price_xpath).text\n subtotal = self.driver.find_element_by_xpath(self.Booking_summary_subtotal_xpath).text\n total = self.driver.find_element_by_xpath(self.Booking_summary_total_amount_xpath).text\n a = item.split(\"$\")\n item_price = a[1]\n b = subtotal.split(\"$\")\n subtotal_price = b[1]\n total_price = float(total)\n booking_total = int(item_price) + float(subtotal_price.replace(',', ''))\n assert total_price == booking_total\n","sub_path":"features/Pages/ConfirmationPage.py","file_name":"ConfirmationPage.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"282238721","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2020/3/21 下午3:52\n# @Author : serendipity-xp\n# @FileName: two_add.py\n# @Software: PyCharm\n# @GitHub :https://github.com/serendipity-xp\n\n\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution(object):\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n dummy_head = ListNode(0)\n cur_l1, cur_l2 = l1, l2\n cur_node = dummy_head\n carry = 0 # 表示进位\n while cur_l1 is not None or cur_l2 is not None:\n x = (cur_l1.val if cur_l1 else 0)\n y = (cur_l2.val if cur_l2 else 0)\n sum_val = x + y + carry\n carry = sum_val / 10\n cur_node.next = ListNode(sum_val % 10)\n cur_node = cur_node.next\n cur_l1 = (cur_l1.next if cur_l1 else None)\n cur_l2 = (cur_l2.next if cur_l2 else None)\n if carry > 0:\n cur_node.next = ListNode(carry)\n return dummy_head.next\n\n\nif __name__ == '__main__':\n l1 = ListNode(2)\n l1.next = ListNode(4)\n l1.next.next = ListNode(3)\n l2 = ListNode(5)\n l2.next = ListNode(6)\n l2.next.next = ListNode(4)\n Solution().addTwoNumbers(l1, l2)\n\n\n","sub_path":"library/two_add/two_add.py","file_name":"two_add.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"620823493","text":"from tkinter import StringVar, messagebox\nimport tkinter.font as tkFont\nimport tkinter as tk\n\nfrom ..config import *\nfrom ..TopLevelObject import *\n\n\nclass Account(TopLevelObject):\n def __init__(self, master):\n super().__init__(master)\n\n def Grid(self, **options):\n super().Grid(options)\n\n self.menuFrame = tk.Frame(self.frame)\n self.openOrders = tk.Button(self.menuFrame, text='Open Orders').grid(row=1, column=1, sticky='NWE')\n self.oderHistory = tk.Button(self.menuFrame, text='Order History').grid(row=1, column=2, sticky='NWE')\n self.tradeHistory = tk.Button(self.menuFrame, text='Trade History').grid(row=1, column=3, sticky='NWE')\n self.funds = tk.Button(self.menuFrame, text='Funds').grid(row=1, column=4, sticky='NWE')\n self.menuFrame.grid(row=1, column=1)\n\n for label in range(7):\n tk.Button(self.frame, text='Account button ' + str(label).zfill(2)).grid(row=label+2, column=1)\n \n\n def Pack(self, **options):\n super().Pack(options)\n\n #tk.Button(self.master, text='Header button1').pack(side='top')\n \n self.button1 = tk.Button(self.frame, text='Account button top')\n self.button1.pack(side='top')\n\n self.button2 = tk.Button(self.frame, text='Account button bottom')\n self.button2.pack(side='bottom')\n","sub_path":"GUI/Account/Account.py","file_name":"Account.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"36793622","text":"#encoding=utf-8\r\nimport os\r\nimport struct\r\n\r\ndef PackAFile(fname):\r\n fs=open(fname,'rb')\r\n stm=fs.read()\r\n fs.close()\r\n entry=bytearray()\r\n entry+=b'abimgdat10'.ljust(16,b'\\0')\r\n p=fname.rfind('\\\\')\r\n if p==-1:\r\n pn=fname.encode('932')\r\n else:\r\n pn=fname[p+1:].encode('932')\r\n entry+=struct.pack('H',len(pn))\r\n entry+=pn\r\n entry+=b'\\x03'\r\n entry+=struct.pack('I',len(stm))\r\n entry+=stm\r\n return entry\r\n\r\ndef GetOriHdr(fname):\r\n fs=open(fname,'rb')\r\n stm=fs.read(0x24)\r\n hdrlen,=struct.unpack('32xI',stm)\r\n hdrs=fs.read(hdrlen)\r\n return stm+hdrs\r\n\r\ndef WriteB(path1,oriname,newname):\r\n cnt=0\r\n nnames=[]\r\n for f in os.listdir(path1):\r\n nnames.append(f)\r\n cnt+=1\r\n hdr=GetOriHdr(oriname)\r\n fs=open(oriname,'rb')\r\n fs.seek(len(hdr))\r\n imgsect=fs.read(17)\r\n magic,cnnt=struct.unpack('<16sB',imgsect)\r\n if magic.strip(b'\\0')!=b'abimage10':\r\n print(magic)\r\n asdgawer\r\n if cnnt!=cnt:\r\n print('not match,count')\r\n afasef\r\n\r\n imgstm=bytearray(imgsect)\r\n for i in range(cnt):\r\n magic,namelen=struct.unpack('16sH',fs.read(18))\r\n na=fs.read(namelen)\r\n if magic.strip(b'\\0')==b'abimgdat13':\r\n hashlen,=struct.unpack('H',fs.read(2))\r\n hashc=fs.read(hashlen)\r\n na+=struct.pack('H',hashlen)+hashc\r\n na+=fs.read(13)\r\n elif magic.strip(b'\\0')==b'abimgdat11':\r\n awerfgasdf\r\n else:\r\n na+=fs.read(1)\r\n imgstm+=magic+struct.pack('H',namelen)+na\r\n\r\n olen,=struct.unpack('I',fs.read(4))\r\n fs.seek(olen,1)\r\n\r\n nstm=open(os.path.join(path1,nnames[i]),'rb').read()\r\n imgstm+=struct.pack('I',len(nstm))+nstm\r\n nfs=open(newname,'wb')\r\n nfs.write(hdr)\r\n nfs.write(imgstm)\r\n nfs.write(fs.read())\r\n nfs.close()\r\n fs.close()\r\n\r\nnewfolders='bfiles'\r\noribf='orib'\r\nnewbf='newb'\r\n\r\nfor f in os.listdir(oribf):\r\n WriteB(os.path.join(newfolders,f),\r\n os.path.join(oribf,f),\r\n os.path.join(newbf,f))\r\n\r\n##WriteB(r'D:\\chinesize\\zeas\\美少女万華鏡\\exp\\button_yes.b',\r\n## r'D:\\Program Files\\美少女万華鏡\\GameData\\da7\\library\\dialog\\button_yes.b',\r\n## r'nbutton_yes.b')\r\n","sub_path":"zeas/美少女万華鏡/packb.py","file_name":"packb.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"557429877","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n'''\n@author: zhaogao\n@license: (C) Copyright 2013-2018.\n@contact: gaozhao89@qq.com\n@software: learn-py\n@file: len206_给简单脚本增加日志功能.py\n@time: 28/05/2018 10:07 AM\n'''\n\n# 你希望在脚本和程序中将诊断信息写入日志文件。\n# 打印日志最简单方式是使用logging���块\n\nimport logging, os\n\n\ndef main():\n # Configure the logging system\n # basicConfig() 在程序中只能被执行一次。如果你稍后想改变日志配置,就需要先获取 root logger ,然后直接修改它\n logging.basicConfig(\n filename=os.path.expanduser('~/PycharmProjects/learn-py/cook/data/len206/app.log'),\n # 如果你想改变输出等级,你可以修改 basicConfig() 调用中的参数\n # level=logging.ERROR\n # 如 果 你 想 要 你 的 日 志 消 息 写 到 标 准 错 误 中, 而 不 是 日 志 文 件 中, 调 用 basicConfig() 时不传文件名参数即可\n level=logging.WARNING,\n format='%(levelname)s:%(asctime)s:%(message)s'\n )\n\n # Variables (to make the calls that follow work)\n hostname = 'www.python.org'\n item = 'spam'\n filename = 'data.csv'\n mode = 'r'\n\n # Example logging calls (insert into your program)\n logging.critical('host %s unknown', hostname)\n logging.error(\"couldn't find %r\", item)\n logging.warning('feature is deprecated')\n logging.info('opening file %r, mode=%r', filename, mode)\n logging.debug('got here')\n\n\nif __name__ == '__main__':\n main()\n\n# 上面五个日志调用(critical(), error(), warning(), info(), debug())以降序方式表示 不同的严重级别。 basicConfig() 的 level 参数是一个过滤器。所有级别低于此级别 的日志消息都会被忽略掉。每个 logging 操作的参数是一个消息字符串,后面再跟一个 或多个参数。构造最终的日志消息的时候我们使用了% 操作符来格式化消息字符串\n","sub_path":"cook/len206_给简单脚本增加日志功能.py","file_name":"len206_给简单脚本增加日志功能.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"33291966","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n'''\nAuthor : 612957\nFile : 判断文件编码.py\nTime : 2019/9/28 16:41\nDesc : \n'''\n\nimport chardet\nfrom bs4 import BeautifulSoup\n\nif __name__ == '__main__':\n with open('hwar.html','r',encoding='utf-8')as fr:\n content = fr.read()\n print(content)\n\n response_analyze = BeautifulSoup(content, \"html5lib\")\n app_name = response_analyze.find_all(name=\"h4\", attrs={\"class\": \"title\"})\n for app in app_name:\n\n print(app.a.string)","sub_path":"pythoncode/判断文件编码.py","file_name":"判断文件编码.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"584481813","text":"import numpy as np\nimport match_projid_coreid as dutils\nimport compare_keywords_with_rcdc as dutils2 # for keywords\n\n\n###########################################################\n# how many articles are there in total\narticle_data = dutils.load_articles_json()\nnum_articles = len(article_data) # 231435\n\n# medline_id to abstracts #231435\narticle_med2abs = dutils.get_article_med2abstract()\n\n\n###########################################################\n# Dictionary of lists\n# Keys: coreid\n# Values: list of predictions\n# 20421 core ids\narticle_core2predictions = dutils.get_article_core2pred() \n\n# 205555 articles that matches with 20421 core ids. \n# count\ncount = 0\nfor key in article_core2predictions.keys():\n count += len(article_core2predictions[key])\n\nprint(count)\ntotnum_articles_in_predictions = count\n\n\n###########################################################\n# Number of articles that have links to grant core ids.\narticle_medid2core = dutils.get_article_medid2core()\nprint(len(article_medid2core)) #210890\ntotnum_medline_articles_coreid = len(article_medid2core)\n\n\n###########################################################\n# Number of articles in keywords file\n# id includes WOS ids and MEDLINE ids. \nid2keywords = dutils2.load_keywords_json()\nprint(len(id2keywords)) #3893154\ntotnum_articles = len(id2keywords)\n\n# Number of articles with keywords\nnum_articles_w_keywords =0 # 1972024\nfor k in id2keywords.keys():\n if len(id2keywords[k]['keywords']) > 1:\n num_articles_w_keywords += 1\n\n# Number of MEDLINE articles\n# Number of MEDLINE articles with keywords \nnum_medline_articles_w_keywords = 0 # 0\nmedline_ids = set()\nfor k in id2keywords.keys():\n if \"MEDLINE\" in k:\n medline_ids.add(k)\n if len(id2keywords[k]['keywords']) > 1:\n num_medline_articles_w_keywords += 1\n\ntotnum_medline_articles = len(medline_ids)\n# 232149\nprint('Number of MEDLINE articles: ' + totnum_medline_articles)\n\n# 0\nprint('Number of MEDLINE articles with keywords: ' + num_medline_articles_w_keywords)\n\n###########################################################\n# totnum_articles : number of articles \n\n\n","sub_path":"datascripts/article_stats.py","file_name":"article_stats.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"3589250","text":"import unittest\nimport xml.dom\n\nfrom fs.path import basename\n\nfrom pdart.db.bundle_db import create_bundle_db_in_memory\nfrom pdart.db.fits_file_db import populate_database_from_fits_file\nfrom pdart.labels.lookup import DictLookup\nfrom pdart.labels.time_coordinates import get_start_stop_times, get_time_coordinates\nfrom pdart.labels.utils import path_to_testfile\nfrom pdart.xml.pretty import pretty_print\n\n\nclass TestTimeCoordinates(unittest.TestCase):\n def test_get_default_target(self) -> None:\n fits_product_lidvid = \"urn:nasa:pds:hst_13012:data_acs_raw:jbz504eoq_raw::2.3\"\n card_dicts = [\n {\"DATE-OBS\": \"2001-01-02\", \"TIME-OBS\": \"08:20:00\", \"EXPTIME\": \"1.0\"}\n ]\n nb = get_time_coordinates(\n get_start_stop_times(DictLookup(\"test_get_default_target\", card_dicts))\n )\n doc = xml.dom.getDOMImplementation().createDocument(None, None, None)\n str: bytes = nb(doc).toxml().encode()\n str = pretty_print(str)\n expected = b\"\"\"\n\n 2001-01-02T08:20:00Z \n 2001-01-02T08:20:01Z \n \n\"\"\"\n self.assertEqual(expected, str)\n\n def test_get_time_coordinates(self) -> None:\n db = create_bundle_db_in_memory()\n db.create_tables()\n fits_product_lidvid = \"urn:nasa:pds:hst_13012:data_acs_raw:jbz504eoq_raw::2.3\"\n os_filepath = path_to_testfile(\"jbz504eoq_raw.fits\")\n\n populate_database_from_fits_file(db, os_filepath, fits_product_lidvid)\n\n file_basename = basename(os_filepath)\n\n card_dicts = db.get_card_dictionaries(fits_product_lidvid, file_basename)\n\n nb = get_time_coordinates(\n get_start_stop_times(DictLookup(\"test_get_time_coordinates\", card_dicts))\n )\n doc = xml.dom.getDOMImplementation().createDocument(None, None, None)\n str: bytes = nb(doc).toxml().encode()\n str = pretty_print(str)\n\n expected = b\"\"\"\n\n 2012-09-27T20:23:28Z \n 2012-09-27T20:27:58Z \n \n\"\"\"\n self.assertEqual(expected, str)\n","sub_path":"pdart/labels/test_time_coordinates.py","file_name":"test_time_coordinates.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"488974469","text":"from django.shortcuts import render\nfrom AppTwo.models import User\nfrom . import forms\n# Create your views here.\n\ndef home(request):\n h = {'Home_Page': ''}\n return render(request, 'home.html', h)\n\ndef user(request):\n form = forms.User()\n\n if request.method == 'POST':\n form = forms.User(request.POST)\n\n if form.is_valid():\n p = form.save()\n print('VALIDATION SUCCESS')\n return render(request, 'user.html', {'forms':form})","sub_path":"DJANGO SHIT/ProTwo/AppTwo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"446505555","text":"from django.conf.urls import patterns, include, url\nfrom django.views.generic import TemplateView\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'Django_SCCOP.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n url(r'^about$', TemplateView.as_view(template_name='about.html'), name=\"about\"),\n\turl(r'^contact$', TemplateView.as_view(template_name='contact.html'), name=\"contact\"),\n)\n \nurlpatterns += patterns('sccop.views',\n\turl(r'^$', \"master\", name=\"home\"),\n\turl(r'^signup$', \"signup\", name=\"signup\"),\n\turl(r'^signin$', \"signin\", name=\"signin\"),\n\turl(r'^signout$', \"signout\", name=\"signout\"),\n\turl(r'^email/send$', \"email_send\", name=\"email_send\"),\n\turl(r'^dashboard$', \"dashboard\", name=\"dashboard\"),\n\turl(r'^log$', \"log\", name=\"log\"),\n)\n\nurlpatterns += patterns('sccop.api',\n\turl(r'^api/update/state/$', \"updateState\", name=\"update_state\"),\n\turl(r'^api/update/location/$', \"updateLocation\", name=\"update_location\"),\n)\n","sub_path":"Django_SCCOP/Django_SCCOP/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"518906457","text":"import unittest\nimport subprocess\nimport json\nimport os\nimport tempfile\n\n\nclass PdnsSysrepoBasicTest(unittest.TestCase):\n webserver_port = 8081\n api_key = \"foobar\"\n dbdir = os.environ.get('PDNS_DB_DIR', '/var/lib/pdns')\n\n default_config = {\n \"pdns-server:pdns-server\": {\n \"backend\": [\n {\n \"name\": \"backend1\",\n \"backendtype\": \"lmdb\",\n \"filename\": \"{}/pdns.lmdb\".format(dbdir)\n }\n ],\n \"listen-addresses\": [\n {\n \"name\": \"main IP\",\n \"ip-address\": \"127.0.0.1\",\n \"port\": \"5300\"\n }\n ],\n \"webserver\": {\n \"port\": webserver_port,\n \"api-key\": api_key\n },\n \"master\": False,\n \"slave\": True\n }\n }\n\n @classmethod\n def importConfig(cls, config: dict):\n p = subprocess.Popen(['sysrepocfg', '--format', 'json', '--import',\n '-m', 'pdns-server'], stdin=subprocess.PIPE)\n config_str = json.dumps(config)\n p.communicate(input=config_str.encode('utf-8'))\n\n @classmethod\n def editConfig(cls, config: dict):\n with tempfile.NamedTemporaryFile() as fp:\n fp.write(json.dumps(config).encode('utf-8'))\n fp.flush()\n subprocess.call(['sysrepocfg', '--format', 'json',\n '--edit={}'.format(fp.name),\n '-m', 'pdns-server'])\n\n @classmethod\n def getRunningDS(cls) -> dict:\n output = subprocess.run(['sysrepocfg', '-X', '--format=json',\n '--module=pdns-server',\n '--datastore=running'],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n print(output)\n return json.loads(output.stdout)\n\n @classmethod\n def getOperationalDS(cls) -> dict:\n output = subprocess.run(['sysrepocfg', '-X', '--format=json',\n '--module=pdns-server',\n '--datastore=operational'],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n print(output)\n return json.loads(output.stdout)\n\n def testImported(self):\n self.importConfig(self.default_config)\n data = self.getRunningDS()\n self.assertFalse(data[\"pdns-server:pdns-server\"][\"master\"])\n self.assertTrue(data[\"pdns-server:pdns-server\"][\"slave\"])\n self.assertEqual(data[\"pdns-server:pdns-server\"][\"webserver\"][\"api-key\"], self.api_key)\n self.assertEqual(data[\"pdns-server:pdns-server\"][\"webserver\"][\"port\"], self.webserver_port)\n self.assertEqual(len(data[\"pdns-server:pdns-server\"][\"listen-addresses\"]), 1)\n\n def testUpdateConfig(self):\n self.importConfig(self.default_config)\n self.editConfig({\n \"pdns-server:pdns-server\": {\n \"slave\": False\n }\n })\n data = self.getRunningDS()\n self.assertFalse(data[\"pdns-server:pdns-server\"][\"slave\"])\n\n def testAddZone(self):\n self.importConfig(self.default_config)\n zonename = \"foo.example.com.\"\n zonetype = \"native\"\n self.editConfig({\n \"pdns-server:zones\": [\n {\n \"name\": zonename,\n \"class\": \"IN\",\n \"zonetype\": zonetype\n }\n ]\n })\n\n data = self.getOperationalDS()\n self.assertEqual(len(data[\"pdns-server:zones-state\"][\"zones\"]), 1)\n self.assertEqual(\n data[\"pdns-server:zones-state\"][\"zones\"][0][\"name\"], zonename)\n self.assertEqual(\n data[\"pdns-server:zones-state\"][\"zones\"][0][\"zonetype\"],\n zonetype)\n\n def testChangeZoneType(self):\n self.importConfig(self.default_config)\n zonename = \"edit.example.com.\"\n zonetype = \"native\"\n self.editConfig({\n \"pdns-server:zones\": [\n {\n \"name\": zonename,\n \"class\": \"IN\",\n \"zonetype\": zonetype\n }\n ]\n })\n\n zonetype = \"master\"\n self.editConfig({\n \"pdns-server:zones\": [\n {\n \"name\": zonename,\n \"class\": \"IN\",\n \"zonetype\": zonetype\n }\n ]\n })\n\n data = self.getOperationalDS()\n self.assertEqual(len(data[\"pdns-server:zones-state\"][\"zones\"]), 1)\n self.assertEqual(\n data[\"pdns-server:zones-state\"][\"zones\"][0][\"name\"], zonename)\n self.assertEqual(\n data[\"pdns-server:zones-state\"][\"zones\"][0][\"zonetype\"],\n zonetype)\n","sub_path":"end-to-end-tests/test_01-initial.py","file_name":"test_01-initial.py","file_ext":"py","file_size_in_byte":4926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"237667415","text":"# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\n\nfrom kfp_component import BaseOp\n\nfrom kubernetes import client, config\nfrom kubernetes.client.rest import ApiException\n\nimport mock\nimport unittest\n\n@mock.patch('kubernetes.config.load_incluster_config')\n@mock.patch('kubernetes.client.CoreV1Api')\nclass BaseOpTest(unittest.TestCase):\n\n def test_execute_success(self, mock_k8s_client, mock_load_config):\n BaseOp().execute()\n\n @mock.patch.dict('os.environ', {\n 'KFP_POD_NAME': 'mock-pod-id'\n })\n def test__exit_gracefully_cancel(self, mock_k8s_client, mock_load_config):\n mock_pod = mock_k8s_client().read_namespaced_pod.return_value\n mock_pod.metadata.annotations = {\n 'workflows.argoproj.io/execution': '{\"deadline\": \"1970-01-01T00:00:00Z\"}'\n }\n\n op = BaseOp()\n op.on_cancelling = mock.MagicMock()\n\n op._exit_gracefully(0, 0)\n\n op.on_cancelling.assert_called_once()\n\n @mock.patch.dict('os.environ', {\n 'KFP_POD_NAME': 'mock-pod-id'\n })\n def test__exit_gracefully_no_cancel(self, mock_k8s_client, mock_load_config):\n mock_pod = mock_k8s_client().read_namespaced_pod.return_value\n mock_pod.metadata.annotations = {}\n\n op = BaseOp()\n op.on_cancelling = mock.MagicMock()\n\n op._exit_gracefully(0, 0)\n\n op.on_cancelling.assert_not_called()","sub_path":"component_sdk/python/tests/test_base_op.py","file_name":"test_base_op.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"513842825","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('expenses', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='AdtExpenses',\n fields=[\n ('vExpenseId', models.AutoField(primary_key=True, serialize=False, db_column='vExpenseId')),\n ('vExpenseDescription', models.CharField(verbose_name='Descripcion', max_length=100)),\n ('vExpenseBalance', models.CharField(verbose_name='Balance', max_length=100)),\n ],\n ),\n migrations.DeleteModel(\n name='AdtUsers',\n ),\n ]\n","sub_path":"AdTominApps/expenses/migrations/0002_auto_20200329_0242.py","file_name":"0002_auto_20200329_0242.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"347761751","text":"# -*- coding:utf-8 -*-\nimport os\n\nif __name__ == '__main__':\n path = os.getcwd()\n sku_id = '10001'\n file = path + os.sep + 'test.txt'\n f = open(file, 'w')\n for i in range(1, 10):\n f.write(sku_id)\n f.write('\\t')\n f.write('2017-01-0{0}'.format(i))\n f.write('\\t')\n f.write('{0}'.format(i * 10))\n f.write('\\n')\n f.close()\n\nimport pandas as pd\n\npd.set_option('display.max_colwidth', 20)\npd.set_option('display.width', 150) # 150\n\ntrain = pd.read_csv(r'/Users/longguangbin/Downloads/train_20181125105600.csv', sep='|')\nflag = pd.read_csv(r'/Users/longguangbin/Downloads/flag_20181125105020.csv', sep='|')\ngranu = pd.read_csv(r'/Users/longguangbin/Downloads/granu_split_20181125175310.csv', sep='|')\n\ngranu['sku_id_s'] = granu['sku_id'].apply(lambda x: x.split('$')[1])\ngranu_s = granu.loc[:, ['sku_id_s', 'granu_split']].drop_duplicates()\ngranu_s.index = range(len(granu_s))\ngranu_s = granu_s.groupby(['sku_id_s']).count().reset_index().rename(columns={'granu_split': 'cnt'})\ngranu_m = granu.merge(granu_s, on=['sku_id_s'])\ncheck_df = granu_m[granu_m['cnt'] == 2]\ncheck_df.index = range(len(check_df))\ncheck_df.to_csv(r'/Users/longguangbin/Downloads/check_1.csv', index=False)\n\nflag = flag.drop_duplicates()\nflag.index = range(len(flag))\n\nflag_2 = flag.copy()\nflag_2.columns = ['a', 'b']\nflag_2['b'] = 'this is a long test' + flag_2['b']\n\ntrain.drop_duplicates()\n","sub_path":"longgb/Scripts/PyCode/scripts/test_01.py","file_name":"test_01.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"647270924","text":"# 02_return_something.py\n# \n# Functions sometimes need to return something. If you have a function\n# that requires information, then you will need to use arguments. \n\n\ndef main():\n\t\n\t# The print function needs an argument. THe argument is the string\n\t# you put in it.\n\tprint(\"I am an argument\")\n\t\n\t# This function returns stuff!\n\ta = subtract(10, 2)\n\tprint(a)\n\t\n\t# Try making your own function that returns something. \n\treturn 0\n\ndef subtract(a, b):\n\treturn a - b\nif __name__ == \"__main__\":\n\timport sys\n\tmain()\n\t\n\tsys.exit()\n\n\n","sub_path":"Lesson_03 How to function/03_return_something.py","file_name":"03_return_something.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"589523426","text":"from typing import List, Callable, Dict, Iterable, Tuple\nimport logging\nimport numpy as np\nimport csv\nfrom os import linesep, sep, system\nfrom collections import Counter\nfrom datetime import datetime\nfrom constants import PATH_TO_DATA, SPLIT_FILES, PATH_TO_CLN_DATA, PATH_TO_PRPD_DATA, PATH_TO_LOG_NORM_DATA, TRAIN, TEST,\\\n VALIDATION, FULL_TRAIN, CLASSES_MAPPING, PATH_TO_NORM_DATA, TRAIN_SIZE, FULL_TRAIN_SIZE,\\\n VALIDATION_SIZE, TEST_SIZE, SMALL_TRAIN_SIZE, ORIGINAL_FILES_WITH_SAME_HEADER\nfrom math import isinf, isnan, floor, ceil, log\nfrom functools import partial\n\n\nclass Transformer:\n '''\n Class Transformer provides transformations of dataset.\n It can drop columns, replace values or transform values.\n\n Before running it has to be configured and then it\n applies all defined transformations.\n '''\n\n _logger = logging.getLogger(\"Transformer\")\n\n def __init__(self, csv_sep: str = \",\"):\n self._replacement = []\n self._transformation = []\n self._drop = []\n self._csv_sep = csv_sep\n self._header = None\n\n def _extract_header_mapping(self, header: List[str]) -> Dict[str, int]:\n header_mapping = dict()\n\n for i, column in enumerate(header):\n if column not in self._drop:\n header_mapping.update([(column, i)])\n\n return header_mapping\n\n def _make_transformation(self, header_mapping: Dict[str, int], row: List[str]) -> List[str]:\n for col, trans in self._transformation:\n row[header_mapping[col]] = trans(row[header_mapping[col]])\n\n return row\n\n def _make_replacing(self, header_mapping: Dict[str, int], row: List[str]) -> List[str]:\n for col, rplc in self._replacement:\n row[header_mapping[col]] = rplc(row[header_mapping[col]])\n\n return row\n\n def _make_drop(self, header_mapping: Dict[str, int], row: List[str]) -> List[str]:\n return [row[i] for _, i in header_mapping.items()]\n\n def add_replacement(self, column: str, to_replace: str, replace_by: str) -> 'Transformer':\n '''\n Adds a replacement.\n\n Parameters\n ----------\n column : str\n A column where the replacement should be applied.\n to_replace : str\n A value that should be replaced.\n replace_by : str\n A value that should replace the original value.\n\n Returns\n -------\n self\n '''\n\n self._replacement.append((column, lambda value: replace_by if value == to_replace else value))\n\n return self\n\n def add_transformation(self, column: str, transformation: Callable[[str], str]) -> 'Transformer':\n '''\n Adds a transformation of column.\n\n Parameters\n ----------\n column : str\n A column to be transformed.\n transformation: Callable[[str], str]\n A transformation that gets an original value and returns a transformed value.\n\n Returns\n -------\n self\n '''\n\n self._transformation.append((column, transformation))\n\n return self\n\n def add_drop(self, column: str) -> 'Transformer':\n '''\n Adds a column that should be drop.\n\n Parameters\n ----------\n column : str\n A column to be drop.\n\n Returns\n -------\n self\n '''\n\n self._drop.append(column)\n\n return self\n\n def set_drop(self, columns: List[str]) -> 'Transformer':\n '''\n Sets columns that should be drop.\n\n Parameters\n ----------\n columns : List[str]\n Columns to be drop.\n\n Returns\n -------\n self\n '''\n\n self._drop = columns\n\n return self\n\n def transform(self, row: List[str], first_line: bool = False) -> List[str]:\n '''\n Transforms a single row.\n\n Parameters\n ----------\n row : List[str]\n A row to be transformed.\n first_line : bool\n If it is first line it extracts a header mapping that is\n required in the later transformation.\n\n Returns\n -------\n row : List[str]\n A transformed row.\n '''\n\n if first_line:\n self._header = self._extract_header_mapping(row)\n return [col for col, _ in self._header.items()]\n else:\n transformed = self._make_transformation(self._header, row)\n replaced = self._make_replacing(self._header, transformed)\n dropped = self._make_drop(self._header, replaced)\n\n return dropped\n\n def run(self, path_to_files: str, files: List[str], results_dir: str):\n '''\n Runs a transformation of the files and stores results into result_dir.\n\n Parameters\n ----------\n path_to_files : str\n A path to the directory with the CSV files.\n files : List[str]\n A list of CSV files to be transformed\n results_dir : str\n A directory where results should be stored.\n '''\n for file in files:\n self._logger.info(\"Processing file: {}\".format(file))\n with open(path_to_files + sep + file, \"r\") as in_file:\n with open(results_dir + sep + file, \"w\") as out_file:\n first_line = True\n for row in csv.reader(in_file, delimiter=self._csv_sep):\n row_to_write = self.transform(row, first_line)\n\n out_file.write(self._csv_sep.join(row_to_write))\n out_file.write(linesep)\n\n if first_line:\n first_line = False\n\n\ndef load_header() -> List[str]:\n '''\n Loads a header of files.\n\n Returns\n -------\n header : List[str]\n A header of files.\n '''\n\n with open(PATH_TO_DATA + sep + SPLIT_FILES[0], \"r\") as f:\n return f.readline()[:-1].split(\",\")\n\n\ndef split_files_with_more_headers(path_to_data: str, files: List[str]):\n '''\n Splits files with more headers that are contained in middle of files.\n\n Parameters\n ----------\n path_to_data : str\n A path to the directory with the CSV files.\n files : List[str]\n A list of files that should be split.\n '''\n\n for file in files:\n logging.info(\"Processing file: {}\".format(file))\n index = 0\n with open(path_to_data + sep + file, \"r\") as original:\n header = None\n split = None\n for line in original:\n if header is None:\n header = line\n split = open(path_to_data + sep + file.replace(\".csv\", \"_\" + str(index) + \".csv\"), \"w\")\n split.write(line)\n elif header == line:\n split.flush()\n split.close()\n index += 1\n split = open(path_to_data + sep + file.replace(\".csv\", \"_\" + str(index) + \".csv\"), \"w\")\n split.write(line)\n else:\n split.write(line)\n split.flush()\n split.close()\n\n\ndef get_number_of_classes_in_file(iterator: Iterable[str]) -> Counter:\n '''\n Gets a number of samples for each class in a file.\n\n Parameters\n ----------\n iterator : Iterable[str]\n An iterator over the file.\n\n Returns\n -------\n counter : Counter\n A counter with a number of samples for each class in a file.\n '''\n\n counter = Counter()\n\n first_line = True\n for row in iterator:\n if first_line:\n first_line = False\n else:\n counter.update([row[-1]])\n\n return counter\n\n\ndef write_row(out_file, row_to_write: List[str], csv_del: str = \",\"):\n '''\n Writes a row into a file.\n\n Parameters\n ----------\n out_file\n A file writer.\n row_to_write : List[str]\n A row that should be written into the file.\n csv_del : str\n A CSV delimiter. Default value is comma \",\".\n\n '''\n\n out_file.write(csv_del.join(row_to_write))\n out_file.write(linesep)\n\n\ndef split_train_test(path_to_data: str, files: List[str], path_to_results: str, transformer: Transformer = None,\n train_ratio: float = 0.8, val: bool = False):\n '''\n Splits files to a train set and test set or train set and validation set.\n The files are split based on the train_ratio. By default the train set\n consists of 80% data and test sets consists of 20% data. The classes\n ratio is preserved.\n\n Parameters\n ----------\n path_to_data : str\n A path to the directory with the CSV files.\n files : List[str]\n A list of CSV files to be split.\n path_to_results : str\n A path to the directory with results.\n transformer : Transformer\n A row transformer. It is optional, by default None.\n train_ratio : float\n A train ratio. It means that test ratio is 1 - train_ratio. By default 0.8.\n val : bool\n If it is train/validation split.\n '''\n\n train = path_to_results + sep + FULL_TRAIN if not val else path_to_results + sep + TRAIN\n test = path_to_results + sep + TEST if not val else path_to_results + sep + VALIDATION\n with open(train, \"w\") as train:\n with open(test, \"w\") as test:\n header_is_written = False\n for file in files:\n logging.info(\"Processing file: {}\".format(file))\n\n number_fo_classes = dict()\n with open(path_to_data + sep + file, \"r\") as in_file:\n logging.info(\"Checking classes counts.\")\n\n for cls, count in get_number_of_classes_in_file(csv.reader(in_file, delimiter=',')).items():\n number_fo_classes.update([(cls, int(count * train_ratio))])\n\n with open(path_to_data + sep + file, \"r\") as in_file:\n logging.info(\"Splitting into train and test.\")\n\n first_line = True\n\n if transformer is not None:\n for row in csv.reader(in_file, delimiter=','):\n if first_line:\n if not header_is_written:\n row_to_write = transformer.transform(row, first_line)\n write_row(train, row_to_write)\n write_row(test, row_to_write)\n\n header_is_written = True\n\n first_line = False\n else:\n row_to_write = transformer.transform(row, first_line)\n\n number_fo_classes[row_to_write[-1]] -= 1\n\n if number_fo_classes[row_to_write[-1]] > 0:\n write_row(train, row_to_write)\n else:\n write_row(test, row_to_write)\n else:\n for row in csv.reader(in_file, delimiter=','):\n if first_line:\n if not header_is_written:\n write_row(train, row)\n write_row(test, row)\n\n header_is_written = True\n\n first_line = False\n else:\n number_fo_classes[row[-1]] -= 1\n\n if number_fo_classes[row[-1]] > 0:\n write_row(train, row)\n else:\n write_row(test, row)\n\n\ndef check_time(path_to_data: str, files: List[str]):\n '''\n Checks if samples are sorted by timestamp.\n\n Parameters\n ----------\n path_to_data : str\n A path to the directory with CSV files.\n files : List[str]\n A list of CSV files that should be checked.\n '''\n\n for file in files:\n logging.info(\"Processing file: {}\".format(file))\n with open(path_to_data + sep + file, \"r\") as in_file:\n prev_time = 0\n first_line = True\n line_number = 0\n for row in csv.reader(in_file, delimiter=','):\n if first_line:\n first_line = False\n else:\n current_time = float(row[2])\n\n if current_time < prev_time:\n logging.error(\"Line {} - Current time {} is smaller than previous time {}\".format(line_number,\n current_time, prev_time))\n\n prev_time = current_time\n\n line_number += 1\n\n\ndef get_size(dataset: str) -> Tuple[int, int, int]:\n '''\n Computes a size of dataset.\n\n Parameters\n ----------\n dataset : str\n A path to the dataset.\n\n Returns\n -------\n size : Tuple[int, int, int]\n The first is number of samples, the second is number of features\n and the last is number of negative samples.\n '''\n\n negatives = 0\n size = 0\n features = 0\n i = 0\n\n logging.info(\"Getting shape of data.\")\n\n with open(dataset, \"r\") as in_data:\n first_line = True\n for row in csv.reader(in_data, delimiter=','):\n if first_line:\n features = len(row) - 1\n first_line = False\n else:\n if CLASSES_MAPPING[row[-1]] == 0:\n negatives += 1\n\n size += 1\n\n if i % 100000 == 0:\n logging.info(\"Row {}\".format(i))\n\n i += 1\n\n logging.info(\"X = ({}, {}), Y = {}, number of negative values = {}\".format(size, features, size, negatives))\n\n return size, features, negatives\n\n\ndef load_dataset_as_array(dataset: str, number_of_negatives: int = None) -> Tuple[np.ndarray, np.ndarray, int, int]:\n '''\n Loads a dataset numpy array. It is possible to control\n a number of negative samples.\n\n Parameters\n ----------\n dataset : str\n A path to the dataset.\n number_of_negatives : int\n A number of negative samples to be loaded.\n\n Returns\n -------\n result : Tuple[np.ndarray, np.ndarray, int, int]\n It contains in this order the X data (samples), the Y data (labels),\n the number of samples and the number of features.\n '''\n\n to_be_skipped = 0\n\n size, features, all_negatives = get_size(dataset)\n\n if number_of_negatives is not None:\n to_be_skipped = all_negatives - number_of_negatives\n else:\n number_of_negatives = all_negatives\n\n logging.info(\"Initializing numpy arrays.\")\n\n data = np.zeros((size - to_be_skipped, features), dtype=np.float)\n labels = np.zeros(size - to_be_skipped, dtype=np.int)\n\n logging.info(\"Starting to read the dataset.\")\n\n step = int(all_negatives / number_of_negatives)\n negatives = 0\n with open(dataset, \"r\") as in_data:\n first_line = True\n i = 0\n for row in csv.reader(in_data, delimiter=','):\n if first_line:\n first_line = False\n else:\n if CLASSES_MAPPING[row[-1]] == 0 and (negatives % step > 0 or negatives / step >= number_of_negatives):\n negatives += 1\n continue\n\n labels[i] = CLASSES_MAPPING[row[-1]]\n\n if CLASSES_MAPPING[row[-1]] == 0:\n negatives += 1\n\n for j in range(features):\n value = np.float(row[j])\n\n if not isinf(value) and not isnan(value):\n data[i][j] = value\n else:\n logging.error(\"Value on line {} in column {} is inf or nan after converting.\".format(i + 1, j + 1))\n\n if i % 100000 == 0:\n logging.info(\"Row {}\".format(i))\n\n i += 1\n\n logging.info(\"Dataset is converted into numpy array.\")\n\n return data, labels, size - to_be_skipped, features\n\n\ndef convert_to_npy(path_to_data: str, type: str, path_to_result: str, number_of_negatives: int = None):\n '''\n Converts a dataset into numpy array and then stores it as memory map.\n\n The path to the result is constructed as:\n path_to_data + sep + type + sep + \"X_{}.npy\".format(type)\n path_to_data + sep + type + sep + \"Y_{}.npy\".format(type)\n\n Parameters\n ----------\n path_to_data : str\n A path to the dataset.\n type : str\n A type of the dataset - train, test, validation...\n path_to_result : str\n A path to the directory with result.\n number_of_negatives : str\n A number of negative samples to be loaded.\n '''\n\n logging.info(\"Converting dataset into numpy array.\")\n\n X, Y, size, features = load_dataset_as_array(path_to_data + sep + type + \".csv\", number_of_negatives)\n\n logging.info(\"Storing X into memmap X.npy.\")\n\n X_memmap = np.memmap(path_to_result + sep + type + sep + \"X_{}.npy\".format(type), dtype=np.float32, mode=\"write\", shape=(size, features))\n X_memmap[:] = X[:]\n del X_memmap\n\n del X\n\n logging.info(\"Storing X is completed.\")\n logging.info(\"Storing Y into memmap Y.npy.\")\n\n Y_memmap = np.memmap(path_to_result + sep + type + sep + \"Y_{}.npy\".format(type), dtype=np.int, mode=\"write\", shape=size)\n Y_memmap[:] = Y[:]\n del Y_memmap\n\n del Y\n\n logging.info(\"Storing Y is completed.\")\n\n\ndef create_labels_for_each_class_separately(path_to_data: str, type: str, size: int):\n '''\n Converts multiclass classification into binary classification.\n It means that for each class it creates new labels that contains\n only {1, 0} where 1 is the current class and 0 is the rest.\n\n The path to the data is constructed as:\n path_to_data + sep + type + sep + \"Y_{}.npy\".format(type)\n\n The path to the result is constructed as:\n path_to_data + sep + type + sep + \"Y_{}_cls_{}.npy\".format(type, class)\n\n Parameters\n ----------\n path_to_data : str\n A path to the directory with data (e.g. normalized_data).\n type : str\n A type of the data (e.g. train or test).\n size : int\n A size of the dataset.\n '''\n\n for cls in range(0, 15):\n logging.info(\"Processing class: {}\".format(cls))\n y_old = np.memmap(path_to_data + sep + type + sep + \"Y_{}.npy\".format(type), dtype=np.int, mode=\"r\", shape=size)\n y_new = np.memmap(path_to_data + sep + type + sep + \"Y_{}_cls_{}.npy\".format(type, cls), dtype=np.int, mode=\"write\", shape=size)\n\n for i in range(size):\n if y_old[i] == cls:\n y_new[i] = 1\n else:\n y_new[i] = 0\n\n del y_new\n\n logging.info(\"Processing is completed.\")\n\n\ndef normalize(value: float, mean: float, std: float, digit: int = 4) -> float:\n '''\n Makes standardization with specific precision.\n\n Parameters\n ----------\n value : float\n A value to be normalized.\n mean : float\n A mean of values.\n std : float\n A standard deviation of values.\n digit : int\n A number of digits after floating point.\n\n Returns\n -------\n results : float\n A normalized value by standardization.\n '''\n\n return round((value - mean) / std, digit)\n\n\ndef load_normalizer() -> Transformer:\n '''\n Loads a normalizer that does standardization\n based on the train statistics.\n\n Returns\n -------\n normalizer : Transformer\n A loaded normalizer that does standardization.\n '''\n\n def normalize_str(value: str, mean: float, std: float) -> str:\n return str(normalize(float(value), mean, std))\n\n normalizer = Transformer()\n\n with open(\"statistics/train/train_results.csv\", mode=\"r\") as stat:\n column_stats = dict()\n first_row = True\n for row in csv.reader(stat, delimiter=\",\"):\n if first_row:\n first_row = False\n else:\n if row[1] == \"Mean\":\n column_stats.update([(\"Mean\", float(row[2]))])\n elif row[1] == \"StandardDeviation\":\n column_stats.update([(\"StandardDeviation\", float(row[2]))])\n\n if len(column_stats) == 2:\n normalizer.add_transformation(row[0], partial(normalize_str, mean=column_stats[\"Mean\"], std=column_stats[\"StandardDeviation\"]))\n column_stats = dict()\n\n return normalizer\n\n\ndef load_log_normalizer() -> Transformer:\n '''\n Loads a normalizer that takes logarithm of the data.\n\n Returns\n -------\n normalizer : Transformer\n A normalizer that takes logarithm of the data.\n '''\n\n def normalize_str(value: str):\n return str(log(float(value) + 1))\n\n normalizer = Transformer()\n\n skip = [1, 2, 3, 18, 20, 21, 22, 23, 25, 26, 32, 33, 34, 35, 45, 46, 47, 48, 49, 50, 51, 52, 57, 58, 59, 60, 61, 62,\n 67, 68, 79]\n\n for index, column in enumerate(load_header()):\n if index not in skip:\n normalizer.add_transformation(column, normalize_str)\n\n return normalizer\n\n\ndef select_samples(path_to_data: str, type: str, ratio: float, size: int, number_of_negatives: int = 1000000) -> int:\n '''\n Selects only part of the data based on specified ratio and number of negative samples.\n\n Parameters\n ----------\n path_to_data : str\n A path to the directory with data.\n type : str\n A type of data (e.g. train or test)\n ratio : float\n How many percent of data should be selected with preserving\n classes ratio if it is possible. At least 10 samples for\n each class is preserved.\n size : int\n A number of samples.\n number_of_negatives : int\n A number of negative samples that is loaded before selecting.\n\n Returns\n -------\n result : int\n A final number of samples.\n '''\n\n y_old = np.memmap(path_to_data + sep + type + sep + \"Y_{}.npy\".format(type), dtype=np.int, mode=\"r\", shape=size)\n\n logging.info(\"Counting classes.\")\n\n cls_counts = Counter()\n for cls in y_old:\n cls_counts.update([cls])\n\n cls_steps = dict()\n cntr_steps = dict()\n for cls in range(15):\n if cls == 0 and cls_counts[0] >= number_of_negatives:\n final_counts = ceil(number_of_negatives * ratio)\n else:\n final_counts = ceil(cls_counts[cls] * ratio)\n\n final_counts = 10 if final_counts < 10 else final_counts\n cls_steps[cls] = floor(cls_counts[cls] / final_counts)\n cls_counts[cls] = int(final_counts)\n cntr_steps[cls] = 0\n\n x_old = np.memmap(path_to_data + sep + type + sep + \"X_{}.npy\".format(type), dtype=np.float32, mode=\"r\", shape=(size, 70))\n\n new_size = sum(cls_counts.values())\n\n logging.info(\"New size of dataset is: {}\".format(new_size))\n logging.info(\"Ratio classes is (in order 0,1,2...): {}\".format(\",\".join([str(x) for _, x in cls_counts.items()])))\n\n y_new = np.memmap(path_to_data + sep + type + sep + \"Y_smaller_{}.npy\".format(type), dtype=np.int, mode=\"write\", shape=new_size)\n x_new = np.memmap(path_to_data + sep + type + sep + \"X_smaller_{}.npy\".format(type), dtype=np.float32, mode=\"write\", shape=(new_size, 70))\n\n logging.info(\"Creating dataset.\")\n\n i_new = 0\n for i in range(size):\n if cntr_steps[y_old[i]] % cls_steps[y_old[i]] == 0 and cntr_steps[y_old[i]] < cls_counts[y_old[i]]:\n y_new[i_new] = y_old[i]\n x_new[i_new] = x_old[i]\n\n i_new += 1\n\n cntr_steps[y_old[i]] += 1\n\n logging.info(\"Dataset is completed.\")\n\n return new_size\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(format=\"%(levelname)s %(name)s: %(message)s\", level=logging.INFO)\n\n # removing headers in middle of file (preparation for data analysis)\n # split_files_with_more_headers(PATH_TO_DATA, ORIGINAL_FILES_WITH_SAME_HEADER[0])\n # transformer = Transformer()\\\n # .add_drop(\"Flow ID\")\\\n # .add_drop(\"Src IP\")\\\n # .add_drop(\"Src Port\")\\\n # .add_drop(\"Dst IP\")\n # transformer.run(PATH_TO_DATA, ORIGINAL_FILES_WITH_SAME_HEADER[1], \"../\")\n # system(\"mv ../\" + ORIGINAL_FILES_WITH_SAME_HEADER[1][0] + \" \" + PATH_TO_DATA + sep + ORIGINAL_FILES_WITH_SAME_HEADER[1][0].replace(\".csv\", \"_dropped.csv\"))\n # split_files_with_more_headers(PATH_TO_DATA, [ORIGINAL_FILES_WITH_SAME_HEADER[1][0].replace(\".csv\", \"_dropped.csv\")])\n\n\n # datetime is converted to timestamp\n # NaN value is replaced by most common value in a column\n # Infinity value is replaced by maximum value in a column\n # columns, that have only one distinct value, are dropped\n # transformer = Transformer()\\\n # .add_transformation(\"Timestamp\", lambda s: str(datetime.strptime(s, \"%d/%m/%Y %H:%M:%S\").timestamp()))\\\n # .add_replacement(\"Flow Byts/s\", \"NaN\", \"0\")\\\n # .add_replacement(\"Flow Byts/s\", \"Infinity\", \"1806642857.14286\")\\\n # .add_replacement(\"Flow Pkts/s\", \"NaN\", \"1000000\")\\\n # .add_replacement(\"Flow Pkts/s\", \"Infinity\", \"6000000.0\")\\\n # .set_drop([\"Bwd Blk Rate Avg\", \"Bwd Byts/b Avg\", \"Bwd PSH Flags\", \"Bwd Pkts/b Avg\", \"Bwd URG Flags\",\n # \"Fwd Blk Rate Avg\", \"Fwd Byts/b Avg\", \"Fwd Pkts/b Avg\"])\n #\n # transformer.run(PATH_TO_DATA, SPLIT_FILES, PATH_TO_CLN_DATA)\n\n # check_time(PATH_TO_CLN_DATA, SPLIT_FILES)\n\n # dropping Timestamp and spit to full train and test\n # transformer = Transformer().set_drop([\"Timestamp\"])\n # split_train_test(PATH_TO_CLN_DATA, SPLIT_FILES, PATH_TO_PRPD_DATA, transformer)\n\n # normalizing data by subtracting mean and dividing by std\n # normalizer = load_normalizer()\n # normalizer.run(PATH_TO_PRPD_DATA, [FULL_TRAIN, TEST], PATH_TO_NORM_DATA)\n\n # normalizing data by log\n # normalizer = load_log_normalizer()\n # normalizer.run(PATH_TO_PRPD_DATA, [FULL_TRAIN, TEST], PATH_TO_LOG_NORM_DATA)\n\n # split to train and validation\n # split_train_test(PATH_TO_NORM_DATA, [FULL_TRAIN], PATH_TO_NORM_DATA, val=True)\n # split_train_test(PATH_TO_LOG_NORM_DATA, [FULL_TRAIN], PATH_TO_LOG_NORM_DATA, val=True)\n\n # converting normalized data to numpy array (memmap)\n # convert_to_npy(PATH_TO_NORM_DATA, \"train\", PATH_TO_NORM_DATA + sep + \"train\")\n # convert_to_npy(PATH_TO_NORM_DATA, \"full_train\", PATH_TO_NORM_DATA + sep + \"full_train\")\n # convert_to_npy(PATH_TO_NORM_DATA, \"test\", PATH_TO_NORM_DATA + sep + \"test\")\n # convert_to_npy(PATH_TO_NORM_DATA, \"validation\", PATH_TO_NORM_DATA + sep + \"validation\")\n # convert_to_npy(PATH_TO_NORM_DATA, \"train\", PATH_TO_NORM_DATA, 600000) # for visualization -> size 2798546\n # create_labels_for_each_class_separately(PATH_TO_NORM_DATA, \"train\", TRAIN_SIZE)\n # create_labels_for_each_class_separately(PATH_TO_NORM_DATA, \"full_train\", FULL_TRAIN_SIZE)\n # create_labels_for_each_class_separately(PATH_TO_NORM_DATA, \"validation\", VALIDATION_SIZE)\n # create_labels_for_each_class_separately(PATH_TO_NORM_DATA, \"test\", TEST_SIZE)\n # convert_to_npy(PATH_TO_NORM_DATA, \"train\", PATH_TO_NORM_DATA + sep + \"small_train\", 1000000) # for training SVM\n # create_labels_for_each_class_separately(PATH_TO_NORM_DATA, \"small_train\", SMALL_TRAIN_SIZE) # for training SVM\n # size = select_samples(PATH_TO_NORM_DATA, \"small_train\", 0.3, SMALL_TRAIN_SIZE, number_of_negatives=1000000) # for training SVM\n # create_labels_for_each_class_separately(PATH_TO_NORM_DATA, \"small_train\", size) # for training SVM\n\n # converting log normalized data to numpy array (memmap)\n # convert_to_npy(PATH_TO_LOG_NORM_DATA, \"train\", PATH_TO_LOG_NORM_DATA + sep + \"train\")\n # convert_to_npy(PATH_TO_LOG_NORM_DATA, \"full_train\", PATH_TO_LOG_NORM_DATA + sep + \"full_train\")\n # convert_to_npy(PATH_TO_LOG_NORM_DATA, \"test\", PATH_TO_LOG_NORM_DATA + sep + \"test\")\n # convert_to_npy(PATH_TO_LOG_NORM_DATA, \"validation\", PATH_TO_LOG_NORM_DATA + sep + \"validation\")\n # create_labels_for_each_class_separately(PATH_TO_LOG_NORM_DATA, \"train\", TRAIN_SIZE)\n # create_labels_for_each_class_separately(PATH_TO_LOG_NORM_DATA, \"full_train\", FULL_TRAIN_SIZE)\n # create_labels_for_each_class_separately(PATH_TO_LOG_NORM_DATA, \"validation\", VALIDATION_SIZE)\n # create_labels_for_each_class_separately(PATH_TO_LOG_NORM_DATA, \"test\", TEST_SIZE)\n","sub_path":"data_transformation.py","file_name":"data_transformation.py","file_ext":"py","file_size_in_byte":28482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"456614298","text":"tmp1 = {\"k1\": \"\",\n \"k2\": \"\",\n \"k3\": \"\"\n }\n\nstring_word = \"8x6.7x2.5\"\nsplit_word = string_word.split(\"x\")\ntruck_key = (\"body_length\", \"body_width\", \"body_height\")\n# truck_dict = dict(zip(truck_key, split_word))\ntmp1[\"k1\"]=split_word[0]\ntmp1[\"k2\"]=split_word[1]\ntmp1[\"k3\"]=split_word[2]\nprint(tmp1)\n# print(\"body_height is {}\".format(truck_dict.get('body_height')))\n\n\ndef __init__(self, start, end):\n self.current = start\n self.end = end\n\n\ndef __iter__(self):\n return self\n\n\ndef __next__(self):\n if self.current >= self.end:\n raise StopIteration\n\n result = self.current ** 2\n self.current += 1\n return result","sub_path":"week_4/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"415315711","text":"# X FIRST, Y SECOND!!!\n\n###########\n# Convention is to use underscores for variables instead of camel case in Python, however i'm not gonna \n# touch it in case they are standard functions from libtcod\n# Note to Self: end of fuctions and control-flow constructs is determined by indentation, not curly braces!\n#\n# Python is not object oriented like Java! define functions before you call them, even when using classes \n# and/or inheritance!\n###########\nimport libtcodpy as libtcod # Can the name be arbitrary?\n\nSCREEN_WIDTH=80\nSCREEN_HEIGHT=50\n#MAX_FPS=20\n\nclass Object:\n def __init__(self, x, y, char, color): # This is basically a constructor # there's two underscores!\n self.x=x\n self.y=y\n self.char=char\n self.color=color\n\n def move (self, distance_x, distance_y):\n self.x += distance_x\n self.y += distance_y\n\n def draw(self):\n libtcod.console_set_default_foreground(con, self.color)\n libtcod.console_put_char(con, self.x, self.y, self.char, libtcod.BKGND_NONE)\n\n def clear(self):\n libtcod.console_put_char(con, self.x, self.y, ' ', libtcod.BKGND_NONE)\n\n# Function (Java's \"method\") to define wich key correspond to what action. Does it modify the player_*pos outside the function aswell? is it limited in scope?\ndef handle_keys():\n key = libtcod.console_wait_for_keypress(True) \n if key.vk == libtcod.KEY_ESCAPE:\n return True\n\n if libtcod.console_is_key_pressed(libtcod.KEY_UP):\n player.move(0, -1)\n elif libtcod.console_is_key_pressed(libtcod.KEY_DOWN):\n player.move(0, 1)\n elif libtcod.console_is_key_pressed(libtcod.KEY_LEFT):\n player.move(-1, 0)\n elif libtcod.console_is_key_pressed(libtcod.KEY_RIGHT):\n player.move(1, 0) \n\n\n# SCREEN INIT\nlibtcod.console_set_custom_font('arial10x10.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)\nlibtcod.console_init_root(SCREEN_WIDTH, SCREEN_HEIGHT, 'Test', False) # the 'root' console will be number 0 (stdout). 3rd parameters is window title, 4th is fullscreen bool\ncon=libtcod.console_new(SCREEN_WIDTH, SCREEN_HEIGHT) # secondary console\n# Setting up player and npc\nplayer=Object(SCREEN_WIDTH/2, SCREEN_HEIGHT/2, '@', libtcod.white)\nnpc=Object(SCREEN_WIDTH/2-5, SCREEN_HEIGHT/2, '@', libtcod.yellow)\nobjects=[npc, player] \n\n#MAIN LOOP: setup console, place @ and wait for presses. The second console_put_char applies to the previous coordinates, to avoid having a trail of @.\nwhile not libtcod.console_is_window_closed():\n libtcod.console_set_default_foreground(0, libtcod.white) # the 0 parameter should be output device, aka stdout\n for object in objects:\n \tobject.draw()\n\n libtcod.console_blit(con, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0, 0)\n libtcod.console_flush() #look this up\n \n for object in objects:\n \tobject.clear()\n \n exit=handle_keys()\n if exit:\n break\n\n#####\n# I don't understand why exit=handle_keys() is after the flush() function, and also what's up with the way we call the handle_keys() function\n#####\n\n\n\n#MAIN LOOP: setup console, place @ and wait for presses. The second console_put_char applies to the previous coordinates, to avoid having a trail of @.\n# while not libtcod.console_is_window_closed():\n# libtcod.console_set_default_foreground(0, libtcod.white) # the 0 parameter should be output device, aka stdout\n# libtcod.console_put_char(con, player_xpos, player_ypos, '@', libtcod.BKGND_NONE) # X FIRST, Y SECOND!\n# libtcod.console_blit(con, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0, 0)\n# libtcod.console_flush() #look this up\n# libtcod.console_put_char(con, player_xpos, player_ypos, ' ', libtcod.BKGND_NONE)\n# exit=handle_keys()\n# if exit:\n# break\n","sub_path":"OLD/roguelike.py","file_name":"roguelike.py","file_ext":"py","file_size_in_byte":3752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"24019129","text":"# ===========================================\n# @Time : 2019/3/27 14:10\n# @Author : antony\n# @Email : 502202879@qq.com\n# @File : win32kb_auto.py\n# @Software: PyCharm\n# ===========================================\nimport win32api\nimport win32con\nimport win32clipboard as w3c\nimport ctypes\nimport threading\n\n\ndef set_clipboard(astring): # 写入剪切板 目前这方法有bug\n w3c.OpenClipboard()\n w3c.EmptyClipboard()\n w3c.SetClipboardData(win32con.CF_TEXT, astring)\n w3c.CloseClipboard()\n\n\nclass Hotkey:\n\n def __init__(self):\n self.stop_flag = False # 置为True时终止热键进程\n self.keys ={\n 10: win32con.VK_F10,\n 98: (win32con.VK_F10, win32con.MOD_CONTROL),\n 99: (win32con.VK_F10, win32con.MOD_CONTROL, win32con.MOD_ALT)}\n self.callbacks = {\n 10: self.print_test,\n 98: self.print_test,\n 99: self.print_test}\n self.args = {\n 10: (),\n 98: ('token to run out ~',),\n 99: ('token to run out ~', '额外信息测试 id:99')} # 一般默认的传参都是 () 特定传参需要注册\n\n def add(self, des_list):\n # des_list = [10, (win32con.VK_F10, win32con.MOD_CONTROL), hotkey_print_test, *()]\n # 4个元素 分别是 id 热键 回调函数 和 回调函数的参数\n if des_list[0] in self.keys:\n print(f'key_id: {des_list[0]} is already used')\n return -1\n else:\n id, key, callback, *args = des_list\n self.keys.update({id: key})\n self.callbacks.update({id: callback})\n self.args.update({id: args if args else ()})\n\n def __iter__(self):\n return iter([(i, self.keys[i], self.callbacks[i], self.args[i]) for i in self.keys])\n\n def print_test(self, x='this is a hotkey run test~', *args):\n print(x, *args)\n if x == 'token to run out ~':\n self.stop_flag = True\n print(' >> 热键监控到此为止~!!')\n\n\nclass HotkeyThread(threading.Thread): # 创建一个Thread.threading的扩展类\n user32 = ctypes.windll.user32 # 加载user32.dll\n\n def __init__(self, hotkey_configs):\n super(HotkeyThread, self).__init__()\n self.useable = True\n if type(hotkey_configs) is not Hotkey:\n print('hotkey_configs type error')\n self.useable = False\n self.hotkey_configs = hotkey_configs\n\n def run(self):\n if not self.useable:\n return -1\n for id, key, callback, args in self.hotkey_configs:\n if type(key) is not int and len(key) > 1:\n mod, vk = eval('|'.join([str(x) for x in key[1:]])), key[0] # 辅助按键的特殊处理例子\n else:\n mod, vk = 0, key\n # 注册快捷键mod是辅助按键,vk是像F10这样的按键\n if not self.user32.RegisterHotKey(None, id, mod, vk):\n print(\"Unable to register id\", id) # 返回一个错误信息\n else:\n print(f'成功注册热键:mod({mod}) vk({vk})')\n try:\n # 以下为检测热键是否被按下,并在最后释放快捷键\n msg = ctypes.wintypes.MSG()\n while True and not self.hotkey_configs.stop_flag:\n if self.user32.GetMessageA(ctypes.byref(msg), None, 0, 0) != 0:\n if msg.message == win32con.WM_HOTKEY:\n # print(msg.message, msg.wParam)\n if msg.wParam in self.hotkey_configs.keys:\n func = self.hotkey_configs.callbacks[msg.wParam]\n args = self.hotkey_configs.args[msg.wParam]\n if args:\n res = func(*args)\n else:\n res = func()\n self.user32.TranslateMessage(ctypes.byref(msg))\n self.user32.DispatchMessageA(ctypes.byref(msg))\n finally:\n # 必须得释放热键,否则下次就会注册失败,所以当程序异常退出,没有释放热键,\n # 那么下次很可能就没办法注册成功了,这时可以换一个热键测试\n for id, key, callback, args in self.hotkey_configs:\n self.user32.UnregisterHotKey(None, id)\n\n\nif __name__ == '__main__':\n # 一个通过热键触发自动root登录(通过pyautogui)的实例\n hot = Hotkey()\n # 增加自己真正需要配置的热键\n from win32kb_auto import typing_root, dobjsylogin\n # 68 对应D键\n hot.add([11, (67, win32con.MOD_CONTROL, win32con.MOD_ALT), dobjsylogin, ()]) #\n hot.add([12, (68, win32con.MOD_CONTROL, win32con.MOD_ALT), typing_root, ()]) #\n p = HotkeyThread(hot)\n p.start()\n","sub_path":"exam/win32keys_comp.py","file_name":"win32keys_comp.py","file_ext":"py","file_size_in_byte":4799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"255213661","text":"import logging\n# from datetime import *\nfrom datetime import datetime, timedelta\nimport time\nimport os\nimport sys\nfrom tokenize import Token\nimport pytz\nimport re\nimport requests\n\nfrom HELPME.bot_sql_integration import *\nfrom HELPME.helperFunctions import *\n\nfrom uuid import uuid4, uuid1\nfrom telegram.utils.helpers import escape_markdown\nfrom telegram.ext import InlineQueryHandler, Updater, CommandHandler, CallbackQueryHandler, CallbackContext, Filters, MessageHandler, ConversationHandler\nfrom telegram import Bot, InlineQueryResultArticle, ParseMode, InputTextMessageContent, InlineKeyboardButton, InlineKeyboardMarkup, Update, message, replymarkup\n\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\ntz = pytz.timezone('Asia/Singapore')\nnow = datetime.now(tz).replace(microsecond=0) # the current time in your local timezone\n\nlogger = logging.getLogger(__name__)\nTOKEN = os.environ[\"API_TOKEN\"]\nPORT = int(os.environ.get('PORT', '8443'))\nBOT_ID = os.environ['BOT_ID']\n\ndef startGroup(update, context):\n \"\"\"Send the welcome message when the command /start is issued in a group.\"\"\"\n # The registration keyboard used to register groups into our Group Database.\n keyboard = [\n [\n InlineKeyboardButton(\"Register\", callback_data='groupRegister'),\n ],\n [\n InlineKeyboardButton(\"Don't Register\", callback_data='groupDontRegister')\n ],\n ]\n\n ## This section is to send a logo before the registration process!\n # context.bot.send_photo(\n # chat_id=update.effective_chat.id,\n # photo='https://res.cloudinary.com/jianoway/image/upload/v1621939877/O%24P%24_Logo.png',\n # )\n\n # Sets up the InlineKeyboardMarkup as the reply_markup to be used in the message.\n reply_markup = InlineKeyboardMarkup(keyboard)\n\n # Sends the welcome message for the group.\n message = context.bot.send_message(\n chat_id=update.effective_chat.id,\n text=\n \"Hello this is O$P$, your personal Telegram loan chaser and debt tracker!\\n\\n\" +\n \"We aim to make the process of tracking which of your 'friends' still owe you \" +\n \"and reminding them as impersonal as possible so you won't feel the paiseh!\"\n \"Along with that, you can now also notify people who you've returned money to\" +\n \"with a simple click of a button.\\n\\n\" +\n \"Simply register your group with us by pressing the button below!\",\n reply_markup=reply_markup,\n )\n return message\n\ndef startPrivate(update, context):\n \"\"\"Send the welcome message when the command /start is issued via PM\"\"\"\n chat_id = update.message.chat_id\n username = update.message.chat.username\n firstname = update.message.chat.first_name\n user = (chat_id, username, 1, firstname)\n\n keyboard = [\n [\n InlineKeyboardButton(\"Register\", callback_data='userRegister'),\n ],\n [\n InlineKeyboardButton(\"Don't Register\", callback_data='userDontRegister')\n ],\n ]\n # Sets up the InlineKeyboardMarkup as the reply_markup to be used in the message.\n reply_markup = InlineKeyboardMarkup(keyboard)\n\n message = context.bot.send_message(\n chat_id=update.effective_chat.id,\n text=\n \"Hi! Thank you for choosing O$P$, your one stop debt chaser!\\n\\n\" +\n \"Simply register with us by clicking pressing the button below!\",\n reply_markup=reply_markup,\n )\n return message\n\ndef scanReceiptPrivateMessage(update, context):\n \"\"\"Prompt the user to send their receipt.\"\"\"\n chat_id = update.effective_chat.id\n context.bot.send_message(\n chat_id=chat_id,\n text=\n \"Please send in the receipt to be scanned! Alternatively, to cancel please type /cancelreceipt\"\n )\n return \"waitingonpicprivate\"\n\ndef scanReceiptPrivatePicture(update, context):\n \"\"\"Parses the image if possible, otherwise will prompt user to send a valid image.\"\"\"\n photos = update.message.photo\n length = len(photos)\n if length == 0:\n context.bot.send_message(\n chat_id=update.effective_chat.id,\n text=\n \"Please send in the receipt to be scanned! Alternatively, to cancel please type /cancelreceipt\"\n )\n return \"waitingonpicprivate\"\n else:\n photo = photos[length - 1]\n fileID = photo.file_id\n filePathURL = \"https://api.telegram.org/bot%s/getfile?file_id=%s\" % (TOKEN, fileID)\n filePath = requests.get(filePathURL).json()[\"result\"][\"file_path\"]\n fileURL = \"https://api.telegram.org/file/bot%s/%s\" % (TOKEN, filePath)\n text = receiptParser(fileURL)\n context.bot.send_message(\n chat_id=update.effective_chat.id,\n text=text\n )\n return ConversationHandler.END\n\ndef cancelReceipt(update, context):\n \"\"\"Cancels the receipt scanning procedure.\"\"\"\n context.bot.send_message(\n chat_id=update.effective_chat.id,\n text=\n \"Your receipt scan has been cancelled!\"\n )\n print('ok')\n return ConversationHandler.END\n\n\ndef getDebtors(update, context):\n \"\"\"Sends the user the message in response to the /whoowesme command.\"\"\"\n userID = update.effective_chat.id\n if not isNotifiable(userID):\n message = context.bot.send_message(\n chat_id=userID,\n text=\n \"Please register with us first by using /start!\"\n )\n return message\n \n \n unsettledTransactions = getUnsettledTransactionsForCreditor(userID)\n keyboardMarkup = formatTransactionsForCreditorKeyboardMarkup(unsettledTransactions)\n\n if len(unsettledTransactions) < 1:\n message = context.bot.send_message(\n chat_id=update.effective_chat.id,\n text='No one owes you money! What great friends you have!!!'\n )\n return message\n\n message = context.bot.send_message(\n chat_id=update.effective_chat.id,\n text='The baddies who have your cash money! >:(',\n reply_markup=keyboardMarkup\n )\n return message\n\ndef getCreditors(update, context):\n \"\"\"Sends the user the message in response to the /whomeowes command.\"\"\"\n userID = update.effective_chat.id\n if not isNotifiable(userID):\n message = context.bot.send_message(\n chat_id=userID,\n text=\n \"Please register with us first by using /start!\"\n )\n return message\n \n unsettledTransactions = getUnsettledTransactionsForDebtor(userID)\n keyboardMarkup = formatTransactionsForDebtorKeyboardMarkup(unsettledTransactions)\n\n if len(unsettledTransactions) < 1:\n message = context.bot.send_message(\n chat_id=update.effective_chat.id,\n text=\"Wow! Amazing! You don't owe anyone any money!\"\n )\n return message\n message = context.bot.send_message(\n chat_id=update.effective_chat.id,\n text=\"The kind people who you've taken from:\",\n reply_markup=keyboardMarkup\n )\n return message\n \ndef cancel(update, context):\n \"\"\"Cancels any ongoing operation for the user in a group.\"\"\"\n groupID = update.effective_chat.id\n userID = update.message.from_user.id\n messageID = update.message.message_id\n setUserStateInactive(userID, groupID)\n resetUserTempAmount(userID, groupID)\n resetUserTempOrderID(userID, groupID)\n resetUserTempMessageID(userID, groupID)\n context.bot.send_message(\n chat_id=groupID,\n reply_to_message_id=messageID,\n text=\"I've been cancelled!\"\n )\n\ndef help(update, context):\n \"\"\"Sends the user the help message.\"\"\"\n return context.bot.send_message(\n chat_id=update.effective_chat.id,\n text=\n \"List of commands:\\n\\n\" +\n \"/start Initialise and register with us.\\n\" +\n \"/help For the confused souls.\\n\" +\n \"/whoowesme To see your debtors (only in private message).\\n\" +\n \"/whomeowes To see your creditors (only in private message).\\n\"+\n \"/cancel To cancel any creation of order.\\n\"\n \"\\nAfter running /start and registering in the group you wish to split bills in, you can start splitting your bills by simply typing @OwePay_bot followed by name of the order.\" +\n \"\\n\\nDue to the nature of Telegram Bots, our bot will only be able to detect users if they have either sent a message in the group after I've been added or users added after me!\" \n )\n\ndef error(update, context):\n \"\"\"Log Errors caused by Updates.\"\"\"\n logger.warning('Update \"%s\" caused error \"%s\"', update, context.error)\n\ndef inline(update, context):\n \"\"\"Handles the Inline Queries sent by the user.\"\"\"\n query = update.inline_query.query\n if query == \"\":\n return\n results = inlineQueryHelper(update)\n update.inline_query.answer(results)\n\ndef button(update, context):\n \"\"\"Handles the button presses for Inline Keyboard Callbacks\"\"\"\n query = update.callback_query\n choice = query.data\n username = query.message.chat.username\n\n if username == None or not 'test,bot' in username: # this is safe because ',' is an invalid character for telegram usernames\n query.answer()\n \n if choice == 'groupRegister':\n groupRegister(update, context)\n return query\n\n if choice == 'groupDontRegister':\n groupDontRegister(update, context)\n return query\n\n if choice == 'userRegister':\n userRegister(update, context)\n return query\n\n if choice == 'userDontRegister':\n userDontRegister(update, context)\n return query\n\n if choice == 'debtorEvenlyPaid':\n debtorEvenlyPaid(update, context)\n return query\n\n if choice == 'debtorEvenlyUnpaid':\n debtorEvenlyUnpaid(update, context)\n return query\n\n if choice == 'SplitEvenlyFinalise':\n splitEvenly(update, context)\n return query\n\n if 'splitevenlycallbackdata' in choice:\n user = choice.replace('splitevenlycallbackdata', '', 1)\n if userAlreadyAdded(user): #split some\n editMessageForSplitEvenly(update, context)\n return query\n \n if 'settledebtforcreditor' in choice:\n settleDebtForCreditor(update, context)\n\n if 'settledebtfordebtor' in choice:\n settleDebtForDebtor(update, context)\n \n if 'notifydebtorcallbackdata' in choice:\n notifyUserFromPrivateMessage(update, context)\n \n if 'splitunevenlycallbackdata' in choice:\n editUnevenlyMessageIndividual(update, context)\n\n if choice == 'splitevenlyaddeveryonecallbackdata':\n editSplitEvenlyAddEveryone(update, context)\n\n if choice == 'splitunevenlyaddeveryonecallbackdata':\n editSplitUnevenlyAddEveryone(update, context)\n\n\n if choice == 'splitunevenlynextitem':\n splitUnevenlyNextItem(update, context)\n \n if choice == 'goodservicetax':\n splitGST(update, context)\n \n if choice == 'servicechargecallbackdata':\n splitSVC(update, context)\n \n if choice == 'splitunevenlyfinalise':\n splitUnevenlyFinalise(update, context)\n \n if choice == 'debtorUnevenlyPaid':\n debtorUnevenlyPaid(update, context)\n\n if choice == 'debtorUnevenlyUnpaid':\n debtorUnevenlyUnpaid(update, context)\n\n if choice == 'newordersplitevenly':\n newOrderSplitEvenly(update, context)\n\n if choice == 'newordersplitunevenly':\n newOrderSplitUnevenly(update, context)\n\ndef newOrderSplitUnevenly(update, context):\n \"\"\"Prompts the user to send in the list of items to be added to the order.\"\"\"\n query = update.callback_query\n groupID = query.message.chat_id\n message_id = query.message.message_id\n userID = query.from_user.id\n\n if not userStateNewOrder(userID, groupID) and userIsMessageCreator(userID, groupID, message_id):\n return\n \n order = catchSplitUnevenlyOrder(userID, groupID)\n orderID = order.orderID\n updateOrderIDToUserGroupRelational(userID, groupID, orderID)\n setOrderDifferentAmountsFromOrderID(orderID)\n message = context.bot.editMessageText(\n chat_id=groupID,\n message_id=message_id,\n text='Please send in the items in the following format:\\nItem Name - Price\\n\\nFor example:\\nChicken Rice - 5\\nCurry Chicken - 5.50\\nNasi Lemak - 4'\n )\n updateUserStateSplitUnevenly(userID, groupID)\n return message\n\n\ndef newOrderSplitEvenly(update, context):\n \"\"\"Prompts the user to send in the amount to be split in the order.\"\"\"\n query = update.callback_query\n groupID = query.message.chat_id\n message_id = query.message.message_id\n userID = query.from_user.id\n\n if not userStateNewOrder(userID, groupID) and userIsMessageCreator(userID, groupID, message_id):\n return\n \n message = context.bot.editMessageText(\n chat_id=groupID,\n message_id=message_id,\n text='Please send in the amount to split!'\n )\n updateUserStateSplitEvenly(userID, groupID)\n return message\n \n\n \n \ndef debtorUnevenlyPaid(update, context):\n \"\"\"\"\"\"\n query = update.callback_query\n groupID = query.message.chat_id\n message_id = query.message.message_id\n debtorID = query.from_user.id\n debtorUsername = getUsername(debtorID)\n text = query.message.text\n orderID = frOrderIDFromMessageAndGroupID(message_id, groupID)\n creditorID = getCreditorIDFromMessageAndGroupID(message_id, groupID)\n\n if str(creditorID) == str(debtorID):\n return\n\n transactionID = getTransactionIDFromOrderIDCreditorIDDebtorID(orderID, creditorID, debtorID)\n amountOwed = getAmountOwedFromTransactionID(transactionID)\n\n textList = text.split('\\n')\n edited = False\n newTextList = []\n for item in textList:\n if not '(@' + debtorUsername + ')' in item:\n newTextList.append(item + '\\n')\n else:\n edited = True\n markTransactionAsSettled(creditorID, debtorID, orderID)\n newText = ''.join(newTextList)\n if edited:\n context.bot.editMessageText(\n chat_id=groupID,\n message_id=message_id,\n text=newText,\n reply_markup=splitUnevenlyFinalisedKeyboardMarkup()\n )\n\ndef debtorUnevenlyUnpaid(update, context):\n query = update.callback_query\n groupID = query.message.chat_id\n message_id = query.message.message_id\n debtorID = query.from_user.id\n debtorUsername = getUsername(debtorID)\n text = query.message.text\n orderID = getOrderIDFromMessageAndGroupID(message_id, groupID)\n creditorID = getCreditorIDFromMessageAndGroupID(message_id, groupID)\n\n if str(creditorID) == str(debtorID):\n return\n\n transactionID = getTransactionIDFromOrderIDCreditorIDDebtorID(orderID, creditorID, debtorID)\n amountOwed = getAmountOwedFromTransactionID(transactionID)\n\n textList = text.split('\\n')\n alreadyInside = False\n newTextList = []\n for item in textList:\n if '(@' + debtorUsername + ')' in item:\n newTextList.append(item + '\\n')\n alreadyInside = True\n else:\n newTextList.append(item + '\\n')\n\n if not alreadyInside:\n debtorName = getFirstName(debtorID)\n stringToAdd = '%s (@%s) - $%s\\n' %(debtorName, debtorUsername, amountOwed)\n newTextList.append(stringToAdd)\n newText = ''.join(newTextList)\n context.bot.editMessageText(\n chat_id=groupID,\n message_id=message_id,\n text=newText,\n reply_markup=splitUnevenlyFinalisedKeyboardMarkup()\n )\n \n\ndef splitUnevenlyFinalise(update, context):\n query = update.callback_query\n groupID = query.message.chat_id\n message_id = query.message.message_id\n userID = query.from_user.id\n text = query.message.text\n date = datetime.now(tz).replace(microsecond=0)\n\n if not (userIsCreditorForMessage(message_id, groupID, userID)):\n return\n \n orderID = getOrderIDFromUserIDAndGroupID(userID, groupID)\n creditorUsername = getUsername(userID)\n textList = text.split('\\n')\n userList = []\n debtList = []\n for item in textList:\n if '-' in item:\n if '(@' + creditorUsername + ')' in item: \n continue\n debtList.append(item)\n noBrackets = item.replace('(', '`')\n noBracketsList = noBrackets.split('`')\n for noBrack in noBracketsList:\n user = ''\n if '@' in noBrack:\n user = noBrack\n \n if user != '':\n user = user.split(') - $')\n userList.append(user)\n\n for user in userList:\n username = user[0]\n debtorID = getUserIDFromUsername(username.replace('@', '', 1))\n if username.replace('@', '', 1) == creditorUsername:\n continue\n amountOwed = user[1]\n transactionID = str(uuid1())\n addTransaction((transactionID, orderID, amountOwed, userID, debtorID, date))\n \n newDebtorList = []\n for debtor in debtList:\n newDebtorList.append(debtor + '\\n')\n debtorString = ''.join(newDebtorList)\n orderName = getOrderNameFromOrderID(orderID)\n messageText = \"Please return %s their cash money for %s!\\n\\n%s\" % ('@' + creditorUsername, orderName, debtorString)\n orderMessage = context.bot.editMessageText(\n chat_id=groupID,\n message_id=message_id,\n text=messageText,\n reply_markup=splitUnevenlyFinalisedKeyboardMarkup()\n )\n resetUserTempOrderID(userID, groupID)\n resetUserTempMessageID(userID, groupID)\n\n \ndef splitGST(update, context):\n query = update.callback_query\n userID = query.from_user.id\n chat_id = query.message.chat_id\n message_id = query.message.message_id\n text = query.message.text\n textList = text.split('\\n')\n newTextList = []\n if 'w/ GST' in text:\n for itemWithoutPara in textList:\n newItem = itemWithoutPara\n if 'People paying for ' in itemWithoutPara:\n if 'and SVC' in itemWithoutPara:\n newItem = itemWithoutPara.replace('w/ GST and ', 'w/ ', 1)\n else:\n newItem = itemWithoutPara.replace(' w/ GST:', ':', 1)\n tempSplitList = itemWithoutPara.split('-')\n tempSplitItem = tempSplitList[len(tempSplitList) - 1]\n if len(tempSplitList) > 0 and tempSplitList[0] != '':\n currentAmount = re.sub(r\"[^\\d.]+\", \"\", str(tempSplitItem))\n if (isValidAmount(currentAmount)):\n newAmount = getFormattedAmountFromString(float(currentAmount) / 1.07)\n newItem = newItem.replace('$%s' % str(currentAmount), '$%s' % newAmount, 1)\n newTextList.append(newItem + '\\n')\n else:\n for itemWithoutPara in textList:\n newItem = itemWithoutPara\n if 'People paying for ' in itemWithoutPara:\n if 'w/ SVC' in itemWithoutPara:\n newItem = itemWithoutPara.replace('w/ ', 'w/ GST and ', 1)\n else:\n newItem = itemWithoutPara.replace(':', ' w/ GST:', 1)\n tempSplitList = itemWithoutPara.split('-')\n tempSplitItem = tempSplitList[len(tempSplitList) - 1]\n if len(tempSplitList) > 0 and tempSplitList[0] != '':\n currentAmount = re.sub(r\"[^\\d.]+\", \"\", str(tempSplitItem))\n if (isValidAmount(currentAmount)):\n newAmount = getFormattedAmountFromString(float(currentAmount) * 1.07)\n newItem = newItem.replace('$%s' % str(currentAmount), '$%s' % newAmount, 1)\n newTextList.append(newItem + '\\n')\n \n newMessage = ''.join(newTextList)\n\n context.bot.editMessageText(\n chat_id=chat_id,\n message_id=message_id,\n text=newMessage,\n reply_markup=query.message.reply_markup\n )\n \n \ndef splitSVC(update, context):\n query = update.callback_query\n userID = query.from_user.id\n chat_id = query.message.chat_id\n message_id = query.message.message_id\n text = query.message.text\n textList = text.split('\\n')\n newTextList = []\n\n if not userIsCreditorForMessage(message_id, chat_id, userID):\n return\n\n if ' SVC:' in text:\n for itemWithoutPara in textList:\n newItem = itemWithoutPara\n if 'People paying for ' in itemWithoutPara:\n if 'w/ GST' in itemWithoutPara:\n newItem = itemWithoutPara.replace(' and SVC:', ':', 1)\n else:\n newItem = itemWithoutPara.replace(' w/ SVC:', ':', 1)\n tempSplitList = itemWithoutPara.split('-')\n tempSplitItem = tempSplitList[len(tempSplitList) - 1]\n if len(tempSplitList) > 0 and tempSplitList[0] != '':\n currentAmount = re.sub(r\"[^\\d.]+\", \"\", str(tempSplitItem))\n if (isValidAmount(currentAmount)):\n newAmount = getFormattedAmountFromString(float(currentAmount) / 1.1)\n newItem = newItem.replace('$%s' % str(currentAmount), '$%s' % newAmount, 1)\n newTextList.append(newItem + '\\n')\n else:\n for itemWithoutPara in textList:\n newItem = itemWithoutPara\n if 'People paying for ' in itemWithoutPara:\n if 'w/ GST:' in itemWithoutPara:\n newItem = itemWithoutPara.replace(':', ' and SVC:', 1)\n else:\n newItem = itemWithoutPara.replace(':', ' w/ SVC:')\n tempSplitList = itemWithoutPara.split('-')\n tempSplitItem = tempSplitList[len(tempSplitList) - 1]\n if len(tempSplitList) > 0 and tempSplitList[0] != '':\n currentAmount = re.sub(r\"[^\\d.]+\", \"\", str(tempSplitItem))\n if (isValidAmount(currentAmount)):\n newAmount = getFormattedAmountFromString(float(currentAmount) * 1.1)\n newItem = newItem.replace('$%s' % str(currentAmount), '$%s' % newAmount, 1)\n newTextList.append(newItem + '\\n')\n \n newMessage = ''.join(newTextList)\n\n context.bot.editMessageText(\n chat_id=chat_id,\n message_id=message_id,\n text=newMessage,\n reply_markup=query.message.reply_markup\n )\n \n\ndef splitUnevenlyNextItem(update, context):\n query = update.callback_query\n userID = query.from_user.id\n chat_id = query.message.chat_id\n message_id = query.message.message_id\n if not (userIsCreditorForMessage(message_id, chat_id, userID)):\n return\n orderID = getOrderIDFromUserIDAndGroupID(userID, chat_id)\n orderName = getOrderNameFromOrderID(orderID)\n text = query.message.text\n textList = text.split('\\n')\n itemToRemove = ''\n for item in textList:\n if 'People paying for ' in item:\n itemToRemove = item\n \n itemToRemovePosition = textList.index(itemToRemove)\n itemsLeftToSplitTitlePosition = textList.index('Items left to split:')\n count = -1\n userListToAdd = []\n for item in textList:\n count += 1\n if count <= itemToRemovePosition:\n continue\n else:\n userListToAdd.append(item)\n\n numOfUsersToAdd = len(userListToAdd)\n if numOfUsersToAdd < 1:\n return\n \n currentSplitList = []\n cleanAmountList = itemToRemove.split('(')\n cleanAmount = cleanAmountList[len(cleanAmountList) - 1]\n amountBeforeSplit = float(re.sub(r\"[^\\d.]+\", \"\", cleanAmount))\n amountAfterSplit = amountBeforeSplit / numOfUsersToAdd\n\n count = -1\n for item in textList:\n count += 1\n if count < itemsLeftToSplitTitlePosition and count != 0 and item != '':\n currentSplitList.append(item)\n else:\n continue\n for userToAdd in userListToAdd:\n inside = False\n for splitUser in currentSplitList:\n if userToAdd in splitUser:\n splitUserPosition = currentSplitList.index(splitUser)\n inside = True\n splitUserList = splitUser.split('-')\n tempSplitUser = splitUserList[len(splitUserList) - 1]\n currentAmount = float(re.sub(r\"[^\\d.]+\", \"\", tempSplitUser))\n\n newAmount = getFormattedAmountFromString(currentAmount + amountAfterSplit)\n print(newAmount)\n currentSplitList[splitUserPosition] = userToAdd + ' - $' + newAmount\n if not inside:\n currentSplitList.append(userToAdd + ' - $' + getFormattedAmountFromString(amountAfterSplit))\n itemList = []\n count = -1\n for item in textList:\n count += 1\n if count > itemsLeftToSplitTitlePosition and count < itemToRemovePosition and item != '':\n itemList.append(item)\n numOfItemsLeft = len(itemList)\n last = numOfItemsLeft < 1\n \n \n if not last:\n nextItem = itemList.pop(0)\n newItemList = []\n for item in itemList:\n newItemList.append(item + '\\n')\n itemListString = ''.join(newItemList)\n newSplitUserList = []\n for splitUser in currentSplitList:\n newSplitUserList.append(splitUser + '\\n')\n splitUserString = ''.join(newSplitUserList)\n messageText = 'Current split for %s:\\n%s\\nItems left to split:\\n%s\\nPeople paying for %s:' % (orderName, splitUserString, itemListString, nextItem)\n context.bot.editMessageText(\n chat_id=chat_id,\n message_id=message_id,\n text=messageText,\n reply_markup=splitUnevenlyKeyboardMarkup(chat_id, last)\n )\n else:\n newSplitUserList = []\n totalAmount = float(0)\n for splitUser in currentSplitList:\n newSplitUserList.append(splitUser + '\\n')\n tempSplitUserList = splitUser.split('-')\n tempSplitUser = tempSplitUserList[len(tempSplitUserList) - 1]\n currentAmount = float(re.sub(r\"[^\\d.]+\", \"\", tempSplitUser))\n totalAmount += currentAmount\n formattedTotal = getFormattedAmountFromString(totalAmount)\n splitUserString = ''.join(newSplitUserList)\n messageText = 'People paying for %s:\\n%s\\nTotal: $%s' % (orderName, splitUserString, formattedTotal)\n context.bot.editMessageText(\n chat_id=chat_id,\n text=messageText,\n message_id=message_id,\n reply_markup=splitUnevenlyKeyboardMarkup(chat_id, last),\n )\n\n\ndef editUnevenlyMessageIndividual(update, context):\n query = update.callback_query\n debtorID = query.data.replace('splitunevenlycallbackdata', '', 1)\n userID = query.from_user.id\n chat_id = query.message.chat_id\n message_id = query.message.message_id\n \n if not (userIsCreditorForMessage(message_id, chat_id, userID)):\n return\n \n text = query.message.text\n textList = text.split('\\n')\n debtorName = getFirstName(debtorID)\n debtorUsername = getUsername(debtorID)\n debtorToAdd = debtorName + ' (@' + debtorUsername + ')'\n if debtorToAdd in textList:\n textList.remove(debtorToAdd)\n else:\n textList.append(debtorToAdd)\n newTextList = []\n for text in textList:\n newTextList.append(text + '\\n')\n\n newText = ''.join(newTextList)\n\n context.bot.editMessageText(\n chat_id=chat_id,\n message_id=message_id,\n text=newText,\n reply_markup=query.message.reply_markup\n )\n\ndef editSplitEvenlyAddEveryone(update, context):\n query = update.callback_query\n userID = query.from_user.id\n chat_id = query.message.chat_id\n message_id = query.message.message_id\n text = query.message.text\n if not (userIsCreditorForMessage(message_id, chat_id, userID)):\n return\n \n userList = getAllUsersFromGroup(chat_id)\n listOfUsersWithNameAndUsername = []\n \n for user in userList:\n username = getUsername(user)\n firstName = getFirstName(user)\n entry = '\\n' + firstName + ' (@' + username + ')'\n if entry not in text:\n listOfUsersWithNameAndUsername.append(entry)\n \n newText = text + ''.join(listOfUsersWithNameAndUsername)\n \n if newText == text:\n return\n\n context.bot.editMessageText(\n chat_id=chat_id,\n message_id=message_id,\n text=newText,\n reply_markup=query.message.reply_markup\n )\n\ndef editSplitUnevenlyAddEveryone(update, context):\n query = update.callback_query\n userID = query.from_user.id\n chat_id = query.message.chat_id\n message_id = query.message.message_id\n text = query.message.text\n if not (userIsCreditorForMessage(message_id, chat_id, userID)):\n return\n \n # relevantHalf = text.split('People paying for ')[1]\n userList = getAllUsersFromGroup(chat_id)\n listOfUsersWithNameAndUsername = []\n \n splitByPara = text.split('\\n')\n\n for user in userList:\n username = getUsername(user)\n firstName = getFirstName(user)\n entry = firstName + ' (@' + username + ')'\n if entry not in splitByPara:\n listOfUsersWithNameAndUsername.append('\\n' + entry)\n \n newText = text + ''.join(listOfUsersWithNameAndUsername)\n\n if text == newText:\n return\n\n context.bot.editMessageText(\n chat_id=chat_id,\n message_id=message_id,\n text=newText,\n reply_markup=query.message.reply_markup\n )\n\n # text = query.message.text\n\n\n\ndef notifyUserFromPrivateMessage(update, context):\n query = update.callback_query\n transactionID = query.data.replace('notifydebtorcallbackdata', '', 1)\n\n lastNotifiedTime = getLastNotifiedTimeFromTransactionID(transactionID)\n currentTime = datetime.now(tz).replace(microsecond=0)\n to_add = timedelta(minutes=60)\n thresholdTime = lastNotifiedTime + to_add \n\n debtorID = getDebtorIDFromTransactionID(transactionID)\n creditorID = getCreditorIDFromTransactionID(transactionID)\n debtorName = getFirstName(debtorID)\n debtorUsername = getUsername(debtorID)\n orderID = getOrderIDFromTransactionID(transactionID)\n orderName = getOrderNameFromOrderID(orderID)\n orderDate = getOrderDateFromOrderID(orderID)\n formattedDate = orderDate.strftime(\"%d %B %Y\")\n groupID = getGroupIDFromOrder(orderID)\n groupName = getGroupNameFromGroupID(groupID)\n \n if not isNotifiable(debtorID):\n context.bot.send_message(\n chat_id=creditorID,\n text = '%s (@%s) is not notifiable.' % (debtorName, debtorUsername)\n )\n return\n\n if currentTime.replace(tzinfo=None) < thresholdTime.replace(tzinfo=None):\n timediff = currentTime.replace(tzinfo=None) - lastNotifiedTime.replace(tzinfo=None)\n timeTillNextSend = 60 - int(timediff.total_seconds()/60)\n context.bot.send_message(\n chat_id=creditorID,\n text = 'You have notified %s (@%s) too recently for %s on %s in %s. Please try again in %s minutes!' % (debtorName, debtorUsername, orderName, formattedDate, groupName, timeTillNextSend)\n ) \n return \n updateLastNotifiedTimeWithTransactionID(transactionID, currentTime)\n\n creditorName = getFirstName(creditorID)\n creditorUsername = getUsername(creditorID)\n amountOwed = getAmountOwedFromTransactionID(transactionID)\n formattedAmount = getFormattedAmountFromString(amountOwed)\n\n context.bot.send_message(\n chat_id=debtorID,\n text='Hi %s! Your friend %s (@%s) from the group %s is asking you to return them their $%s for %s %s.' % (debtorName, creditorName, creditorUsername,groupName, formattedAmount, orderName, formattedDate)\n )\n context.bot.send_message(\n chat_id=creditorID,\n text='%s (@%s) has been notified to return $%s for %s in %s' % (debtorName, debtorUsername, formattedAmount, orderName, groupName)\n )\n\ndef updateOrderMessageAsSettledWhenTransactionSettled(transactionID):\n if transactionAlreadySettled(transactionID):\n return\n bot = Bot(TOKEN)\n orderID = getOrderIDFromTransactionID(transactionID)\n debtorID = getDebtorIDFromTransactionID(transactionID)\n messageID = getMessageIDFromOrder(orderID)\n groupID = getGroupIDFromOrder(orderID)\n \n debtorName = getFirstName(debtorID)\n debtorUsername = getUsername(debtorID)\n entry = '%s (@%s)' % (debtorName, debtorUsername)\n\n isEven = orderIsEvenlySplit(orderID)\n\n placeholderGroupMessage = bot.forward_message(\n chat_id = -528685244,\n from_chat_id=groupID,\n message_id=messageID,\n )\n text = placeholderGroupMessage.text\n\n textList = text.split('\\n')\n\n newTextList =[]\n for item in textList:\n if entry in item:\n continue\n else:\n newTextList.append(item + '\\n')\n\n newText = ''.join(newTextList)\n\n reply_markup = ''\n\n if isEven:\n reply_markup = splitEvenlyFinalisedKeyboardMarkup()\n else:\n reply_markup = splitUnevenlyFinalisedKeyboardMarkup()\n \n bot.editMessageText(\n chat_id=groupID,\n message_id=messageID,\n text=newText,\n reply_markup=reply_markup,\n )\n \n\ndef settleDebtForCreditor(update, context):\n query = update.callback_query\n chat_id = query.message.chat_id\n message_id = query.message.message_id\n userID = query.from_user.id\n text = query.message.text\n\n transactionID = query.data.replace('settledebtforcreditor', '', 1)\n updateTransactionAsSettledWithTransactionID(transactionID)\n updateOrderMessageAsSettledWhenTransactionSettled(transactionID)\n\n unsettledTransactions = getUnsettledTransactionsForCreditor(userID)\n keyboardMarkup = formatTransactionsForCreditorKeyboardMarkup(unsettledTransactions)\n if (keyboardMarkup!=None):\n context.bot.editMessageText(\n chat_id=chat_id,\n message_id=message_id,\n text=text,\n reply_markup = keyboardMarkup\n )\n else:\n context.bot.editMessageText(\n chat_id=chat_id,\n message_id=message_id,\n text='All debts settled! You have such responsible friends... Unlike me ):'\n )\n\ndef settleDebtForDebtor(update, context):\n query = update.callback_query\n chat_id = query.message.chat_id\n message_id = query.message.message_id\n userID = query.from_user.id\n text = query.message.text\n\n transactionID = query.data.replace('settledebtfordebtor', '', 1)\n try:\n updateTransactionAsSettledWithTransactionID(transactionID)\n updateOrderMessageAsSettledWhenTransactionSettled(transactionID)\n finally:\n unsettledTransactions = getUnsettledTransactionsForDebtor(userID)\n keyboardMarkup = formatTransactionsForDebtorKeyboardMarkup(unsettledTransactions)\n\n if (keyboardMarkup!=None):\n context.bot.editMessageText(\n chat_id=chat_id,\n message_id=message_id,\n text=text,\n reply_markup=keyboardMarkup\n )\n else:\n context.bot.editMessageText(\n chat_id=chat_id,\n message_id=message_id,\n text='All debts settled! How responsible of you...'\n )\n \n\ndef editMessageForSplitEvenly(update, context):\n query = update.callback_query\n chat_id = query.message.chat_id\n message_id = query.message.message_id\n userID = query.from_user.id\n text = query.message.text\n\n if not (userIsCreditorForMessage(message_id, chat_id, userID)):\n return\n \n debtorID = query.data.replace('splitevenlycallbackdata', '', 1)\n debtorUsername = getUsername(debtorID)\n debtorName = getFirstName(debtorID)\n entry = debtorName + ' (@' + debtorUsername + ')'\n \n if entry in text:\n text = text.replace('\\n' + entry, '', 1)\n else:\n text = text + '\\n' + entry\n \n context.bot.editMessageText(\n chat_id=chat_id,\n message_id=message_id,\n text=text,\n reply_markup=query.message.reply_markup,\n )\n\n \ndef debtorEvenlyPaid(update, context):\n query = update.callback_query\n chat_id = query.message.chat_id\n message_id = query.message.message_id\n username = query.from_user.username\n debtorID = query.from_user.id\n text = query.message.text\n debtorName = getFirstName(debtorID)\n entry = '%s (@%s)' % (debtorName, username)\n textList = text.split('\\n')\n newTextList = []\n\n creditorID = getCreditorIDFromMessageAndGroupID(message_id, chat_id)\n\n if str(creditorID) == str(debtorID):\n return\n\n for item in textList:\n if entry in item:\n continue\n else:\n newTextList.append(item + '\\n')\n\n textAfterRemove = ''.join(newTextList)\n\n orderID = getOrderIDFromMessageAndGroupID(message_id, chat_id)\n \n\n if textAfterRemove != text:\n markTransactionAsSettled(creditorID, debtorID, orderID)\n context.bot.editMessageText(\n chat_id=chat_id,\n message_id=message_id,\n text=textAfterRemove,\n reply_markup=query.message.reply_markup\n )\n \n return None\n\ndef debtorEvenlyUnpaid(update, context):\n query = update.callback_query\n chat_id = query.message.chat_id\n message_id = query.message.message_id\n username = query.from_user.username\n debtorID = query.from_user.id\n debtorName = getFirstName(debtorID)\n text = query.message.text\n creditorID = getCreditorIDFromMessageAndGroupID(message_id, chat_id)\n\n if str(creditorID) == str(debtorID):\n return\n entry = '%s (@%s)' % (debtorName, username)\n textList = text.split('\\n')\n newTextList = []\n for item in textList:\n if entry in item:\n return\n else:\n newTextList.append(item + '\\n')\n\n newTextList.append(entry + '\\n')\n textAfterAdd = ''.join(newTextList)\n\n orderID = getOrderIDFromMessageAndGroupID(message_id, chat_id)\n creditorID = getCreditorIDFromMessageAndGroupID(message_id, chat_id)\n\n if textAfterAdd != text:\n markTransactionAsUnsettled(creditorID, debtorID, orderID)\n context.bot.editMessageText(\n chat_id=chat_id,\n message_id=message_id,\n text=textAfterAdd,\n reply_markup=query.message.reply_markup\n )\n\n return None\n \n\ndef groupRegister(update, context):\n query = update.callback_query\n chat_id = query.message.chat_id\n groupname = query.message.chat.title\n message_id = query.message.message_id\n group = (chat_id, groupname)\n if (groupAlreadyAdded(chat_id)):\n context.bot.editMessageText(\n chat_id=chat_id,\n message_id=message_id,\n text=\"Your group has already been registered with us.\"\n )\n else:\n addGroup(group)\n print('donkey')\n context.bot.editMessageText(\n chat_id=query.message.chat_id,\n message_id=query.message.message_id,\n text=\"Your group is now registered!\\n\\nBegin splitting bills by sending a message starting with @OwePay_bot followed by the name of the bill. For example:\\n\\n@OwePay_bot Assorted Sausages\\n\\nDue to the nature of Telegram Bots, our bot will only be able to detect users if they have either sent a message in the group after I've been added or users added after me!\",\n )\n\n\n\ndef splitEvenly(update, context):\n query = update.callback_query\n groupID = query.message.chat_id\n message_id = query.message.message_id\n userID = query.from_user.id\n text = query.message.text\n date = datetime.now(tz).replace(microsecond=0)\n\n if not (userIsCreditorForMessage(message_id, groupID, userID)):\n return\n \n totalAmount = getUserTempAmount(userID, groupID)\n listOfUsers = tuple(text.replace(\"People who have your cash money:\\n\", \"\", 1).replace(\"\\n\",\",\",text.count(\"\\n\")).split(','))\n numberOfUsers = len(listOfUsers)\n\n if numberOfUsers == 0:\n return\n \n listOfUsernames = []\n for user in listOfUsers:\n tempList = []\n tempList.append(user.split('@')[1])\n for tempItem in tempList:\n listOfUsernames.append(tempItem.split(')')[0])\n \n\n splitAmount = totalAmount / numberOfUsers\n orderID = getOrderIDFromUserIDAndGroupID(userID, groupID)\n orderName = getOrderNameFromOrderID(orderID)\n creditorUsername = getUsername(userID)\n creditorName = getFirstName(userID)\n \n listOfUserID = getUserIDListFromUsernameList(listOfUsernames)\n\n if len(listOfUserID) < 1:\n return\n \n setUserStateInactive(userID, groupID)\n resetUserTempAmount(userID, groupID)\n resetUserTempOrderID(userID, groupID)\n resetUserTempMessageID(userID, groupID)\n\n messageText = \"Please return @%s $%s each for %s\" % (creditorUsername, getFormattedAmountFromString(splitAmount), orderName)\n for username in listOfUsers:\n messageText = messageText + '\\n' + username\n\n if \"%s (@%s)\" % (creditorName, creditorUsername) in messageText:\n messageText = messageText.replace(\"\\n%s (@%s)\" % (creditorName, creditorUsername), \"\", 1)\n\n orderMessage = context.bot.editMessageText(\n chat_id=update.effective_chat.id,\n message_id=message_id,\n text=messageText,\n reply_markup=splitEvenlyFinalisedKeyboardMarkup(),\n )\n order = Order(orderID, groupID, orderName, splitAmount, userID, date)\n messageID = orderMessage.message_id\n addMessageIDToOrder(str(orderID), messageID)\n createTransactionBetweenSomeUsers(order, listOfUserID)\n\n\ndef splitDifferentAmounts(update, context, userID, groupID):\n textString = update.message.text\n textStringWithoutParagraphs = textString.split('\\n')\n textListSeparated = []\n messageID = update.message.message_id\n itemList = []\n orderID = getOrderIDFromUserIDAndGroupID(userID, groupID)\n orderName = getOrderNameFromOrderID(orderID)\n for text in textStringWithoutParagraphs:\n tempText = text.split ('-')\n tempList = []\n for t in tempText:\n tempList.append(removeCrustFromString(t))\n textListSeparated.append(tempList)\n for item in textListSeparated:\n tempList = []\n if len(item) != 2 or not isValidAmount(item[1]):\n context.bot.send_message(\n chat_id=groupID,\n reply_to_message_id=messageID,\n text='Please send your order in a valid format!'\n )\n return\n tempList.append(item[0])\n if (isValidAmount(item[1])):\n tempList.append(getFormattedAmountFromString(item[1]))\n else:\n context.bot.send_message(\n chat_id=groupID,\n reply_to_message_id=messageID,\n text='%s is not a valid amount' % (item[1])\n )\n itemList.append(tempList)\n\n firstItem = itemList.pop(0)\n firstItemString = firstItem[0] + ' ($' + firstItem[1] + ')'\n itemListString = itemListToString(itemList)\n messageText = 'Current split for %s:\\n\\nItems left to split:%s\\n\\nPeople paying for %s:' % (orderName, itemListString, firstItemString)\n orderMessage = context.bot.send_message(\n chat_id=update.effective_chat.id,\n text=messageText,\n reply_markup=splitUnevenlyKeyboardMarkup(groupID, False)\n )\n print(splitUnevenlyKeyboardMarkup(groupID, False))\n messageID = orderMessage.message_id\n addMessageIDToOrder(orderID, messageID)\n setUserStateInactive(userID, groupID)\n return orderMessage\n \ndef getTotalAmountFromMessage(update, context):\n chat_message=update.message.text\n value = int(''.join(filter(str.isdigit, chat_message)))\n total_amount = float(value/100)\n return total_amount\n\n\n#############################\n# when split among us is called this will update regisfter the userid and the\n# amount of money\n##############\n\n\ndef getOrderNameFromMessage(update):\n text = update.message.text\n return str(text.split('New Order: ')[1])\n\ndef messageContainsNewOrder(update, context):\n if \"New Order:\" in update.message.text: \n orderName = getOrderNameFromMessage(update)\n user_id = update.message.from_user.id\n GroupID = update.message.chat_id\n updateUserStateNewOrder(user_id, GroupID)\n updateOrderIDToUserGroupRelational(user_id, GroupID, orderName)\n message = context.bot.send_message(\n chat_id=update.effective_chat.id,\n text=\n \"Please choose if you wish to split %s evenly or unevenly\" % orderName,\n reply_markup=waitingForUserToChooseSplitKeyboardMarkup()\n )\n updateMessageIDToUserGroupRelational(user_id, GroupID, message.message_id)\n return message\n\ndef catchSplitEvenlyOrderFromUpdate(update):\n order_id = str(uuid1())\n user_id = update.message.from_user.id\n group_id = update.message.chat_id\n order_amount= update.message.text.replace('$', '', 1)\n date = datetime.now(tz).replace(microsecond=0)\n order_name = getOrderIDFromUserIDAndGroupID(user_id, group_id)\n addOrder((order_id, group_id, order_name, order_amount, user_id, date))\n return Order(order_id, group_id, order_name, order_amount, user_id, date)\n\ndef catchSplitUnevenlyOrder(user_id, group_id):\n order_id = str(uuid1())\n order_amount = 0\n date = datetime.now(tz).replace(microsecond=0)\n order_name = getOrderIDFromUserIDAndGroupID(user_id, group_id)\n addOrder((order_id, group_id, order_name, order_amount, user_id, date))\n return Order(order_id, group_id, order_name, order_amount, user_id, date)\n\n\ndef waitingForSomeNames(update, context, user_id, group_id):\n order = catchSplitEvenlyOrderFromUpdate(update)\n orderID = order.orderID\n orderAmount = order.orderAmount\n updateUserTempAmount(user_id, group_id, orderAmount)\n updateUserStateWaitingForSomeNames(user_id, group_id)\n updateOrderIDToUserGroupRelational(user_id, group_id, orderID)\n\n message = context.bot.send_message(\n chat_id=update.effective_chat.id,\n text='People who have your cash money:',\n reply_markup=splitEvenlyKeyboardMarkup(update.effective_chat.id)\n )\n messageID = message.message_id\n addMessageIDToOrder(orderID, messageID)\n return message\n\ndef createTransactionBetweenSomeUsers(order, userIDList):\n creditorID = order.creditorID\n orderID = order.orderID\n users = userIDList\n splitAmount = order.orderAmount\n date = order.date\n\n for userID in users:\n if str(userID) == str(creditorID):\n None\n else:\n transaction_id = str(uuid1())\n addTransaction((transaction_id, orderID, splitAmount, creditorID, userID, date))\n\n return UsersAndSplitAmount(users, splitAmount)\n\n\n\n#order123 = (\"b62aa85b-cb98-11eb-baef-d0509938caba\",-524344128,'thai food',123.45,339096917)\n#createTransactionbetweenallusers(order123)\n\ndef groupDontRegister(update, context):\n query = update.callback_query\n context.bot.editMessageText(\n chat_id=query.message.chat_id,\n message_id=query.message.message_id,\n text=\n \"Thank you for your interest in our bot! We hope to see you soon!\\n\\n\" +\n \"If you ever feel like registering your Group with our bot in the future,\" +\n \" simply run /start to get started!\",\n )\n\ndef userRegister(update, context):\n query = update.callback_query\n chat_id = query.message.chat_id\n username = query.message.chat.username\n message_id = query.message.message_id\n firstname = query.message.chat.first_name\n user = (chat_id, username, 1, firstname)\n if (userAlreadyAdded(chat_id)):\n if not(isNotifiable(chat_id)):\n makeNotifiable(chat_id)\n context.bot.editMessageText(\n chat_id=chat_id,\n message_id=message_id,\n text=\"You are now registered!\\n\\nAdd this bot to your telegram groups to split bills among your friends! Bills can be split by sending a message starting with @OwePay_bot followed by the name of the order after registering the bot in the group with the /start command. For example:\\n\\n@OwePay_bot Assorted Meats\\n\\nDue to the nature of Telegram Bots, our bot will only be able to detect users if they have either sent a message in the group after I've been added or users added after me!\",\n )\n else:\n context.bot.editMessageText(\n chat_id=chat_id,\n message_id=message_id,\n text=\"You have already been registered with us.\",\n )\n else:\n addUser(user)\n context.bot.editMessageText(\n chat_id=query.message.chat_id,\n message_id=query.message.message_id,\n text=\"You are now registered!\\n\\nAdd this bot to your telegram groups to split bills among your friends! Bills can be split by sending a message starting with @OwePay_bot followed by the name of the order after registering the bot in the group with the /start command. For example:\\n\\n@OwePay_bot Assorted Meats\\n\\nDue to the nature of Telegram Bots, our bot will only be able to detect users if they have either sent a message in the group after I've been added or users added after me!\",\n )\n\ndef userDontRegister(update, context):\n query = update.callback_query\n context.bot.editMessageText(\n chat_id=query.message.chat_id,\n message_id=query.message.message_id,\n text=\n \"Thank you for your interest in our bot! We hope to see you soon!\\n\\n\" +\n \"If you ever feel like registering with our bot in the future, simply run /start\" +\n \" to get started!\",\n )\n#############################\n# checks if msg is sent from a bot\n##############\ndef viabot_check(update, context):\n return (update.message.via_bot!=None and str(update.message.via_bot.id) == str(BOT_ID))\n\n# def echo(update: Update, _: CallbackContext) -> None:\ndef echo(update, context):\n \"\"\"Echo the update for debugging purposes.\"\"\"\n print(update)\n\ndef askUserToSendValidAmount(update, context):\n group_id = update.message.chat_id\n user_id = update.message.from_user.id\n text = update.message.text\n message = context.bot.send_message(\n chat_id=group_id,\n text=\"%s is not a valid amount.\\n\\nPlease key in a valid amount e.g $123, 123, 123.10 or /cancel to stop the creation of the order.\" % text\n )\n return message\n\ndef groupMemberScanner(update, context):\n \"\"\"\"Constantly monitors group chat to check if members are counted in the group or not\"\"\"\n group_id = update.message.chat_id\n message_id = update.message.message_id\n user_id = update.message.from_user.id\n username = update.message.from_user.username\n firstname = update.message.from_user.first_name\n \n if len(update.message.new_chat_members) > 0:\n for newMember in update.message.new_chat_members:\n if newMember.is_bot:\n continue\n newUserID = newMember.id\n addUserToGroup(newUserID, group_id)\n if not userAlreadyAdded(newUserID):\n newUsername = newMember.username\n newFirstname = newMember.first_name\n user = (newUserID, newUsername, 0, newFirstname)\n addUser(user)\n \n if update.message.left_chat_member != None:\n print(update.message.left_chat_member.id)\n leftMember = update.message.left_chat_member\n leftMemberID = leftMember.id\n if userInGroup(leftMemberID, group_id):\n deleteUserFromGroup(leftMemberID, group_id)\n if not userAlreadyAdded(leftMemberID):\n leftUsername = leftMember.username\n leftFirstname = leftMember.first_name\n user = (leftMemberID, leftUsername, 0, leftFirstname)\n addUser(user)\n\n if not(userAlreadyAdded(user_id)):\n user = (user_id, username, 0, firstname)\n addUser(user)\n\n\n if not(userInGroup(user_id, group_id)):\n increaseGroupMemberCount(group_id)\n addUserToGroup(user_id, group_id)\n \n\n if not(groupAlreadyAdded(group_id)):\n return 'Group with id %s not added' % group_id\n \n if userStateSplitEvenly(user_id, group_id):\n text = update.message.text\n if isValidAmount(text):\n waitingForSomeNames(update, context, user_id, group_id)\n return \"User %s has state 'splitevenly'\" % user_id\n else:\n askUserToSendValidAmount(update, context)\n return \"User %s sending invalid amount\" % user_id\n\n if userStateSplitUnevenly(user_id, group_id):\n splitDifferentAmounts(update, context, user_id, group_id)\n return \"User %s has state 'splitunevenly'\" % user_id\n\n if viabot_check(update, context):\n bot = update.message.via_bot.id\n messageContainsNewOrder(update, context)\n return \"Bot found %s\" % bot\n\n\n\ndef main():\n \"\"\"Start the bot.\"\"\"\n updater = Updater(\n TOKEN, use_context=True)\n # Get the dispatcher to register handlers\n dp = updater.dispatcher\n\n # on different commands - answer in Telegram\n dp.add_handler(CommandHandler(\"start\", startGroup, Filters.chat_type.groups))\n dp.add_handler(CommandHandler(\"start\", startPrivate, Filters.chat_type.private))\n dp.add_handler(CommandHandler(\"whoowesme\", getDebtors, Filters.chat_type.private))\n dp.add_handler(CommandHandler(\"whomeowes\", getCreditors, Filters.chat_type.private))\n dp.add_handler(CommandHandler(\"help\", help))\n dp.add_handler(CommandHandler(\"cancel\", cancel, Filters.chat_type.groups))\n dp.add_handler(CallbackQueryHandler(button))\n dp.add_handler(InlineQueryHandler(inline))\n #dp.add_handler(MessageHandler(Filters.chat_type.groups, echo))\n dp.add_handler(MessageHandler(Filters.chat_type.groups, groupMemberScanner))\n dp.add_handler(ConversationHandler(\n [\n CommandHandler(\"scanreceipt\", scanReceiptPrivateMessage)\n ], \n {\n \"waitingonpicprivate\": [CommandHandler(\"cancelreceipt\", cancelReceipt), MessageHandler(Filters.chat_type.private, scanReceiptPrivatePicture)],\n\n }, \n [\n CommandHandler(\"cancelreceipt\", cancelReceipt)\n ],\n allow_reentry=True\n ))\n\n # log all errors\n dp.add_error_handler(error)\n\n updater.start_webhook(listen=\"0.0.0.0\",\n port=PORT,\n url_path=TOKEN,\n webhook_url=\"https://owepaybot.herokuapp.com/\" + TOKEN)\n # updater.start_polling()\n updater.idle()\n\nif __name__ == '__main__':\n main()\n","sub_path":"owepaybot.py","file_name":"owepaybot.py","file_ext":"py","file_size_in_byte":54362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"540601629","text":"import numpy as np\nfrom keras.layers import Conv2D, MaxPooling2D, UpSampling2D, Add, Multiply\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.core import SpatialDropout2D, Activation\nfrom keras import backend as K\nimport tensorflow as tf\nfrom keras.layers.merge import concatenate\nfrom keras import Sequential\nfrom keras.layers import Lambda\n# Number of output masks (1 in case you predict only one type of objects)\nINPUT_CHANNELS = 3\n# Pretrained weights\n\ndef double_conv_layer(x, size, dropout=0.0, batch_norm=True):\n if K.image_dim_ordering() == 'th':\n axis = 1\n else:\n axis = 3\n conv = Conv2D(size, (3, 3), padding='same',)(x)\n if batch_norm is True:\n conv = BatchNormalization(axis=axis)(conv)\n conv = Activation('relu')(conv)\n conv = Conv2D(size, (3, 3), padding='same')(conv)\n if batch_norm is True:\n conv = BatchNormalization(axis=axis)(conv)\n conv = Activation('relu')(conv)\n if dropout > 0:\n conv = SpatialDropout2D(dropout)(conv)\n return conv\ndef UpSampling2DBilinear(stride, **kwargs):\n def layer(x):\n input_shape = K.int_shape(x)\n output_shape = (stride * input_shape[1], stride * input_shape[2])\n return tf.image.resize_bilinear(x, output_shape, align_corners=True)\n return Lambda(layer, **kwargs)\n\n\ndef dsv(x, size,scale_factor, dropout=0.0, batch_norm=True):\n if K.image_dim_ordering() == 'th':\n axis = 1\n else:\n axis = 3\n conv = Conv2D(size, (3, 3), padding='same')(x)\n if batch_norm is True:\n conv = BatchNormalization(axis=axis)(conv)\n conv = Activation('relu')(conv)\n conv = Conv2D(size, (3, 3), padding='same')(conv)\n if batch_norm is True:\n conv = BatchNormalization(axis=axis)(conv)\n conv = Activation('relu')(conv)\n if dropout > 0:\n conv = SpatialDropout2D(dropout)(conv)\n\n upsampler = UpSampling2DBilinear(stride=scale_factor)(conv)\n\n return upsampler\ndef gating(x, size, dropout=0.0, batch_norm=True):\n if K.image_dim_ordering() == 'th':\n axis = 1\n else:\n axis = 3\n conv = Conv2D(size, (1, 1), padding='valid')(x)\n if batch_norm is True:\n conv = BatchNormalization(axis=axis)(conv)\n conv = Activation('relu')(conv)\n\n if dropout > 0:\n conv = SpatialDropout2D(dropout)(conv)\n return conv\n\ndef grid_attention(input_signal,gating_signal,inter_channels):\n if K.image_dim_ordering() == 'th':\n axis = 1\n else:\n axis = 3\n theta_x = Conv2D(inter_channels,\n kernel_size=(1,1), strides=(2,2), padding='valid',\n use_bias=False)(input_signal)\n theta_x_size = theta_x.shape\n phi_g = Conv2D(inter_channels,\n kernel_size=(1,1), padding='valid', use_bias=True)(gating_signal)\n\n cancat =Add()([phi_g, theta_x])\n f = Activation('relu')(cancat)\n psi = Conv2D(filters=1, kernel_size=(1,1), padding='valid', use_bias=True)(f)\n sigm_psi_f = Activation('sigmoid')(psi)\n\n input_signal_shape=input_signal.shape\n # upsample the attentions and multiply\n #print('sigm_psi_f is {0}'.format(sigm_psi_f))\n scale_factor=2\n upsampler = UpSampling2DBilinear(stride=scale_factor)(sigm_psi_f)\n #print('upsampled is {0}'.format(upsampler.shape))\n upsampler_conc = concatenate([upsampler, upsampler], axis = axis)\n for i in range(input_signal_shape[3]-2):\n upsampler_conc = concatenate([upsampler_conc, upsampler], axis=axis)\n #print('upsampler_conc is {0}'.format(upsampler_conc .shape))\n y = Multiply()([input_signal,upsampler_conc])\n #final_dimention=input_signal_shape[3]\n W_y =Conv2D (inter_channels, kernel_size=(1,1), strides=(1,1), padding='valid')(y)\n w_y = BatchNormalization(axis=axis)(W_y)\n\n return w_y, sigm_psi_f\n\ndef build(inp, nc):\n if K.image_dim_ordering() == 'th':\n inputs = inp\n axis = 1\n else:\n inputs =inp\n axis = 3\n filters = 32\n OUTPUT_MASK_CHANNELS = nc\n\n dropout_val = 0.2\n layer_name = 'first_conv_layer'\n conv_224 = double_conv_layer(inputs, filters)\n pool_112 = MaxPooling2D(pool_size=(2, 2))(conv_224)\n #print('pool_112 is {0}'.format(pool_112.shape))\n layer_name = 'second_conv_layer'\n conv_112 = double_conv_layer(pool_112, 2 * filters)\n pool_56 = MaxPooling2D(pool_size=(2, 2))(conv_112)\n #print('pool_56 is {0}'.format(pool_56.shape))\n layer_name = 'third_conv_layer'\n conv_56 = double_conv_layer(pool_56, 4 * filters)\n pool_28 = MaxPooling2D(pool_size=(2, 2))(conv_56)\n #print('pool_28 is {0}'.format(pool_28.shape))\n layer_name = 'fourth_conv_layer'\n conv_28 = double_conv_layer(pool_28, 8 * filters)\n pool_14 = MaxPooling2D(pool_size=(2, 2))(conv_28)\n #print('pool_14 is {0}'.format(pool_14.shape))\n layer_name = 'fifth_conv_layer'\n conv_14 = double_conv_layer(pool_14, 16 * filters,)\n #print('conv_14 is {0}'.format(conv_14.shape))\n pool_7 = MaxPooling2D(pool_size=(2, 2))(conv_14)\n #print('pool_7 is {0}'.format(pool_7.shape))\n layer_name = 'six_conv_layer'\n center = double_conv_layer(pool_7,32* filters)\n #print('center is {0}'.format(center.shape))\n gate_signal= gating(center,32*filters) \n #print('gate_signal is {0}'.format(gate_signal.shape))\n g_conv2, att2 = grid_attention(conv_14, gate_signal,inter_channels=16*filters)\n #print('g_conv2 is {0}'.format(g_conv2.shape))\n up_14 = concatenate([UpSampling2D(size=(2, 2))(center), g_conv2], axis=axis)\n layer_name = 'first_upconv_layer'\n up_14 = double_conv_layer(up_14, filters*16)\n #print('up_14 is {0}'.format(up_14.shape))\n g_conv3, att3 = grid_attention(conv_28, up_14,inter_channels=8*filters)\n up_28 = concatenate([UpSampling2D(size=(2, 2))(up_14), g_conv3], axis=axis)\n layer_name = 'second_upconv_layer'\n up_28 = double_conv_layer(up_28, filters*8)\n #print('up_28 is {0}'.format(up_28.shape))\n g_conv4, att4 = grid_attention(conv_56, up_28,inter_channels=4*filters)\n up_56 = concatenate([UpSampling2D(size=(2, 2))(up_28), g_conv4], axis=axis)\n layer_name = 'fourth_upconv_layer'\n up_56 = double_conv_layer(up_56, filters*4,)\n #print('up_56 is {0}'.format(up_56.shape))\n g_conv5, att5 = grid_attention(conv_112, up_56, inter_channels=2*filters)\n up_112 = concatenate([UpSampling2D(size=(2, 2))(up_56), g_conv5], axis=axis)\n layer_name = 'fifth_upconv_layer'\n up_112 = double_conv_layer(up_112, filters*2,)\n #print('up_112 is {0}'.format(up_112.shape))\n up_224 = concatenate([UpSampling2D(size=(2, 2))(up_112), conv_224], axis=axis)\n layer_name = 'sixth_upconv_layer'\n up_224 = double_conv_layer(up_224, filters)\n #print('up_224 is {0}'.format(up_224.shape))\n\n up_conv_14 = dsv(up_14, OUTPUT_MASK_CHANNELS,16)\n up_conv_28 = dsv(up_28, OUTPUT_MASK_CHANNELS,8)\n up_conv_56 = dsv(up_56, OUTPUT_MASK_CHANNELS,4)\n up_conv_112 = dsv(up_112, OUTPUT_MASK_CHANNELS,2)\n up_conv_224 = dsv(up_224, OUTPUT_MASK_CHANNELS,1, dropout_val)\n final = concatenate([up_conv_14, up_conv_28,up_conv_56,up_conv_112,up_conv_224], axis=axis)\n\n\n return final","sub_path":"models/weakly_sup/base_unet.py","file_name":"base_unet.py","file_ext":"py","file_size_in_byte":7142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"310629675","text":"# Copyright (C) 2018-2021 Intel Corporation\n# SPDX-License-Identifier: Apache-2.0\n\nimport numpy as np\n\nfrom mo.front.common.partial_infer.utils import is_fully_defined\nfrom mo.graph.graph import Node, Graph\nfrom mo.ops.op import Op\nfrom mo.utils.broadcasting import bi_directional_shape_broadcasting, bi_directional_broadcasting\n\n\nclass Select(Op):\n op = 'Select'\n\n def __init__(self, graph: Graph, attrs: dict):\n mandatory_props = {\n 'op': self.op,\n 'type': self.op,\n 'version': 'opset1',\n 'in_ports_count': 3,\n 'out_ports_count': 1,\n 'infer': self.infer,\n 'type_infer': self.type_infer,\n 'auto_broadcast': 'numpy'\n }\n super().__init__(graph, mandatory_props, attrs)\n\n def backend_attrs(self):\n return ['auto_broadcast']\n\n @staticmethod\n def infer(node: Node):\n node_name = node.soft_get('name', node.id)\n assert len([port for port in node.in_ports().values() if not port.disconnected()]) == 3, \\\n \"Select operation must have 3 inputs: 'condition', 'then' and 'else' tensors for node {}\".format(node_name)\n\n condition_value = node.in_port(0).data.get_value()\n resulting_tensors = [node.in_port(1).data.get_value(), node.in_port(2).data.get_value()]\n\n a_shape = node.in_port(1).data.get_shape()\n b_shape = node.in_port(2).data.get_shape()\n output_shape = bi_directional_shape_broadcasting(a_shape, b_shape)\n assert output_shape is not None, 'Input shapes for node {} are not broadcast-able'.format(node_name)\n node.out_port(0).data.set_shape(output_shape)\n\n if condition_value is not None:\n if resulting_tensors[0] is not None:\n resulting_tensors[0] = bi_directional_broadcasting(resulting_tensors[0], b_shape)\n if resulting_tensors[1] is not None:\n resulting_tensors[1] = bi_directional_broadcasting(resulting_tensors[1], a_shape)\n condition_value = bi_directional_broadcasting(condition_value, output_shape)\n\n output_value = np.ma.where(condition_value, resulting_tensors[0], resulting_tensors[1])\n if condition_value.size != 1:\n if np.any(output_value == None):\n # If any element of output value is None that means that we use the value from the 'then' or the\n # 'else' tensor which is not defined, this means that we cannot perform value propagation.\n output_value = None\n else:\n output_value = output_value.astype(resulting_tensors[not np.bool(condition_value.item(0))].dtype)\n\n if output_value is not None:\n node.out_port(0).data.set_value(output_value)\n\n @staticmethod\n def type_infer(node: Node):\n assert node.in_port(1).get_source().get_data_type() == node.in_port(2).get_source().get_data_type(), \\\n 'The data type of the second and the third inputs must be equal for the node {}'.format(node.name)\n node.out_port(0).set_data_type(node.in_port(1).get_source().get_data_type())\n","sub_path":"model-optimizer/extensions/ops/select.py","file_name":"select.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"98415771","text":"import requests\nfrom pprint import pprint\n\ncoindesk_url = 'https://api.coindesk.com/v1/bpi/currentprice.json'\n\n\ndef main():\n num_of_bitcoin = get_number_of_bitcoin()\n data = request_exchange_rate()\n dollars_exchange_rate = get_exchange_rate(data)\n bitcoin_value_in_dollars = calculate_bitcoin_to_dollar(dollars_exchange_rate, num_of_bitcoin)\n display_result(num_of_bitcoin, bitcoin_value_in_dollars)\n\ndef get_number_of_bitcoin():\n while True:\n try:\n num_of_bitcoin = float(input('Enter the number bitcoins you want to convert: '))\n if num_of_bitcoin<=0:\n raise ValueError('Number of bitcoin must be >0')\n return num_of_bitcoin\n except:\n print('Enter a number greater than 0')\n\n\ndef request_exchange_rate():\n try:\n response = requests.get(coindesk_url)\n response.raise_for_status() #raises an exception for 400 or 500 status code\n data = response.json() #convert response to json (like python dictionary)\n return data\n except Exception as e:\n print(e)\n print('There was an error making the request')\n\ndef get_exchange_rate(data): #extra info from data returned from request\n dollars_exchange_rate = data['bpi']['USD']['rate_float']\n return dollars_exchange_rate\n \n\ndef calculate_bitcoin_to_dollar(dollars_exchange_rate, num_of_bitcoin):\n bitcoin_value_in_dollars= dollars_exchange_rate * num_of_bitcoin\n return bitcoin_value_in_dollars\n\ndef display_result( num_of_bitcoin,bitcoin_value_in_dollars):\n print(f'$ {bitcoin_value_in_dollars:.2f} is the equivalent of {num_of_bitcoin} bitcoins')\n\n\n\n\nif __name__ == \"__main__\":\n main()\n\n #APIpowered by Coindesk","sub_path":"bitcoin.py","file_name":"bitcoin.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"373092883","text":"# method_1\nclass Solution:\n def productExceptSelf(self, nums: List[int]) -> List[int]:\n n = len(nums)\n L = [1]*n\n R = [1]*n\n ans = [0]*n\n # 计算前缀后缀乘积\n for i in range(1,n):\n L[i] = L[i-1]*nums[i-1]\n\n for i in range(n-2,-1,-1):\n R[i] = R[i+1]*nums[i+1]\n \n for i in range(n):\n ans[i] = L[i]*R[i]\n\n return ans\n\n# method_2\nclass Solution:\n def productExceptSelf(self, nums: List[int]) -> List[int]:\n n = len(nums)\n ans = [1]*n\n left = 1\n right = 1\n \n for i in range(n):\n ans[i] *= right\n ans[-1-i] *= left\n right *= nums[i]\n left *= nums[-1-i]\n\n return ans","sub_path":"Qustion Code/238. 除自身以外数组的乘积.py","file_name":"238. 除自身以外数组的乘积.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"388226047","text":"##############################################################################\n#\n# Copyright (c) 2001, 2002 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"ZCML directive handlers for browser resources\n\"\"\"\nimport os\n\nfrom zope.component import queryUtility\nfrom zope.component.interface import provideInterface\nfrom zope.component.zcml import handler\nfrom zope.configuration.exceptions import ConfigurationError\nfrom zope.interface import Interface\nfrom zope.interface import implementer\nfrom zope.interface import provider\nfrom zope.publisher.interfaces.browser import IBrowserRequest\nfrom zope.publisher.interfaces.browser import IDefaultBrowserLayer\nfrom zope.security.checker import Checker\nfrom zope.security.checker import CheckerPublic\nfrom zope.security.checker import NamesChecker\nfrom zope.security.proxy import Proxy\n\nfrom zope.browserresource.directory import DirectoryResourceFactory\nfrom zope.browserresource.file import File\nfrom zope.browserresource.file import FileResourceFactory\nfrom zope.browserresource.i18nfile import I18nFileResourceFactory\nfrom zope.browserresource.icon import IconViewFactory\nfrom zope.browserresource.interfaces import IResourceFactory\nfrom zope.browserresource.interfaces import IResourceFactoryFactory\n\n\nallowed_names = ('GET', 'HEAD', 'publishTraverse', 'browserDefault',\n 'request', '__call__')\n\n\n@implementer(IResourceFactory)\n@provider(IResourceFactoryFactory)\nclass ResourceFactoryWrapper:\n\n def __init__(self, factory, checker, name):\n self.__factory = factory\n self.__checker = checker\n self.__name = name\n\n def __call__(self, request):\n resource = self.__factory(request)\n resource.__Security_checker__ = self.__checker\n resource.__name__ = self.__name\n return resource\n\n\ndef resource(_context, name, layer=IDefaultBrowserLayer,\n permission='zope.Public', factory=None,\n file=None, image=None, template=None):\n\n if permission == 'zope.Public':\n permission = CheckerPublic\n\n checker = NamesChecker(allowed_names, permission)\n\n too_many = bool(factory) + bool(file) + bool(image) + bool(template)\n if too_many > 1:\n raise ConfigurationError(\n \"Must use exactly one of factory or file or image or template\"\n \" attributes for resource directives\"\n )\n\n if image or template:\n import warnings\n warnings.warn_explicit(\n 'The \"template\" and \"image\" attributes of resource '\n 'directive are deprecated in favor of pluggable '\n 'file resource factories based on file extensions. '\n 'Use the \"file\" attribute instead.',\n DeprecationWarning,\n _context.info.file, _context.info.line)\n if image:\n file = image\n elif template:\n file = template\n\n _context.action(\n discriminator=('resource', name, IBrowserRequest, layer),\n callable=resourceHandler,\n args=(name, layer, checker, factory, file, _context.info),\n )\n\n\ndef resourceHandler(name, layer, checker, factory, file, context_info):\n if factory is not None:\n factory = ResourceFactoryWrapper(factory, checker, name)\n else:\n ext = os.path.splitext(os.path.normcase(file))[1][1:]\n factory_factory = queryUtility(IResourceFactoryFactory, ext,\n FileResourceFactory)\n factory = factory_factory(file, checker, name)\n handler('registerAdapter', factory, (layer,),\n Interface, name, context_info)\n\n\ndef resourceDirectory(_context, name, directory, layer=IDefaultBrowserLayer,\n permission='zope.Public'):\n if permission == 'zope.Public':\n permission = CheckerPublic\n\n checker = NamesChecker(allowed_names + ('__getitem__', 'get'),\n permission)\n\n if not os.path.isdir(directory):\n raise ConfigurationError(\n \"Directory %s does not exist\" % directory\n )\n\n factory = DirectoryResourceFactory(directory, checker, name)\n _context.action(\n discriminator=('resource', name, IBrowserRequest, layer),\n callable=handler,\n args=('registerAdapter',\n factory, (layer,), Interface, name, _context.info),\n )\n\n\ndef icon(_context, name, for_, file=None, resource=None,\n layer=IDefaultBrowserLayer, title=None,\n width=16, height=16):\n\n iname = for_.getName()\n\n if title is None:\n title = iname\n if title.startswith('I'):\n title = title[1:] # Remove leading 'I'\n\n if file is not None and resource is not None:\n raise ConfigurationError(\n \"Can't use more than one of file, and resource \"\n \"attributes for icon directives\"\n )\n elif file is not None:\n resource = '-'.join(for_.__module__.split('.'))\n resource = \"{}-{}-{}\".format(resource, iname, name)\n ext = os.path.splitext(file)[1]\n if ext:\n resource += ext\n\n # give this module another name, so we can use the \"resource\" directive\n # in it that won't conflict with our local variable with the same name.\n from zope.browserresource import metaconfigure\n metaconfigure.resource(_context, file=file, name=resource, layer=layer)\n elif resource is None:\n raise ConfigurationError(\n \"At least one of the file, and resource \"\n \"attributes for resource directives must be specified\"\n )\n\n vfactory = IconViewFactory(resource, title, width, height)\n\n _context.action(\n discriminator=('view', name, vfactory, layer),\n callable=handler,\n args=('registerAdapter',\n vfactory, (for_, layer), Interface, name, _context.info)\n )\n\n _context.action(\n discriminator=None,\n callable=provideInterface,\n args=(for_.__module__ + '.' + for_.getName(),\n for_)\n )\n\n\nclass I18nResource:\n\n type = IBrowserRequest\n default_allowed_attributes = '__call__'\n\n def __init__(self, _context, name=None, defaultLanguage='en',\n layer=IDefaultBrowserLayer, permission=None):\n self._context = _context\n self.name = name\n self.defaultLanguage = defaultLanguage\n self.layer = layer\n self.permission = permission\n self.__data = {}\n\n def translation(self, _context, language, file=None, image=None):\n\n if file is not None and image is not None:\n raise ConfigurationError(\n \"Can't use more than one of file, and image \"\n \"attributes for resource directives\"\n )\n elif file is None and image is None:\n raise ConfigurationError(\n \"At least one of the file, and image \"\n \"attributes for resource directives must be specified\"\n )\n\n if image is not None:\n import warnings\n warnings.warn_explicit(\n 'The \"image\" attribute of i18n-resource directive is '\n 'deprecated in favor of simple files. Use the \"file\" '\n 'attribute instead.',\n DeprecationWarning,\n _context.info.file, _context.info.line)\n file = image\n\n self.__data[language] = File(_context.path(file), self.name)\n\n def __call__(self, require=None):\n if self.name is None:\n return\n\n if self.defaultLanguage not in self.__data:\n raise ConfigurationError(\n \"A translation for the default language (%s) \"\n \"must be specified\" % self.defaultLanguage\n )\n\n permission = self.permission\n factory = I18nFileResourceFactory(self.__data, self.defaultLanguage)\n\n if permission:\n if require is None:\n require = {}\n\n if permission == 'zope.Public':\n permission = CheckerPublic\n\n if require:\n checker = Checker(require)\n\n factory = self._proxyFactory(factory, checker)\n\n self._context.action(\n discriminator=('i18n-resource', self.name, self.type, self.layer),\n callable=handler,\n args=('registerAdapter',\n factory, (self.layer,), Interface, self.name,\n self._context.info)\n )\n\n def _proxyFactory(self, factory, checker):\n def proxyView(request,\n factory=factory, checker=checker):\n resource = factory(request)\n\n # We need this in case the resource gets unwrapped and\n # needs to be rewrapped\n resource.__Security_checker__ = checker\n\n return Proxy(resource, checker)\n\n return proxyView\n","sub_path":"src/zope/browserresource/metaconfigure.py","file_name":"metaconfigure.py","file_ext":"py","file_size_in_byte":9241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"74748546","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2021/03/19 10:03 下午\r\n# @Author : lishouxian\r\n# @Email : gzlishouxian@gmail.com\r\n# @File : word2vec_textrnn.py\r\n# @Software: PyCharm\r\nfrom abc import ABC\r\nimport tensorflow as tf\r\nfrom config import classifier_config\r\n\r\n\r\nclass TextRNN(tf.keras.Model, ABC):\r\n \"\"\"\r\n TextRNN模型\r\n \"\"\"\r\n\r\n def __init__(self, num_classes, embedding_dim, vocab_size, embeddings_matrix=None):\r\n super(TextRNN, self).__init__()\r\n hidden_dim = classifier_config['hidden_dim']\r\n if classifier_config['embedding_method'] is '':\r\n self.embedding = tf.keras.layers.Embedding(vocab_size + 1, embedding_dim, mask_zero=True)\r\n else:\r\n self.embedding = tf.keras.layers.Embedding(vocab_size + 1, embedding_dim, weights=[embeddings_matrix],\r\n trainable=False)\r\n self.bilstm = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(hidden_dim, return_sequences=True))\r\n self.dropout = tf.keras.layers.Dropout(classifier_config['dropout_rate'], name='dropout')\r\n if classifier_config['use_attention']:\r\n self.attention_w = tf.Variable(tf.zeros([1, 2 * hidden_dim]))\r\n self.dense = tf.keras.layers.Dense(num_classes,\r\n activation='softmax',\r\n kernel_regularizer=tf.keras.regularizers.l2(0.1),\r\n bias_regularizer=tf.keras.regularizers.l2(0.1),\r\n name='dense')\r\n\r\n @tf.function\r\n def call(self, inputs, training=None):\r\n inputs = self.embedding(inputs)\r\n bilstm_outputs = self.bilstm(inputs)\r\n if classifier_config['use_attention']:\r\n output = tf.nn.tanh(bilstm_outputs)\r\n output = tf.matmul(output, self.attention_w, transpose_b=True)\r\n alpha = tf.nn.softmax(output, axis=1)\r\n outputs = alpha * bilstm_outputs\r\n bilstm_outputs = tf.nn.tanh(outputs)\r\n dropout_outputs = self.dropout(bilstm_outputs, training)\r\n outputs = tf.reduce_sum(dropout_outputs, axis=1)\r\n outputs = self.dense(outputs)\r\n return outputs\r\n","sub_path":"engines/models/TextRNN.py","file_name":"TextRNN.py","file_ext":"py","file_size_in_byte":2241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"204853241","text":"import requests\nimport threading\nimport time\nfrom collections import deque\nfrom Queue import Empty\nfrom solariat_bottle.daemons.exc import ApplicationError, FeedAPIError, \\\n InfrastructureError, UnauthorizedRequestError\nfrom solariat_bottle.settings import LOGGER, get_var\n\n\nclass RequestsClient(object):\n \"\"\"FeedAPI http client\"\"\"\n\n authtoken = None\n authtoken_expired = set()\n lock = threading.Lock()\n\n def __init__(self, options=None, sleep_timeout=30, user_agent='FeedApi'):\n self.headers = {}\n self.new_session()\n self.sleep_timeout = sleep_timeout\n self.user_agent = user_agent\n self.options = options\n self.headers = {'Content-Type': 'application/json',\n 'User-Agent': self.user_agent}\n\n def get_authtoken(self, expired=None):\n with self.lock:\n if expired is None:\n self.__class__.authtoken_expired = set()\n if self.__class__.authtoken:\n return self.__class__.authtoken\n return self.__gen_authtoken()\n\n if expired not in self.__class__.authtoken_expired:\n self.__class__.authtoken_expired.add(expired)\n return self.__gen_authtoken()\n return self.__class__.authtoken\n\n def __gen_authtoken(self):\n post_data = {\n 'username': self.options.username,\n 'password': self.options.password,\n }\n #url = '/api/v1.2/authtokens'\n url = '/api/%s/authenticate' % get_var('API_VERSION')\n\n while True:\n try:\n url_str = '%s%s' % (self.options.url, url)\n LOGGER.debug('Trying to authenticate using url: %s %s', url_str, self.options)\n response = self.post(\n url_str,\n json=post_data,\n headers={'Content-Type': 'application/json',\n 'User-Agent': self.user_agent})\n LOGGER.debug('Got auth token: %s' % response)\n except FeedAPIError as err:\n LOGGER.warning(err, exc_info=True)\n time.sleep(self.sleep_timeout)\n else:\n if not ('token' in response or 'item' in response):\n LOGGER.error(\"Bad auth response %s\", response)\n time.sleep(self.sleep_timeout)\n continue\n\n if 'item' in response:\n response = response['item']\n\n try:\n authtoken = response['token'].encode('utf-8')\n except KeyError:\n LOGGER.exception(response)\n time.sleep(self.sleep_timeout)\n else:\n self.__class__.authtoken = authtoken\n return authtoken\n\n def new_session(self):\n self.session = requests.Session()\n self.session.headers = self.headers\n\n def post(self, url, data=None, json=None, **kwargs):\n from requests.compat import json as json_lib\n\n try:\n response = self.session.request(\n 'POST', url, data=data, json=json,\n stream=False, # return connection to pool not waiting for response\n **kwargs)\n except requests.ConnectionError as e:\n self.new_session()\n raise InfrastructureError(unicode(e))\n\n if response.status_code == 401:\n raise UnauthorizedRequestError(response.text)\n\n if response.status_code != 200:\n raise InfrastructureError(u\"HTTP status: {} Response: {}\".format(\n response.status_code, response.text))\n\n try:\n data = response.json()\n except (TypeError, json_lib.JSONDecodeError):\n raise ApplicationError(u\"Bad response: {}\".format(response.text))\n else:\n if not data.get('ok'):\n raise ApplicationError(data.get('error', 'Unknown Error'))\n return data\n\n def api_posts(self, post_data=None, number_of_retries=None):\n api_url = '/api/%s/posts' % get_var('API_VERSION')\n\n payload = {\"serialized_to_json\": True,\n \"return_response\": False,\n \"post_object_data\": post_data,\n \"channel\": 'no',\n \"content\": 'no'}\n url = '%s%s' % (self.options.url, api_url)\n return self.post_authenticated(url, json=payload, number_of_retries=number_of_retries)\n\n def apply_token(self, url, post_data, authtoken):\n if not ('token' in url or (post_data and 'token' in post_data)):\n return '%s?token=%s' % (url, authtoken)\n return url\n\n def post_authenticated(self, url, json=None, number_of_retries=None):\n assert self.options and self.options.username and self.options.password\n\n authtoken = None\n expired = None\n\n while True:\n if not authtoken:\n authtoken = self.get_authtoken(expired)\n expired = None\n auth_url = self.apply_token(url, json, authtoken)\n try:\n return self.post(auth_url, json=json)\n except ApplicationError as err:\n if str(err) == 'Auth token %s is expired' % authtoken:\n LOGGER.info(err)\n expired = authtoken\n authtoken = None\n else:\n LOGGER.exception(err)\n break\n except UnauthorizedRequestError as err:\n LOGGER.warning(err, exc_info=True)\n expired = authtoken\n authtoken = None\n except InfrastructureError as err:\n LOGGER.exception(err)\n if number_of_retries is None:\n time.sleep(self.sleep_timeout)\n elif isinstance(number_of_retries, int) and number_of_retries > 0:\n number_of_retries -= 1\n else:\n break\n\n\nclass FeedApiThread(threading.Thread):\n \"\"\"FeedApi implementation with injectable http client,\n compatible with daemons.feedapi_old.FeedAPI\n \"\"\"\n _client = None\n\n @property\n def client(self):\n if self._client is None:\n _client = RequestsClient(self.options, self.sleep_timeout, self.user_agent)\n self._client = _client\n return self._client\n\n _counter = 0\n QUIT = object()\n\n def __init__(self, args=(), kwargs=None):\n\n self.__class__._counter += 1\n threading.Thread.__init__(self, name='FeedAPI-%d' % self._counter)\n if kwargs is None:\n kwargs = {}\n self.task_queue = args[0]\n self.options = args[1]\n self.user_agent = kwargs.get('User-Agent', self.name)\n self.sleep_timeout = 30\n self._busy = False\n self._elapsed_times = deque([], 25)\n self._stopped = threading.Event()\n\n def stop(self):\n self._stopped.set()\n\n def stopped(self):\n return self._stopped.isSet()\n\n def run(self):\n post_data = None\n start_time = time.time()\n wait_timeout = 0.1 if get_var('ON_TEST') else 30\n\n while not self.stopped():\n try:\n post_data = self.task_queue.get(block=True, timeout=wait_timeout)\n except Empty:\n self.stop()\n self._busy = False\n break\n start_time = time.time()\n if post_data is self.QUIT or post_data is None or post_data == 'QUIT':\n LOGGER.debug('received QUIT signal')\n self.task_queue.task_done()\n break\n\n self._busy = True\n self.client.api_posts(post_data)\n self.task_queue.task_done()\n self._elapsed_times.append(time.time() - start_time)\n self._busy = False\n\n @property\n def average_processing_time(self):\n size = len(self._elapsed_times)\n if size > 0:\n return sum(self._elapsed_times) / (size * 1.0)\n else:\n return -1\n\n def is_busy(self):\n return self._busy\n","sub_path":"daemons/feedapi.py","file_name":"feedapi.py","file_ext":"py","file_size_in_byte":8122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"185059222","text":"#!/usr/bin/env python\n# -*-coding:utf-8-*-\n\nimport urllib\nimport urllib.request\n\nlocal_path = r'/home/arthur/Desktop/wps/temp/'\nfile_name = r'aa/bb.jpg'\n\nr_file_path = local_path + file_name\nr_file_path = r_file_path.encode(\"utf-8\")\npic_url = \"http://www.jsxiaoguo.com/Content/Style/Default/Images/rd-a-hh-DefaultImg.jpg\"\n\nprint(r_file_path)\n\nurllib.request.urlretrieve(pic_url,r_file_path)\n","sub_path":"temp/t2.py","file_name":"t2.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"296793324","text":"import pandas as pd \n\npd.set_option('max_rows',5)\n\na = pd.DataFrame({'Yes':[50,21],'No':[131,2]})\nb = pd.DataFrame({'Bob':['I liked it.','It was awful.'],\n\t\t\t\t\t'Sue':['Pretty good','Bland.']},\n\t\t\t\t\tindex=['Product A','Product B'])\nc = pd.Series([1,2,3,4,5,])\nd = pd.Series([30,35,40],index=['2015 Sales','2016 Sales','2017 Sales'],name='Sales')\ne = pd.read_csv('mel_data.csv')\n#e.select_dtypes(include='int?',exclude='object') #剔除非数字列\ne1 = ['Rooms', 'Price', 'Distance', 'Postcode', 'Bedroom2', 'Bathroom', 'Car',\n 'Landsize', 'BuildingArea', 'YearBuilt', 'Lattitude', 'Longtitude',\n 'Propertycount']\nprint(e.groupby('Price').Price.count())\n\n\n\n\n\n\n\n\n\n\n#import sqlites\n#conn = sqlites.connect(\"file path .sqlite\")\n#fires = pd.read_sql_query(\"SELECT * FROM fires\",conn)\n\n#conn = sqlites3.connect('fires.sqlite')\n#fires.head(10).to_sql('fires',conn)\n\n\n\n\n'''\npd.DataFrame()\npd.Series()\ndata =pd.read_csv(,index_col=) 默认是数字,可选择是第几列\ndata.to_csv(\"data.csv\")\npd.read_excel(,sheet_name=) 导入EXCEL要加表名。 \ndata.to_excel('data.xlsx',sheet_name='Total Woman') 导出也需要表名\ndata.shape()\ndata.head()\ndata.columns()\ndata.loc[[],[]] 行列用字符表示\ndata.iloc[[],[]] 行列用数字表示 eg:.iloc[0:100,[0,5,9]]\n\t\t\t\t\t\t\t\t\tiloc[[0,3,4],[3,4,5]]\n\t\t\t\t\t\t\t\t\tiloc[3,4] 直接选定第几行\n\ndata.loc[(data.att == some)&(data.att1 >= some)] 选出条件匹配的两项\n & : 与 | : 或 ! : 非\n data.loc[data.col.isin(['att1','att2'])] 选出某col的att1,att2属性的数据\n data.loc[data.col.isnull()] isnull() notnull()\n 选出某col的is null (NaN)的数据 (或 not null)\n data['col1'] = 'some' 新建一个Series,都是some\n data.col.describe() 一个简单的描述,根据dtype的不同会有变化\n data.col.mean() 求平均数\n data.col.unique() 唯一值\n data.col.value_counts() 每个值出现的次数统计\n .map() .apply() 没太懂,31醒了看\n\n data.group('str1').str1.count() groupby() 将数据分组\n eg : data.group('str1').str2.min()\n agg \n'''","sub_path":"machine_learn/P_pandes.py","file_name":"P_pandes.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"615360001","text":"#\n# * A predicate is a Boolean combination of terms.\n# * @author Edward Sciore\n# *\n#\nfrom simpledb.record.Schema import Schema\n\n\nclass Predicate(object):\n\n #\n # * Create an empty predicate, corresponding to \"true\".\n #\n def __init__(self, *args):\n self.terms = []\n #\n # * Create a predicate containing a single term.\n # * @param t the term\n #\n if len(args) == 1:\n t = args[0]\n self.terms.append(t)\n\n #\n # * Modifies the predicate to be the conjunction of\n # * itself and the specified predicate.\n # * @param pred the other predicate\n #\n def conjoinWith(self, pred):\n for t in pred.terms:\n self.terms.append(t)\n\n #\n # * Returns true if the predicate evaluates to true\n # * with respect to the specified scan.\n # * @param s the scan\n # * @return true if the predicate is true in the scan\n #\n def isSatisfied(self, s):\n\n for t in self.terms:\n if not t.isSatisfied(s):\n return False\n return True\n\n #\n # * Calculate the extent to which selecting on the predicate\n # * reduces the number of records output by a query.\n # * For example if the reduction factor is 2, then the\n # * predicate cuts the size of the output in half.\n # * @param p the query's plan\n # * @return the integer reduction factor.\n #\n def reductionFactor(self, p):\n factor = 1\n for t in self.terms:\n factor *= t.reductionFactor(p)\n return factor\n\n #\n # * Return the subpredicate that applies to the specified schema.\n # * @param sch the schema\n # * @return the subpredicate applying to the schema\n #\n def selectSubPred(self, sch):\n result = Predicate()\n for t in self.terms:\n if t.appliesTo(sch):\n result.terms.append(t)\n if len(result.terms) == 0:\n return None\n else:\n return result\n\n #\n # * Return the subpredicate consisting of terms that apply\n # * to the union of the two specified schemas,\n # * but not to either schema separately.\n # * @param sch1 the first schema\n # * @param sch2 the second schema\n # * @return the subpredicate whose terms apply to the union of the two schemas but not either schema separately.\n #\n def joinSubPred(self, sch1, sch2):\n result = Predicate()\n newsch = Schema()\n newsch.addAll(sch1)\n newsch.addAll(sch2)\n for t in self.terms:\n if not t.appliesTo(sch1) and not t.appliesTo(sch2) and t.appliesTo(newsch):\n result.terms.append(t)\n if len(result.terms) == 0:\n return None\n else:\n return result\n\n #\n # * Determine if there is a term of the form \"F=c\"\n # * where F is the specified field and c is some constant.\n # * If so, the method returns that constant.\n # * If not, the method returns null.\n # * @param fldname the name of the field\n # * @return either the constant or null\n #\n def equatesWithConstant(self, fldname):\n for t in self.terms:\n c = t.equatesWithConstant(fldname)\n if c is not None:\n return c\n return None\n\n #\n # * Determine if there is a term of the form \"F1=F2\"\n # * where F1 is the specified field and F2 is another field.\n # * If so, the method returns the name of that field.\n # * If not, the method returns null.\n # * @param fldname the name of the field\n # * @return the name of the other field, or null\n #\n def equatesWithField(self, fldname):\n for t in self.terms:\n s = t.equatesWithField(fldname)\n if s is not None:\n return s\n return None\n\n def __str__(self):\n if len(self.terms) == 0:\n return \"\"\n result = self.terms[0].__str__()\n for i in range(1, len(self.terms)):\n result += \" and \" + self.terms[i].__str__()\n return result\n","sub_path":"simpledb/query/Predicate.py","file_name":"Predicate.py","file_ext":"py","file_size_in_byte":4160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"419482868","text":"from historia.utils import unique_id, random_country_colors\nfrom historia.country.models.province import Province\nfrom historia.log import LogAction\n\nclass Country(object):\n \"\"\"\n Top level of government.\n Representation of a Country.\n \"\"\"\n def __init__(self, manager, initial_hex, ancestor=None):\n super(self.__class__, self).__init__()\n self.manager = manager\n self.id = unique_id('co')\n\n # ancestor country (mother country)\n # The country this country was formed out of\n self.ancestor = ancestor\n\n # hexes this country controls\n # create a province\n capital = Province(self.manager, initial_hex, self, is_capital=True)\n self.provinces = [capital]\n self.capital = capital\n self.manager.logger.log(self, {\n 'capital': capital.id\n })\n self.manager.logger.log(self, {\n 'provinces': capital.id\n }, LogAction.extend)\n\n # Vassal countries under this country\n self.vassals = []\n self.is_vassal = False\n\n # tuple of Country, relation int\n self.relations = []\n\n map_color, border_color = random_country_colors()\n self.display = {\n 'map_color': map_color.hex,\n 'border_color': border_color.hex\n }\n\n self.name = ''\n\n def settle_hex(self, hex_inst):\n \"Settles a new hex, creating a province and returning it\"\n province = Province(self.manager, hex_inst, self, is_capital=False)\n self.provinces.append(province)\n return province\n\n @property\n def pops(self):\n pops = []\n for p in self.provinces:\n pops.extend(p.pops)\n return pops\n\n def __repr__(self):\n return \"\".format(self.name, self.id)\n\n def __eq__(self, other):\n return self.id == other.id\n\n def __key__(self):\n return self.id\n\n def __hash__(self):\n return hash(self.__key__())\n\n\n def export(self):\n \"Export country data\"\n return {\n 'display': self.display,\n 'name': self.name,\n 'provinces': [p.id for p in self.provinces]\n }\n","sub_path":"historia/country/models/country.py","file_name":"country.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"411923942","text":"import os\nimport json\n\nimport oss2\n\nfrom oss_command import config\n\n\ndef load_config():\n config_file = config.config_file\n cfg = dict()\n if not os.path.exists(config_file):\n key = os.environ.get(\"oss_command_key\", None)\n secret = os.environ.get(\"oss_command_secret\", None)\n if not key and not secret:\n raise Exception(\"Run oss_command config first\")\n cfg[\"key\"] = key\n cfg[\"secret\"] = secret\n return cfg\n with open(config_file, \"r\") as f:\n cfg = json.load(f)\n return cfg\n\n\ndef get_bucket(endpoint):\n cfg = load_config()\n auth = oss2.Auth(cfg[\"key\"], cfg[\"secret\"])\n bucket_name, endpoint = endpoint.split(\".\", 1)\n bucket = oss2.Bucket(auth, endpoint, bucket_name)\n return bucket\n","sub_path":"oss_command/commands/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"285689939","text":"count=0\ndef hanoi(n,src,dst,mid):\n global count\n if n == 1:\n print(\"{}号圆盘:{}->{}\".format(1,src,dst))\n count += 1\n else:\n hanoi(n-1,src,mid,dst)\n print(\"{}号圆盘:{}->{}\".format(n,src,dst))\n count+=1\n hanoi(n-1,mid,dst,src)\nh = eval(input(\"请输入圆盘数量:\"))\nhanoi(h,\"A\",\"C\",\"B\")\nprint(\"一共搬运了{}次\".format(count))","sub_path":"PythonProgramming/class5/example5.3.py","file_name":"example5.3.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"557364134","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------\n\nfrom azure.identity import DefaultAzureCredential\nfrom azure.mgmt.iothub import IotHubClient\n\n\"\"\"\n# PREREQUISITES\n pip install azure-identity\n pip install azure-mgmt-iothub\n# USAGE\n python iothub_create_or_update.py\n\n Before run the sample, please set the values of the client ID, tenant ID and client secret\n of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,\n AZURE_CLIENT_SECRET. For more info about how to get the value, please see:\n https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal\n\"\"\"\n\n\ndef main():\n client = IotHubClient(\n credential=DefaultAzureCredential(),\n subscription_id=\"91d12660-3dec-467a-be2a-213b5544ddc0\",\n )\n\n response = client.iot_hub_resource.begin_create_or_update(\n resource_group_name=\"myResourceGroup\",\n resource_name=\"testHub\",\n iot_hub_description={\n \"etag\": \"AAAAAAFD6M4=\",\n \"location\": \"centraluseuap\",\n \"properties\": {\n \"cloudToDevice\": {\n \"defaultTtlAsIso8601\": \"PT1H\",\n \"feedback\": {\"lockDurationAsIso8601\": \"PT1M\", \"maxDeliveryCount\": 10, \"ttlAsIso8601\": \"PT1H\"},\n \"maxDeliveryCount\": 10,\n },\n \"enableDataResidency\": False,\n \"enableFileUploadNotifications\": False,\n \"eventHubEndpoints\": {\"events\": {\"partitionCount\": 2, \"retentionTimeInDays\": 1}},\n \"features\": \"None\",\n \"ipFilterRules\": [],\n \"messagingEndpoints\": {\n \"fileNotifications\": {\n \"lockDurationAsIso8601\": \"PT1M\",\n \"maxDeliveryCount\": 10,\n \"ttlAsIso8601\": \"PT1H\",\n }\n },\n \"minTlsVersion\": \"1.2\",\n \"networkRuleSets\": {\n \"applyToBuiltInEventHubEndpoint\": True,\n \"defaultAction\": \"Deny\",\n \"ipRules\": [\n {\"action\": \"Allow\", \"filterName\": \"rule1\", \"ipMask\": \"131.117.159.53\"},\n {\"action\": \"Allow\", \"filterName\": \"rule2\", \"ipMask\": \"157.55.59.128/25\"},\n ],\n },\n \"routing\": {\n \"endpoints\": {\n \"eventHubs\": [],\n \"serviceBusQueues\": [],\n \"serviceBusTopics\": [],\n \"storageContainers\": [],\n },\n \"fallbackRoute\": {\n \"condition\": \"true\",\n \"endpointNames\": [\"events\"],\n \"isEnabled\": True,\n \"name\": \"$fallback\",\n \"source\": \"DeviceMessages\",\n },\n \"routes\": [],\n },\n \"storageEndpoints\": {\n \"$default\": {\"connectionString\": \"\", \"containerName\": \"\", \"sasTtlAsIso8601\": \"PT1H\"}\n },\n },\n \"sku\": {\"capacity\": 1, \"name\": \"S1\"},\n \"tags\": {},\n },\n ).result()\n print(response)\n\n\n# x-ms-original-file: specification/iothub/resource-manager/Microsoft.Devices/stable/2021-07-02/examples/iothub_createOrUpdate.json\nif __name__ == \"__main__\":\n main()\n","sub_path":"sdk/iothub/azure-mgmt-iothub/generated_samples/iothub_create_or_update.py","file_name":"iothub_create_or_update.py","file_ext":"py","file_size_in_byte":3854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"88173872","text":"n1=int(input('Um valor:'))\r\nn2=int(input('Outro valor:'))\r\n#print('A soma vale {}'.format(n1+n2))\r\ns=n1+n2\r\nm=n1*n2\r\nd=n1/n2\r\ndi=n1/n2\r\ne=n1**n2\r\nprint('A soma é {}, o produto é {} \\n e a divisão é {:.3f}' .format(s, m, d), end=' ')\r\nprint('Divisão inteira {} \\n e potência {}'.format(di, e))\r\n","sub_path":"testes_aulas/aula07b.py","file_name":"aula07b.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"313761988","text":"from flask import url_for\nfrom flask.ext.testing import TestCase\n\nfrom webapp import app, db\nfrom webapp.models import Monkey, Friendship, BestFriend\nfrom config import HEROKU_POSTGRESQL_CHARCOAL_URL\n\n\ndef setup_module():\n app.config['SQLALCHEMY_DATABASE_URI'] = HEROKU_POSTGRESQL_CHARCOAL_URL\n app.config['WTF_CSRF_ENABLED'] = False\n db.create_all()\n\n\ndef teardown_module():\n db.session.remove()\n db.drop_all()\n\n\nclass TestProfilePage(TestCase):\n def create_app(self):\n return app\n\n def test_profile_page_is_working(self):\n monkey = Monkey(name='Sajjad', age='21', email='Sajjad@nono.com')\n db.session.add(monkey)\n db.session.commit()\n response = self.client.get(url_for('profile',\n monkey_id=monkey.monkey_id))\n self.assert_200(response)\n\n def test_edit_info_inside_profile_page_valid_input_works(self):\n monkey = Monkey(name='Sajjad', age='21', email='Sajjad@nono.com')\n db.session.add(monkey)\n db.session.commit()\n response = self.client.get(url_for('profile',\n monkey_id=monkey.monkey_id))\n assert b'Sajjad@nono.com' in response.data\n\n data = {\n 'name': 'Sajjad',\n 'age': '21',\n 'email': 'Sajjad@gmail.com'\n }\n response = self.client.post(url_for('profile',\n monkey_id=monkey.monkey_id),\n data=data,\n follow_redirects=True)\n self.assert_200(response)\n assert b'Sajjad@gmail.com' in response.data\n\n def test_best_friend_status_not_yet_and_name_of_bf_works(self):\n monkey = Monkey(name='Sajjad', age='21', email='Sajjad@nono.com')\n db.session.add(monkey)\n db.session.commit()\n response = self.client.get(url_for('profile',\n monkey_id=monkey.monkey_id))\n assert b'Best friend: Not yet' in response.data\n\n bf = Monkey(name='Alice', age='100', email='Alice@nono.com')\n db.session.add(bf)\n db.session.commit()\n best_friend = BestFriend(monkey_id=monkey.monkey_id,\n best_friend_id=bf.monkey_id)\n db.session.add(best_friend)\n db.session.commit()\n response = self.client.get(url_for('profile',\n monkey_id=monkey.monkey_id))\n assert b'Best friend: Alice' in response.data\n\n def test_terminate_monkey_works(self):\n monkey = Monkey(name='About2Terminate', age='21', email='ATT@no.com')\n monkey2 = Monkey(name='PoorFriend', age='21', email='ATT@no.com')\n monkey3 = Monkey(name='EvenPoorer', age='21', email='ATT@no.com')\n db.session.add(monkey)\n db.session.add(monkey2)\n db.session.add(monkey3)\n db.session.commit()\n friendship = Friendship(monkey_id=monkey.monkey_id,\n friend_id=monkey2.monkey_id)\n friendship_reciprocal = Friendship(monkey_id=monkey2.monkey_id,\n friend_id=monkey.monkey_id)\n best_friend = BestFriend(monkey_id=monkey.monkey_id,\n best_friend_id=monkey3.monkey_id)\n db.session.add(friendship)\n db.session.add(best_friend)\n db.session.commit()\n response = self.client.get(url_for('terminate',\n monkey_id=monkey.monkey_id),\n follow_redirects=True)\n self.assert_200(response)\n assert b'About2Terminate was terminated' in response.data\n assert monkey not in Monkey.query.all()\n assert friendship not in Friendship.query.all()\n assert best_friend not in BestFriend.query.all()\n\n def test_edit_info_a_non_existent_monkey_gets_handled(self):\n data = {\n 'name': 'Sajjad',\n 'age': '21',\n 'email': 'Sajjad@gmail.com'\n }\n response = self.client.post(url_for('profile',\n monkey_id=999999999),\n data=data)\n self.assert_200(response)\n assert b'500: Internal Server Error' in response.data\n","sub_path":"tests/test_profile_page.py","file_name":"test_profile_page.py","file_ext":"py","file_size_in_byte":4326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"389845667","text":"'''\nIn this exercise, you will practice both File I/O as well as using Exceptions\nin a real-world scenario.\n\nYou have a folder containing three text files of books from Project Gutenberg:\n- war_and_peace.txt\n- pride_and_prejudice.txt\n- crime_and_punishment.txt\n\n1) Open war_and_peace.txt, read the whole file content and store it in a variable\n\n2) Open crime_and_punishment.txt and overwrite the whole content with an empty string\n\n3) Loop over all three files and print out only the first character each. Your program\n should NEVER terminate with a Traceback.\n\n a) Which Exception can you expect to encounter? Why?\n\n b) How do you catch it to avoid the program from terminating with a Traceback?\n\n\nBONUS CHALLENGE: write a custom Exception that inherits from Exception and raise it if the\nfirst 100 characters of any of the files contain the string \"Prince\".\n\n'''\n\nimport os\npath = (\"/Users/ridinhome/Documents/CodingNomads/labs/09_exceptions/books/\")\nwar_and_peace = []\ncrime_and_punishment = (\"\")\nfirst_letter = {}\nos.chdir(path)\nfile_list = [\"war_and_peace.txt\",\"crime_and_punishment.txt\",\"pride_and_prejudice.txt\"]\n\n###,\n\n# with open(\"war_and_peace.txt\",\"r\") as tolstoy:\n# for item in tolstoy:\n# war_and_peace.append(item)\n#\n# print (war_and_peace)\n\n# with open(\"crime_and_punishment.txt\",\"w\") as dostoyevsky:\n# dostoyevsky.write(crime_and_punishment)\n\nfor item in file_list:\n with open(item,\"r\") as book:\n lines = book.readline()\n first_letter[item] = lines[0][0]\n\nfor value in first_letter.values():\n print (value)\n\n\n\n\n\n","sub_path":"09_exceptions/09_04_files_exceptions.py","file_name":"09_04_files_exceptions.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"411221294","text":"from time import sleep\r\nprint('\\033[1;36m-=-\\033[m' * 20)\r\nprint('\\033[1;36m *-*-*-*-* CLASSE CACHORRO! *-*-*-*-*\\033[m')\r\nprint('\\033[1;36m-=-\\033[m' * 20)\r\nsleep(2)\r\n\r\nclass Cachorro:\r\n def __init__(self, nome, raca, idade, peso):\r\n self.nome = nome\r\n self.raca = raca\r\n self.idade = idade\r\n self.peso = peso\r\n\r\n def adora_comer(self):\r\n self.peso = self.peso + 0.5\r\n\r\n\r\nc1 = Cachorro(nome = 'Charlotte', raca = 'S.R.D', idade = 7, peso = 9.7)\r\nprint('Oi, esta é {}, um cão da raça: {}. \\nSua idade é {} anos e de tanto comer pesa {}kg! '.format(c1.nome, c1.raca, c1.idade, c1.peso))\r\nsleep(5)\r\nprint('\\n{} adora comer.... Quer ver??'.format(c1.nome))\r\nsleep(3)\r\nprint('EI!! Psiu! Vem!!')\r\nsleep(2)\r\nprint('{}!!!'.format(c1.nome))\r\nsleep(3)\r\nprint('MmMmM... {} está comendo...'.format(c1.nome))\r\nsleep(5)\r\nc1.adora_comer()\r\nprint('Uau!!! Agora {} está pesando {}kg!'.format(c1.nome, c1.peso))","sub_path":"Charlotte_SamuelMachado.py","file_name":"Charlotte_SamuelMachado.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"133254494","text":"from business_logic import *\n\ndef main():\n\n print('GUIDE MANUAL\\n---------------------------')\n print('PLEASE SELECT NUMBER BETWEEN 1 - 6 TO RETRIEVE MESSAGE FOR GUEST')\n print('AND NUMBER BETWEEN 1 - 5 TO WELCOME AND ASSIGN GUEST TO HOTEL\\n')\n while True:\n try:\n guest_id = user_input_guest()\n instance_of_guest = get_guest_data(guest_id)\n hotel_id = user_input_hotel()\n instance_of_hotel = get_hotel_data(hotel_id)\n\n #required message\n print(f'{instance_of_guest.greeting()} {instance_of_hotel.get_hotel_name()} {instance_of_guest.get_room()}')\n except:\n print('Invalid operation!')\n\nif __name__ == \"__main__\":\n main()\n \n\n","sub_path":"main_menu.py","file_name":"main_menu.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"22026937","text":"'''\nAuthor: Brian Loi\nDate: September 14, 2017\nClass: ISTA 130\nSection Leader: Sebastion Andrews\n\nDescription:\nThis program uses turtle graphics to draw a castle.\n'''\n\nimport turtle\n\ndef house(a_turtle, size):\n '''\n Draw a simple house of the given size.\n\n Parameters:\n a_turtle: a turtle that is used to draw the house\n size: an int that determines the size of the house\n\n Returns: None\n '''\n polygon(a_turtle, 4, size)\n a_turtle.left(90)\n a_turtle.forward(size)\n a_turtle.right(90)\n polygon(a_turtle, 3, size)\n a_turtle.left(90)\n a_turtle.backward(size)\n a_turtle.right(90)\n return None\n\ndef castle(a_turtle, size):\n '''\n Draw a simple castle of the given size.\n\n Parameters:\n a_turtle: a turtle that is used to draw the castle\n size: an int that determines the size of the castle\n\n Returns: None\n '''\n polygon(a_turtle, 4, size)\n a_turtle.penup()\n a_turtle.backward(size * 0.25)\n a_turtle.left(90)\n a_turtle.forward(size)\n a_turtle.right(90)\n a_turtle.pendown()\n house(a_turtle, size * 0.5)\n a_turtle.forward(size * 0.5)\n house(a_turtle, size * 0.5)\n a_turtle.forward(size * 0.5)\n house(a_turtle, size * 0.5)\n a_turtle.penup()\n a_turtle.backward(size * 0.75)\n a_turtle.left(90)\n a_turtle.backward(size)\n a_turtle.right(90)\n a_turtle.pendown()\n return None\n\ndef polygon(some_turtle, sides, length):\n '''\n Draws a regular polygon using a turtle depending on the specified number\n of sides and length of the sides.\n\n Parameters:\n some_turtle: a turtle used to draw the polygon\n sides: an int that determines the number of sides in the polgyon\n length: an int that determines the length of the sides in the polygon\n\n Returns: None\n '''\n for i in range(sides):\n some_turtle.pendown()\n some_turtle.forward(length)\n some_turtle.left(360/sides)\n some_turtle.penup()\n return None\n\n#==============================================\ndef main():\n '''\n Draws a castle\n '''\n\n #Creates a turtle object to draw the castle. Sets the turtle's settings.\n yertle = turtle.Turtle()\n yertle.speed(0)\n yertle.penup()\n yertle.backward(200)\n yertle.pendown()\n yertle.pencolor('dark slate grey')\n yertle.pensize(5)\n\n #Repeatedly draws simple castles 4 times to create a larger castle drawing\n for i in range (4):\n castle(yertle, 100)\n yertle.forward(100)\n yertle.right(180)\n castle(yertle, 100)\n yertle.right(180)\n\n yertle.getscreen().exitonclick() #Keeps the turtle graphics window open\n\nif __name__ == '__main__':\n main()\n","sub_path":"ISTA130/hw2/castles.py","file_name":"castles.py","file_ext":"py","file_size_in_byte":2669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"242519380","text":"\"\"\"\r\n===========\r\nGroup analysis file\r\n===========\r\nScript for group level analyses.\r\n(Source reconstruction for all subjects and statistical tests)\r\n\"\"\"\r\n\r\nimport mne\r\nimport os\r\nimport numpy as np\r\nimport open_files as op \r\nfrom mne.channels import find_ch_adjacency\r\n\r\nimport source_reconstruction as source\r\nfrom tools import (add_to_array, zscore, save_results, \r\n check_list_cond, get_epochs_in_condition, \r\n sujets_exclusion_psds)\r\nfrom open_files import recover_epochs_sonetaa\r\nfrom spectral_density import (power_spectral_density_multitapper, power_spectral_density_welch)\r\nfrom morphing import (morph_surface_source_space, morph_volume_source_space, \r\n compute_morph_surface, compute_morph_volume)\r\nfrom statistical_tests import (cluster_permutation_test_1sample, \r\n cluster_permutation_test_2sample) \r\nfrom parameters import (subjects_dir)\r\n\r\n#global exclus_file\r\n#global subjects_dir\r\n\r\n################################################################################################################\r\n#### SOURCE RECONSTRUCTION\r\n################################################################################################################\r\n\r\n\r\ndef source_reconstruction_group(path_to_eeg_group, path_results_source_rec, list_subjects, \r\n method, lambda2, coreg, plot, redo):\r\n \"\"\"Reconstruct sources for all EEG subjects. \r\n Automatically uses subject MRI or a template MRI.\r\n \r\n Parameters\r\n ----------\r\n liste_participants : list\r\n list of list of subjects path to eeg and path to mri.\r\n method : str\r\n method for source reconstruction\r\n \"\"\"\r\n\r\n for (path_or_name_eeg, path_to_mri) in list_subjects:\r\n epochs_HDC = recover_epochs_sonetaa(path_or_name_eeg, 'HDC', path_to_mri, True)\r\n epochs_RS = recover_epochs_sonetaa(path_or_name_eeg, 'RS', path_to_mri, True)\r\n\r\n #set folders to save results of source reconstruction\r\n if os.path.isdir(path_or_name_eeg):\r\n #save results in subject folder\r\n folder_to_save_HDC = path_or_name_eeg + '/HDC'\r\n folder_to_save_RS = path_or_name_eeg + '/RS'\r\n else:\r\n #create a subject folder to save results\r\n path_results_subject = os.path.join(path_results_source_rec, path_or_name_eeg)\r\n if not os.path.exists(path_results_subject):\r\n os.mkdir(path_results_subject)\r\n folder_to_save_HDC = os.path.join(path_results_subject, 'HDC')\r\n folder_to_save_RS = os.path.join(path_results_subject, 'RS')\r\n #source rec for RS\r\n _, noise_cov = source.source_reconstruction(epochs_RS, method, lambda2, folder_to_save_RS, \r\n path_to_mri = path_to_mri, coreg = coreg, \r\n plot = plot, redo = redo)\r\n #source rec for HDC, using RS noise cov matrix\r\n _, _ = source.source_reconstruction(epochs_HDC, method, lambda2, folder_to_save_HDC,\r\n path_to_mri = path_to_mri, coreg = coreg, \r\n plot = plot, redo = redo, noise_cov = noise_cov)\r\n \r\n print('Source reconstruction computed for all subjects with method ' + method + '!')\r\n\r\n################################################################################################################\r\n#### POWER ANALYSIS\r\n################################################################################################################\r\n\r\ndef set_function_names(level):\r\n if level == \"cortex\":\r\n compute_morph, morph_source_space = compute_morph_surface, morph_surface_source_space\r\n elif level in [\"cereb\", \"cerebellum\"]:\r\n compute_morph, morph_source_space = compute_morph_volume, morph_volume_source_space \r\n \r\n return compute_morph, morph_source_space\r\n\r\ndef power_analysis_sensor_groups_psds(liste_ASD, liste_TD, path_to_figures, \r\n liste_cond, frequency):\r\n \"\"\"PSD analyses at sensor level between TD and ASD, between 2 conditions\r\n Save only the PSDs for later statistical analyses\r\n \"\"\"\r\n liste_cond, cond1 = check_list_cond(liste_cond)\r\n mean_psd_asd1, mean_psd_asd2 = None, None\r\n mean_psd_td1, mean_psd_td2 = None, None\r\n std_psd_asd1, std_psd_asd2 = None, None\r\n std_psd_td1, std_psd_td2 = None, None\r\n\r\n for i, liste in enumerate([liste_ASD, liste_TD]):\r\n for (path_or_name_eeg, path_to_mri) in liste:\r\n epochs_RS = recover_epochs_sonetaa(path_or_name_eeg, 'RS', path_to_mri)\r\n epochs_HDC = recover_epochs_sonetaa(path_or_name_eeg, 'HDC', path_to_mri)\r\n \r\n #compute PSD in cond 1 and cond 2\r\n for cond in liste_cond:\r\n epochs_condition = get_epochs_in_condition(cond, epochs_HDC, epochs_RS)\r\n psd, _, _ = power_spectral_density_welch(epochs_condition, frequency)\r\n \r\n #psd : variable nb of epochs (1) x n sensors x frequencies\r\n # average over frequencies n epochs x n sensors\r\n psd = np.mean(psd, axis = 2)\r\n moy_epochs = np.mean(psd, axis =0) #shape n sensors\r\n moy_epochs = np.reshape(moy_epochs, (1, moy_epochs.shape[0]))\r\n std_epochs = np.std(psd, axis = 0)\r\n std_epochs = np.reshape(std_epochs, (1, std_epochs.shape[0]))\r\n\r\n if cond is cond1 and i == 0:\r\n mean_psd_asd1 = add_to_array(mean_psd_asd1, moy_epochs)\r\n std_psd_asd1 = add_to_array(std_psd_asd1, std_epochs)\r\n elif cond is cond1 and i != 0:\r\n mean_psd_td1 = add_to_array(mean_psd_td1, moy_epochs)\r\n std_psd_td1 = add_to_array(std_psd_td1, std_epochs)\r\n elif cond is not cond1 and i == 0:\r\n mean_psd_asd2 = add_to_array(mean_psd_asd2, moy_epochs)\r\n std_psd_asd2 = add_to_array(std_psd_asd2, std_epochs)\r\n elif cond is not cond1 and i != 0:\r\n mean_psd_td2 = add_to_array(mean_psd_td2, moy_epochs)\r\n std_psd_td2 = add_to_array(std_psd_td2, std_epochs)\r\n\r\n save_results(\"PSD_sensors\", liste_cond, frequency, liste_TD+liste_ASD, \r\n path_to_figures = path_to_figures, Mtd1 = mean_psd_td1, Mtd2 = mean_psd_td2, \r\n Masd1 = mean_psd_asd1, Masd2 = mean_psd_asd2, \r\n Std1 = std_psd_td1, Std2= std_psd_td2,\r\n Sasd1 = std_psd_asd1, Sasd2 = std_psd_asd2)\r\n\r\ndef power_analysis_source_groups_psds(path_results_subjects, liste_ASD, liste_TD, path_to_figures, \r\n method, lambda2, subject_to, area, liste_cond,\r\n frequency, tfce = True, n_epochs = None):\r\n \"\"\" \r\n PSD analyses at source level between TD and ASD, between 2 conditions\r\n Write the Power Spectral densities for later statistical analyses\r\n\r\n path_results_subjects: path to where the subjects informations are stored\r\n liste_ASD: list of ASD subjects\r\n liste_TD: list of TD subjects\r\n path_to_figures: path to the folder where the figures and files are saved\r\n method: method for source reconstruction (MNE or eLORETA)\r\n lambda2: parameter to solve inverse problem\r\n subject_to: name of the subject to morph the subjects PSDs to a common source space (used fsaverage)\r\n area: cerebellum or cortex\r\n liste_cond: list of conditions of interest (HDC / RS)\r\n frequency: frequency of interest (alpha, theta...)\r\n \"\"\"\r\n liste_cond, cond1 = check_list_cond(liste_cond)\r\n compute_morph, morph_source_space = set_function_names(area)\r\n\r\n #compute zscore for each participant between HDC and RS\r\n mean_psd_asd1, mean_psd_asd2 = None, None\r\n mean_psd_td1, mean_psd_td2 = None, None\r\n std_psd_asd1, std_psd_asd2 = None, None\r\n std_psd_td1, std_psd_td2 = None, None\r\n\r\n for i, liste in enumerate([liste_ASD, liste_TD]):\r\n for (path_or_name_eeg, path_to_mri) in liste:\r\n epochs_RS = recover_epochs_sonetaa(path_or_name_eeg, 'RS', path_to_mri)\r\n epochs_HDC = recover_epochs_sonetaa(path_or_name_eeg, 'HDC', path_to_mri) \r\n \r\n #recover inverse operator and compute morph matrix for later morphing\r\n inverse_op = op.recover_inverse_op(path_or_name_eeg, 'RS', method, path_results_subjects)\r\n if i == 0:\r\n morph, src = compute_morph(subjects_dir, inverse_op, subject_to)\r\n \r\n for cond in liste_cond:\r\n #recover inverse operator\r\n if cond in [\"RS\", \"eo\", \"eyeo\", \"ec\", \"eyec\"]:\r\n inverse_op = op.recover_inverse_op(path_or_name_eeg, 'RS', method, path_results_subjects)\r\n else:\r\n inverse_op = op.recover_inverse_op(path_or_name_eeg, 'HDC', method, path_results_subjects)\r\n epochs_condition = get_epochs_in_condition(cond, epochs_HDC, epochs_RS)\r\n #compute PSD : a generator of PSDs over epochs (psd = sources x freq)\r\n psd = power_spectral_density_multitapper(epochs_condition[:n_epochs], inverse_op, \r\n method, lambda2, frequency, return_type='stc')\r\n \r\n #compute the mean and std of the subject PSDs over epochs\r\n array_epochs = None\r\n for (_, stc) in enumerate(psd):\r\n #transport PSD to common source space\r\n psd_morphed = stc.mean()\r\n psd_morphed = morph_source_space(morph, src, psd_morphed, subjects_dir, \r\n inverse_op, subject_to, path_to_figures)\r\n array_epochs = add_to_array(array_epochs, psd_morphed.data, axis = 1)\r\n\r\n moy_epochs = np.mean(array_epochs, axis = 1)\r\n moy_epochs = np.expand_dims(moy_epochs, axis = 0)\r\n std_epochs = np.std(array_epochs, axis = 1)\r\n std_epochs = np.expand_dims(std_epochs, axis = 0)\r\n \r\n #add the mean and std to the relevant list \r\n if cond is cond1 and i == 0:\r\n mean_psd_asd1 = add_to_array(mean_psd_asd1, moy_epochs)\r\n std_psd_asd1 = add_to_array(std_psd_asd1, std_epochs)\r\n elif cond is cond1 and i != 0:\r\n mean_psd_td1 = add_to_array(mean_psd_td1, moy_epochs)\r\n std_psd_td1 = add_to_array(std_psd_td1, std_epochs)\r\n elif cond is not cond1 and i == 0:\r\n mean_psd_asd2 = add_to_array(mean_psd_asd2, moy_epochs)\r\n std_psd_asd2 = add_to_array(std_psd_asd2, std_epochs)\r\n elif cond is not cond1 and i != 0:\r\n mean_psd_td2 = add_to_array(mean_psd_td2, moy_epochs)\r\n std_psd_td2 = add_to_array(std_psd_td2, std_epochs)\r\n\r\n save_results(\"PSD_\"+area, liste_cond, frequency, liste_TD + liste_ASD, tfce, path_to_figures, \r\n method, Mtd1 = mean_psd_td1, Mtd2 = mean_psd_td2, \r\n Masd1 = mean_psd_asd1, Masd2 = mean_psd_asd2, \r\n Std1 = std_psd_td1, Std2= std_psd_td2,\r\n Sasd1 = std_psd_asd1, Sasd2 = std_psd_asd2)\r\n \r\ndef power_analysis_statistics(path_results_subjects, psd_file, path_to_figures, list_subjects,\r\n liste_TD, liste_ASD, method, subject_to, level, liste_cond,\r\n tfce = True, compare = \"all\", score = \"zscore\", frequency = \"theta\"):\r\n \"\"\"\r\n Open an array of PSDs and compute statistics (inter and/or intra group)\r\n \"\"\"\r\n #exclusions\r\n indices_td, indices_asd = sujets_exclusion_psds(path_to_figures)\r\n indices_asd, indices_td = np.asarray(indices_asd), np.asarray(indices_td)\r\n\r\n liste_cond, _ = check_list_cond(liste_cond)\r\n (path_or_name_eeg, path_to_mri) = list_subjects[0] \r\n epochs_RS = recover_epochs_sonetaa(path_or_name_eeg, 'RS', path_to_mri) \r\n\r\n if level not in [\"sensor\", \"sensors\"]:\r\n inverse_op = op.recover_inverse_op(path_or_name_eeg, 'RS', method, path_results_subjects)\r\n compute_morph, _ = set_function_names(level)\r\n _, src = compute_morph(subjects_dir, inverse_op, subject_to)\r\n\r\n parent_folder = os.path.dirname(psd_file)\r\n\r\n # Load dara\r\n npzfile = np.load(psd_file, allow_pickle = True)\r\n\r\n # Exclusions\r\n Mtd1 = np.delete(npzfile[\"Mtd1\"], obj = indices_td, axis = 0)\r\n Mtd2 = np.delete(npzfile[\"Mtd2\"], obj = indices_td, axis = 0)\r\n Masd1 = np.delete(npzfile[\"Masd1\"], obj = indices_asd, axis = 0)\r\n Masd2 = np.delete(npzfile[\"Masd2\"], obj = indices_asd, axis = 0)\r\n Std1 = np.delete(npzfile[\"Std1\"], obj = indices_td, axis = 0)\r\n Sasd1 = np.delete(npzfile[\"Sasd1\"], obj = indices_asd, axis = 0)\r\n\r\n #compute z score\r\n score_td = zscore(Mtd2, Mtd1, Std1)\r\n score_asd = zscore(Masd2, Masd1, Sasd1)\r\n \r\n if level in [\"sensor\", \"sensors\"]:\r\n connectivity, _ = find_ch_adjacency(epochs_RS.info, ch_type='eeg')\r\n else:\r\n connectivity = mne.spatial_src_connectivity(src)\r\n if compare == \"all\":\r\n clu = cluster_permutation_test_1sample(score_td, connectivity, tfce = tfce)\r\n save_results(level, liste_cond, frequency, liste_TD, tfce, parent_folder, \r\n method, score = score, Xtd=score_td, T_obs = clu[0], clusters = clu[1],\r\n clusters_pvalues = clu[2], participants = \"td\")\r\n \r\n clu = cluster_permutation_test_1sample(score_asd, connectivity, tfce = tfce)\r\n save_results(level, liste_cond, frequency, liste_ASD, tfce, parent_folder, method, \r\n score = score, Xasd=score_asd, T_obs = clu[0], clusters = clu[1],\r\n clusters_pvalues = clu[2], participants = \"asd\")\r\n\r\n clu = cluster_permutation_test_2sample(score_asd, score_td, connectivity, tfce = tfce)\r\n save_results(level, liste_cond, frequency, liste_ASD + liste_TD, tfce, parent_folder, method, \r\n score = score, Xasd=score_asd, Xtd=score_td, T_obs = clu[0], clusters = clu[1],\r\n clusters_pvalues = clu[2])\r\n\r\n","sub_path":"HDC/EEG/analyses_groupes.py","file_name":"analyses_groupes.py","file_ext":"py","file_size_in_byte":14494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"319534008","text":"# DO *NOT* WRITE YOUR NAME TO MAINTAIN ANONYMITY FOR PLAGIARISM DETECTION\n#\n# Call multibase a nonempty finite sequence of strictly positive\n# integers (a_n, ..., a_0) all at most equal to 10.\n# A positive integer is said to be a valid representation in the\n# multibase if it is of the form x_k...x_0 with k <= n and for all\n# i in {0,...,k}, x_i < a_i. Its representation in base 10 is defined as\n# x_0 + x_1*a_0 + x_2*a_0*a_1 + ... + x_k*a_0*a_1*...*a_{k-1}.\n#\n# Determines the largest integer with a valid representation\n# in the multibase, and converts representations between base\n# 10 and the multibase.\n#\n# For instance, consider the multibase (8, 10, 6, 1).\n# - 3820 is a valid representation in the multibase; it is the number\n# that in base 10 reads as 0 + 2*1 + 8*6*1 + 3*10*6*1 = 230.\n# - 432, as a decimal number, can be represented in the multibase,\n# reading as 7200, since 2*6 + 7*10*6 = 432.\n\nimport sys\n\ntry: \n multibase = [int(x) for x in input('Enter a nonempty sequence of integers '\n 'between 1 and 10: '\n ).split()\n ]\n if not len(multibase) or any(b < 1 or b > 10 for b in multibase): \n raise ValueError\nexcept ValueError:\n print('Incorrect input, giving up.')\n sys.exit()\ntry: \n input_multibase_representation =\\\n int(input('Enter a first positive number: '))\n if input_multibase_representation < 0: \n raise ValueError\nexcept ValueError:\n print('Incorrect input, giving up.')\n sys.exit()\ntry: \n input_base_10_representation =\\\n int(input('Enter a second positive number: '))\n if input_base_10_representation < 0: \n raise ValueError\nexcept ValueError:\n print('Incorrect input, giving up.')\n sys.exit()\n\nvalid_multibase_representation = True\nvalid_base_10_representation = True\nmax_number = 0\noutput_multibase_representation = 0\noutput_base_10_representation = 0\n\n# INSERT YOUR CODE HERE\nr_multibase=multibase[::-1]\nfor i in range(1,len(r_multibase)):\n r_multibase[i]=r_multibase[i]*r_multibase[i-1]\nmax_num_base=multibase[::-1]\n\nfor i in range(1,len(max_num_base)):\n max_number=(max_num_base[i]-1)*r_multibase[i-1]+max_number\nmax_number=max_number+max_num_base[0]-1\n#print(max_num_base,r_multibase)\n\nm1=multibase[::-1]\nm2=[int(x) for x in str(input_multibase_representation)[::-1]]\nif len(m2)>len(m1):\n valid_multibase_representation=False\nelse:\n for i in range(len(m2)) :\n if m2[i]>=m1[i]:\n valid_multibase_representation=False\n break\n else:\n if i==0:\n output_base_10_representation=output_base_10_representation+m2[0]\n elif i >0:\n output_base_10_representation=output_base_10_representation+m2[i]*r_multibase[i-1]\n\n\nif input_base_10_representation > max_number:\n valid_base_10_representation=False\nelse:\n b=''\n num=input_base_10_representation\n for i in range(len(m1)):\n a=num//m1[i]\n #print(b,num % m1[i])\n b=str(num % m1[i])+b\n num=a\n #print(b,str(num % m1[i]))\n output_multibase_representation=int(b)\n\n\n\n\n\n\n\nprint('The largest number that can be represented in this multibase is:',\n max_number\n )\nif not valid_multibase_representation:\n print(input_multibase_representation,\n 'is not a valid representation in the given multibase.'\n )\nelse:\n print('In base 10,', input_multibase_representation,\n 'reads as:', output_base_10_representation\n )\nif not valid_base_10_representation:\n print(input_base_10_representation, 'cannot be represented in the '\n 'given multibase.'\n )\nelse:\n print('In the given multibase,', input_base_10_representation,\n 'reads as:', output_multibase_representation\n )\n\n\n\n\n\n","sub_path":"quiz3/quiz_3.py","file_name":"quiz_3.py","file_ext":"py","file_size_in_byte":3836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"632510674","text":"\"\"\"\r\n基于python和selenium实现的大麦网自动刷新抢票脚本\r\n用户要提前添加好个人信息和收货地址\r\n\"\"\"\r\n\r\nimport requests\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.common.exceptions import TimeoutException\r\nimport time\r\n\r\n# 设置抢票链接和开票时间\r\nURL = \"https://piao.damai.cn/138382.html?spm=a2o6e.search.0.0.2b5328df7CB40F\"\r\nHOUR = 11\r\nMIN = 18\r\n\r\ndriver = webdriver.Chrome()\r\n# 设置等待时间\r\nwait = WebDriverWait(driver, 5)\r\n# 以周杰伦的为例\r\ndriver.get(URL)\r\n\r\n# test\r\n# driver.get(\"https://piao.damai.cn/141699.html?spm=a2o6e.search.0.0.10f94d15pF81cd\")\r\n\r\n\r\ndef choose(seletor):\r\n try:\r\n # 控件可点击时才选定\r\n choice = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, seletor)))\r\n return choice\r\n except TimeoutException as e:\r\n print(\"Time out!\")\r\n return None\r\n except Exception:\r\n print(\"Not found!\")\r\n return None\r\n\r\n# 点击登录\r\nlogin = choose(\"#userLoginInfo > span > a:nth-child(1)\")\r\nlogin.click()\r\nusername = choose(\"#login_email\")\r\nusername.send_keys(\"13112390306\")\r\n\"\"\"\r\n由于密码框控件被设置为不可见\r\n先自行输入密码并记住密码\r\n方便刷新\r\n(也可用cookie实现)\r\n\"\"\"\r\n\r\n# 10秒等待用户输入密码后再开始刷\r\ntime.sleep(10)\r\n\r\nwhile 1:\r\n if HOUR == time.localtime().tm_hour:\r\n while 1:\r\n if MIN == time.localtime().tm_min:\r\n print(\"开始抢票\")\r\n driver.get(URL)\r\n price = None\r\n plus = None\r\n buybtn = None\r\n submit = None\r\n # 点击价格\r\n while None == price:\r\n # 这里选的是580票面的,如果选其他票面,修改对应的选择器内容即可\r\n price = choose(\"li.itm-oos:nth-child(2)\")\r\n print(price)\r\n price.click()\r\n # 数量加1\r\n while None == plus:\r\n plus = choose(\"a.btn:nth-child(3)\")\r\n plus.click()\r\n # 立即抢购\r\n while None == buybtn:\r\n buybtn = choose(\"#btnBuyNow\")\r\n buybtn.click()\r\n # 提交订单\r\n while None == submit:\r\n submit = choose(\"#orderConfirmSubmit\")\r\n submit.click()\r\n break\r\n \r\ntime.sleep(10)\r\n# driver.quit()\r\nprice(\"抢票成功\")\r\n","sub_path":"damai.py","file_name":"damai.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"250318820","text":"import xlsxwriter\nimport xlrd\nexcel = xlrd.open_workbook(\"mainbasket_daftarsteaming.xlsx\")\nsheetdata = excel.sheet_by_index(0)\n'''\ndata.name = nama sheet\ndata.nrows = jumah baris\ndata.ncols = jumlah kolom\n'''\n\n\nworkbook = xlsxwriter.Workbook('mainbasket_vsmsatufitur.xlsx')\nworksheet1 = workbook.add_worksheet()\n\ndata=[]\nkumpulan_katadasar=\"\"\nfor i in range(1,sheetdata.nrows):\n\n value = sheetdata.cell_value(rowx=i, colx=2)\n\n kumpulan_katadasar=kumpulan_katadasar+value\n data.append(value)\n\nprint (kumpulan_katadasar)\n\n\ntemp = {}\nkal = kumpulan_katadasar.split(\" \")\nfor i in kal:\n if i not in temp:\n temp[i] = 1\n else:\n hasil_sementara = temp[i]\n temp[i] = hasil_sementara + 1\n\n\n# print (temp)\n\n\ndef list_fitur():\n t = {}\n semua_kata = \"\"\n for i in data:\n #print (i)\n semua_kata = semua_kata + i + \" \"\n\n for j in semua_kata.split(\" \"):\n t[j] = 0\n\n del t[\"\"]\n return t\n\nprint (len(list_fitur()))\n\nprint ((list_fitur()))\n\ndef hapus_fitur():\n temp=[]\n tampung_data=[]\n for baris in range(1, sheetdata.nrows):\n value = sheetdata.cell_value(rowx=baris, colx=2)\n tempkat = value.split(\" \")\n tampung_data.append(tempkat)\n\n kolom=0\n for kata in list_fitur():\n count=0\n for i in range(len(tampung_data)):\n if kata in tampung_data[i] :\n count+=1\n\n if count>1:\n if kata not in temp:\n temp.append(kata)\n worksheet1.write(0,kolom+1,kata)\n\n\n kolom+=1\n\n break\n return temp\n\nprint (\"panjang\",len(hapus_fitur()))\nprint (\"temp_fitur\",(hapus_fitur()))\n\n\n\ndef hitung_katatiapbaris():\n tampung_data = []\n for baris in range(1, sheetdata.nrows):\n value = sheetdata.cell_value(rowx=baris, colx=2)\n temp = value.split(\" \")\n dict_baris = {}\n for i in temp:\n if i == '':\n continue\n temp_count = 0\n\n for j in temp:\n\n if i == j:\n temp_count += 1\n dict_baris[i] = temp_count\n tampung_data.append(dict_baris)\n\n return tampung_data\n\nfor baris in range(1,sheetdata.nrows):\n kolom=1\n for temp_fitur in hapus_fitur():\n\n if temp_fitur not in hitung_katatiapbaris()[baris-1]:\n hasil = 0\n #continue\n else:\n hasil=hitung_katatiapbaris()[baris-1][temp_fitur]\n\n print (\"data ke>>\",baris,\"kata>>\",temp_fitur,\"ada>>\",hasil)\n\n worksheet1.write(baris, kolom, int(hasil))\n\n kolom+=1\nworkbook.close()\n\n\n\n","sub_path":"mainbasket_sastrawi_seringmuncul.py","file_name":"mainbasket_sastrawi_seringmuncul.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"194432152","text":"import time\nimport sys\n\n'''\n Progress Bar\n Parameters: width = number of iterations\n'''\n\nclass progressBar():\n\n ''' Init function '''\n def __init__(self, width):\n if width is None:\n self.width = 40\n else:\n self.width = width\n\n sys.stdout.write(\"[%s]\" % (\" \" * self.width))\n sys.stdout.flush()\n sys.stdout.write(\"\\b\" * (self.width+1)) # return to start of line, after '['\n \n self.iter = 0\n \n ''' Update function > use this inside for loops '''\n def update(self):\n sys.stdout.write(\"-\")\n sys.stdout.flush()\n \n self.iter = self.iter + 1\n \n if self.iter == self.width:\n sys.stdout.write(\"]\\n\") # this ends the progress bar\n \n\nif __name__ == '__main__':\n\n pBar = progressBar(40)\n\n for i in range(pBar.width):\n time.sleep(0.1) # do real work here\n # update the bar\n pBar.update()","sub_path":"progressBar.py","file_name":"progressBar.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"13370866","text":"import math\n\nN = 5\nARR = [2, 4, 4, 0, 2]\n\nN = 7\nARR = [6, 4, 0, 2, 4, 0, 2]\n#\n# N = 8\n# ARR = [7, 5, 1, 1, 7, 3, 5, 3]\n#\nN = int(input())\nARR = list(map(int, input().split()))\n\n\ndef calculate(n, arr):\n if n % 2 == 0:\n n = n // 2\n start = 1\n finalResult = pow(2, n, 1000000000 + 7)\n else:\n n = n // 2 + 1\n start = 0\n finalResult = pow(2, (n - 1), 1000000000 + 7)\n\n result = {}\n for i in range(n):\n index = start + 2 * i\n if index == 0:\n result.__setitem__(0, 1)\n else:\n result.__setitem__(index, 2)\n\n isOk = True\n for i in range(len(arr)):\n if result.get(arr[i]) == None:\n isOk = False\n break\n\n if result.get(arr[i]) == 0:\n isOk = False\n break\n\n result.__setitem__(arr[i], result.get(arr[i])-1)\n\n if isOk == False:\n print(0)\n return\n\n if sum(result.values()) == 0:\n print(finalResult)\n else:\n print(0)\n\n\ncalculate(N, ARR)\n","sub_path":"Python_codes/p03846/s527402211.py","file_name":"s527402211.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"70215043","text":"#!/usr/bin/env python\n\nfrom collections import Counter\n\ncounts = Counter() # <1>\n\nwith open(\"../DATA/breakfast.txt\") as breakfast_in:\n for line in breakfast_in:\n item = line.rstrip('\\n\\r') # <2>\n counts[item] += 1 # <3>\n\n# for item, count in counts.items(): # <4>\n# print(item, count)\n\nprint(counts)\n\n\nwith open('../DATA/words.txt') as words_in:\n all_letters = [w[0] for w in words_in]\n\nword_counter = Counter(all_letters)\n\nprint(word_counter.most_common(6))\n\nprint(Counter(w[0] for w in open('../DATA/words.txt')).most_common(6))\n","sub_path":"EXAMPLES/count_with_counter.py","file_name":"count_with_counter.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"473924029","text":"import sys\nimport os\n \ndef createEntityModel(_entityName):\n header = \"\"\"#ifndef INCLUDED_EXPEDITION_COMPONENTS_MODELS_{upperEntityName}_MODEL_HPP_\n#define INCLUDED_EXPEDITION_COMPONENTS_MODELS_{upperEntityName}_MODEL_HPP_\n\n#include \n\nnamespace expd {{\n\n class {entityName}Model : public ModelBase {{\n public:\n {entityName}Model(void);\n ~{entityName}Model(void);\n }};\n\n}}\n\n#endif // INCLUDED_EXPEDITION_COMPONENTS_MODELS_{upperEntityName}_MODEL_HPP_\n\"\"\".format(\n upperEntityName = _entityName.upper(), \n entityName = _entityName\n )\n source = \"\"\"#include \n\nnamespace expd {{\n\n {entityName}Model::{entityName}Model(void) {{\n \n }}\n\n {entityName}Model::~{entityName}Model(void) {{\n \n }}\n\n}}\n\"\"\".format(\n entityName = _entityName\n)\n \n return (source, header)\n\ndef createEntityView(_entityName):\n header = \"\"\"#ifndef INCLUDED_EXPEDITION_COMPONENTS_VIEWS_{upperEntityName}_VIEW_HPP_\n#define INCLUDED_EXPEDITION_COMPONENTS_VIEWS_{upperEntityName}_VIEW_HPP_\n\n#include \n\nnamespace expd {{\n class {entityName}Model;\n class {entityName}View : public ViewBase {{\n public:\n {entityName}View({entityName}Model *_model);\n ~{entityName}View(void) override;\n\n\t\tvoid update(float _delta) override;\n\t\tvoid draw(sf::RenderTarget& _target, sf::RenderStates _states) const override;\n\n private:\n {entityName}Model *m_Model;\n }};\n\n}}\n\n#endif // INCLUDED_EXPEDITION_COMPONENTS_VIEWS_{upperEntityName}_VIEW_HPP_\n\"\"\".format(\n upperEntityName = _entityName.upper(), \n entityName = _entityName\n)\n source = \"\"\"#include \n#include \n\nnamespace expd {{\n\n {entityName}View::{entityName}View({entityName}Model *_model) :\n m_Model(_model) {{\n \n }}\n {entityName}View::~{entityName}View(void) {{\n \n }}\n\n void {entityName}View::update(float _delta) {{\n\n }}\n void {entityName}View::draw(sf::RenderTarget& _target, sf::RenderStates _states) const {{\n\n }}\n}}\n\"\"\".format(\n entityName = _entityName\n)\n \n return (source, header)\n\ndef createEntityController(_entityName):\n header = \"\"\"#ifndef INCLUDED_EXPEDITION_COMPONENTS_CONTROLLERS_{upperEntityName}_CONTROLLER_HPP_\n#define INCLUDED_EXPEDITION_COMPONENTS_CONTROLLERS_{upperEntityName}_CONTROLLER_HPP_\n\n#include \n\nnamespace expd {{\n\tclass {entityName}Model;\n\tclass {entityName}Controller : public ControllerBase {{\n\tpublic:\n\t\t{entityName}Controller({entityName}Model *_model);\n\t\t~{entityName}Controller(void) override;\n\n\t\tvoid update(float _delta) override;\n\t\tbool handleMessage(const GameMessage& _message) override;\n\t\tbool handleEvent(const sf::Event& _event) override;\n\n\tprivate:\n\t\t{entityName}Model * m_Model;\n\t}};\n}}\n\n#endif // INCLUDED_EXPEDITION_COMPONENTS_CONTROLLERS_{upperEntityName}_CONTROLLER_HPP_\n\"\"\".format(\n upperEntityName = _entityName.upper(), \n entityName = _entityName\n)\n source = \"\"\"#include \n#include \n\nnamespace expd {{\n\n\t{entityName}Controller::{entityName}Controller({entityName}Model *_model) :\n\t\tControllerBase(_model),\n\t\tm_Model(_model) {{\n\n\t}}\n\t{entityName}Controller::~{entityName}Controller(void) {{\n\n\t}}\n\n\tvoid {entityName}Controller::update(float _delta) {{\n\n\t}}\n\tbool {entityName}Controller::handleMessage(const GameMessage& _message) {{\n\t\treturn false;\n\t}}\n\tbool {entityName}Controller::handleEvent(const sf::Event& _event) {{\n\t\treturn false;\n\t}}\n}}\n\"\"\".format(\n entityName = _entityName\n)\n return (source, header)\n\nclass EntityCreation:\n 'Class to help creating entities'\n\n def __init__(self, projectName, projectPath):\n self.ProjectName = projectName\n self.ProjectPath = projectPath\n self.SourceLocation = \"src\"\n self.HeaderLocation = \"include\"\n self.ModelFolder = \"Models\"\n self.ViewFolder = \"Views\"\n self.ControllerFolder = \"Controllers\"\n self.ComponentsFolder = \"Components\"\n pass\n\n def createEntity(self, _entityName):\n (self.modelSource, self.modelHeader) = createEntityModel(_entityName)\n (self.viewSource, self.viewHeader) = createEntityView(_entityName)\n (self.controllerSource, self.controllerHeader) = createEntityController(_entityName)\n\n self.ModelSourceFilePath = os.path.join(self.ProjectPath, self.SourceLocation, self.ProjectName, self.ComponentsFolder, self.ModelFolder, _entityName + \"Model.cpp\")\n self.ModelHeaderFilePath = os.path.join(self.ProjectPath, self.HeaderLocation, self.ProjectName, self.ComponentsFolder, self.ModelFolder, _entityName + \"Model.hpp\")\n\n self.ViewSourceFilePath = os.path.join(self.ProjectPath, self.SourceLocation, self.ProjectName, self.ComponentsFolder, self.ViewFolder, _entityName + \"View.cpp\")\n self.ViewHeaderFilePath = os.path.join(self.ProjectPath, self.HeaderLocation, self.ProjectName, self.ComponentsFolder, self.ViewFolder, _entityName + \"View.hpp\")\n\n self.ControllerSourceFilePath = os.path.join(self.ProjectPath, self.SourceLocation, self.ProjectName, self.ComponentsFolder, self.ControllerFolder, _entityName + \"Controller.cpp\")\n self.ControllerHeaderFilePath = os.path.join(self.ProjectPath, self.HeaderLocation, self.ProjectName, self.ComponentsFolder, self.ControllerFolder, _entityName + \"Controller.hpp\")\n\n pass\n\n def validateEntityFilesExist(self, _entityName):\n\n if (os.path.exists(self.ModelSourceFilePath)):\n print('Model Source file exists')\n return False\n if (os.path.exists(self.ModelHeaderFilePath)):\n print('Model Header file exists')\n return False\n\n if (os.path.exists(self.ViewSourceFilePath)):\n print('View Source file exists')\n return False\n if (os.path.exists(self.ViewHeaderFilePath)):\n print('View Header file exists')\n return False\n\n if (os.path.exists(self.ControllerSourceFilePath)):\n print('Controller Source file exists')\n return False\n if (os.path.exists(self.ControllerHeaderFilePath)):\n print('Controller Header file exists')\n return False\n\n return True\n \n def createEntityFiles(self, _entityName):\n with open(self.ModelSourceFilePath,'w+') as f:\n f.write(self.modelSource)\n with open(self.ModelHeaderFilePath,'w+') as f:\n f.write(self.modelHeader)\n \n with open(self.ViewSourceFilePath,'w+') as f:\n f.write(self.viewSource)\n with open(self.ViewHeaderFilePath,'w+') as f:\n f.write(self.viewHeader)\n \n with open(self.ControllerSourceFilePath,'w+') as f:\n f.write(self.controllerSource)\n with open(self.ControllerHeaderFilePath,'w+') as f:\n f.write(self.controllerHeader)\n\n\nif __name__ == '__main__':\n EntityName = \"TileBound\"\n ProjectName = \"Expedition\"\n\n Path = os.getcwd()\n res = Path[:Path.find(ProjectName) + len(ProjectName)]\n\n entityCreate = EntityCreation(ProjectName, res)\n\n entityCreate.createEntity(EntityName)\n\n if (not entityCreate.validateEntityFilesExist(EntityName)):\n exit()\n\n entityCreate.createEntityFiles(EntityName)\n ","sub_path":"utility/Python/CreateEntity.py","file_name":"CreateEntity.py","file_ext":"py","file_size_in_byte":7571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"483542236","text":"import json2dat\nimport os\nimport re\nimport multiprocessing\n\nGraph_Json_Path = '../data/graph/'\nGraph_Json_Data = '../data/graph_json_simple'\nGraph_Binary_Path = '../data/graph_binary'\nMeta_File = '../data/meta'\nThread_Count = 8\n\n\ndef convert(graph_files, meta_info, out_path):\n for gf in graph_files:\n filename, _ = os.path.splitext(os.path.split(gf)[1])\n output_file = os.path.join(out_path, filename + '.dat')\n if os.path.exists(output_file):\n print(\"Skip: %s\" % output_file)\n else:\n c = json2dat.Converter(meta_info, gf, output_file+'.tmp')\n c.do()\n os.rename(output_file+'.tmp', output_file)\n print(multiprocessing.current_process().name + ' Finished')\n\n\ndef get_graph_files(path):\n graph_files = []\n re_gf = re.compile(\"part-\\d+\")\n for root, _, files in os.walk(path):\n for name in files:\n m = re_gf.match(name)\n if not m: continue\n if m.end(0) == len(name):\n graph_files.append(os.path.join(root, name))\n return graph_files\n\n\n#def create_graph_files(path):\n\n\nif __name__ == '__main__':\n gf = [Graph_Json_Data]\n c = len(gf)\n print(c)\n t_c = int(c / Thread_Count)\n tasks = []\n for i in range(0, c):\n p_gf = gf[:]\n t = multiprocessing.Process(name='Task-%d-%d'% (i, i+len(p_gf)-1),\n target=convert, args=(p_gf, Meta_File, Graph_Binary_Path,))\n tasks.append(t)\n t.start()\n for t in tasks:\n t.join()\n","sub_path":"data_process/convert_to_binary.py","file_name":"convert_to_binary.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"495164947","text":"import pytest\nimport torch\n\nfrom baal.utils import array_utils\nfrom baal.utils.iterutils import map_on_tensor\n\n\n@pytest.fixture()\ndef a_tensor():\n return torch.randn([10, 3, 32, 32])\n\n\ndef test_stack_in_memory_single(a_tensor):\n iterations = 10\n out = array_utils.stack_in_memory(a_tensor, iterations=iterations)\n assert out.shape == (10 * iterations, 3, 32, 32)\n\n\ndef test_stack_in_memory_multi(a_tensor):\n iterations = 10\n t = [a_tensor, a_tensor]\n out = map_on_tensor(lambda ti: array_utils.stack_in_memory(ti, iterations=iterations), t)\n assert out[0].shape == (10 * iterations, 3, 32, 32)\n assert out[1].shape == (10 * iterations, 3, 32, 32)\n\n\nif __name__ == '__main__':\n pytest.main()\n","sub_path":"tests/utils/test_array_utils.py","file_name":"test_array_utils.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"26713796","text":"import json\nfrom pymongo import MongoClient\nimport math\nimport pandas as pd\nfrom bson import ObjectId\n\nDB_URI = 'mongodb:///admin'\nDB_NAME = 'interactive_cloze'\n\nmongo_cursor = MongoClient(DB_URI, connect = False)\ndb = mongo_cursor[DB_NAME]\n\nCSV_FILE = \"raw_survey\"\n\nCOLLECTION_NAME = \"survey\"\n\ndef get_survey_key():\n survey_key = None\n with open('survey_key2.json') as f:\n survey_key = json.load(f)\n \n if survey_key:\n return survey_key\n\n return False\n\ndef populate_db():\n print (\"populating db with \" + CSV_FILE + \".csv\")\n db[COLLECTION_NAME].remove({})\n df = pd.read_csv( CSV_FILE + \".csv\")\n for i,row in df.iterrows():\n doc = dict()\n for column in df.columns:\n if (not (type(row[column]) is str)):\n if (not math.isnan(row[column])):\n doc[column] = row[column]\n else:\n doc[column] = row[column]\n db[COLLECTION_NAME].update({'ResponseId':doc['ResponseId']}, doc, upsert = True)\n print ('[' + CSV_FILE + '][' + str(i) + \"] inserted into db...\")\n print (\"COMPLETE: populated db with \" + CSV_FILE + \".csv\")\n\ndef clean_and_process():\n print (\"cleaning and processing db...\")\n survey_key = get_survey_key()\n \n if survey_key:\n cnt = 0\n total = db[COLLECTION_NAME].find().count()\n for doc in db[COLLECTION_NAME].find(no_cursor_timeout=True):\n for key in doc.keys():\n if key[0] == 'Q':\n question_label = key[1:]\n #iterate categories\n for i in range(len(survey_key)):\n category_label = survey_key[i]['category_label']\n #iterate docs\n for j in range(len(survey_key[i]['docnames'])):\n docname = survey_key[i]['docnames'][j]['docname']\n timing_qno = survey_key[i]['docnames'][j]['timing_qno']\n\n if '_' in question_label:\n if timing_qno == question_label.split('_')[0]:\n db[COLLECTION_NAME].update({'_id':doc['_id']}, {'$set':{category_label + '_docname': docname}}, upsert=True)\n db[COLLECTION_NAME].update({'_id':doc['_id']}, {'$set':{category_label + '_' + question_label.split('_')[1]: doc[key]}}, upsert=True)\n break\n \n else:\n #iterate questions\n # print (survey_key[i]['docnames'][j])\n for k in range(len(survey_key[i]['docnames'][j]['questions'])):\n qno = survey_key[i]['docnames'][j]['questions'][k]['qno']\n answer = survey_key[i]['docnames'][j]['questions'][k]['answer']\n\n if qno == question_label:\n if doc[key] == answer:\n db[COLLECTION_NAME].update({'_id':doc['_id']}, {'$set':{category_label + '_docname': docname}}, upsert=True)\n db[COLLECTION_NAME].update({'_id':doc['_id']}, {'$set':{category_label + '_Q' + str(k+1): True}}, upsert=True)\n else:\n db[COLLECTION_NAME].update({'_id':doc['_id']}, {'$set':{category_label + '_docname': docname}}, upsert=True)\n db[COLLECTION_NAME].update({'_id':doc['_id']}, {'$set':{category_label + '_Q' + str(k+1): False}}, upsert=True)\n\n cnt += 1\n print (str(cnt) + '/' + str(total))\n print (\"COMPLETE: db processed...\")\n\ndef create_csv():\n print (\"creating csv...\")\n survey_key = get_survey_key()\n\n attrs = ['MID']\n \n for i in range(len(survey_key)):\n category_label = survey_key[i]['category_label']\n attrs.append(category_label + '_Q1')\n attrs.append(category_label + '_Q2')\n attrs.append(category_label + '_Q3')\n attrs.append(category_label + '_First Click')\n attrs.append(category_label + '_Last Click')\n attrs.append(category_label + '_Page Submit')\n attrs.append(category_label + '_Click Count')\n attrs.append(category_label + '_docname')\n\n \n file_name = \"survey_results.csv\"\n\n results = dict()\n for attr in attrs:\n results[attr] = list()\n\n for doc in db[COLLECTION_NAME].find({'MID':{'$exists':True}},no_cursor_timeout=True):\n if (doc['StartDate'] == 'Start Date') or (doc['StartDate'] == '{\"ImportId\":\"startDate\",\"timeZone\":\"America/New_York\"}'):\n continue\n for attr in attrs:\n if attr in doc:\n results[attr].append(doc[attr])\n else:\n results[attr].append(None)\n\n # for attr in attrs:\n # print (attr + ' ' +str(len(results[attr])))\n # print (results)\n df = pd.DataFrame(data=results)\n df.to_csv(file_name)\n print (file_name + \" saved.\")\n\npopulate_db()\nclean_and_process()\ncreate_csv()\n","sub_path":"comprehensionQuestions/score_survey.py","file_name":"score_survey.py","file_ext":"py","file_size_in_byte":5220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"522282538","text":"\"\"\"Pendulum solution.\"\"\"\n\nimport tensorflow as tf\nimport gym\n\n\nclass BipedalWalkerAgent:\n def __init__(self):\n self.actor, self.critic = (None, None)\n self.load_models()\n assert((self.actor, self.critic) != (None, None))\n\n def load_models(self):\n try:\n self.critic = tf.keras.models \\\n .load_model('./bipedal_walker_solution/critic')\n self.actor = tf.keras.models \\\n .load_model('./bipedal_walker_solution/actor')\n return True\n except Exception as err:\n print(err)\n\n def get_action(self, state):\n return self.actor(state)*2\n\n\ndef play(steps):\n env = gym.make('BipedalWalker-v3')\n agent = BipedalWalkerAgent()\n state = env.reset()\n agent.actor.summary()\n agent.critic.summary()\n for i in range(steps):\n action = agent.get_action(state[None])[0]\n state, reward, done, _ = env \\\n .step(action)\n state = state\n env.render()\n\n\nplay(steps=1000)\n","sub_path":"bipedal_walker_solution/play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"462841942","text":"import netaddr\nfrom oslo_config import cfg\nfrom oslo_log import log\n\nfrom ovn_k8s import constants\nfrom ovn_k8s.lib import ovn\nfrom ovn_k8s import utils\n\nLOG = log.getLogger(__name__)\n\n\ndef init_conf(args):\n # Register options\n opts = [\n cfg.StrOpt('lrouter_name', default=constants.DEFAULT_LROUTER_NAME),\n cfg.StrOpt('k8s_api_server_host', default='127.0.0.1'),\n cfg.IntOpt('k8s_api_server_port', default='8080'),\n cfg.StrOpt('ovn_nb_remote',\n default='unix:/var/run/openvswitch/nb_db.sock'),\n cfg.FloatOpt('coalesce_interval', default='0.1',\n help=('Interval in seconds for coalescing events.'\n 'There will be a delay in event processing equal '\n 'to the value of this parameter')),\n cfg.BoolOpt('enable_networkpolicy', default=False,\n help=('Set to True to enable watching and processing '\n 'network policy objects'))]\n cfg.CONF.register_opts(opts)\n cfg.CONF(args=args, project='ovn-k8s')\n\n\ndef _check_vswitch(lswitch_name):\n lswitch_raw_data = ovn.ovn_nbctl('find', 'Logical_Switch',\n 'name=%s' % lswitch_name)\n lswitch_data = ovn.parse_ovn_nbctl_output(lswitch_raw_data)\n if len(lswitch_data) > 1:\n LOG.warn(\"I really was not expecting more than one switch... I'll \"\n \"pick the first, there's a %.2f\\% chance I'll get it right\" %\n (100 / len(lswitch_data)))\n if lswitch_data:\n lswitch_data = lswitch_data[0]\n LOG.debug(\"OVN Logical Switch for K8S host found. Skipping creation\")\n return lswitch_data\n\n\ndef init_host(host_name, host_subnet):\n \"\"\"Initializes a host adding it to the logical topology\"\"\"\n # Check for logical router, if not found create one\n lrouter_name = cfg.CONF.lrouter_name\n lrouter_raw_data = ovn.ovn_nbctl('find', 'Logical_Router',\n 'name=%s' % lrouter_name)\n lrouter_data = ovn.parse_ovn_nbctl_output(lrouter_raw_data)\n if len(lrouter_data) > 1:\n LOG.warn(\"I really was not expecting more than one router... I'll \"\n \"pick the first, there's a %.2f\\% chance I'll get it right\",\n (100 / len(lrouter_data)))\n if lrouter_data:\n lrouter_data = lrouter_data[0]\n LOG.debug(\"Logical router for K8S networking found. \"\n \"Skipping creation\")\n else:\n LOG.debug(\"Creating Logical Router for K8S networking with name:%s\",\n lrouter_name)\n output = ovn.ovn_nbctl('create', 'Logical_Router',\n 'name=%s' % lrouter_name)\n LOG.debug(\"Will use OVN Logical Router:%s\", output)\n # Check for host logical switch. If not found create one\n lswitch_name = host_name\n LOG.info(\"OVN lswitch for the host: %s\", lswitch_name)\n lswitch_data = _check_vswitch(lswitch_name)\n if lswitch_data:\n LOG.debug(\"OVN Logical Switch for K8S host found. Skipping creation\")\n else:\n LOG.debug(\"Creating LogicalSwitch for K8S host with name: %s\",\n lswitch_name)\n ovn.ovn_nbctl('ls-add', lswitch_name)\n\n # Check for logical router port connecting local logical switch to\n # kubernetes router.\n # If not found create one, and connect it to both router and switch\n lrp_raw_data = ovn.ovn_nbctl('find', 'Logical_Router_port',\n 'name=%s' % lswitch_name)\n lrp_data = ovn.parse_ovn_nbctl_output(lrp_raw_data)\n if len(lrp_data) > 1:\n LOG.warn(\"I really was not expecting more than one router port... \"\n \"I'll pick the first, there's a %.2f\\% chance I'll get it \"\n \"right\", (100 / len(lrp_data)))\n if lrp_data:\n lrp_data = lrp_data[0]\n LOG.debug(\"OVN logical router port for K8S host found.\"\n \"Skipping creation\")\n # TODO: worry about changes in IP address and subnet\n else:\n lrp_mac = utils.generate_mac()\n cidr = netaddr.IPNetwork(host_subnet)\n ip_address = netaddr.IPAddress(cidr.first + 1)\n lrp_uuid = ovn.ovn_nbctl('--', '--id=@lrp', 'create',\n 'Logical_Router_port',\n 'name=%s' % lswitch_name,\n 'network=%s/%s' % (ip_address,\n cidr.prefixlen),\n 'mac=\"%s\"' % lrp_mac, '--', 'add',\n 'Logical_Router', lrouter_name, 'ports',\n '@lrp', '--', 'lsp-add',\n lswitch_name, 'rp-%s' % lswitch_name)\n ovn.ovn_nbctl('set', 'Logical_Switch_port', 'rp-%s' % lswitch_name,\n 'type=router', 'options:router-port=%s' % lswitch_name,\n 'addresses=\"%s\"' % lrp_mac)\n LOG.debug(\"Configured logical router port: %s\", lrp_uuid)\n","sub_path":"ovn_k8s/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":5020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"637708609","text":"#!/usr/bin/env python\nimport re\nimport sys\n\nclass AccessPoint:\n\t\"\"\"\n\thold access point data and gps coords\n\t\"\"\"\n\n\tdef __init__(self, bssid):\n\t\t#capture ID and starting info\n\t\tself.bssid = bssid\n\t\t\n\t\t#create arrays to hold lat/long/sig strength\n\t\tself.lat_a = []\n\t\tself.lon_a = []\n\t\tself.strength = []\n\n\tdef get_bssid(self):\n\t\t\"\"\"return bssid of access point\"\"\"\n\t\tif self.bssid:\n\t\t\treturn self.bssid\n\t\telse:\n\t\t\treturn -1\n\n\tdef update(self, lat_u, lon_u, dbm_u):\n\t\t\"\"\"update access point's lat/long/signal strength\n\t\t\t:param lat_u: latitude update\n\t\t\t:param lon_u: longitude update\n\t\t\t:param dbm_u: signal strength update\n\t\t\"\"\"\n\t\tself.lat_a.append(lat_u)\n\t\tself.lon_a.append(lon_u)\n\t\tself.strength.append(dbm_u)\n\n\tdef get_current_lat(self):\n\t\t\"\"\":returns: last recorded latitude of access point\"\"\"\n\t\tif self.lat_a[-1]:\n\t\t\treturn self.lat_a[-1]\n\t\telse:\n\t\t\treturn -1\n\n\tdef get_current_lon(self):\n\t\t\"\"\":returns: last recorded longitude of access point\"\"\"\n\t\tif self.lon_a[-1]:\n\t\t\treturn self.lon_a[-1]\n\t\telse:\n\t\t\treturn -1\n\n\tdef get_current_strength(self):\n\t\t\"\"\":returns: last recorded signal strength of access point\"\"\"\n\t\tif self.strength[-1]:\n\t\t\treturn self.strength[-1]\n\t\telse:\n\t\t\treturn -1\n\ndef ap_exists(bssid, ap_list):\n\t\"\"\"check if ap object is in master list of AccessPoints\n\t\t:param bssid: access point BSSID from .gpsxml FILE\n\t\t:param ap_list: master list of APs to check against\n\t\t:returns: boolean value - False if AP is not in list/True if Ap is in list\n\t\"\"\"\n\tsize = len(ap_list)\n\n\tif size > 0:\n\t\tfor x in range(size):\n\t\t\tif bssid == ap_list[x].get_bssid():\n\t\t\t\treturn True\n\telse:\n\t\treturn False\n\n\treturn False\n\ndef inflate_ap(ap, line):\n\t\"\"\"pull data from gpsxml file and add to new AccessPoint object\n\t\t:param ap: AccessPoint object\n\t\t:param line: next line in gpsxml file to pull data from\n\t\t:returns: AccessPoint object with initial location/signal data\n\t\"\"\"\n\tlat = re.search(lat_re,line)\n\tlat = lat.group(0)[5:-1]\n\n\tlon = re.search(lon_re, line)\n\tlon= lon.group(0)[5:-1]\n\n\tsig = re.search(sig_re, line)\n\tsig = sig.group(0)[12:-1]\n\n\tap.update(lat, lon, sig)\n\n\treturn ap\n\n\n\n#build out regular expressions for each piece of data in the gpsxml file\nbssid_re = '(bssid=\"([0-9A-F]{2}[:]){5}([0-9A-F]{2})\")'\nlat_re = '(lat=\"([0-9]{2})[.]([0-9]{6})\")'\nlon_re = '(lon=\"[-?]([0-9]{2}[0-9]?)[.]([0-9]{6})\")'\nsig_re = '(signal_dbm=\"[-]([0-9]{2})\")'\n\n#open gpsxml file (how to do this dynamically?) - could just run through periodically\ntry:\n\tf = open('gpstest', 'r')\nexcept IOError:\n\tprint(\"DEBUG: ERROR - COULD NOT READ FILE\")\n\tsys.exit()\n\n#initalize global list of access point objects\nap_list = []\n\n#should this be a function? will it be run often? how to pull updates from file continuiously? \nfor line in f:\n\tbssid = re.search(bssid_re, line)\n\tif bssid:\n\t\tbssid = bssid.group(0)[7:-1]\n\t\t#filter out probe packets\n\t\tif not bssid == '00:00:00:00:00:00':\n\t\t\tif not ap_exists(bssid, ap_list):\n\t\t\t\t#create new access point\n\t\t\t\tpt = AccessPoint(bssid)\n\t\t\t\t#add to global AccessPoint object list\n\t\t\t\tap_list.append(inflate_ap(pt, line))\n\nfor x in range(len(ap_list)):\n\tprint(ap_list[x].get_bssid())\n\tprint(ap_list[x].get_current_strength())\n\n\n\n#for line in f:\n\n\n#ap = AccessPoint(match)\n\n#print(ap.get_bssid())\n\n\n\n\n","sub_path":"final_proj/testbed_trilat.py","file_name":"testbed_trilat.py","file_ext":"py","file_size_in_byte":3213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"507770282","text":"from Algorithm.RAISLD import Alg_RAISLD\nfrom Load_Dataset import load_dataset,load_ref\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\n\n\ndef _RAISLDe_it(trainSet,ref,save_path,**kw):\n x_list=[]\n train_num=trainSet.shape[0]\n dim=trainSet.shape[1]\n inner_loops=round(train_num/kw['batchSize'])\n model=Alg_RAISLD(\n np.zeros(dim),\n train_num,kw['alpha'],kw['d'])\n curr_iter_count=0\n model.initialize(trainSet)\n for epoch in tqdm(range((int)(kw['num_epochs']))):\n for i in range(inner_loops):\n curr_iter_count+=1\n model.Sample_Datas(\n trainSet,\n train_num,\n kw['batchSize'],\n model.p)\n model.Grads_Calc()\n model.average_grads()\n grad=model.grad_avg\n model.update()\n #eta=kw['lr_a']*(round(model.t.item())+kw['lr_b'])**(-kw['lr_gamma'])*model.r.item()\n eta=kw['lr_a']*(curr_iter_count+kw['lr_b'])**(-kw['lr_gamma'])\n noise=np.random.normal(0,1,dim)*np.sqrt(2*eta)\n model.curr_x=model.curr_x-grad*eta+noise\n x_list.append(model.curr_x)\n x_list=np.array(x_list).astype(np.float32)\n model.save_figure(x_list,ref,save_path,'RAISLDe')\n np.save(save_path,x_list)\n\ndef RAISLDe_sample(**kw):\n # Creat the save folder and name for result\n save_name='RAISLDe'+' '+\\\n 'lr[{:.2e},{:.2f},{:.2f}] alpha[{:.2f}] d[{:.1f}]'.format(\\\n kw['lr_a'],kw['lr_b'],kw['lr_gamma'],kw['alpha'],kw['d'])\n if not os.path.exists(kw['save_folder']+'RAISLDe'):\n os.makedirs(kw['save_folder']+'RAISLDe')\n save_path=kw['save_folder']+'RAISLDe/'+save_name\n # Print information before train\n print(save_name)\n # Set the random seed\n np.random.seed(kw['random_seed'])\n # Load DataSet as sparse matrix\n trainSet=load_dataset()\n ref=load_ref()\n # Main function\n _RAISLDe_it(trainSet,ref,save_path,**kw)\n","sub_path":"graduation_project/GM/Train/RAISLDe.py","file_name":"RAISLDe.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"233490805","text":"class Solution(object):\n def findLexSmallestString(self, s, a, b):\n \"\"\"\n :type s: str\n :type a: int\n :type b: int\n :rtype: str\n \"\"\"\n n = len(s)\n nums = []\n for c in s:\n nums.append(ord(c) - ord('0'))\n \n # enumerate rotate\n memo = set()\n best = s\n idx = 0\n for i in range(n):\n idx = (i * b) % n\n if idx in memo:\n break\n # change odd only to get min\n besto = nums[1]\n for offset in range(10):\n besto = min(besto, (nums[1] + offset * a) % 10)\n offset = besto - nums[1]\n for j in range(n):\n if j % 2 == 1:\n nums[j] = (nums[j] + offset) % 10\n print(nums)\n nums_ = [str(i) for i in nums]\n tmp = \"\".join(nums_)\n best = min(best, tmp)\n print(i, tmp, best)\n memo.add(idx)\n nums = nums[b:] + nums[:b]\n\n return best\n \n\nif __name__ == \"__main__\":\n a = Solution()\n print(a.findLexSmallestString(\"43987654\", 7, 3))","sub_path":"python/leetcode/1625_lexico.py","file_name":"1625_lexico.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"590240562","text":"# ввод размерности матрицы\ns = input().split()\nrow, col = int(s[0]), int(s[1])\n\n# формирование нулевой матрицы введенной размерности\nmat = [[0] * col for _ in range(row)]\n\nst = 'up'\nn1 = 0\ni = 1\n\nwhile i < row * col:\n \n if st == 'up':\n for j in range(n1, col - n1 - 1):\n if mat[n1][j] == 0:\n mat[n1][j] = i\n i += 1\n st = 'right'\n \n if st == 'right':\n for j in range(n1, row - n1 - 1):\n if mat[j][col - n1 - 1] == 0:\n mat[j][col - n1 - 1] = i\n i += 1\n st = 'down'\n \n if st == 'down':\n for j in range(n1, col - n1 - 1):\n if mat[row - n1 - 1][col - j - 1] == 0:\n mat[row - n1 - 1][col - j - 1] = i\n i += 1\n st = 'left' \n \n if st == 'left':\n for j in range(n1, row - n1 - 1):\n if mat[row - j - 1][n1] == 0:\n mat[row - j - 1][n1] = i\n i += 1\n st = 'up'\n n1 += 1\nif row * col % 2 == 1 and mat[row // 2][col // 2] == 0:\n mat[row // 2][col // 2] = row * col \n \n\n# вывод матрицы\n[print(*i) for i in mat]\n","sub_path":"Python_advanced/spiral_matrix.py","file_name":"spiral_matrix.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"440855937","text":"\nn_features = 200\nlatent_dim=100\n\n\n\nimport scipy.io as sio\n\n\nimport numpy as np\nnp.random.seed(666)\nimport tensorflow as tf\n#from tensorflow.math import reduce_sum\n#import tensorflow.math\nimport os\nfrom keras.backend.tensorflow_backend import set_session\nconfig = tf.ConfigProto()\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\nconfig.gpu_options.per_process_gpu_memory_fraction = 0.5\nset_session(tf.Session(config=config))\n\n\nimport keras\nfrom keras.datasets import mnist\nfrom keras.layers.merge import _Merge\nfrom keras.layers import Input, Dense, Reshape, Flatten, Dropout, Average\nfrom keras.layers import BatchNormalization, Activation, ZeroPadding2D,Concatenate\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.layers.convolutional import UpSampling2D, Conv2D\nfrom keras.models import Sequential, Model\nfrom keras.optimizers import RMSprop,SGD, Adam\nfrom functools import partial\nfrom keras import layers, models\nfrom keras.models import load_model\n\n\n\ndef loadData():\n \n msdata = np.load('/home/SharedData/saurabh/HS/multispectralData.npy')\n pcdata = np.load('/home/SharedData/saurabh/HS/panchromaticData.npy')\n labels = np.load('/home/SharedData/saurabh/HS/labelsData.npy')\n \n return msdata, pcdata, labels\n\n\n\n\n\n\nmsdata, pcdata, gt = loadData()\n\nmsdata=np.transpose(msdata,(0,2,3,1))\npcdata=np.transpose(pcdata,(0,2,3,1))\ngt=np.transpose(gt,(1,0))\ngt=np.ravel(gt)\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import OneHotEncoder\n\nlabel_encoder = LabelEncoder()\ninteger_encoded = label_encoder.fit_transform(gt)\n\nonehot_encoder = OneHotEncoder(sparse=False)\ninteger_encoded = integer_encoded.reshape(len(integer_encoded), 1)\nY = onehot_encoder.fit_transform(\n integer_encoded)\n\n\n#preprocessing b/w -1 and +1\n\nmsdata = msdata.astype(np.float32)\npcdata = pcdata.astype(np.float32)\n\nit2 = 5000\nfor it1 in range(0,80000,5000):\n\n print(it1,it2)\n msdata[it1:it2,:,:,:] = (msdata[it1:it2,:,:,:] - msdata[it1:it2,:,:,:].mean(axis=(0, 1, 2), keepdims=True))/(msdata[it1:it2,:,:,:].std(axis=(0, 1,2), keepdims=True))\n pcdata[it1:it2,:,:,:] = (pcdata[it1:it2,:,:,:] - pcdata[it1:it2,:,:,:].mean(axis=(0,1, 2), keepdims=True))/(pcdata[it1:it2,:,:,:].std(axis=(0,1,2), keepdims=True))\n it2 += 5000\n\nprint(msdata.shape, pcdata.shape)\n\n#from sklearn.model_selection import train_test_split\n\n#(X_train_one, Xtest_one, Y, Ytest) = train_test_split(msdata, gt, random_state = 666, test_size= 0.75)\n#(X_train_two, Xtest_two, Y, Ytest) = train_test_split(pcdata, gt, random_state = 666, test_size = 0.75 )\n\nclassifier = load_model('/home/SharedData/Avinandan/TeacherStudentExperiments/MultiModal/twostream.h5')\nstreamone = Model(inputs=classifier.get_layer('MultiModal_Input_1').input,\n outputs=classifier.get_layer('MultiModal_Output_1').output)\nstreamtwo = Model(inputs=classifier.get_layer('Multimodal_Input_2').input,\n outputs=classifier.get_layer('MultiModal_Output_2').output)\n#generator = load_model('/home/SharedData/Avinandan/Semi Supervised GAN/2N/generator2N.h5')\n#discriminator = load_model('/home/SharedData/Avinandan/Semi Supervised GAN/2N/discriminator.h5')\n\nprint(classifier.summary())\n \n\nfinalclassifierinput = Input(shape=(2*n_features,))\n\nfinalclassifier = finalclassifierinput\n\nfor layer in classifier.layers[35:]:\n finalclassifier = layer(finalclassifier)\n\n# create the model\n#new_model = Model(layer_input, x)\n\nfinalclassifier = Model(inputs=finalclassifierinput,\n outputs=finalclassifier)\nprint(finalclassifier.summary())\n\n\ndata1 = streamone.predict(msdata)\ndata2 = streamtwo.predict(pcdata)\n\n\ndata=np.concatenate((data1, data2), axis = 1)\n\nrandom_latent_vectors = np.random.normal(0,1, size = (data1.shape[0],latent_dim)) #sample random points\n\n#print(random_latent_vectors.shape,data2.shape,data1.shape)\n\n\ntopvalid = 0\ntoploss = 5000\n\n#610\n#2025 98.28\n#2517 98.51\n\nfor x in range(4815,4845,1):\n\n generator = load_model('/home/SharedData/Avinandan/TeacherStudentExperiments/MultiModal/models/generator-{0}.h5'.format(x))\n #generator = load_model('/home/SharedData/Avinandan/Semi Supervised GAN/2N/generator2N.h5')\n #latent, conditional\n generated_images = generator.predict([random_latent_vectors,data2])\n #generated_images = generator.predict([random_latent_vectors,data1],verbose=1)\n\n #generated_images = np.reshape(generated_images,(,100))\n #print(generated_images.shape)\n\n X_MultiModal1 = np.concatenate((generated_images,data2),axis=1)\n\n #print(X_MultiModal1.shape,Y.shape)\n\n from sklearn.model_selection import train_test_split\n\n\n #(Xtrain_MultiModal, Xtest_MultiModal,Ytrain_MultiModal,Ytest_MultiModal,) = train_test_split(X_MultiModal,Y_MultiModal, random_state = 666)\n\n #(Xtrain_MultiModal, Xtest_MultiModal,Ytrain_MultiModal,Ytest_MultiModal,) = train_test_split(data,Y, random_state = 666)\n\n #(generated_images_train, generated_images_test,Ytrain_MultiModal,Ytest_MultiModal,) = train_test_split(generated_images,Y, random_state = 666)\n #(secondstream_train, secondstream_test,Ytrain_MultiModal,Ytest_MultiModal,) = train_test_split(data2,Y, random_state = 666)\n #(firststream_train, firststream_test,Ytrain_MultiModal,Ytest_MultiModal,) = train_test_split(data1,Y, random_state = 666)\n\n #results = onestream.evaluate([Xtest_MultiModal, Xtest_MultiModal],Ytest_MultiModal, batch_size=32)\n\n #print('test loss, test acc:', results)\n\n (Xtrain_MultiModal1, Xtest_MultiModal1,Ytrain_MultiModal,Ytest_MultiModal,) = train_test_split(X_MultiModal1,Y, random_state = 666, test_size = 0.75)\n\n sgd = SGD(lr=0.0001, momentum=0.9, decay=1e-6)\n finalclassifier.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy'])\n\n #results = finalclassifier.evaluate(Xtest_MultiModal,Ytest_MultiModal, batch_size=32)\n results1 = finalclassifier.evaluate(Xtest_MultiModal1,Ytest_MultiModal, batch_size=32)\n\n print(\" \")\n #print('REAL DATA %d test loss, test acc:', results)\n print('EPOCH GENERATED DATA test loss, test acc:',x, results1)\n\n if results1[1]> topvalid and results1[0]< toploss:\n topvalid = results1[1]\n toploss = results1[0]\n index = x\n\n\nprint(\"%d EPOCH, %f acc\",index,topvalid)\n\n\n\n\n\n\n\n\n\n","sub_path":"MultiModal/testmodelsone.py","file_name":"testmodelsone.py","file_ext":"py","file_size_in_byte":6307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"47407668","text":"\"\"\"\n===========\nHexbin plot\n===========\n\nThis example shows how to plot the location of events occurring in a match\nusing hexbins.\n\"\"\"\nfrom urllib.request import urlopen\n\nfrom matplotlib.colors import LinearSegmentedColormap\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom highlight_text import ax_text\n\nfrom mplsoccer import VerticalPitch, add_image, FontManager, Sbopen\n\n##############################################################################\n# Load the first game that Messi played as a false-9 and the match before.\nparser = Sbopen()\ndf_false9 = parser.event(69249)[0] # 0 index is the event file\ndf_before_false9 = parser.event(69251)[0] # 0 index is the event file\n# filter messi's actions (starting positions)\ndf_false9 = df_false9.loc[df_false9.player_id == 5503, ['x', 'y']]\ndf_before_false9 = df_before_false9.loc[df_before_false9.player_id == 5503, ['x', 'y']]\n\n##############################################################################\n# Create a custom colormap.\n# Note see the `custom colormaps\n# `_\n# example for more ideas.\nflamingo_cmap = LinearSegmentedColormap.from_list(\"Flamingo - 10 colors\",\n ['#e3aca7', '#c03a1d'], N=10)\n\n##############################################################################\n# Plot Messi's first game as a false-9.\npitch = VerticalPitch(line_color='#000009', line_zorder=2, pitch_color='white')\nfig, ax = pitch.draw(figsize=(4.4, 6.4))\nhexmap = pitch.hexbin(df_false9.x, df_false9.y, ax=ax, edgecolors='#f4f4f4',\n gridsize=(8, 8), cmap=flamingo_cmap)\n\n##############################################################################\n# Load a custom font.\nURL = 'https://raw.githubusercontent.com/google/fonts/main/apache/roboto/Roboto%5Bwdth,wght%5D.ttf'\nURL2 = 'https://raw.githubusercontent.com/google/fonts/main/apache/robotoslab/RobotoSlab%5Bwght%5D.ttf'\nrobotto_regular = FontManager(URL)\nrobboto_bold = FontManager(URL2)\n\n##############################################################################\n# Load images.\n\n# Load the StatsBomb logo and Messi picture\nMESSI_URL = 'https://upload.wikimedia.org/wikipedia/commons/b/b8/Messi_vs_Nigeria_2018.jpg'\nmessi_image = Image.open(urlopen(MESSI_URL))\nSB_LOGO_URL = ('https://raw.githubusercontent.com/statsbomb/open-data/'\n 'master/img/SB%20-%20Icon%20Lockup%20-%20Colour%20positive.png')\nsb_logo = Image.open(urlopen(SB_LOGO_URL))\n\n##############################################################################\n# Plot the chart again with a title.\n# We will use mplsoccer's grid function to plot a pitch with a title and endnote axes.\n\nfig, axs = pitch.grid(figheight=10, title_height=0.08, endnote_space=0,\n title_space=0,\n # Turn off the endnote/title axis. I usually do this after\n # I am happy with the chart layout and text placement\n axis=False,\n grid_height=0.82, endnote_height=0.03)\nhexmap = pitch.hexbin(df_false9.x, df_false9.y, ax=axs['pitch'], edgecolors='#f4f4f4',\n gridsize=(8, 8), cmap=flamingo_cmap)\naxs['endnote'].text(1, 0.5, '@your_twitter_handle', va='center', ha='right', fontsize=15,\n fontproperties=robotto_regular.prop)\naxs['title'].text(0.5, 0.7, \"Lionel Messi's Actions\", color='#000009',\n va='center', ha='center', fontproperties=robotto_regular.prop, fontsize=30)\naxs['title'].text(0.5, 0.25, \"First game as a false nine\", color='#000009',\n va='center', ha='center', fontproperties=robotto_regular.prop, fontsize=20)\nax_sb_logo = add_image(sb_logo, fig,\n # set the left, bottom and height to align with the endnote\n left=axs['endnote'].get_position().x0,\n bottom=axs['endnote'].get_position().y0,\n height=axs['endnote'].get_position().height)\n\n##############################################################################\n# Plot Messi's actions in the matches before and after becoming a false-9.\n# We will use mplsoccer's grid function, which is a convenient way to plot a grid\n# of pitches with a title and endnote axes.\n\nfig, axs = pitch.grid(ncols=2, axis=False, endnote_height=0.05)\nhexmap_before = pitch.hexbin(df_before_false9.x, df_before_false9.y, ax=axs['pitch'][0],\n edgecolors='#f4f4f4',\n gridsize=(8, 8), cmap='Reds')\nhexmap2_after = pitch.hexbin(df_false9.x, df_false9.y, ax=axs['pitch'][1], edgecolors='#f4f4f4',\n gridsize=(8, 8), cmap='Blues')\nax_sb_logo = add_image(sb_logo, fig,\n # set the left, bottom and height to align with the endnote\n left=axs['endnote'].get_position().x0,\n bottom=axs['endnote'].get_position().y0,\n height=axs['endnote'].get_position().height)\nax_messi = add_image(messi_image, fig, interpolation='hanning',\n # set the left, bottom and height to align with the title\n left=axs['title'].get_position().x0,\n bottom=axs['title'].get_position().y0,\n height=axs['title'].get_position().height)\n\n# titles using highlight_text and a google font (Robotto)\n\nTITLE_STR1 = 'The Evolution of Lionel Messi'\nTITLE_STR2 = 'Actions in the match and\\n becoming a False-9'\ntitle1_text = axs['title'].text(0.5, 0.7, TITLE_STR1, fontsize=28, color='#000009',\n fontproperties=robotto_regular.prop,\n ha='center', va='center')\nhighlight_text = [{'color': '#800610', 'fontproperties': robboto_bold.prop},\n {'color': '#08306b', 'fontproperties': robboto_bold.prop}]\nax_text(0.5, 0.3, TITLE_STR2, ha='center', va='center', fontsize=18, color='#000009',\n fontproperties=robotto_regular.prop, highlight_textprops=highlight_text, ax=axs['title'])\n\n# sphinx_gallery_thumbnail_path = 'gallery/pitch_plots/images/sphx_glr_plot_hexbin_003.png'\n\n# Messi Photo from: https://en.wikipedia.org/wiki/Lionel_Messi#/media/File:Messi_vs_Nigeria_2018.jpg\n# License: https://creativecommons.org/licenses/by-sa/3.0/;\n# Creator: Кирилл Венедиктов\n\nplt.show() # If you are using a Jupyter notebook you do not need this line\n","sub_path":"examples/pitch_plots/plot_hexbin.py","file_name":"plot_hexbin.py","file_ext":"py","file_size_in_byte":6477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"430380245","text":"def reader(file):\r\n f_out = file[:-2] + 'out'\r\n f = open(file,'r')\r\n T = int(f.readline())\r\n cases = []\r\n for t in range(T):\r\n KCS = f.readline()\r\n KCS_list = KCS.split(' ')\r\n cases.append(KCS_list)\r\n return cases, f_out\r\n\r\ndef solver(cases, f_out):\r\n f_out = open(f_out,'w')\r\n for c in range(len(cases)):\r\n case = cases[c]\r\n K = int(case[0]) \r\n C = int(case[1])\r\n result = [i*K**(C-1)+1 for i in range(K)]\r\n #ZAMIENIC RESULT W STRINGA\r\n string = ''\r\n for i in result:\r\n string += str(i) + ' '\r\n print(\"Case #{}: {}\".format(c + 1, string), file = f_out)\r\n f_out.close()\r\n\r\ndef main():\r\n cases, f_out = reader('D-small-attempt0.in')\r\n solver(cases, f_out)\r\n \r\nmain()\r\n","sub_path":"codes/CodeJamCrawler/16_0_4/marcinowski/Fractiles_2.py","file_name":"Fractiles_2.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"598503619","text":"'''problem 7\n\n\nBy listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.\n\nWhat is the 10 001st prime number?\n'''\n\nimport time\nstart_time = time.time()\n\n\nprimes = [2]\nchecked = [2]\ncomposites = []\n\n#print(len(primes))\n\npin = 3\n\nwhile len(primes)<10001:\n for p in range(0,len(primes)-1):\n if pin%primes[p] == 0:\n composites.append(pin)\n # if pin in composites:\n # continue\n if pin not in composites:\n primes.append(pin)\n if len(primes)%1000==0:\n print('Passing prime # {}'.format(len(primes)))\n print('Computation has taken {} seconds so far.'.format(time.time()-start_time))\n print('Prime density: {}'.format(len(primes)/pin))\n pin+=2\n composites = []\n\nprint('The {}th prime is {}.'.format(len(primes),primes[len(primes)-1]))\nprint('Computation has taken {} seconds so far.'.format(time.time()-start_time))\nprint('Prime density: {}'.format(len(primes)/primes[len(primes)-1]))","sub_path":"problem_007.py","file_name":"problem_007.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"488685385","text":"from .EmbConstant import *\r\nfrom .WriteHelper import write_string_utf8\r\nfrom .PecGraphics import get_graphic_as_string\r\nimport math\r\n\r\nSTRIP_SPEEDS = False\r\nSEQUIN_CONTINGENCY = CONTINGENCY_SEQUIN_UTILIZE\r\nMAX_JUMP_DISTANCE = 121\r\nMAX_STITCH_DISTANCE = 121\r\n\r\n\r\ndef csv(f, values):\r\n string = \"\"\r\n for v in values:\r\n if len(string) > 0:\r\n string += ','\r\n string += ('\\\"%s\\\"' % v)\r\n write_string_utf8(f, string + \"\\n\")\r\n\r\n\r\ndef distance(dx, dy):\r\n dx *= dx\r\n dy *= dy\r\n return math.sqrt(dx + dy)\r\n\r\n\r\ndef angle(dx, dy):\r\n tau = math.pi * 2\r\n angle = math.atan2(dy, dx)\r\n angle += tau / float(2)\r\n angle /= tau\r\n return angle\r\n\r\n\r\ndef write(pattern, f, settings=None):\r\n names = get_common_name_dictionary()\r\n\r\n deltas = settings is not None and \"deltas\" in settings\r\n displacement = settings is not None and \"displacement\" in settings\r\n\r\n extends = pattern.extends()\r\n width = extends[2] - extends[0]\r\n height = extends[3] - extends[1]\r\n\r\n csv(f, ('#', '[VAR_NAME]', '[VAR_VALUE]'))\r\n count_stitches = pattern.count_stitches()\r\n csv(f, ('>', 'STITCH_COUNT:', str(count_stitches)))\r\n count_threads = pattern.count_color_changes()\r\n csv(f, ('>', 'THREAD_COUNT:', str(count_threads)))\r\n csv(f, ('>', 'EXTENTS_LEFT:', str(extends[0])))\r\n csv(f, ('>', 'EXTENTS_TOP:', str(extends[1])))\r\n csv(f, ('>', 'EXTENTS_RIGHT:', str(extends[2])))\r\n csv(f, ('>', 'EXTENTS_BOTTOM:', str(extends[3])))\r\n csv(f, ('>', 'EXTENTS_WIDTH:', str(width)))\r\n csv(f, ('>', 'EXTENTS_HEIGHT:', str(height)))\r\n\r\n stitch_counts = {}\r\n for s in pattern.stitches:\r\n command = s[2]\r\n if command in stitch_counts:\r\n stitch_counts[command] += 1\r\n else:\r\n stitch_counts[command] = 1\r\n\r\n if len(stitch_counts) != 0:\r\n for the_key, the_value in stitch_counts.items():\r\n try:\r\n name = \"COMMAND_\" + names[the_key]\r\n except (IndexError, KeyError):\r\n name = \"COMMAND_UNKNOWN_\" + str(the_key)\r\n csv(f, (\r\n '>',\r\n name,\r\n str(the_value)\r\n ))\r\n\r\n write_string_utf8(f, \"\\n\")\r\n\r\n if len(pattern.extras) > 0:\r\n csv(f, (\r\n '#',\r\n '[METADATA_NAME]',\r\n '[METADATA]'\r\n ))\r\n for the_key, the_value in pattern.extras.items():\r\n if isinstance(the_value, tuple):\r\n the_value = \"\\n\" + get_graphic_as_string(the_value)\r\n csv(f, (\r\n '@',\r\n str(the_key),\r\n str(the_value)\r\n ))\r\n write_string_utf8(f, \"\\n\")\r\n\r\n if len(pattern.threadlist) > 0:\r\n csv(f, (\r\n '#',\r\n '[THREAD_NUMBER]',\r\n '[HEX_COLOR]',\r\n '[DESCRIPTION]',\r\n '[BRAND]',\r\n '[CATALOG_NUMBER]',\r\n '[DETAILS]',\r\n '[WEIGHT]'\r\n ))\r\n for i, thread in enumerate(pattern.threadlist):\r\n csv(f, (\r\n '$',\r\n str(i),\r\n thread.hex_color(),\r\n thread.description,\r\n thread.brand,\r\n thread.catalog_number,\r\n thread.details,\r\n thread.weight,\r\n ))\r\n write_string_utf8(f, \"\\n\")\r\n\r\n if len(pattern.stitches) > 0:\r\n if displacement:\r\n csv(f, (\r\n '#',\r\n '[STITCH_INDEX]',\r\n '[STITCH_TYPE]',\r\n '[X]',\r\n '[Y]',\r\n '[DX]',\r\n '[R]',\r\n '[ANGLE]'\r\n ))\r\n elif deltas:\r\n csv(f, (\r\n '#',\r\n '[STITCH_INDEX]',\r\n '[STITCH_TYPE]',\r\n '[X]',\r\n '[Y]',\r\n '[DX]',\r\n '[DY]'\r\n ))\r\n else:\r\n csv(f, (\r\n '#',\r\n '[STITCH_INDEX]',\r\n '[STITCH_TYPE]',\r\n '[X]',\r\n '[Y]'\r\n ))\r\n current_x = 0\r\n current_y = 0\r\n for i, stitch in enumerate(pattern.stitches):\r\n try:\r\n name = names[stitch[2]]\r\n except (IndexError, KeyError):\r\n name = \"UNKNOWN \" + str(stitch[2])\r\n if displacement:\r\n dx = stitch[0] - current_x\r\n dy = stitch[1] - current_y\r\n csv(f, (\r\n '*',\r\n str(i),\r\n name,\r\n str(stitch[0]),\r\n str(stitch[1]),\r\n str(dx),\r\n str(dy),\r\n str(distance(dx, dy)),\r\n str(angle(dx, dy))\r\n ))\r\n elif deltas:\r\n dx = stitch[0] - current_x\r\n dy = stitch[1] - current_y\r\n csv(f, (\r\n '*',\r\n str(i),\r\n name,\r\n str(stitch[0]),\r\n str(stitch[1]),\r\n str(dx),\r\n str(dy)\r\n ))\r\n else:\r\n csv(f, (\r\n '*',\r\n str(i),\r\n name,\r\n str(stitch[0]),\r\n str(stitch[1]),\r\n ))\r\n current_x = stitch[0]\r\n current_y = stitch[1]\r\n\r\n\r\ndef get_common_name_dictionary():\r\n return {\r\n NO_COMMAND: \"NO_COMMAND\",\r\n STITCH: \"STITCH\",\r\n JUMP: \"JUMP\",\r\n TRIM: \"TRIM\",\r\n STOP: \"STOP\",\r\n END: \"END\",\r\n SLOW: \"SLOW\",\r\n FAST: \"FAST\",\r\n COLOR_CHANGE: \"COLOR_CHANGE\",\r\n SEQUIN_MODE: \"SEQUIN_MODE\",\r\n SEQUIN_EJECT: \"SEQUIN_EJECT\",\r\n SEW_TO: \"SEW_TO\",\r\n NEEDLE_AT: \"NEEDLE_AT\",\r\n STITCH_BREAK: \"STITCH_BREAK\",\r\n SEQUENCE_BREAK: \"SEQUENCE_BREAK\",\r\n COLOR_BREAK: \"COLOR_BREAK\",\r\n TIE_ON: \"TIE_ON\",\r\n TIE_OFF: \"TIE_OFF\",\r\n FRAME_EJECT: \"FRAME_EJECT\",\r\n MATRIX_TRANSLATE: \"MATRIX_TRANSLATE\",\r\n MATRIX_SCALE: \"MATRIX_SCALE\",\r\n MATRIX_ROTATE: \"MATRIX_ROTATE\",\r\n MATRIX_RESET: \"MATRIX_RESET\",\r\n OPTION_ENABLE_TIE_ON: \"OPTION_ENABLE_TIE_ON\",\r\n OPTION_ENABLE_TIE_OFF: \"OPTION_ENABLE_TIE_OFF\",\r\n OPTION_DISABLE_TIE_ON: \"OPTION_DISABLE_TIE_ON\",\r\n OPTION_DISABLE_TIE_OFF: \"OPTION_DISABLE_TIE_OFF\",\r\n OPTION_MAX_STITCH_LENGTH: \"OPTION_MAX_STITCH_LENGTH\",\r\n OPTION_MAX_JUMP_LENGTH: \"OPTION_MAX_JUMP_LENGTH\",\r\n OPTION_IMPLICIT_TRIM: \"OPTION_IMPLICIT_TRIM\",\r\n OPTION_EXPLICIT_TRIM: \"OPTION_EXPLICIT_TRIM\",\r\n CONTINGENCY_NONE: \"CONTINGENCY_NONE\",\r\n CONTINGENCY_JUMP_NEEDLE: \"CONTINGENCY_JUMP_NEEDLE\",\r\n CONTINGENCY_SEW_TO: \"CONTINGENCY_SEW_TO\",\r\n }\r\n","sub_path":"pyembroidery/CsvWriter.py","file_name":"CsvWriter.py","file_ext":"py","file_size_in_byte":6934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"177916738","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys\n\n# Запись о багаже пассажира авиарейса содержит следующие поля:\n# номер рейса, дата вылета, пункт назначения, фамилия пассажира, количество мест багажа,\n# суммарный вес багажа.\n# Поиск выполнять по номеру рейса, дате вылета, пункту назначения, весу багажа (превышение максимально допустимого).\n\n\nclass SimpleIterator:\n\n def __init__(self, limit):\n self.limit = limit\n self.counter = 0\n\n def __next__(self):\n if self.counter < self.limit:\n self.counter += 1\n return 1\n else:\n raise StopIteration\n\n\nif __name__ == '__main__':\n # Список данных о багаже.\n baggage = []\n # Организовать бесконечный цикл запроса команд.\n while True:\n # Запросить команду из терминала.\n command = input(\">>> \").lower()\n # Выполнить действие в соответствие с командой.\n if command == 'exit':\n break\n elif command == 'add':\n # Запросить запись о багаже.\n second_name = input(\"Введите фамилию пассажира: \")\n number_of_seats = int(input(\"Введите кол-во мест багажа: \"))\n flight_number = list(map(int, input(\"Введите номер рейса: \").split(\".\")))\n date = list(map(int, input(\"Введите дату вылета: \").split(\".\")))\n location = list(map(str, input(\"Введите пункт назначения: \").split(\".\")))\n weight = list(map(int, input(\"Введите суммарный вес багажа: \").split(\".\")))\n\n # Создать словарь.\n information = {\n 'second_name': second_name,\n 'number_of_seats': number_of_seats,\n 'flight_number': flight_number,\n 'date': date,\n 'location': location,\n 'weight': weight\n }\n\n baggage.append(information)\n if len(baggage) > 1:\n baggage.sort(key=lambda item: item.get('name', ''))\n elif command == 'list':\n line = '+-{}-+-{}-+-{}-+-{}-+-{}-+-{}-+-{}-+-{}-+-{}-+'.format(\n '-' * 4,\n '-' * 30,\n '-' * 20,\n '-' * 8,\n '-' * 8,\n '-' * 8,\n '-' * 8,\n '-' * 8,\n '-' * 11\n )\n print(line)\n print(\n '| {:^3} | {:^30} | {:^20} | {:^8} | {:^8} | {:^8} | {:^8} | {:^8} |'.format(\n \"№\",\n \"Ф.И.О.\",\n \"Группа\",\n \"1-ая оценка\",\n \"2-ая оценка\",\n \"3-ая оценка\",\n \"4-ая оценка\",\n \"5-ая оценка\"\n )\n )\n print(line)\n # Вывести данные о всех сотрудниках.\n for idx, person in enumerate(students, 1):\n print(\n '| {:>3} | {:<30} | {:<20} | {:>11} | {:>11} | {:>11} | {:>11} | {:>11} |'.format(\n idx,\n person.get('name', ''),\n person.get('group', ''),\n person.get('marks[0]', f'{marks[0]}'),\n person.get('marks[1]', f'{marks[1]}'),\n person.get('marks[2]', f'{marks[2]}'),\n person.get('marks[3]', f'{marks[3]}'),\n person.get('marks[4]', f'{marks[4]}')\n )\n )\n print(line)\n elif command.startswith('select '):\n parts = command.split(' ', maxsplit=2)\n period = int(parts[1])\n\n count = 0\n for person in students:\n if 2 in marks:\n count += 1\n print(\n '{:>4}: {}'.format(count, person.get('name', ''))\n )\n # Если счетчик равен 0, то работники не найдены.\n if count == 0:\n print(\"Нет сту��ентов, которые получили оценку - 2.\")\n elif command == 'help':\n # Вывести справку о работе с программой.\n print(\"Список команд:\\n\")\n print(\"add - добавить студента;\")\n print(\"list - вывести список студентов;\")\n print(\"select <оценка> - найти студентов которые получили такую оценку;\")\n print(\"help - отобразить справку;\")\n print(\"exit - завершить работу с программой.\")\n else:\n print(f\"Неизвестная команда {command}\", file=sys.stderr)","sub_path":"individ_1.py","file_name":"individ_1.py","file_ext":"py","file_size_in_byte":5390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"317159445","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimg = cv2.imread(\"t_shape.png\")\nrows,coloums,channels = img.shape\nM1 = np.float32([[1,0,50],[0,1,50]])\ntrans1 = cv2.warpAffine(img,M1,(coloums,rows))\nM2 = np.float32([[1,0,0],[0,1,100]])\ntrans2 = cv2.warpAffine(img,M2,(coloums,rows))\nM3 = np.float32([[1,0,50],[0,1,-50]])\ntrans3 = cv2.warpAffine(img,M3,(coloums,rows))\nM4 = np.float32([[1,0,-50],[0,1,-50]])\ntrans4 = cv2.warpAffine(img,M4,(coloums,rows))\n\n\nM5 = cv2.getRotationMatrix2D((coloums/2,rows/2),45,1)\nrot1 = cv2.warpAffine(img,M5,(coloums,rows))\nM6 = cv2.getRotationMatrix2D((coloums/2,rows/2),90,1)\nrot2 = cv2.warpAffine(img,M6,(coloums,rows))\nM7 = cv2.getRotationMatrix2D((coloums/2,rows/2),180,1)\nrot3 = cv2.warpAffine(img,M7,(coloums,rows))\nM8 = cv2.getRotationMatrix2D((coloums/2,rows/2),135,1)\nrot4 = cv2.warpAffine(img,M8,(coloums,rows))\n\n\nblur1 = cv2.blur(img,(3,3))\nblur2 = cv2.GaussianBlur(img,(3,3),0)\n\n\nfig, axs = plt.subplots(2, 5)\naxs[0,0].imshow(cv2.cvtColor(trans1,cv2.COLOR_BGR2RGB))\naxs[0,1].imshow(cv2.cvtColor(trans2,cv2.COLOR_BGR2RGB))\naxs[0,2].imshow(cv2.cvtColor(trans3,cv2.COLOR_BGR2RGB))\naxs[0,3].imshow(cv2.cvtColor(trans4,cv2.COLOR_BGR2RGB))\naxs[0,4].imshow(cv2.cvtColor(rot1,cv2.COLOR_BGR2RGB))\naxs[1,0].imshow(cv2.cvtColor(rot2,cv2.COLOR_BGR2RGB))\naxs[1,1].imshow(cv2.cvtColor(rot3,cv2.COLOR_BGR2RGB))\naxs[1,2].imshow(cv2.cvtColor(rot4,cv2.COLOR_BGR2RGB))\naxs[1,3].imshow(cv2.cvtColor(blur1,cv2.COLOR_BGR2RGB))\naxs[1,4].imshow(cv2.cvtColor(blur2,cv2.COLOR_BGR2RGB))\nplt.show()","sub_path":"OpenCV/assignment2_1.py","file_name":"assignment2_1.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"256035923","text":"#정렬된 배열에서 특정 수의 개수 구하기\n\n#정렬된 수열에서 길이 x인 원소의 개수를 세는 메서드\ndef count_by_value(array,x):\n n = len(array) # 데이터의 개수\n\n # x가 처음 등장한 인덱스 계산\n a = first(array,x,0,n-1)\n\n if a == None:\n return 0 # 값이 x인 원소의 개수는 0개이므로 0 반환\n \n # x가 마지막으로 등장한 인덱스 계산\n b = last(array,x,0,n-1)\n\n return b - a + 1\n\n#처음 위치를 찾는 이진 탐색 메서드\n\ndef first(array,target,start,end):\n if start>end:\n return None\n mid = (start+end)//2\n # 해당 값을 가지는 원소 중에서 가장 왼쪽에 있는 경우에만 인덱스 반환\n if (mid == 0 or target > array[mid-1]) and array[mid] == target:\n return mid\n # 중간점의 값 보다 찾고자 하는 값이 적거나 같은 경우 왼쪽 확인\n elif array[mid] >= target:\n return first(array,target,start,mid-1)\n # 중간점의 값 보다 찾고자 하는 값이 크거나 같은 경우 오른쪽 확인\n else:\n return first(array,target,mid+1,end)\n\ndef last(array,target,start,end):\n if start>end:\n return None\n mid = (start+end)//2\n # 해당 값을 가지는 원소 중에서 가장 왼쪽에 있는 경우에만 인덱스 반환\n if (mid == n-1 or target < array[mid+1]) and array[mid] == target:\n return mid\n # 중간점의 값 보다 찾고자 하는 값이 적거나 같은 경우 왼쪽 확인\n elif array[mid] > target:\n return last(array,target,start,mid-1)\n # 중간점의 값 보다 찾고자 하는 값이 크거나 같은 경우 오른쪽 확인\n else:\n return last(array,target,mid+1,end)\n\nn,x = map(int,input().split())\narray = list(map(int,input().split()))\n\ncount = count_by_value(array,x)\n\nif count == 0:\n print(-1)\nelse:\n print(count)\n","sub_path":"이코테/이진탐색/정렬된 배수에서 특정 수의 개수 구하기-2.py","file_name":"정렬된 배수에서 특정 수의 개수 구하기-2.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"157961448","text":"# -*- encoding: UTF-8 -*-\n\nimport psutil\nimport datetime\n\nclass ServerInfo:\n\n @staticmethod\n def cpu_percent():\n return psutil.cpu_percent()\n\n @staticmethod\n def cpu_times():\n return psutil.cpu_times()\n\n @staticmethod\n def cpu_info():\n info = {}\n info[\"cpu_count\"] = psutil.cpu_count(logical=False)\n info[\"cpu_logical_count\"] = psutil.cpu_count()\n info[\"cpu_freq\"] = psutil.cpu_freq()._asdict()\n return info\n\n @staticmethod\n def mem_info():\n return psutil.virtual_memory()._asdict()\n\n @staticmethod\n def disk_info():\n partitions = psutil.disk_partitions()\n disks = []\n for partition in partitions:\n usage = None\n if partition.fstype:\n usage = psutil.disk_usage(partition.device)\n item = {\n \"device\": partition.device,\n \"mountpoint\": partition.mountpoint,\n \"fstype\": partition.fstype,\n \"opts\": partition.opts,\n \"usage\": None\n }\n if usage:\n item[\"usage\"] = {\n \"total\": usage.total,\n \"used\": usage.used,\n \"free\": usage.free,\n \"percent\": usage.percent\n }\n disks.append(item)\n return disks\n\n @staticmethod\n def processes():\n processes = []\n for proc in psutil.process_iter():\n try:\n pinfo = proc.as_dict(attrs=['pid', 'name', \"cpu_percent\", \"memory_info\", \"username\", \"exe\"])\n pinfo[\"memory_info\"] = proc.memory_info()\n except Exception as e:\n print(e)\n pass\n else:\n processes.append(pinfo)\n return processes\n\n @staticmethod\n def boot_time():\n time = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime(\"%Y-%m-%d %H:%M:%S\")\n return time","sub_path":"server_info.py","file_name":"server_info.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"330842741","text":"from typing import List\n\n\nclass Solution:\n def minPathSum(self, grid: List[List[int]]) -> int:\n row, col = len(grid), len(grid[0])\n dp = [[0]*col for _ in range(row)]\n dp[row-1][col-1] = grid[row-1][col-1]\n for i in range(col-2, -1, -1):\n dp[row-1][i] = dp[row-1][i+1] + grid[row-1][i]\n for i in range(row-2, -1, -1):\n dp[i][col-1] = dp[i+1][col-1] + grid[i][col-1]\n for i in range(row-2, -1, -1):\n for j in range(col-2, -1, -1):\n dp[i][j] = grid[i][j] + min(dp[i][j+1], dp[i+1][j])\n return dp[0][0]\n\n\ns = Solution()\nprint(s.minPathSum([[1, 2, 3], [4, 5, 6]]))\n","sub_path":"Python/DP/64_MinimumPathSum/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"371528273","text":"from __future__ import annotations\n\nimport logging\nimport time\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass, field\nfrom typing import (\n Callable,\n Generic,\n Mapping,\n MutableMapping,\n MutableSequence,\n Optional,\n Sequence,\n TypeVar,\n)\n\nfrom snuba.utils.metrics import MetricsBackend\nfrom snuba.utils.streams.processing.strategies.abstract import (\n ProcessingStrategy,\n ProcessingStrategyFactory,\n)\nfrom snuba.utils.streams.types import Message, Partition, TPayload\n\n\nlogger = logging.getLogger(__name__)\n\n\nTResult = TypeVar(\"TResult\")\n\n\nclass AbstractBatchWorker(ABC, Generic[TPayload, TResult]):\n \"\"\"\n The ``BatchProcessingStrategy`` requires an instance of this class to\n handle user provided work such as processing raw messages and flushing\n processed batches to a custom backend.\n \"\"\"\n\n @abstractmethod\n def process_message(self, message: Message[TPayload]) -> Optional[TResult]:\n \"\"\"\n Called with each raw message, allowing the worker to do incremental\n (preferably local!) work on events. The object returned is put into\n the batch maintained internally by the ``BatchProcessingStrategy``.\n\n If this method returns `None` it is not added to the batch.\n\n A simple example would be decoding the message payload value and\n extracting a few fields.\n \"\"\"\n pass\n\n @abstractmethod\n def flush_batch(self, batch: Sequence[TResult]) -> None:\n \"\"\"\n Called with a list of processed (by ``process_message``) objects.\n The worker should write the batch of processed messages into whatever\n store(s) it is maintaining. Afterwards the offsets are committed by\n the ``BatchProcessingStrategy``.\n\n A simple example would be writing the batch to another topic.\n \"\"\"\n pass\n\n\n@dataclass\nclass Offsets:\n __slots__ = [\"lo\", \"hi\"]\n\n lo: int # inclusive\n hi: int # exclusive\n\n\n@dataclass\nclass Batch(Generic[TResult]):\n results: MutableSequence[TResult] = field(default_factory=list)\n offsets: MutableMapping[Partition, Offsets] = field(default_factory=dict)\n created: float = field(default_factory=lambda: time.time())\n messages_processed_count: int = 0\n # the total amount of time, in milliseconds, that it took to process\n # the messages in this batch (does not included time spent waiting for\n # new messages)\n processing_time_ms: float = 0.0\n\n\nclass BatchProcessingStrategy(ProcessingStrategy[TPayload]):\n \"\"\"\n The ``BatchProcessingStrategy`` is a processing strategy that accumulates\n processed message values, periodically flushing them after a given\n duration of time has passed or number of output values have been\n accumulated. Users need only provide an implementation of what it means\n to process a raw message and flush a batch of events via an\n ``AbstractBatchWorker`` instance.\n\n Messages are processed as they are read from the consumer, then added to\n an in-memory batch. These batches are flushed based on the batch size or\n time sent since the first message in the batch was recieved (e.g. \"500\n items or 1000ms\"), whichever threshold is reached first. When a batch of\n items is flushed, the consumer offsets are synchronously committed.\n \"\"\"\n\n def __init__(\n self,\n commit: Callable[[Mapping[Partition, int]], None],\n worker: AbstractBatchWorker[TPayload, TResult],\n max_batch_size: int,\n max_batch_time: int,\n metrics: MetricsBackend,\n ) -> None:\n self.__commit = commit\n self.__worker = worker\n self.__max_batch_size = max_batch_size\n self.__max_batch_time = max_batch_time\n self.__metrics = metrics\n\n self.__batch: Optional[Batch[TResult]] = None\n self.__closed = False\n\n def poll(self) -> None:\n \"\"\"\n Check if the current in-flight batch should be flushed.\n \"\"\"\n assert not self.__closed\n\n if self.__batch is not None and (\n len(self.__batch.results) >= self.__max_batch_size\n or time.time() > self.__batch.created + self.__max_batch_time / 1000.0\n ):\n self.__flush()\n\n def submit(self, message: Message[TPayload]) -> None:\n \"\"\"\n Process a message.\n \"\"\"\n assert not self.__closed\n\n start = time.time()\n\n self.__metrics.timing(\n \"receive_latency\",\n (start - message.timestamp.timestamp()) * 1000,\n tags={\n \"topic\": message.partition.topic.name,\n \"partition\": str(message.partition.index),\n },\n )\n\n # Create the batch only after the first message is seen.\n if self.__batch is None:\n self.__batch = Batch()\n\n result = self.__worker.process_message(message)\n\n # XXX: ``None`` is indistinguishable from a potentially valid return\n # value of ``TResult``!\n if result is not None:\n self.__batch.results.append(result)\n\n duration = (time.time() - start) * 1000\n self.__batch.messages_processed_count += 1\n self.__batch.processing_time_ms += duration\n self.__metrics.timing(\"process_message\", duration)\n\n if message.partition in self.__batch.offsets:\n self.__batch.offsets[message.partition].hi = message.next_offset\n else:\n self.__batch.offsets[message.partition] = Offsets(\n message.offset, message.next_offset\n )\n\n def close(self) -> None:\n self.__closed = True\n\n def terminate(self) -> None:\n self.__closed = True\n\n def join(self, timeout: Optional[float] = None) -> None:\n # The active batch is discarded when exiting without attempting to\n # write or commit, so this method can exit immediately without\n # blocking.\n pass\n\n def __flush(self) -> None:\n \"\"\"\n Flush the active batch and reset the batch state.\n \"\"\"\n assert not self.__closed\n assert self.__batch is not None, \"cannot flush without active batch\"\n\n logger.info(\n \"Flushing %s items (from %r)\",\n len(self.__batch.results),\n self.__batch.offsets,\n )\n\n self.__metrics.timing(\n \"process_message.normalized\",\n self.__batch.processing_time_ms / self.__batch.messages_processed_count,\n )\n\n batch_results_length = len(self.__batch.results)\n if batch_results_length > 0:\n logger.debug(\"Flushing batch via worker\")\n flush_start = time.time()\n self.__worker.flush_batch(self.__batch.results)\n flush_duration = (time.time() - flush_start) * 1000\n logger.info(\"Worker flush took %dms\", flush_duration)\n self.__metrics.timing(\"batch.flush\", flush_duration)\n self.__metrics.timing(\n \"batch.flush.normalized\", flush_duration / batch_results_length\n )\n\n logger.debug(\"Committing offsets for batch\")\n commit_start = time.time()\n offsets = {\n partition: offsets.hi for partition, offsets in self.__batch.offsets.items()\n }\n self.__commit(offsets)\n logger.debug(\"Committed offsets: %s\", offsets)\n commit_duration = (time.time() - commit_start) * 1000\n logger.debug(\"Offset commit took %dms\", commit_duration)\n\n self.__batch = None\n\n\nclass BatchProcessingStrategyFactory(ProcessingStrategyFactory[TPayload]):\n def __init__(\n self,\n worker: AbstractBatchWorker[TPayload, TResult],\n max_batch_size: int,\n max_batch_time: int,\n metrics: MetricsBackend,\n ) -> None:\n self.__worker = worker\n self.__max_batch_size = max_batch_size\n self.__max_batch_time = max_batch_time\n self.__metrics = metrics\n\n def create(\n self, commit: Callable[[Mapping[Partition, int]], None]\n ) -> ProcessingStrategy[TPayload]:\n return BatchProcessingStrategy(\n commit,\n self.__worker,\n self.__max_batch_size,\n self.__max_batch_time,\n self.__metrics,\n )\n","sub_path":"snuba/utils/streams/processing/strategies/batching.py","file_name":"batching.py","file_ext":"py","file_size_in_byte":8214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"646569231","text":"'''\nredis实现的分布式锁\n'''\nimport redis_pool\nimport redis\nimport threading\nimport time\n\n\nredis_client = redis.Redis(connection_pool=redis_pool.pool)\n\n\ndef task():\n print(threading.current_thread().name)\n\n\ndef doSomething():\n '''\n 分布式锁实现,没有时设置并设置超时时间,完成任务后删除\n 会有任务超过锁超时时间的问题。。。\n '''\n try:\n redis_client.set('lock', 1, ex=20, nx=True)\n for i in range(3):\n task()\n time.sleep(5)\n except Exception as e:\n print(e)\n finally:\n redis_client.delete('lock')\n\n\nif __name__ == '__main__':\n threads = []\n for i in range(3):\n t = threading.Thread(\n name='thread-' + str(i),\n target=doSomething,\n daemon=True)\n threads.append(t)\n for t in threads:\n t.start()\n for t in threads:\n t.join()\n","sub_path":"redis/distributed_lock_redis.py","file_name":"distributed_lock_redis.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"173876335","text":"\n# my package\nfrom param import Param\nfrom run import run\nfrom systems.consensus import Consensus\nfrom other_policy import LCP_Policy, WMSR_Policy\n\n# standard package\nimport numpy as np \nfrom torch import nn as nn \nfrom torch import tanh\nimport torch \n\nclass ConsensusParam(Param):\n\tdef __init__(self):\n\t\tsuper().__init__()\n\t\tself.env_name = 'Consensus'\n\t\tself.env_case = None\n\n\t\t#\n\t\tself.pomdp_on = True\n\t\tself.r_comm = 5\n\t\tself.n_agents = 5\n\t\tself.n_malicious = 1\n\t\tself.agent_memory = 2\n\t\tself.n_neighbors = 4\n\t\tself.single_agent_sim = False\n\t\tself.multi_agent_sim = True \n\n\t\t# dim \n\t\tself.state_dim_per_agent = 1 \n\t\tself.state_dim = self.n_agents*self.state_dim_per_agent\n\t\tself.action_dim_per_agent = 1\n\t\tself.action_dim = self.n_agents*self.action_dim_per_agent\n\n\t\t# RL\n\t\tself.rl_train_model_fn = '../models/consensus/rl_current.pt'\n\t\tself.rl_continuous_on = False\n\t\tself.rl_lr_schedule_on = False\n\t\tself.rl_gpu_on = False\n\t\tself.rl_max_episodes = 50000\n\t\tself.rl_batch_size = 500\n\t\tself.rl_gamma = 0.98\n\t\tself.rl_K_epoch = 5\n\t\tself.rl_num_actions = 5\n\t\tself.a_min = -1\n\t\tself.a_max = 1\n\t\tself.rl_discrete_action_space = np.linspace(self.a_min, self.a_max, self.rl_num_actions)\n\t\tself.rl_warm_start_on = False \n\t\tself.rl_warm_start_fn = '../models/consensus/rl_current.pt'\n\t\tself.rl_module = \"PPO\" # PPO_w_DeepSet, DDPG, PPO, (DDPG_w_DeepSet)\n\t\tself.rl_log_interval = 20\n\t\tself.rl_scale_reward = 0.01\n\n\t\th_s = 32 # hidden layer\n\t\tself.rl_activation = tanh\n\t\tif self.rl_module is 'DDPG':\n\t\t\t# ddpg param\n\t\t\tself.rl_lr_mu = 5e-5\n\t\t\tself.rl_lr_q = 5e-4\n\t\t\tself.rl_buffer_limit = 5e6\n\t\t\tself.rl_action_std = 1\n\t\t\tself.rl_max_action_perturb = 0.5\n\t\t\tself.rl_tau = 0.995\n\t\t\t# network architecture\n\t\t\tself.rl_mu_network_architecture = nn.ModuleList([\n\t\t\t\tnn.Linear(n,h_mu), \n\t\t\t\tnn.Linear(h_mu,h_mu),\n\t\t\t\tnn.Linear(h_mu,m)])\n\t\t\tself.rl_q_network_architecture = nn.ModuleList([\n\t\t\t\tnn.Linear(n+m,h_q),\n\t\t\t\tnn.Linear(h_q,h_q),\n\t\t\t\tnn.Linear(h_q,1)])\n\t\t\tself.rl_network_activation = tanh \t\t\n\n\t\telif self.rl_module is 'PPO':\n\t\t\t# ppo param\n\t\t\tself.rl_lr = 5e-4\n\t\t\tself.rl_lmbda = 0.95\n\t\t\tself.rl_eps_clip = 0.2\n\n\t\t\tself.rl_layers = nn.ModuleList([\n\t\t\t\tnn.Linear(self.agent_memory*self.n_neighbors,h_s),\n\t\t\t\tnn.Linear(h_s,h_s),\n\t\t\t\tnn.Linear(h_s,len(self.rl_discrete_action_space)),\n\t\t\t\tnn.Linear(h_s,1)\n\t\t\t\t])\n\n\t\t# IL\n\t\tself.il_train_model_fn = '../models/consensus/il_current.pt'\n\t\tself.il_imitate_model_fn = '../models/consensus/rl_current.pt'\n\t\tself.il_controller_class = None \n\n\t\t# Sim\n\t\tself.sim_rl_model_fn = '../models/consensus/rl_current.pt'\n\t\tself.sim_il_model_fn = '../models/consensus/il_current.pt'\n\t\tself.sim_render_on = True\n\t\tself.sim_t0 = 0\n\t\tself.sim_tf = 8\n\t\tself.sim_dt = 0.01\n\t\tself.sim_times = np.arange(self.sim_t0,self.sim_tf,self.sim_dt)\n\t\tself.sim_nt = len(self.sim_times)\n\n\t\tself.plots_fn = 'plots.pdf'\n\n\n\nif __name__ == '__main__':\n\tparam = ConsensusParam()\n\tenv = Consensus(param)\n\n\t# x0 = np.array([0.4, np.pi/2, 0.5, 0])\n\t# x0 = np.array([0.07438156, 0.33501733, 0.50978889, 0.52446423])\n\n\n\tcontrollers = {\n\t\t'LCP': LCP_Policy(env),\n\t\t# 'WMSR': WMSR_Policy(env),\n\t\t'RL':\ttorch.load(param.sim_rl_model_fn),\n\t\t# 'IL':\ttorch.load(param.sim_il_model_fn),\n\t\t# 'SCP':\tFilePolicy(scp_file),\n\t}\n\n\trun(param, env, controllers)","sub_path":"code/examples/run_consensus.py","file_name":"run_consensus.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"426927533","text":"# coding: utf8\nfrom __future__ import unicode_literals\n\nimport Queue\nimport time\n\nimport requests\n\nimport IRC\nimport message_parsing\nimport utils\n\n\nclass Troll(IRC.Bot):\n \"\"\"\n Troll class who respond with random quote\n \"\"\"\n\n def __init__(self, parent, username, Target, server, channel_to_reply):\n IRC.Bot.__init__(self, parent, Target, username, server)\n self.queue = Queue.Queue()\n self.channel_to_reply = channel_to_reply\n\n def init(self):\n \"\"\"\n init the bot (send i can help you to target)\n\n :return: Nothing what did you expect\n \"\"\"\n self.reply(\"I can help you {} :)\".format(self.target), \"PRIVMSG\")\n\n def main(self):\n \"\"\"\n main loop of bot , reply to every Message with a quote and send the conversation to main channel\n\n :return: Nothing what did you expect\n \"\"\"\n message = self.queue.get()\n res = self.get_citation()\n self.reply(\"{}=>{}\".format(message.pseudo, message.content), \"PUBMSG\", target=self.channel_to_reply)\n time.sleep(0.1 * len(res))\n self.reply(\"{}<={}\".format(message.pseudo, res), \"PUBMSG\", target=self.channel_to_reply)\n self.reply(res, \"PRIVMSG\")\n\n @staticmethod\n def get_citation():\n \"\"\"\n get a random quote\n\n :return: random quote\n \"\"\"\n r = requests.get(\"http://www.quotationspage.com/random.php3\")\n return utils.parse_html_balise(\"a\", utils.parse_html_balise(\"dt\", r.text))\n\n\ndef create_troll(message, bot):\n param = message.content.split()\n if message.pseudo not in [\"Tagashy\", \"ghozt\"]:\n return\n if len(param) != 2:\n if message.msg_type == \"PRIVMSG\":\n bot.reply(\"!troll \", \"PRIVMSG\", target=message.pseudo)\n else:\n bot.reply(\"!troll \", \"PUBMSG\")\n else:\n if param[1].lower() not in {\"hackira\", \"arod\", \"dazax\", \"dvor4x\", \"notfound\", \"sambecks\", \"thanat0s\", \"gelu\",\n \"geluchat\", bot.username, \"#root-me\"}:\n troll = Troll(bot.parent, bot.username, param[1], bot.server, bot.target)\n reg = message_parsing.Message(pseudo=param[1], msg_type=\"PRIVMSG\")\n bot.parent.add_bot(reg, troll, bot.username, bot.server, bot.target)\n if message.msg_type == \"PRIVMSG\":\n bot.reply(\"trolling {} :P\".format(param[1]), \"PRIVMSG\", target=message.pseudo)\n else:\n bot.reply(\"trolling {} :P\".format(param[1]), \"PUBMSG\")\n","sub_path":"RandomQuote.py","file_name":"RandomQuote.py","file_ext":"py","file_size_in_byte":2534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"355061135","text":"#!/usr/bin/env python\n\nimport os\nimport time\n#import serial\nimport rospy\nimport math\nfrom std_msgs.msg import Float64\nfrom std_msgs.msg import UInt16\n\nclass Motors:\n def __init__(self):\n self.thrust = True\n\n self.maxPowerValue = 1900\n self.minPowerValue = 1100\n\n self.powerR = 0 \n self.powerL = 0 \n\n rospy.Subscriber(\"right_thruster\", Float64, self.right_callback)\n rospy.Subscriber(\"left_thruster\", Float64, self.left_callback)\n\n self.r_pwm_pub = rospy.Publisher(\"rpwm\", UInt16, queue_size=10)\n self.l_pwm_pub = rospy.Publisher(\"lpwm\", UInt16, queue_size=10)\n\n def right_callback(self, right_t):\n self.powerR = right_t.data\n #rospy.logwarn(self.powerR)\n\n def left_callback(self, left_t):\n self.powerL = left_t.data\n #rospy.logwarn(self.powerL)\n\n def move_thrusters(self,powerR=1500, powerL=1500):\n #validate the pwm range\n if powerR < 1100 or powerR > 1900 or powerL < 1100 or powerL > 1900:\n rospy.logwarn(\"Thruster power must be between 1100 - 1900\")\n else:\n pwmR = powerR\n pwmL = powerL\n self.r_pwm_pub.publish(pwmR)\n self.l_pwm_pub.publish(pwmL)\n\n def newtons(self, powerR=0, powerL=0):\n #validate the Newtons range\n if (powerR < -30 or powerR > 36.5 or powerL < -30 or powerL > 36.5):\n rospy.logwarn(\"Saturation range\")\n realPowerValueR = powerR * 0.5\n realPowerValueL = powerL * 0.5\n\n else:\n if (powerR >= 0):\n realPowerValueR = round((powerR / 36.5 * 385)+1515)\n elif (powerR < 0):\n realPowerValueR = round((powerR / 30 * 385)+1485)\n if (powerL <= 0):\n realPowerValueL = round((powerL / 30 * 385)+1485)\n elif(powerL > 0):\n realPowerValueL = round((powerL / 36.5 * 385)+1515)\n\n self.move_thrusters(realPowerValueR,realPowerValueL)\n #print('moving')\n\n def run(self, powerR = 0, powerL = 0):\n self.newtons(powerR, powerL)\n\ndef main():\n rospy.init_node('ardumotors', anonymous=True)\n rate = rospy.Rate(250) # 100hz\n m = Motors()\n while not rospy.is_shutdown() and m.thrust:\n #if m.thrust:\n m.run(m.powerR, m.powerL)\n rate.sleep()\n rospy.spin()\n\nif __name__ == \"__main__\":\n try:\n main()\n except rospy.ROSInterruptException:\n pass","sub_path":"scripts/ardumotors.py","file_name":"ardumotors.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"287244467","text":"class Disponibilidad:\r\n\r\n def __init__(self, pId=None, pDescripcion=None):\r\n self.id = pId\r\n self.descripcion = pDescripcion\r\n\r\n def __getitem__(self, item):\r\n return self.__dict__[item]\r\n\r\n def __str__(self):\r\n return 'Descripción: {}'.format(self.descripcion)\r\n\r\n\r\ndef getDisponibilidadesRegistradas(bd):\r\n try:\r\n cursor = bd.connection.cursor()\r\n cursor.execute('SELECT id, descripcion FROM disponibilidad')\r\n retorno = cursor.fetchall()\r\n bd.connection.commit()\r\n cursor.close()\r\n disponibilidades = list()\r\n for tuplaDisponibilidad in retorno:\r\n disponibilidad = Disponibilidad(\r\n tuplaDisponibilidad[0], tuplaDisponibilidad[1])\r\n disponibilidades.append(disponibilidad)\r\n return disponibilidades\r\n except Exception as e:\r\n print(\"Error en getDisponibilidadesRegistradas \", e)\r\n\r\n\r\ndef agregarDisponibilidadEmpleado(bd, id_disponibilidad, id_empleado):\r\n try:\r\n cursor = bd.connection.cursor()\r\n cursor.execute('INSERT INTO empleado_disponibilidad (id_empleado, id_disponibilidad) VALUES ({}, {})'.format(\r\n id_empleado, id_disponibilidad))\r\n bd.connection.commit()\r\n cursor.close()\r\n #print('Disponibilidad \"', id_disponibilidad, '\" agregada en el empleado')\r\n except Exception as e:\r\n print(\"Error en agregarDisponibilidadEmpleado \", e)\r\n\r\n\r\ndef quitarDisponibilidadEmpleado(bd, id_disponibilidad, id_empleado):\r\n try:\r\n cursor = bd.connection.cursor()\r\n cursor.execute('DELETE FROM empleado_disponibilidad WHERE id_empleado = {} AND id_disponibilidad = {}'.format(\r\n id_empleado, id_disponibilidad))\r\n bd.connection.commit()\r\n cursor.close()\r\n #print('Disponibilidad quitada del empleado')\r\n except Exception as e:\r\n print(\"Error en quitarDisponibilidadEmpleado \", e)\r\n\r\n\r\ndef quitarTodaLaDisponibilidadDelEmpleado(bd, id_empleado):\r\n try:\r\n cursor = bd.connection.cursor()\r\n cursor.execute(\r\n 'DELETE FROM empleado_disponibilidad WHERE id_empleado = {}'.format(id_empleado))\r\n bd.connection.commit()\r\n cursor.close()\r\n #print('Toda disponibilidad quitada del empleado')\r\n except Exception as e:\r\n print(\"Error en quitarTodaLaDisponibilidadDelEmpleado \", e)\r\n\r\n\r\ndef agregarDisponibilidadAnuncio(bd, id_disponibilidad, id_anuncio):\r\n try:\r\n cursor = bd.connection.cursor()\r\n cursor.execute('INSERT INTO anuncio_disponibilidad (id_anuncio, id_disponibilidad) VALUES ({}, {})'.format(\r\n id_anuncio, id_disponibilidad))\r\n bd.connection.commit()\r\n cursor.close()\r\n #print('Disponibilidad \"', id_disponibilidad, '\" agregada en el anuncio')\r\n except Exception as e:\r\n print(\"Error en agregarDisponibilidadAnuncio \", e)\r\n\r\n\r\ndef quitarDisponibilidadAnuncio(bd, id_disponibilidad, id_anuncio):\r\n try:\r\n cursor = bd.connection.cursor()\r\n cursor.execute('DELETE FROM anuncio_disponibilidad WHERE id_anuncio = {} AND id_disponibilidad = {}'.format(\r\n id_anuncio, id_disponibilidad))\r\n bd.connection.commit()\r\n cursor.close()\r\n #print('Disponibilidad quitada del anuncio')\r\n except Exception as e:\r\n print(\"Error en quitarDisponibilidadAnuncio \", e)\r\n\r\n\r\ndef quitarTodaLaDisponibilidadDelAnuncio(bd, id_anuncio):\r\n try:\r\n cursor = bd.connection.cursor()\r\n cursor.execute(\r\n 'DELETE FROM anuncio_disponibilidad WHERE id_anuncio = {}'.format(id_anuncio))\r\n bd.connection.commit()\r\n cursor.close()\r\n #print('Toda disponibilidad quitada del anuncio')\r\n except Exception as e:\r\n print(\"Error en quitarTodaLaDisponibilidadDelAnuncio \", e)\r\n","sub_path":"Implementacion/Disponibilidad.py","file_name":"Disponibilidad.py","file_ext":"py","file_size_in_byte":3828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"512938387","text":"from Board import *\nfrom Bank import *\nfrom Title import Property, Utility\nimport math \nimport util\n\nclass Player():\n #Dual means both Regular and Banker, used only if there are less than 5 players; Bank can be automated\n #PLAYER_TITLES = [\"Regular\", \"Banker/Auctioneer\", \"Dual\"] \n\n PLAYER_MINIMUM = 2\n PLAYER_MAXIMUM = 8\n \n def __init__(self, id, name):\n self.id = id #Identification Number\n self.name = name #Name of player\n self.money = 0 #Cash on hand\n self.position = 0 #Position ranges from 0 - 40 (for game's 41 spaces) - Start at \"Go\" tile\n self.bankrupt = False #Bankrupt status\n \n self.inJail = False #Check if user is in jail \n self.jail_cards = [] #Jail cards in possession\n self.jail_turns = 0 #Number of remaining turns in jail\n\n self.debt = [] #Records of debts - money owned to other players \n\n self.consecutiveDoubles = 0 #Start with no doubles \n self.order = None #Determine the order of play in game - default is None. \n\n self.titleDeeds = [] #Start with no title deeds owned\n self.propertyOwned = 0 #Number of properties owned \n self.colorMonopoly = [] #List of color group monopolies owned \n self.utilityOwned = 0 #Number of utilities owned\n self.transportsOwned = 0 #Number of transports owned\n\n self.num_homes = 0 #Number of homes in total \n self.num_hotels = 0 #Number of hotels in total \n\n\n #Get the id of user\n def getuserID(self): \n return self.id \n \n #Get the name of user\n def getName(self): \n return self.name \n\n #Get the monetary value of the player\n def getMonetaryValue(self): \n return self.money \n \n #Add money to or subtract money from player\n def changeMonetaryValue(self, amount): \n self.money += amount\n \n #Get the position of the player on the board\n def getPosition(self): \n return self.position \n\n #Set the position of player on board\n def setPosition(self, position): \n self.position = position \n\n #Get the order of play of player\n def getOrder(self):\n return self.order \n\n #Set the order of play for player\n def setOrder(self, order): \n self.order = order \n \n #Get the list of properties of player\n def getTitleDeeds(self): \n return self.titleDeeds\n \n #Add a title deed to the player's list of possessions\n def addTitleDeed(self, titleDeed, mortgaged = False): \n titleType = titleDeed.getTitleType()\n titleName = titleDeed.getName()\n\n if (titleType == \"Property\"): \n self.titleDeeds.append({\"Title Deed\": titleDeed, \"Mortgaged\": mortgaged, \"Houses\": 0, \"Hotels\": 0, \"Color Group\": titleDeed.getColorGroup()})\n self.propertyOwned += 1\n \n #Check if adding the property means the player has a monopoly\n colorGroupName = titleDeed.getColorGroup() \n colorGroupList = Property.getColorGroup(colorGroupName)\n\n createMonopoly = True\n for propertyItem in colorGroupList:\n if (propertyItem == titleName):\n #Property item refers to the title deed being added \n continue\n for titleDeed in self.titleDeeds:\n titleDeedInList = False \n\n if (propertyItem == titleDeed[\"Title Deed\"].getName()): \n titleDeedInList = True \n \n if (not titleDeedInList): \n #If given property item is not part of the owner's list of title deeds, the new item would not result in a monopoly\n createMonopoly = False\n break\n\n if (createMonopoly): \n self.colorMonopoly.append({\"Color Group\": colorGroupName, \"Number Houses Built\": 0, \"Number Hotels Built\": 0})\n\n elif (titleType == \"Utility\"):\n self.titleDeeds.append({\"Title Deed\": titleDeed, \"Mortgaged\": mortgaged, \"Houses\": None, \"Hotels\": None, \"Color Group\": None}) \n self.utilityOwned += 1\n elif(titleType == \"Transports\"): \n self.titleDeeds.append({\"Title Deed\": titleDeed, \"Mortgaged\": mortgaged, \"Houses\": None, \"Hotels\": None, \"Color Group\": None}) \n self.transportsOwned += 1\n \n #Remove a title deed from a player's list of possessions \n def removeTitleDeed(self, titleDeedName): \n titleDeedCard = None \n record = None \n\n #Remove the title deed from the list\n for titleDeed in self.titleDeeds: \n if titleDeed[\"Title Deed\"].getName() == titleDeedName:\n titleDeedCard = titleDeed[\"Title Deed\"]\n record = self.titleDeeds.remove(titleDeed)\n \n #Reduce the number of properties owned by this player\n if (titleDeedCard.getTitleType() == \"Property\"): \n colorGroup = titleDeedCard.getColorGroup()\n\n #Check if removing property would result in player to lose monopoly\n #This already assumes the color group has no property already\n monopolyList = self.getColorMonopoly() \n\n #If color group is in the monopoly list, the property being removed results in monopoly loss\n if (colorGroup in monopolyList): \n for monopolyItem in monopolyList:\n if (monopolyItem[\"Color Group\"] == colorGroup): \n monopolyList.remove(monopolyItem)\n\n self.propertyOwned -= 1 \n elif (titleDeedCard.getTitleType() == \"Utility\"):\n self.utilityOwned -= 1\n elif (titleDeedCard.getTitleType() == \"Transports\"): \n self.transportsOwned -= 1\n\n return titleDeedCard\n\n def getPropertyOwned(self): \n return self.propertyOwned\n \n def getColorMonopoly(self):\n return self.colorMonopoly\n \n def getUtilityOwned(self):\n return self.utilityOwned\n \n def getTransportsOwned(self):\n return self.transportsOwned\n\n #Get total number of homes owned\n def getNumHomes(self): \n return self.num_homes\n \n #Get total number of hotels owned \n def getNumHotels(self): \n return self.num_hotels \n\n #Get the status of player in jail\n def getInJailStatus(self):\n return self.inJail\n \n #Set the in jail status\n def setInJailStatus(self, status): \n self.inJail = status\n\n #Add a jail-free card to player's possession\n def addEscapeJailCard(self, card): \n self.jail_cards.append(card)\n\n #Remove a jail-free card from player's possession, starting with the most recent card first\n def removeEscapeJailCard(self):\n card = self.jail_cards.pop()\n return card\n \n #Check if there are jail cards available \n def jailCardsAvailable(self): \n if (len(self.jail_cards) > 0): \n return True\n \n return False\n\n #Get the current number of jail turns\n def getJailTurns(self): \n return self.jail_turns\n \n #Set the number of jail turns\n def setJailTurns(self, turns): \n self.jail_turns = turns\n \n #Subtract the number of jail turns\n def subtractJailTurns(self): \n self.jail_turns -= 1\n\n #Get the bankrupt status\n def getBankruptStatus(self):\n return self.bankrupt\n \n #Set the bankrupt status\n def setBankruptStatus(self, status = False): \n self.bankrupt = status\n\n #Get the debt records of player\n def getDebtRecord(self): \n return self.debt\n \n #Set the debt records of player\n def addDebtRecord(self, playerName, amount): \n #Check if there is an existing debt to that player, and if so update record\n existingRecord = False \n \n #If there is existing debt, just increase debt amount. \n for debtRecord in self.debt: \n if (debtRecord[\"Player\"] == playerName):\n debtRecord[\"Debt Owned\"] = debtRecord[\"Debt Owned\"] + amount\n existingRecord = True\n \n #If there is no record, add new debt to record \n if (not existingRecord): \n self.debt.append({\"Player\": playerName, \"Debt Owned\": amount})\n \n #Reduce debt records of player (if reducing debt)\n def reduceDebt(self, playerName, amount): \n \n #Search for the player to update debt or remove record altogether\n for debtRecord in self.debt: \n if (debtRecord[\"Player\"] == playerName):\n debtRecord[\"Debt Owned\"] = debtRecord[\"Debt Owned\"] - amount\n \n #Should the debt amount reaches below or at zero, remove record\n if (debtRecord[\"Debt Owned\"] <= 0):\n self.debt.remove(debtRecord) \n\n \"\"\"Methods associated with the player interacting in the game \"\"\"\n #Move the player across the board when it is their turn \n def move(self, moveNum, dice, bank = None):\n #TODO: Add logic regarding if user has jail-free cards or has money to self-bail \n if (self.jail_turns > 0):\n return 0\n\n #Check if player rolled doubles \n if dice.getDoubleStatus(): \n self.consecutiveDoubles += 1\n\n #Check if user goes to jail if 3 doubles in a row\n if self.consecutiveDoubles >= 3: \n self.setInJailStatus(True)\n self.setPosition(Board.TILES_JAIL[0])\n self.consecutiveDoubles = 0 \n\n #Reset the dice double status\n dice.resetDoubleStatus()\n\n return #If going to jail, end the turn right here\n\n else: \n #Reset consecutive doubles if different numbers are rolled\n self.consecutiveDoubles = 0 \n \n #Calculate new position of player\n newPosition = self.getPosition() + moveNum \n \n #Add one to position if went past jail, assuming player was starting next to jail at minimum.\n #Number 35 is the highest possible new position if user rolled doubles twice and was closest to jail by one spot\n if (newPosition >= Board.TILES_JAIL[0] and newPosition < 35) and (self.getPosition() < Board.TILES_JAIL[0] or self.getPosition() > 35):\n newPosition += 1\n\n #Check if player has cycled through the board, assuming player does not go to jail directly\n if (newPosition > len(Board.TILES_LIST)):\n newPosition -= len(Board.TILES_LIST)\n \n #Collect more money by passing GO\n self.changeMonetaryValue(Bank.PASS_GO)\n if (bank != None): \n bank.subtract(Bank.PASS_GO)\n \n #Apply new position \n self.setPosition(newPosition)\n \n #Read and do the chance card \n def doChanceCard(self, card, board, bank):\n #Get user's position \n position = self.getPosition() \n\n #Get the type of chance card and the associated value\n cardKind = card.getKind()\n cardValue = card.getValue() \n\n #Do actions based on chance card \n if cardKind == \"Advance\":\n #Record user was on this space first\n board.hit(position)\n\n #Read the values, and do the actions based on the value\n if cardValue == \"Go\": \n self.setPosition(Board.TILES_GO[0])\n\n #Collect money\n self.changeMonetaryValue(Bank.PASS_GO)\n bank.subtract(Bank.PASS_GO)\n\n elif cardValue == \"Utility\":\n #Keep track if nearest utility is found \n found = False \n newPositionUtility = None\n\n #Go to the nearest utility\n for posUtil in Board.TILES_UTILITY: \n if position < posUtil: \n newPositionUtility = posUtil\n found = True\n break \n \n #If not nearest utility found, go to first utility. \n #Note it may be possible that user does not collect cash if passing Go\n if not found:\n newPositionUtility = Board.TILES_UTILITY[0]\n\n #If player would cycle the board, re-calibrate the position number and collect 200 if necessary\n if (newPositionUtility < position):\n #Collect more money by passing GO\n self.changeMonetaryValue(Bank.PASS_GO)\n bank.subtract(Bank.PASS_GO)\n\n self.setPosition(newPositionUtility)\n \n elif cardValue == \"Transports\":\n #Keep track if nearest transports is found \n found = False \n newPositionTransports = None\n\n #Go to the nearest transport\n for posTransports in Board.TILES_TRANSPORTS: \n if position < posTransports: \n newPositionTransports = posTransports\n found = True\n break \n \n #If not nearest utility found, go to first transports. \n #Note it may be possible that user does not collect cash if passing Go\n if not found:\n newPositionTransports = Board.TILES_TRANSPORTS[0]\n \n #If player would cycle the board, re-calibrate the position number and collect 200 if necessary\n if (newPositionTransports < position):\n #Collect more money by passing GO\n self.changeMonetaryValue(Bank.PASS_GO)\n bank.subtract(Bank.PASS_GO)\n\n self.setPosition(newPositionTransports)\n \n elif cardValue <= 0: \n #If negative, this means player must go back\n newPosition = position + cardValue \n self.setPosition(newPosition)\n\n elif cardValue == \"Go to Jail\": \n #Player goes to jail directly, do not collect amount of passing GO\n self.setInJailStatus(True)\n self.setPosition(Board.TILES_JAIL[0])\n \n else: \n #If player would cycle the board, re-calibrate the position number and collect 200 if necessary\n if (cardValue < position):\n #Collect more money by passing GO\n self.changeMonetaryValue(Bank.PASS_GO)\n bank.subtract(Bank.PASS_GO)\n \n #Set new position\n self.setPosition(cardValue)\n\n elif cardKind == \"Credit\": \n bank.subtract(cardValue)\n self.changeMonetaryValue(cardValue)\n elif cardKind == \"Debit\": \n self.changeMonetaryValue(cardValue) \n bank.add(abs(cardValue))\n elif cardKind == \"Debit Complex\": \n #debit from each home and hotel \n numHomePay = cardValue[0] * self.getNumHomes()\n numHotelPay = cardValue[1] * self.getNumHotels() \n \n #Debit the amount from player \n self.changeMonetaryValue(numHomePay + numHotelPay)\n\n #Add the amount to the bank \n bank.add(abs(numHomePay + numHotelPay))\n elif cardKind == \"Escape Jail\":\n self.addEscapeJailCard(card)\n \n #Read and do the community card \n def doCommunityCard(self, card, board, bank):\n #Get user's position \n position = self.getPosition() \n\n #Get the type of chance card and the associated value\n cardKind = card.getKind()\n cardValue = card.getValue() \n\n #Do actions based on community card \n if cardKind == \"Advance\": \n #Record user was on this space first\n board.hit(position)\n\n #Read the values, and do the actions based on the value\n if cardValue == \"Go\": \n self.setPosition(Board.TILES_GO[0])\n \n #Collect money\n self.changeMonetaryValue(Bank.PASS_GO)\n bank.subtract(Bank.PASS_GO)\n\n elif cardValue == \"Go to Jail\": \n print(\"You have been sent to jail.\")\n self.setInJailStatus(True)\n self.setPosition(Board.TILES_JAIL[0])\n \n elif cardKind == \"Credit\": \n bank.subtract(cardValue)\n self.changeMonetaryValue(cardValue)\n elif cardKind == \"Debit\": \n self.changeMonetaryValue(cardValue) \n bank.add(abs(cardValue))\n elif cardKind == \"Debit Complex\": \n #debit from each home and hotel \n numHomePay = cardValue[0] * self.getNumHomes()\n numHotelPay = cardValue[1] * self.getNumHotels() \n \n #Debit the amount from player \n self.changeMonetaryValue(numHomePay + numHotelPay)\n\n #Add the amount to the bank \n bank.add(abs(numHomePay + numHotelPay)) \n elif cardKind == \"Escape Jail\":\n self.addEscapeJailCard(card)\n\n #User pays tax if lands on a tax tile\n def payTax(self, bank): \n #Get position of player to get tax type, and create value to hold tax amount\n position = self.getPosition()\n taxCharged = 0 \n \n #Get the type of tax \n if (Board.TILES_LIST[position] == \"Income Tax\"):\n taxCharged = Bank.INCOME_TAX\n elif (Board.TILES_LIST[position] == \"Luxury Tax\"):\n taxCharged = Bank.LUXURY_TAX\n\n #Check current amounts of player before paying tax\n monetaryAmount = self.getMonetaryValue() \n newPossibleMonetaryAmount = monetaryAmount - abs(taxCharged)\n \n #Check if the player already has no money currently\n if (monetaryAmount <= 0): \n #Record the amount of money owned to the bank\n self.addDebtRecord(\"Bank\", abs(taxCharged))\n\n #Check if the new monetary value causes player to go below zero. If so, the remaining amount must be recorded as debt\n elif (newPossibleMonetaryAmount < 0): \n #Make payment that can be paid now \n payableNow = newPossibleMonetaryAmount + abs(taxCharged)\n self.changeMonetaryValue(-1 * payableNow)\n bank.add(abs(payableNow))\n\n #Add the amount to debt record\n amountDebt = newPossibleMonetaryAmount\n self.addDebtRecord(\"Bank\", amountDebt)\n else: \n #If sufficient amount, pay the tax to the bank\n #Tax the player, and add the money to bank\n self.changeMonetaryValue(taxCharged)\n bank.add(abs(taxCharged))\n\n #Options to escape jail - Note player can collect rent (provided not mortgaged) or make changes to the title deeds\n def escapeJailOptions(self, bank, dice): \n #Return the Get Out of Jail Free card to the deck in game if used \n card = None\n validOptionSelected = False\n\n jailMessage = \"You are currently in jail, and you have \" + str(self.getJailTurns()) + \" left in jail.\" + \"\\nYou do have the following options if you wish to get out of jail early.\" + \"\\n1. Pay 50 dollar fine - Type 'Pay 50' to use this option.\" + \"\\n2. Roll a double - Type 'Roll Dice' to use this option.\"\n \n if (self.jailCardsAvailable()): \n jailMessage += \"\\n3. Use a get out of jail free card - Type 'Jail Free Card' to use this option.\"\n \n while (not validOptionSelected): \n print(jailMessage)\n jailOption = input(\"Select an option based on the options listed.\") #This needs to be validated\n \n #Pay 50 fine, user may not go forward until the next turn\n if (jailOption == \"Pay 50\"): \n #User must have sufficient funds to pay the bank \n if (self.getMonetaryValue() > 0):\n self.changeMonetaryValue(-1 * Bank.JAIL_PAYMENT)\n bank.add(Bank.JAIL_PAYMENT)\n\n #Reset the statuses \n self.setInJailStatus(False)\n self.setJailTurns(0)\n\n #Player goes to just visiting jail \n self.setPosition(Board.TILES_LIST[\"Just Visiting\"])\n\n validOptionSelected = True\n else: \n print(\"You do not have sufficient funds to get out of jail.\")\n\n #Use get out of jail free card\n elif (jailOption == \"Jail Free Card\" and self.jailCardsAvailable()): \n card = self.removeEscapeJailCard() \n\n #Reset the statuses \n self.setInJailStatus(False)\n self.setJailTurns(0)\n\n #Player goes to just visiting jail \n self.setPosition(Board.TILES_LIST[\"Just Visiting\"])\n\n validOptionSelected = True\n \n #Roll a double\n elif (jailOption == \"Roll Dice\"):\n total = dice.rollDice()\n\n #If player rolls a double \n if (dice.getDoubleStatus()):\n #Advance to the tile according to your roll\n #Calculate new position of player\n newPosition = self.getPosition() + total\n\n #Apply new position \n self.setPosition(newPosition)\n\n #Reset the statuses \n self.setInJailStatus(False)\n self.setJailTurns(0)\n\n #Reset the double status - user does not do another dice roll\n dice.resetDoubleStatus()\n\n validOptionSelected = True\n else: \n print(\"You did not roll a double.\") \n\n #Reduce one jail turn \n self.subtractJailTurns()\n\n #If this results in no more jail turns left, player must pay 50. If so reset statuses. \n if (self.getInJailStatus() == 0):\n print(\"\\nYou may now escape jail as a result, but you must pay 50 to the bank.\")\n self.changeMonetaryValue(-1 * Bank.JAIL_PAYMENT)\n bank.add(Bank.JAIL_PAYMENT)\n #Reset the statuses \n self.setInJailStatus(False)\n self.setJailTurns(0)\n self.setPosition(Board.TILES_LIST[\"Just Visiting\"])\n \n #By virtue, valid option does not need to be selected\n validOptionSelected = True\n else: \n print(\"Currently, you must remain in jail.\")\n else:\n if (jailOption == \"Jail Free Card\"): \n print(\"You do not have any jail free cards you can use at this time.\")\n \n #Print message reporting user did not type in a valid response. \n print(\"You did not select a valid option to escape jail. Please try again.\")\n \n return card \n\n #User pays the rent to the other player\n #Check if the current player has run out of money but still has property - i.e. owes debt\n def payRent(self, owner, titleDeedName, boardTile, dice):\n titleDeedCard = None\n titleDeedRecord = None\n rentAmount = 0\n\n #Get the title deed information \n titleDeedsList = owner.getTitleDeeds() \n for titleDeedItem in titleDeedsList: \n if (titleDeedName == titleDeedItem[\"Title Deed\"].getName()):\n titleDeedRecord = titleDeedItem\n titleDeedCard = titleDeedItem[\"Title Deed\"]\n \n #No payment can be made given no information is available \n if (titleDeedCard == None): \n print(\"There is no title deed card information available for \" + titleDeedName)\n return \n\n #Check if the title deed is in mortgages, if so do not collect rent\n if (titleDeedRecord[\"Mortgaged\"]):\n print(\"This property \" + titleDeedCard.getName() + \" is currently mortgaged, and rent cannot be collected at this time.\") \n return #Go back to the caller function; do not collect rent\n\n #If title deed is a property, additional checking is needed to determine the rent value.\n if (boardTile == \"Property\"): \n #Check if the owner owns a monopoly - that is owns all title deeds of that color group \n colorGroup = titleDeedCard.getColorGroup() \n\n #If the owner has a monopoly on that color group\n if (colorGroup in owner.getColorMonopoly()): \n #Get the number of houses and hotels of that property\n num_Houses = titleDeedRecord[\"Houses\"]\n num_Hotels = titleDeedRecord[\"Hotels\"]\n\n if (num_Houses): \n #There is at least one house on the property\n rentAmount = titleDeedCard.getRentCosts(Property.HOMES_RENT[num_Houses - 1])\n elif (num_Hotels): \n #There may be no homes on the property, but there is a hotel \n rentAmount = titleDeedCard.getRentCosts(Property.HOTELS_COST)\n else: \n #This is an undeveloped site \n rentAmount = titleDeedCard.getRentValue() * Property.DOUBLE_RENT\n else: \n #There is no monopoly on the color group associated for that property\n rentAmount = titleDeedCard.getRentValue() \n\n #If utility, roll dice, and the rental amount based on number of utilities owned\n elif (boardTile == \"Utility\"): \n #Roll the dice\n diceRoll = dice.rollDice()\n \n #If owner has both utilities - use 10 \n if (owner.getUtilityOwned() == Utility.UTILITY_BOTH):\n rentAmount = diceRoll * titleDeedCard.getRentCosts[Utility.UTILITY_BOTH - 1] * Bank.RENT_MULTIPLIER\n else: #If owner owns this utility only - use 4\n rentAmount = diceRoll * titleDeedCard.getRentCosts[Utility.UTILITY_ONE - 1] * Bank.RENT_MULTIPLIER\n\n #If transports, calculate the rent amount based on number of transports title deeds owned by owner\n elif (boardTile == \"Transports\"):\n #Get the number of transports owned by the owner\n transportsOwned = owner.getTransportsOwned() \n\n #Calculate the rental payment\n rentAmount = titleDeedCard.getRentCosts[transportsOwned - 1] \n\n #Check current amounts of player before making rental payment \n monetaryAmount = self.getMonetaryValue() \n newPossibleMonetaryAmount = monetaryAmount - rentAmount\n \n #Check if the player already has no money currently\n if (monetaryAmount <= 0): \n #Record the amount of money owned to that player\n self.addDebtRecord(owner.getName(), rentAmount)\n\n #Since there is no tangible object of monetary value being exchanged, there is no additional debt accumulated. \n\n #Check if the new monetary value causes player to go below zero. If so, the remaining amount must be recorded as debt\n elif (newPossibleMonetaryAmount < 0): \n #Make payment that can be paid now \n payableNow = newPossibleMonetaryAmount + rentAmount\n self.changeMonetaryValue(-1 * payableNow)\n owner.changeMonetaryValue(payableNow) \n\n #Add the amount to debt record\n amountDebt = newPossibleMonetaryAmount\n self.addDebtRecord(owner.getName(), amountDebt)\n \n #If player has sufficient funds\n else: \n self.changeMonetaryValue(-1 * rentAmount)\n owner.changeMonetaryValue(rentAmount) \n\n #Check if there is any existing debt to that player, and if so reduce debt. \n debtOwned = self.getDebtRecord() \n\n for record in debtOwned: \n if (record[\"Player\"] == owner.getName()): \n self.reduceDebt(owner.getName(), rentAmount)\n \n #Reset the dice doubles\n dice.resetDoubleStatus() \n\n \"\"\"Methods associated with adding by purchasing or auctioning from the bank (or by bankruptcy of another player) \"\"\"\n #Add a title deed to player's possession (as a result of the bank)\n def acquireTitleDeed(self, titleDeed, purchaseValue, bank = None): \n #Add title deed to possession\n self.addTitleDeed(titleDeed)\n\n #Remove card from bank's possession\n if (bank != None): \n bank.removeTitleDeed(titleDeed)\n\n #Set the owner to the title deed \n titleDeed.setOwner(self.getName())\n \n #Check current amounts of player before repaying mortgage\n monetaryAmount = self.getMonetaryValue() \n newPossibleMonetaryAmount = monetaryAmount - purchaseValue\n \n #Check if the player already has no money currently\n if (monetaryAmount <= 0): \n #Record the amount of money owned to the bank\n self.addDebtRecord(\"Bank\", purchaseValue)\n\n self.changeMonetaryValue(-1 * purchaseValue)\n if (bank != None): \n bank.add(purchaseValue)\n\n #Check if the new monetary value causes player to go below zero. If so, the remaining amount must be recorded as debt (on the condition has title deeds)\n elif (newPossibleMonetaryAmount < 0): \n #Make payment that can be paid now \n payableNow = newPossibleMonetaryAmount + purchaseValue\n self.changeMonetaryValue(-1 * payableNow)\n if (bank != None): \n bank.changeMonetaryValue(payableNow) \n\n #Add the amount to debt record\n amountDebt = newPossibleMonetaryAmount\n self.addDebtRecord(\"Bank\", amountDebt)\n else: \n #If there are sufficient funds to pay mortgage w/ interest in full \n #Make the purchase\n self.changeMonetaryValue(-1 * purchaseValue)\n if (bank != None): \n bank.add(purchaseValue)\n\n #Check if there is any existing debt to the bank, and if so reduce debt. \n debtOwned = self.getDebtRecord() \n\n for record in debtOwned: \n if (record[\"Player\"] == \"Bank\"): \n self.reduceDebt(\"Bank\", purchaseValue)\n\n print(\"The title deed \" + titleDeed.getName() + \" has been added.\")\n \n \"\"\"Methods associated with existing properties or making changes including selling and mortgaging\"\"\" \n #Add a mortgage to a property\n def addMortgage(self, titleDeedName, mortgageValue, bank): \n for titleDeed in self.titleDeeds: \n if (titleDeed[\"Title Deed\"].getName() == titleDeedName): \n titleDeed[\"Mortgaged\"] = True\n \n bank.giveMortgageLoan(mortgageValue)\n self.changeMonetaryValue(mortgageValue)\n\n #Remove and repay a mortgage from a property\n def removeMortgage(self, titleDeedName, repayAmount, bank): \n for titleDeed in self.titleDeeds: \n if (titleDeed[\"Title Deed\"].getName() == titleDeedName): \n titleDeed[\"Mortgaged\"] = False\n \n #Check current amounts of player before repaying mortgage\n monetaryAmount = self.getMonetaryValue() \n newPossibleMonetaryAmount = monetaryAmount - repayAmount\n \n #Check if the player already has no money currently \n if (monetaryAmount <= 0): \n #Record the amount of money owned to the bank\n self.addDebtRecord(\"Bank\", repayAmount)\n\n #Check if the new monetary value causes player to go below zero. If so, the remaining amount must be recorded as debt\n elif (newPossibleMonetaryAmount < 0): \n #Make payment that can be paid now \n payableNow = newPossibleMonetaryAmount + repayAmount\n self.changeMonetaryValue(-1 * payableNow)\n bank.changeMonetaryValue(payableNow) \n\n #Add the amount to debt record\n amountDebt = newPossibleMonetaryAmount\n self.addDebtRecord(\"Bank\", amountDebt)\n else: \n #If there are sufficient funds to pay mortgage w/ interest in full \n self.changeMonetaryValue(-1 * repayAmount)\n bank.creditMortgagePayment(repayAmount)\n\n #Purchase a home for the property\n def purchaseHome(self, propertyName, buildingCost, bank):\n propertyFound = False\n colorGroup = None\n propertyRecord = None\n\n #Search for the property \n for titleDeed in self.titleDeeds: \n if (titleDeed[\"Title Deed\"].getName() == propertyName):\n propertyFound = True\n colorGroup = titleDeed[\"Title Deed\"].getColorGroup()\n propertyRecord = titleDeed\n \n #Add the house to the property name if found\n if (propertyFound): \n propertyRecord[\"Houses\"] = propertyRecord[\"Houses\"] + 1\n self.num_homes += 1\n \n #Add the number of houses built for that monopoly\n for monopolyColor in self.colorMonopoly:\n if (colorGroup == monopolyColor[\"Color Group\"]):\n monopolyColor[\"Number of Houses Built\"] = monopolyColor[\"Number of Houses Built\"] + 1\n\n #Check current amounts of player before repaying mortgage\n monetaryAmount = self.getMonetaryValue() \n newPossibleMonetaryAmount = monetaryAmount - buildingCost\n \n #Check if the player already has no money currently\n if (monetaryAmount <= 0): \n #Record the amount of money owned to the bank\n self.addDebtRecord(\"Bank\", buildingCost)\n\n #Make the purchase\n self.changeMonetaryValue(-1 * buildingCost) \n bank.purchaseHome(buildingCost)\n\n #Check if the new monetary value causes player to go below zero. If so, the remaining amount must be recorded as debt\n elif (newPossibleMonetaryAmount < 0): \n #Make payment that can be paid now \n payableNow = newPossibleMonetaryAmount + buildingCost\n self.changeMonetaryValue(-1 * payableNow)\n bank.purchaseHome(payableNow) \n\n #Add the amount to debt record\n amountDebt = newPossibleMonetaryAmount\n self.addDebtRecord(\"Bank\", amountDebt)\n else: \n #If there are sufficient funds to pay mortgage w/ interest in full \n #Make the purchase\n self.changeMonetaryValue(-1 * buildingCost) \n bank.purchaseHome(buildingCost)\n\n #Check if there is any existing debt to the bank, and if so reduce debt. \n debtOwned = self.getDebtRecord() \n\n for record in debtOwned: \n if (record[\"Bank\"] == \"Bank\"): \n self.reduceDebt(\"Bank\", buildingCost)\n \n #Purchase a hotel for the property, and return four houses to the bank\n def purchaseHotel(self, propertyName, buildingCost, bank): \n propertyFound = False\n colorGroup = None\n propertyRecord = None\n\n #Search for the property \n for titleDeed in self.titleDeeds: \n if (titleDeed[\"Title Deed\"].getName() == propertyName):\n propertyFound = True\n colorGroup = titleDeed[\"Title Deed\"].getColorGroup()\n propertyRecord = titleDeed\n \n #Add the hotel to the property name if found, return four houses\n if (propertyFound): \n propertyRecord[\"Hotels\"] = propertyRecord[\"Hotels\"] + 1\n self.num_hotels += 1\n\n propertyRecord[\"Houses\"] = 0\n self.num_homes -= Property.HOMES_MAX\n\n #Add the number of hotels built for that monopoly, and reflect four houses returned\n for monopolyColor in self.colorMonopoly:\n if (colorGroup == monopolyColor[\"Color Group\"]):\n monopolyColor[\"Number of Hotels Built\"] = monopolyColor[\"Number of Hotels Built\"] + 1\n monopolyColor[\"Number of Houses Built\"] = monopolyColor[\"Number of Hotels Built\"] - Property.HOMES_MAX\n \n #Check current amounts of player before repaying mortgage\n monetaryAmount = self.getMonetaryValue() \n newPossibleMonetaryAmount = monetaryAmount - buildingCost\n \n #Check if the player already has no money currently (on the condition has title deeds)\n if (monetaryAmount <= 0): \n #Record the amount of money owned to that player, assuming player has title deeds\n self.addDebtRecord(\"Bank\", buildingCost)\n\n self.changeMonetaryValue(-1 * buildingCost) \n bank.purchaseHotel(buildingCost)\n\n #Check if the new monetary value causes player to go below zero. If so, the remaining amount must be recorded as debt (on the condition has title deeds)\n elif (newPossibleMonetaryAmount < 0): \n #Make payment that can be paid now \n payableNow = newPossibleMonetaryAmount + buildingCost\n self.changeMonetaryValue(-1 * payableNow)\n bank.purchaseHotel(payableNow)\n\n #Add the amount to debt record\n amountDebt = newPossibleMonetaryAmount\n self.addDebtRecord(\"Bank\", amountDebt)\n else: \n #If there are sufficient funds to pay mortgage w/ interest in full \n #Make the purchase\n self.changeMonetaryValue(-1 * buildingCost) \n bank.purchaseHotel(buildingCost)\n\n #Check if there is any existing debt to the bank, and if so reduce debt. \n debtOwned = self.getDebtRecord() \n\n for record in debtOwned: \n if (record[\"Player\"] == \"Bank\"): \n self.reduceDebt(\"Bank\", buildingCost)\n \n #Return four houses back to the bank\n bank.returnHomesWithHotel()\n \n #Sell a home from the property\n def sellHome(self, propertyName, sellingAmount, bank): \n propertyFound = False\n colorGroup = None\n propertyRecord = None\n\n #Search for the property \n for titleDeed in self.titleDeeds: \n if (titleDeed[\"Title Deed\"].getName() == propertyName):\n propertyFound = True \n colorGroup = titleDeed[\"Title Deed\"].getColorGroup()\n propertyRecord = titleDeed\n \n #Remove the house to the property name if found\n if (propertyFound): \n propertyRecord[\"Houses\"] = propertyRecord[\"Houses\"] - 1\n self.num_homes -= 1\n \n #Add the number of houses built for that monopoly\n for monopolyColor in self.colorMonopoly:\n if (colorGroup == monopolyColor[\"Color Group\"]):\n monopolyColor[\"Number of Houses Built\"] = monopolyColor[\"Number of Houses Built\"] - 1\n \n #Make the sell\n self.changeMonetaryValue(sellingAmount) \n bank.sellHome(sellingAmount)\n\n #Check if there is any existing debt to the bank, and if so reduce debt. \n debtOwned = self.getDebtRecord() \n\n for record in debtOwned: \n if (record[\"Player\"] == \"Bank\"): \n amountOwned = record[\"Debt Owned\"]\n currentMonetaryAmount = self.getMonetaryValue()\n\n #To reduce debt, the sell must result in positive monetary cash amount\n if (currentMonetaryAmount > 0):\n if (currentMonetaryAmount >= amountOwned): \n #Player has enough cash to clear the debt, and has at least some money\n self.changeMonetaryValue(-1 * amountOwned) \n self.reduceDebt(\"Bank\", amountOwned) \n else: \n #Player does not have enough cash to clear debt fully \n self.changeMonetaryValue(-1 * amountOwned) \n self.reduceDebt(\"Bank\", amountOwned - currentMonetaryAmount)\n \n #Sell a hotel from the property, and get four houses back from the bank\n def sellHotel(self, propertyName, sellingAmount, bank): \n propertyFound = False\n colorGroup = None\n propertyRecord = None\n\n #Search for the property \n for titleDeed in self.titleDeeds: \n if (titleDeed[\"Title Deed\"].getName() == propertyName):\n propertyFound = True\n colorGroup = titleDeed[\"Title Deed\"].getColorGroup()\n propertyRecord = titleDeed\n \n #Add the hotel to the property name if found, return four houses\n if (propertyFound): \n propertyRecord[\"Hotels\"] = propertyRecord[\"Hotels\"] - 1\n self.num_hotels -= 1\n\n propertyRecord[\"Houses\"] = Property.HOMES_MAX\n self.num_homes += Property.HOMES_MAX\n\n #Add the number of hotels built for that monopoly, and reflect four houses returned\n for monopolyColor in self.colorMonopoly:\n if (colorGroup == monopolyColor[\"Color Group\"]):\n monopolyColor[\"Number of Hotels Built\"] = monopolyColor[\"Number of Hotels Built\"] - 1\n monopolyColor[\"Number of Houses Built\"] = monopolyColor[\"Number of Hotels Built\"] + Property.HOMES_MAX\n \n #Make the purchase\n self.changeMonetaryValue(sellingAmount) \n bank.sellHotel(sellingAmount)\n\n #Return four houses back to the bank\n bank.getHomesWithHotel()\n\n #Check if there is any existing debt to the bank, and if so reduce debt. \n debtOwned = self.getDebtRecord() \n\n for record in debtOwned: \n if (record[\"Player\"] == \"Bank\"): \n amountOwned = record[\"Debt Owned\"]\n currentMonetaryAmount = self.getMonetaryValue()\n\n #To reduce debt, the sell must result in positive monetary cash amount\n if (currentMonetaryAmount > 0):\n if (currentMonetaryAmount >= amountOwned): \n #Player has enough cash to clear the debt, and has at least some money\n self.changeMonetaryValue(-1 * amountOwned) \n self.reduceDebt(\"Bank\", amountOwned) \n else: \n #Player does not have enough cash to clear debt fully \n self.changeMonetaryValue(-1 * amountOwned) \n self.reduceDebt(\"Bank\", amountOwned - currentMonetaryAmount)\n\n #Sell the title deed to another player\n def sellTitle(self, titleDeedName, sellingAmount = 0):\n titleDeed = self.removeTitleDeed(titleDeedName)\n self.changeMonetaryValue(sellingAmount)\n \n #Return the card to allow receiver to gain possession\n return titleDeed\n\n #Inherit a title deed from a sell by another player (i.e. original owner)\n def inheritTitle(self, titleDeedCard, purchaseAmount, mortgaged = False, bank = None): \n self.addTitleDeed(titleDeedCard, mortgaged)\n self.changeMonetaryValue(-1 * purchaseAmount)\n\n if (mortgaged): \n #Get the mortgage value\n mortgageValue = titleDeedCard.getMortgageValue()\n\n print(\"This title deed \" + titleDeedCard.getName() + \" is mortgaged. You have two options.\\n\" + \n \"1. Repay the Mortgage Now\\n\" + \n \"2. Pay 10\\% Interest Now\\n\" + \n \"Please type either 'Repay Mortgage' or 'Pay Interest Only'\")\n\n option = input(\"Type in your option: \") #This requires validation \n\n if (option == \"Repay Mortgage\"): \n #Calculate repayment amount with interest\n repayAmount = int(math.ceil((mortgageValue + (mortgageValue * Bank.MORTGAGE_INTEREST))/100.0) * 100)\n\n #Make the repayment mortgage to the bank \n self.removeMortgage(titleDeedCard.getName(), repayAmount, bank)\n\n print(self.getName() + \", your repayment for \" + titleDeedCard.getName() + \" was successful.\\n\")\n\n elif (option == \"Pay Interest Only\"): \n #Calculate interest amount\n interestAmount = int(math.ceil(mortgageValue * Bank.MORTGAGE_INTEREST)/100.0) * 100\n\n #Pay the interest only, user retains mortgage \n self.changeMonetaryValue(-1 * interestAmount)\n if (bank != None): \n bank.add(interestAmount)\n \n #Check if user has run out of cash\n def runOutOfCash(self): \n if (self.getMonetaryValue() <= 0): \n return True #User does not have cash \n return False \n \n #Provide amount for auctioning or selling (if receiver)\n def provideAmount(self, currentPlayStatus, titleDeedName, bidAmount = 0):\n amount = 0 \n inputValid = False\n\n while (not inputValid): \n if (currentPlayStatus == \"Auction\"): \n \n #auctionMessage = \"Please enter your bidding bid for \" + titleDeedName + \". If you wish to skip the bid, please enter amount as '0'.\"\n #auctionMessage += \"\\nEnter bid here: \"\n\n #name of some function to send to Controller....\n #util.dataHandling(auctionMessage) \n\n print(\"Please enter your bidding bid for \" + titleDeedName + \". If you wish to skip the bid, please enter amount as '0'.\") \n\n #Validate the input \n amount = input(\"\\nEnter bid here: \") \n \n elif (currentPlayStatus == \"Selling\"):\n print(\"Please enter the amount you wish to purchase for \" + titleDeedName + \".\")\n\n #Validate the input \n amount = input(\"\\nEnter bid here: \") \n \n if (amount < 0 or amount == None): \n print(\"This is not an acceptable value. Please try again.\")\n elif (currentPlayStatus == \"Auction\" and amount < bidAmount):\n print(\"You must enter a bid amount higher than or equal to the starting amount. Please enter a higher value.\")\n elif (currentPlayStatus == \"Selling\" and amount <= 0):\n print(\"You must enter a non-zero positive value for selling. Please enter a higher value.\")\n else: \n inputValid = True\n\n return amount\n \n #Accept or reject an amount for selling a title deed\n def decideAmount(self, receiverName, titleDeedName, sellingOfferAmount): \n print(\"Player \" + receiverName + \" can purchase your property for \" + str(sellingOfferAmount) + \n \". Do you wish to sell \" + titleDeedName + \" at this amount?\")\n\n #Validate the input\n response = input(\"Enter either 'Accept' or 'Decline': \")\n\n if (response == \"Accept\"):\n return True\n \n #Default amount if not accepted or some other response\n return False\n \n \n\n \n\n\n\n\n","sub_path":"src/Player.py","file_name":"Player.py","file_ext":"py","file_size_in_byte":47147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"21967637","text":"'''\nfilename: graph.py\nconsisting: functions to create graph and subgraph\naffliation: milestone 1\n'''\n\nimport networkx as nx\nfrom a_star import *\nfrom load import *\n\ndef graphMaker(nodeFile, edgeFile):\n # initiates a graph \n G = nx.Graph()\n\n # nodes\n node = nodeLoader(nodeFile)\n for parse in node:\n G.add_node(int(parse[0]), pos=(float(parse[1]), float(parse[2])))\n\n # edges\n edge = edgeLoader(edgeFile)\n for parse in edge:\n G.add_edge(int(parse[1]), int(parse[2]), weight=float(parse[3]))\n\n # return graph\n return G\n\ndef subgraphMaker(G, posts):\n # initiates the subgraph\n subgraph = nx.Graph()\n\n #nodes\n node_pos = G.nodes().data('pos')\n for post in posts:\n subgraph.add_node(post, pos=node_pos[post])\n\n #edges\n for i in range(len(posts)):\n for j in range(i+1, len(posts)):\n subgraph.add_edge(posts[i], posts[j], weight= astar_path_length(G, posts[i], posts[j]))\n \n #return subgraph\n return subgraph\n\n","sub_path":"src/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"61105516","text":"import unittest\nimport numpy as np\nimport pytest\nfrom scipy.optimize import OptimizeResult\nfrom zquantum.core.circuit import ParameterGrid\nfrom zquantum.core.interfaces.optimizer_test import OptimizerTests\nfrom .grid_search import GridSearchOptimizer\n\n\n@pytest.fixture(params=[ParameterGrid([[0, 1.5, 0.1], [0, 1.5, 0.1]])])\ndef optimizer(request):\n return GridSearchOptimizer(request.param)\n\n\nclass TestGridSearchOptimizer(OptimizerTests):\n\n def test_get_values_grid(self):\n # Given\n param_ranges = [(0, 1.1, 0.5)] * 2\n grid = ParameterGrid(param_ranges)\n grid_search_optimizer = GridSearchOptimizer(grid)\n optimization_results = OptimizeResult()\n history = [\n {\"value\": 0},\n {\"value\": 1},\n {\"value\": 2},\n {\"value\": 3},\n {\"value\": 4},\n {\"value\": 5},\n {\"value\": 6},\n {\"value\": 7},\n {\"value\": 8},\n ]\n optimization_results[\"history\"] = history\n correct_values_grid = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])\n\n # When\n values_grid = grid_search_optimizer.get_values_grid(optimization_results)\n\n # Then\n np.testing.assert_array_equal(values_grid, correct_values_grid)\n","sub_path":"src/python/zquantum/optimizers/grid_search_test.py","file_name":"grid_search_test.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"645671465","text":"import os\nimport sys\nimport copy\nimport datetime\nimport collections\nimport robel\nimport gym\nimport torch\nimport torch.nn as nn\nimport gym\nimport numpy as np\nimport argparse\nimport itertools\n\n\nfrom modules import *\nimport utils\n\nfrom tensorboardX import SummaryWriter\n\n\nimport pdb\n\ndef eval_policy(policy, env_name, broken_info = False, eval_episodes=3, real_robot = False, seed = 0):\n env_seed = 2 ** 32 - 1 - seed\n if real_robot:\n eval_env = gym.make(env_name, device_path='/dev/tty.usbserial-FT3WI485')\n else:\n eval_env = gym.make(env_name)\n eval_env.seed(env_seed)\n\n avg_reward = 0.\n for _ in range(eval_episodes):\n state, done = eval_env.reset(), False\n if args.trim_state:\n state = utils.trim_state(state)\n if broken_info:\n state = np.concatenate((state, np.ones(9)))\n while not done:\n action = policy.select_action(np.array(state), evaluate=True)\n state, reward, done, _ = eval_env.step(action)\n if args.trim_state:\n state = utils.trim_state(state)\n avg_reward += reward\n if broken_info:\n state = np.concatenate((state, np.ones(9)))\n \n avg_reward /= eval_episodes\n\n print(\"---------------------------------------\")\n print(\"Evaluation over {} episodes: {:.3f}\".format(eval_episodes, avg_reward))\n print(\"---------------------------------------\")\n return avg_reward\n\nenv = gym.make('DClawTurnFixed-v0')\n# env = gym.make('DClawTurnFixed-v0', device_path='/dev/tty.usbserial-FT3WI485')\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--start-timesteps\", type=int, default=int(1e4))\n # parser.add_argument(\"--start-timesteps\", type=int, default=int(256))\n parser.add_argument(\"--max-timesteps\", type=int, default=int(1e7))\n parser.add_argument(\"--eval-freq\", type=int, default=20)\n parser.add_argument(\"--save-freq\", type=int, default=5000)\n parser.add_argument(\"--record-freq\", type=int, default=5000)\n # parser.add_argument(\"--eval-freq\", type=int, default=1)\n # parser.add_argument(\"--save-freq\", type=int, default=1)\n # parser.add_argument(\"--record-freq\", type=int, default=1)\n parser.add_argument(\"--seed\", type=int, default=0)\n parser.add_argument(\"--buffer-max-size\", type=int, default=int(1e6))\n parser.add_argument(\"--agent-training-episodes\", type=int, default=int(10))\n parser.add_argument(\"--restore-step\", type=int, default=0)\n parser.add_argument(\"--broken-timesteps\", type=int, default=1)\n parser.add_argument(\"--hidden-size\", type=int, default=512)\n parser.add_argument(\"--broken-info\", type=bool, default=True,\n help=\"whether use broken joints indice as a part of state\")\n parser.add_argument(\"--broken-angle\", type=float, default=-0.6)\n parser.add_argument(\"--std\", type=float, default=0.1)\n parser.add_argument('--gamma', type=float, default=0.99, metavar='G',\n help='discount factor for reward (default: 0.99)')\n parser.add_argument('--tau', type=float, default=0.005, metavar='G',\n help='target smoothing coefficient(τ) (default: 0.005)')\n parser.add_argument('--env-name', default='DClawTurnFixed-v0',\n help='Mujoco Gym environment (default: HalfCheetah-v2)')\n parser.add_argument('--policy', default=\"Gaussian\",\n help='Policy Type: Gaussian | Deterministic (default: Gaussian)')\n parser.add_argument('--eval', type=bool, default=True,\n help='Evaluates a policy a policy every 10 episode (default: True)')\n parser.add_argument('--alpha', type=float, default=0.2, metavar='G',\n help='Temperature parameter α determines the relative importance of the entropy\\\n term against the reward (default: 0.2)')\n parser.add_argument('--automatic_entropy_tuning', type=bool, default=False, metavar='G',\n help='Automaically adjust α (default: False)')\n parser.add_argument('--target_update_interval', type=int, default=1, metavar='N',\n help='Value target update per no. of updates per step (default: 1)')\n parser.add_argument('--lr', type=float, default=0.0003, metavar='G',\n help='learning rate (default: 0.0003)')\n parser.add_argument('--batch_size', type=int, default=256, metavar='N',\n help='batch size (default: 256)')\n parser.add_argument('--trim-state', type=bool, default=True)\n args = parser.parse_args()\n env.seed(args.seed)\n if not os.path.exists('./logs'):\n os.system('mkdir logs')\n if not os.path.exists('./saved_models'):\n os.system('mkdir saved_models')\n outdir = datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")\n outdir = os.path.join('./saved_models', outdir)\n os.system('mkdir ' + outdir)\n with open(outdir+'/setting.txt','w') as f:\n # f.writelines(\"fix the broken info bug\\n\")\n f.writelines(\"using random adversary sac\\n\")\n for each_arg, value in args.__dict__.items():\n f.writelines(each_arg + \" : \" + str(value)+\"\\n\")\n writer = SummaryWriter(logdir=('logs/gac{}').format(datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")))\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n state_dim = env.reset().shape[0]\n if args.trim_state:\n state_dim -= 9\n original_state_dim = state_dim\n\n if args.broken_info:\n state_dim += 9\n action_dim = env.action_space.sample().shape[0]\n max_action = env.action_space.high[0]\n agent = SAC(num_inputs=state_dim,\n action_space=env.action_space,\n args=args,\n writer=writer,\n outdir=outdir,\n device=device)\n \"advesarial agent code\"\n # if args.restore_step:\n # print(\"restoring the model {}\".format(args.restore_step))\n # ddpg.restore_model_for_train(args.restore_step)\n # ddpg.index = 0\n # adversary.restore_model(args.restore_step)\n current_state = env.reset()\n if args.broken_info:\n joint_info = np.ones(9)\n current_state = np.concatenate((current_state, joint_info))\n def step(adversarial_action: int, current_state):\n \"input obs obs is processed and its broken info must be all 1s\"\n \"return unprocessed next_state\"\n if args.broken_info:\n current_state = np.concatenate((current_state, np.ones(9)))\n current_state[original_state_dim + adversarial_action] = 0\n # broken_timesteps = 1\n \n total_done = False\n reward_list = []\n for i in range(args.broken_timesteps):\n agent_action = agent.select_action(current_state, evaluate=True)\n agent_action[adversarial_action] = -0.6\n next_state, reward, done, info = env.step(agent_action)\n original_next_state = next_state\n if args.trim_state:\n next_state = utils.trim_state(next_state)\n if args.broken_info:\n joint_info = np.ones(9)\n joint_info[adversarial_action] = 0\n next_state = np.concatenate((next_state, joint_info))\n reward_list.append(reward)\n if done:\n total_done = done\n break\n current_state = next_state\n avg_reward = np.array(reward_list).mean()\n return original_next_state, avg_reward, total_done, info\n episode = 0\n t = 0\n agent_t = 0\n adversary_t = 0\n \n done = False\n minimal_index = 0\n \n for i_episode in itertools.count(1):\n if t > args.max_timesteps:\n break\n for agent_episode in range(args.agent_training_episodes):\n done = False\n \" the agent training loop\"\n broken_joints = collections.deque(maxlen=1)\n current_state = env.reset()\n if args.trim_state:\n current_state = utils.trim_state(current_state)\n if args.broken_info:\n joint_info = np.ones(9)\n current_state = np.concatenate((current_state, joint_info))\n episode_steps = 0\n \n while not done:\n t += 1\n agent_t += 1\n if args.broken_info:\n current_state[original_state_dim + minimal_index] = 0\n \n if agent_t == args.start_timesteps:\n print(\"start ddpg learning\")\n if agent_t < args.start_timesteps:\n original_action = env.action_space.sample()\n else:\n original_action = agent.select_action(current_state, evaluate=False)\n action = copy.deepcopy(original_action)\n action[minimal_index] = args.broken_angle\n next_state, reward, done, info = env.step(action)\n episode_steps += 1\n mask = 1 if episode_steps == env._max_episode_steps else float(not done)\n if args.trim_state:\n next_state = utils.trim_state(next_state)\n if args.broken_info:\n next_state = np.concatenate((next_state, np.ones(9)))\n next_state[original_state_dim + minimal_index] = 0\n # suc = info['score/success']\n agent.add_buffer(current_state, original_action, next_state, reward, mask)\n if agent_t > args.start_timesteps:\n agent.update_parameters()\n current_state = next_state\n\n minimal_index = random.randint(0,8)\n\n if i_episode % args.eval_freq == 0:\n print(\"-------------------------------------------\")\n print(\"steps:{:07d}\".format(t))\n print(\"episode:{:07d}\".format(i_episode))\n avg_reward = eval_policy(agent, 'DClawTurnFixed-v0', broken_info = args.broken_info)\n writer.add_scalar('/eval/avg_reward',avg_reward, i_episode)\n\n","sub_path":"train/train_random_sac.py","file_name":"train_random_sac.py","file_ext":"py","file_size_in_byte":10110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"180116996","text":"from random import shuffle, randint\nfrom peewee import fn, JOIN\n\nfrom config import *\nfrom business_objects.Models import Definition as Definition\nfrom business_objects.Models import Word as Word\n\n# TODO: This is still giving duplicates - change it so that it does not\n# TODO: probably has something to do with querying definitions\n# TODO: try querying words instead\n\n\nclass DefinitionQuestion:\n word_index = None\n question_text = None\n answer_choices = None\n chapter_index = None\n question_type = None\n\n def make_definition_question(\n self,\n chapter_index,\n question_type=None,\n cumulative=False,\n ):\n # if no question type is requested, flip a coin to determine the question type\n self.chapter_index = chapter_index\n if question_type not in [0, 1]:\n self.question_type = randint(0, 1)\n else:\n self.question_type = question_type\n\n # question type 1 is word prompt with definition choices\n # this is pretty inefficient currently as it pings the database 5 times\n # question type 0 only makes one query\n # TODO: make this more efficient\n if self.question_type == 1:\n\n if cumulative:\n query = (\n Word\n .select()\n .where(Word.chapter_index <= chapter_index)\n .order_by(fn.Rand())\n .limit(number_of_multiple_choices)\n )\n\n else:\n query = (\n Word\n .select()\n .where(Word.chapter_index == chapter_index)\n .order_by(fn.Rand())\n .limit(number_of_multiple_choices)\n )\n\n definition_list = []\n for word in query:\n random_definition = (\n Definition\n .select()\n .where(Definition.word_index == word.word_index)\n .order_by(fn.Rand())\n .get()\n )\n definition = {\n \"text\": random_definition.definition,\n \"index\": random_definition.word_index_id\n }\n definition_list.append(definition)\n self.answer_choices = definition_list\n self.question_text = query[0].word\n self.word_index = query[0].word_index\n\n # question type 0 is definition prompt with word choices\n elif self.question_type == 0:\n\n if cumulative:\n query = (Definition\n .select(Definition, Word)\n .join(Word)\n .where(Word.chapter_index <= chapter_index)\n .order_by(fn.Rand())\n .limit(number_of_multiple_choices)\n )\n else:\n query = (Definition\n .select(Definition, Word)\n .join(Word)\n .where(Word.chapter_index == chapter_index)\n .order_by(fn.Rand())\n .limit(number_of_multiple_choices)\n )\n\n word_list = []\n for element in query:\n word = {\n \"text\": element.word_index.word,\n \"index\": element.word_index_id\n }\n word_list.append(word)\n\n self.answer_choices = word_list\n self.question_text = query[0].definition\n self.word_index = query[0].word_index_id\n\n shuffle(self.answer_choices)\n\n return self\n\n def get_json_min(self):\n return {\n \"prompt\": self.question_text,\n \"answers\": self.answer_choices,\n \"chapter_index\": self.chapter_index,\n \"question_type\": self.question_type\n }\n","sub_path":"business_objects/DefinitionQuestion.py","file_name":"DefinitionQuestion.py","file_ext":"py","file_size_in_byte":3972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"236493924","text":"from csptools import *\nimport logging\n\nlogging.getLogger().setLevel(logging.INFO)\n\ndomain = {1,2,3}\nE = [ [1,2],[2,3] ] # list of pairs...\nF = [ [3,1], [1,3] ]\nstructure = RelationalStructure(domain, [[E,2], [F,2]])\n\n# outputs a majority polymorphism\nfor m in majority(structure):\n print(m)\n break\n \nfor o in olsak(structure,structure):\n print(o)\n break\n","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"367315290","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Mar 18 11:43:18 2020\r\n\r\n@author: salam_000\r\n\"\"\"\r\n\r\nimport re\r\n\r\n\r\ndef morse(text):\r\n encrypt = {\r\n 'A': '.-', 'B': '-...', 'C': '-.-.', \r\n 'D': '-..', 'E': '.', 'F': '..-.', \r\n 'G': '--.', 'H': '....', 'I': '..', \r\n 'J': '.---', 'K': '-.-', 'L': '.-..', \r\n 'M': '--', 'N': '-.', 'O': '---', \r\n 'P': '.--.', 'Q': '--.-', 'R': '.-.', \r\n 'S': '...', 'T': '-', 'U': '..-', \r\n 'V': '...-', 'W': '.--', 'X': '-..-',\r\n 'Y': '-.--', 'Z': '--..', ' ': '.....'\r\n }\r\n decrypt = {value: key for key, value in encrypt.items()}\r\n \r\n if re.match(r'(\\s|-|\\.) +', text):\r\n return ' '.join(decrypt[i] for i in text.split())\r\n return ' '.join(encrypt[i] for i in text.upper())\r\nprint(morse('shaxi'))\r\n\"\"\"\r\nimport sys\r\nif __name__ == \"__main__\":\r\n print(morse(sys.argv[0])) \"\"\"\r\n \r\n\"\"\"Running the script directly from the console, it will be the main program.\r\n In this case, to pass the argument to the morse function and print result \r\n is wanted. To import the more function in another Python file, no need to\r\n to run this part of code. sys.arg[0] contains the file name (morse.py)\"\"\"","sub_path":"morse.py","file_name":"morse.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"23681323","text":"#! /usr/bin/evn python\nimport netfilterqueue\nimport subprocess\nimport scapy.all as scapy\n\n\nclass DNS_spoofing:\n def __init__(self, target_address, spoofed_address):\n self.target_address = target_address\n self.spoofed_address = spoofed_address\n self.queue = netfilterqueue.NetfilterQueue()\n self.queue.bind(0, self.process_packet)\n\n def process_packet(self, packet):\n scapy_packet = scapy.IP(packet.get_payload())\n if scapy_packet.haslayer(scapy.DNSRR):\n print(\"\\r\"+scapy_packet.summary(), end=\"\")\n qname = scapy_packet[scapy.DNSQR].qname\n if self.target_address in str(qname):\n answer = scapy.DNSRR(rrname=qname, rdata=self.spoofed_address)\n scapy_packet[scapy.DNS].an = answer\n scapy_packet[scapy.DNS].ancount = 1\n del scapy_packet[scapy.IP].len\n del scapy_packet[scapy.IP].chksum\n del scapy_packet[scapy.UDP].len\n del scapy_packet[scapy.UDP].chksum\n packet.set_payload(bytes(scapy_packet))\n packet.accept()\n\n def run(self):\n subprocess.call(\"iptables -I FORWARD -j NFQUEUE --queue-num 0\", shell=True)\n self.queue.run()\n","sub_path":"MITM-Framework/files/DNS_Spoofing.py","file_name":"DNS_Spoofing.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"24125934","text":"import itertools, os, re\nimport tempfile, subprocess\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torchtext\nfrom torchtext.vocab import Vectors, GloVe\nuse_gpu = torch.cuda.is_available()\n\nclass Logger():\n '''Prints to a log file and to standard output''' \n def __init__(self, path):\n if os.path.exists(path):\n self.path = path\n else:\n raise Exception('path does not exist')\n \n def log(self, info, stdout=True):\n with open(os.path.join(self.path, 'log.log'), 'a') as f:\n print(info, file=f)\n if stdout:\n print(info)\n \n def save_model(self, model_dict):\n #with open(os.path.join(self.path, 'model.pkl'), 'w') as f:\n torch.save(model_dict, os.path.join(self.path, 'model.pkl'))\n\nclass AverageMeter():\n '''Computes and stores the average and current value. \n Taken from the PyTorch ImageNet tutorial'''\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 = self.sum + val * n\n self.count = self.count + n\n self.avg = self.sum / self.count\n\ndef moses_multi_bleu(outputs, references, lw=False):\n '''Outputs, references are lists of strings. Calculates BLEU score using https://raw.githubusercontent.com/moses-smt/mosesdecoder/master/scripts/generic/multi-bleu.perl -- Python function from Google '''\n \n # Save outputs and references as temporary text files\n out_file = tempfile.NamedTemporaryFile()\n out_file.write('\\n'.join(outputs).encode('utf-8'))\n out_file.write(b'\\n')\n out_file.flush() #?\n ref_file = tempfile.NamedTemporaryFile()\n ref_file.write('\\n'.join(references).encode('utf-8'))\n ref_file.write(b'\\n')\n ref_file.flush() #?\n \n # Use moses multi-bleu script\n with open(out_file.name, 'r') as read_pred:\n bleu_cmd = ['scripts/multi-bleu.perl']\n bleu_cmd = bleu_cmd + ['-lc'] if lw else bleu_cmd\n bleu_cmd = bleu_cmd + [ref_file.name]\n try: \n bleu_out = subprocess.check_output(bleu_cmd, stdin=read_pred, stderr=subprocess.STDOUT)\n bleu_out = bleu_out.decode('utf-8')\n #print(bleu_out)\n bleu_score = float(re.search(r'BLEU = (.+?),', bleu_out).group(1))\n except subprocess.CalledProcessError as error:\n print(error)\n raise Exception('Something wrong with bleu script')\n bleu_score = 0.0\n \n # Close temporary files\n out_file.close()\n ref_file.close()\n \n return bleu_score\n\n","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"123056432","text":"import argparse\nimport glob\nimport os\nimport sys\nimport random\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data.dataloader import DataLoader\nfrom torch.autograd import Variable\nfrom torch import cuda\n\nimport baseline as encoder\nimport pr_dataset\n\n\ndef test(model, data, num_per_class, cuda_dev):\n correct_total, xy_count = 0, 0\n labels = data.idx2name.items()\n num_classes = len(data.get_all_labels())\n correct = np.zeros(num_classes)\n confusion = np.zeros((num_classes, num_classes))\n predict_confusion = np.zeros((num_classes, num_classes))\n for i, label in labels:\n # get (x, y)'s from dataset object, select num_per_class of them\n class_datapoints = list(data.get_from_class(label))\n random.shuffle(class_datapoints)\n num_d = min(num_per_class, len(class_datapoints))\n probs = np.zeros(num_classes) # [0. for j in range(len(data.get_all_labels()))]\n preds = np.zeros(num_classes)\n for x, y in class_datapoints[:num_d]:\n model.eval()\n z = model([x])\n # record softmax \"probabilities\" for each label\n p = torch.nn.functional.softmax(z).cpu().data.numpy()\n probs = probs + p\n # make prediction\n _, y_hat = torch.max(z, 1)\n preds[y_hat.data[0]] += 1\n c = int(y_hat.data[0] == y)\n correct[i] += c\n correct_total += c\n xy_count += 1\n # column i shows probabilities that composer i is classified as...\n confusion[:, i] = probs / num_d\n correct[i] /= num_d\n predict_confusion[:, i] = preds / num_d\n\n print(\"*\"*10, \"Probabilities\", \"*\"*10, \"\\n\")\n print(\" \" * 11, end=\"\")\n short_label = []\n for _, label in labels:\n l = min(8, len(label))\n short_label.append(\"{:>8}\".format(label[:l]))\n for sl in short_label:\n print(\"{}\".format(sl), end=\" \")\n print()\n for j, sl in enumerate(short_label):\n print(sl, end=\" \")\n for i in range(confusion.shape[1]):\n print(\"{:8.1%}\".format(confusion[j][i]), end=\" \")\n print()\n\n print(\"\\n\" + \"*\"*10, \"Predictions\", \"*\"*10, \"\\n\")\n print(\" \" * 11, end=\"\")\n short_label = []\n for _, label in labels:\n l = min(8, len(label))\n short_label.append(\"{:>8}\".format(label[:l]))\n for sl in short_label:\n print(\"{}\".format(sl), end=\" \")\n print()\n for j, sl in enumerate(short_label):\n print(sl, end=\" \")\n for i in range(predict_confusion.shape[1]):\n print(\"{:8.1%}\".format(predict_confusion[j][i]), end=\" \")\n print()\n print()\n for sl in short_label:\n print(sl, end=\" \")\n print()\n for i in range(correct.shape[0]):\n print(\"{:8.2%}\".format(correct[i]), end=\" \")\n\n print(\"\\n\\nAverage accuracy: {:.3%}\\n\".format(float(correct_total) / xy_count))\n\n\ndef main(opts):\n if opts.use_cuda is not None:\n print(\"using CUDA device {}\".format(opts.use_cuda), file=sys.stderr)\n cuda_dev = int(opts.use_cuda)\n else:\n cuda_dev = None\n\n # load the data\n dataset = pr_dataset.PianoRollDataset(os.getcwd() + \"/\" + opts.data_dir, \"labels.csv\", \"val\")\n\n # load the model\n enc = encoder.Encoder(\n dataset.get_y_count(),\n opts.batch_size,\n rnn_size=opts.rnn_size,\n num_rnn_layers=opts.rnn_layers,\n use_cuda=cuda_dev,\n max_w=opts.max_w\n )\n\n if opts.load:\n enc.load_state_dict(torch.load(opts.load))\n if cuda_dev is not None:\n enc = enc.cuda(cuda_dev)\n\n test(enc, dataset, 100, opts.use_cuda)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--rnn_size\", type=int, default=128)\n parser.add_argument(\"--rnn_layers\", type=int, default=3)\n parser.add_argument(\"--data_dir\", default=\"preprocessed\")\n parser.add_argument(\"--max_epochs\", type=int, default=1000)\n parser.add_argument(\"--max_w\", type=int, default=5000)\n parser.add_argument(\"--test\", action=\"store_true\")\n parser.add_argument(\"--batch_size\", type=int, default=1)\n parser.add_argument(\"-m\", \"--model_dir\", default=\"model\")\n parser.add_argument(\"-e\", \"--num_epochs\", type=int, default=5)\n parser.add_argument(\"--num_batch_valid\", type=int, default=1)\n parser.add_argument(\"--beam_size\", type=int, default=5)\n parser.add_argument(\"-s\", \"--seed\", type=int, default=0)\n parser.add_argument(\"-c\", \"--use_cuda\", type=int, default=None)\n parser.add_argument(\"-l\", \"--init_lr\", type=int, default=5)\n parser.add_argument(\"--load\", default=None)\n\n args = parser.parse_args()\n main(args)","sub_path":"baseline_test.py","file_name":"baseline_test.py","file_ext":"py","file_size_in_byte":4668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"295556017","text":"from twilio.rest import Client\nimport config\n\n# Your Account SID from twilio.com/console\naccount_sid = config.ACCOUNT_SID\n# Your Auth Token from twilio.com/console\nauth_token = config.AUTH_TOKEN\n\ndef sendMessage(recipient, body):\n client = Client(account_sid, auth_token)\n message = client.messages.create(\n to=recipient, \n from_=config.MESSAGE_FROM,\n body=body)\n print (\"Sent to \" + recipient + \": \" + body)\n # print (message.sid)\n\nif __name__ == \"__main__\":\n recipient = \"+14084203598\"\n body = \"THERE IS A DISASTER DUDE\"\n sendMessage(recipient, body)\n","sub_path":"send_sms.py","file_name":"send_sms.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"396881846","text":"# -*- coding: utf-8 -*-\nimport cv2\nimport numpy as np\n# try:\n# from sklearn.externals import joblib\n# except ImportError:\nimport joblib\nimport pandas as pd\nimport os\nimport re\nfrom pyzbar.pyzbar import decode\nimport inout\nfrom csv_process import read_csv, write_csv\n\n\ndef qr_inout_csv(csv_file,stream_size=(320,240), font=cv2.FONT_HERSHEY_SIMPLEX):\n \"\"\"\n grコードを読み込み、その人の入退室データを書き込む\n \"\"\"\n data = read_csv(csv_file)\n cap = cv2.VideoCapture(0)\n while True: \n # 映像データを読み込んでサイズ変更\n rst, stream = cap.read()\n stream = cv2.resize(stream, stream_size)\n \n # streamからqrを検出する\n decoded_objs = decode(stream)\n if decoded_objs != []:\n for obj in decoded_objs:\n print('Type: ', obj)\n str_dec_obj = obj.data.decode('utf-8', 'ignore')\n # 文字列から数値を抽出\n id = int(re.sub(\"\\\\D\",\"\", str_dec_obj))\n # csvにidの人の入退室時間をpandasの形式で書き込む\n inout.inout_to_csv(id, csv_file)\n\n print('QR code: {}'.format(str_dec_obj))\n x, y, w, h = obj.rect\n # qrコードを四角で囲う\n cv2.rectangle(stream, (x,y), (x+w,y+h), (0,0,255), 1)\n # 文字列を表示\n cv2.putText(stream, str_dec_obj,(x,y-10), font, 1, (0,255,0), 3, cv2.LINE_AA)\n\n # 画像をウインドウに表示\n cv2.imshow(\"img\", stream)\n \n # 'q'を入力でアプリケーション終了\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n \n #終了処理\n cap.release()\n cv2.destroyAllWindows()\n\n\nif __name__ == \"__main__\":\n now = pd.Timestamp.now()\n today_csv = now.strftime(\"%Y-%m-%d\") + \".csv\"\n base_csv = \"data/train_data_arasi.csv\"\n if os.path.exists(today_csv) == False:\n today_data = read_csv(base_csv)\n write_csv(today_data, today_csv)\n\n qr_inout_csv(today_csv)","sub_path":"inout_system/qr_inout.py","file_name":"qr_inout.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
+{"seq_id":"333569494","text":"import datetime\nimport re\nimport time\nimport redis\nfrom urllib.parse import urlparse, urlencode, parse_qs\n\nimport scrapy\nfrom lxml.etree import HTML\nfrom selenium import webdriver\nfrom selenium.webdriver import ChromeOptions\n\noption = ChromeOptions()\noption.add_experimental_option('excludeSwitches', ['enable-automation'])\n\n\ndef get_cookie(url):\n driver = webdriver.Chrome(options=option)\n driver.get(url)\n time.sleep(3)\n cookies = driver.get_cookies()\n driver.quit()\n items = []\n dict_ = {}\n for i in range(len(cookies)):\n cookie_value = cookies[i]\n item = cookie_value['name'] + '=' + cookie_value['value']\n items.append(item)\n dict_[cookie_value['name']] = cookie_value['value']\n return dict_\n\n\ndef format_doc_no(doc_no: str):\n doc = ''\n if doc_no and len(doc_no) <= 30 and re.findall(r'^[\\u4e00-\\u9fa5]', doc_no):\n doc = doc_no\n return doc\n\n\ndef format_file_type(doc_no: str):\n file_type = ''\n if '〔' in doc_no:\n file_type = obj_first(re.findall('^(.*?)〔', doc_no))\n elif '[' in doc_no:\n file_type = obj_first(re.findall(r'^(.*?)\\[', doc_no))\n elif obj_first(re.findall(r'^(.*?)\\d{4}', doc_no)):\n file_type = obj_first(re.findall(r'^(.*?)\\d{4}', doc_no))\n elif '第' in doc_no:\n file_type = obj_first(re.findall('^(.*?)第', doc_no))\n elif obj_first(re.findall(r'^(.*?)\\d', doc_no)):\n file_type = obj_first(re.findall(r'^(.*?)\\d', doc_no))\n return '' if re.findall(r'^\\d', file_type) else file_type\n\n\ndef time_map(t_str, error=''):\n \"\"\"\n >>>time_map('发布日期:2020年2月18日')\n 2020-02-18\n \"\"\"\n try:\n year, month, day = re.findall(r'(\\d{4})\\D(\\d{1,2})\\D(\\d{1,2})', t_str.strip())[0]\n return '{}-{:0>2}-{:0>2}'.format(year, month, day)\n except:\n return error\n\n\ndef obj_first(obj, error=''):\n return obj[0] if obj else error\n\n\ndef get_html_content(response: scrapy.http.Response, con_xpath: str) -> str:\n \"\"\"\n 返回网页响应中的正文主体html代码\n :param response: 网页响应\n :param con_xpath: 正文的爬取范围 eg:'//*[@id=\"mainText\"]'\n :return: 正文主体html代码\n \"\"\"\n html_content = response.xpath(con_xpath).get()\n html_content = re.sub(r'|\\<\\!--[\\s\\S]*?--\\>|